id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
24,236
cl-gcrypt.lisp
gorozhin_cl-gcrypt/src/cl-gcrypt.lisp
(in-package #:cl-user) (defpackage #:cl-gcrypt (:use #:cl #:cl-gcrypt.helper)) (in-package #:cl-gcrypt) (cffi:define-foreign-library libgcrypt (:darwin (:or "libgcrypt.20.dylib" "libgcrypt.dylib.20" "libgcrypt.dylib")) (:unix (:or "libgcrypt.so.20" "libgcrypt.20.so" "libgcrypt.so")) (t (:default "libgcrypt"))) (cffi:use-foreign-library libgcrypt) (cffi:defctype #.(lispify "gcry_ctx_t" 'type) :pointer) (cffi:defctype #.(lispify "gcry_error_t" 'type) :uint) (export '#.(lispify "gcry_error_t" 'type)) (cffi:defcfun #.(namify-function-definition "gcry_check_version") :string (req-version :string)) (export '#.(namify-function "gcry_check_version")) (defmacro #.(namify-function "gcry_control") (cmd &rest arguments) `(cffi:foreign-funcall "gcry_control" :int ,cmd ,@arguments #.(lispify "gcry_error_t" 'type))) (export '#.(namify-function "gcry_control")) (defenum (#.(lispify "GCRYCTL_CFB_SYNC" 'enumvalue) 3) (#.(lispify "GCRYCTL_RESET" 'enumvalue) 4) (#.(lispify "GCRYCTL_FINALIZE" 'enumvalue) 5) (#.(lispify "GCRYCTL_GET_KEYLEN" 'enumvalue) 6) (#.(lispify "GCRYCTL_GET_BLKLEN" 'enumvalue) 7) (#.(lispify "GCRYCTL_TEST_ALGO" 'enumvalue) 8) (#.(lispify "GCRYCTL_IS_SECURE" 'enumvalue) 9) (#.(lispify "GCRYCTL_GET_ASNOID" 'enumvalue) 10) (#.(lispify "GCRYCTL_ENABLE_ALGO" 'enumvalue) 11) (#.(lispify "GCRYCTL_DISABLE_ALGO" 'enumvalue) 12) (#.(lispify "GCRYCTL_DUMP_RANDOM_STATS" 'enumvalue) 13) (#.(lispify "GCRYCTL_DUMP_SECMEM_STATS" 'enumvalue) 14) (#.(lispify "GCRYCTL_GET_ALGO_NPKEY" 'enumvalue) 15) (#.(lispify "GCRYCTL_GET_ALGO_NSKEY" 'enumvalue) 16) (#.(lispify "GCRYCTL_GET_ALGO_NSIGN" 'enumvalue) 17) (#.(lispify "GCRYCTL_GET_ALGO_NENCR" 'enumvalue) 18) (#.(lispify "GCRYCTL_SET_VERBOSITY" 'enumvalue) 19) (#.(lispify "GCRYCTL_SET_DEBUG_FLAGS" 'enumvalue) 20) (#.(lispify "GCRYCTL_CLEAR_DEBUG_FLAGS" 'enumvalue) 21) (#.(lispify "GCRYCTL_USE_SECURE_RNDPOOL" 'enumvalue) 22) (#.(lispify "GCRYCTL_DUMP_MEMORY_STATS" 'enumvalue) 23) (#.(lispify "GCRYCTL_INIT_SECMEM" 'enumvalue) 24) (#.(lispify "GCRYCTL_TERM_SECMEM" 'enumvalue) 25) (#.(lispify "GCRYCTL_DISABLE_SECMEM_WARN" 'enumvalue) 27) (#.(lispify "GCRYCTL_SUSPEND_SECMEM_WARN" 'enumvalue) 28) (#.(lispify "GCRYCTL_RESUME_SECMEM_WARN" 'enumvalue) 29) (#.(lispify "GCRYCTL_DROP_PRIVS" 'enumvalue) 30) (#.(lispify "GCRYCTL_ENABLE_M_GUARD" 'enumvalue) 31) (#.(lispify "GCRYCTL_START_DUMP" 'enumvalue) 32) (#.(lispify "GCRYCTL_STOP_DUMP" 'enumvalue) 33) (#.(lispify "GCRYCTL_GET_ALGO_USAGE" 'enumvalue) 34) (#.(lispify "GCRYCTL_IS_ALGO_ENABLED" 'enumvalue) 35) (#.(lispify "GCRYCTL_DISABLE_INTERNAL_LOCKING" 'enumvalue) 36) (#.(lispify "GCRYCTL_DISABLE_SECMEM" 'enumvalue) 37) (#.(lispify "GCRYCTL_INITIALIZATION_FINISHED" 'enumvalue) 38) (#.(lispify "GCRYCTL_INITIALIZATION_FINISHED_P" 'enumvalue) 39) (#.(lispify "GCRYCTL_ANY_INITIALIZATION_P" 'enumvalue) 40) (#.(lispify "GCRYCTL_SET_CBC_CTS" 'enumvalue) 41) (#.(lispify "GCRYCTL_SET_CBC_MAC" 'enumvalue) 42) (#.(lispify "GCRYCTL_ENABLE_QUICK_RANDOM" 'enumvalue) 44) (#.(lispify "GCRYCTL_SET_RANDOM_SEED_FILE" 'enumvalue) 45) (#.(lispify "GCRYCTL_UPDATE_RANDOM_SEED_FILE" 'enumvalue) 46) (#.(lispify "GCRYCTL_SET_THREAD_CBS" 'enumvalue) 47) (#.(lispify "GCRYCTL_FAST_POLL" 'enumvalue) 48) (#.(lispify "GCRYCTL_SET_RANDOM_DAEMON_SOCKET" 'enumvalue) 49) (#.(lispify "GCRYCTL_USE_RANDOM_DAEMON" 'enumvalue) 50) (#.(lispify "GCRYCTL_FAKED_RANDOM_P" 'enumvalue) 51) (#.(lispify "GCRYCTL_SET_RNDEGD_SOCKET" 'enumvalue) 52) (#.(lispify "GCRYCTL_PRINT_CONFIG" 'enumvalue) 53) (#.(lispify "GCRYCTL_OPERATIONAL_P" 'enumvalue) 54) (#.(lispify "GCRYCTL_FIPS_MODE_P" 'enumvalue) 55) (#.(lispify "GCRYCTL_FORCE_FIPS_MODE" 'enumvalue) 56) (#.(lispify "GCRYCTL_SELFTEST" 'enumvalue) 57) (#.(lispify "GCRYCTL_DISABLE_HWF" 'enumvalue) 63) (#.(lispify "GCRYCTL_SET_ENFORCED_FIPS_FLAG" 'enumvalue) 64) (#.(lispify "GCRYCTL_SET_PREFERRED_RNG_TYPE" 'enumvalue) 65) (#.(lispify "GCRYCTL_GET_CURRENT_RNG_TYPE" 'enumvalue) 66) (#.(lispify "GCRYCTL_DISABLE_LOCKED_SECMEM" 'enumvalue) 67) (#.(lispify "GCRYCTL_DISABLE_PRIV_DROP" 'enumvalue) 68) (#.(lispify "GCRYCTL_SET_CCM_LENGTHS" 'enumvalue) 69) (#.(lispify "GCRYCTL_CLOSE_RANDOM_DEVICE" 'enumvalue) 70) (#.(lispify "GCRYCTL_INACTIVATE_FIPS_FLAG" 'enumvalue) 71) (#.(lispify "GCRYCTL_REACTIVATE_FIPS_FLAG" 'enumvalue) 72) (#.(lispify "GCRYCTL_SET_SBOX" 'enumvalue) 73) (#.(lispify "GCRYCTL_DRBG_REINIT" 'enumvalue) 74) (#.(lispify "GCRYCTL_SET_TAGLEN" 'enumvalue) 75) (#.(lispify "GCRYCTL_GET_TAGLEN" 'enumvalue) 76) (#.(lispify "GCRYCTL_REINIT_SYSCALL_CLAMP" 'enumvalue) 77) (#.(lispify "GCRYCTL_AUTO_EXPAND_SECMEM" 'enumvalue) 78) (#.(lispify "GCRYCTL_SET_ALLOW_WEAK_KEY" 'enumvalue) 79) (#.(lispify "GCRYCTL_CFB_SYNC" 'enumvalue) 3) (#.(lispify "GCRYCTL_RESET" 'enumvalue) 4) (#.(lispify "GCRYCTL_FINALIZE" 'enumvalue) 5) (#.(lispify "GCRYCTL_GET_KEYLEN" 'enumvalue) 6) (#.(lispify "GCRYCTL_GET_BLKLEN" 'enumvalue) 7) (#.(lispify "GCRYCTL_TEST_ALGO" 'enumvalue) 8) (#.(lispify "GCRYCTL_IS_SECURE" 'enumvalue) 9) (#.(lispify "GCRYCTL_GET_ASNOID" 'enumvalue) 10) (#.(lispify "GCRYCTL_ENABLE_ALGO" 'enumvalue) 11) (#.(lispify "GCRYCTL_DISABLE_ALGO" 'enumvalue) 12) (#.(lispify "GCRYCTL_DUMP_RANDOM_STATS" 'enumvalue) 13) (#.(lispify "GCRYCTL_DUMP_SECMEM_STATS" 'enumvalue) 14) (#.(lispify "GCRYCTL_GET_ALGO_NPKEY" 'enumvalue) 15) (#.(lispify "GCRYCTL_GET_ALGO_NSKEY" 'enumvalue) 16) (#.(lispify "GCRYCTL_GET_ALGO_NSIGN" 'enumvalue) 17) (#.(lispify "GCRYCTL_GET_ALGO_NENCR" 'enumvalue) 18) (#.(lispify "GCRYCTL_SET_VERBOSITY" 'enumvalue) 19) (#.(lispify "GCRYCTL_SET_DEBUG_FLAGS" 'enumvalue) 20) (#.(lispify "GCRYCTL_CLEAR_DEBUG_FLAGS" 'enumvalue) 21) (#.(lispify "GCRYCTL_USE_SECURE_RNDPOOL" 'enumvalue) 22) (#.(lispify "GCRYCTL_DUMP_MEMORY_STATS" 'enumvalue) 23) (#.(lispify "GCRYCTL_INIT_SECMEM" 'enumvalue) 24) (#.(lispify "GCRYCTL_TERM_SECMEM" 'enumvalue) 25) (#.(lispify "GCRYCTL_DISABLE_SECMEM_WARN" 'enumvalue) 27) (#.(lispify "GCRYCTL_SUSPEND_SECMEM_WARN" 'enumvalue) 28) (#.(lispify "GCRYCTL_RESUME_SECMEM_WARN" 'enumvalue) 29) (#.(lispify "GCRYCTL_DROP_PRIVS" 'enumvalue) 30) (#.(lispify "GCRYCTL_ENABLE_M_GUARD" 'enumvalue) 31) (#.(lispify "GCRYCTL_START_DUMP" 'enumvalue) 32) (#.(lispify "GCRYCTL_STOP_DUMP" 'enumvalue) 33) (#.(lispify "GCRYCTL_GET_ALGO_USAGE" 'enumvalue) 34) (#.(lispify "GCRYCTL_IS_ALGO_ENABLED" 'enumvalue) 35) (#.(lispify "GCRYCTL_DISABLE_INTERNAL_LOCKING" 'enumvalue) 36) (#.(lispify "GCRYCTL_DISABLE_SECMEM" 'enumvalue) 37) (#.(lispify "GCRYCTL_INITIALIZATION_FINISHED" 'enumvalue) 38) (#.(lispify "GCRYCTL_INITIALIZATION_FINISHED_P" 'enumvalue) 39) (#.(lispify "GCRYCTL_ANY_INITIALIZATION_P" 'enumvalue) 40) (#.(lispify "GCRYCTL_SET_CBC_CTS" 'enumvalue) 41) (#.(lispify "GCRYCTL_SET_CBC_MAC" 'enumvalue) 42) (#.(lispify "GCRYCTL_ENABLE_QUICK_RANDOM" 'enumvalue) 44) (#.(lispify "GCRYCTL_SET_RANDOM_SEED_FILE" 'enumvalue) 45) (#.(lispify "GCRYCTL_UPDATE_RANDOM_SEED_FILE" 'enumvalue) 46) (#.(lispify "GCRYCTL_SET_THREAD_CBS" 'enumvalue) 47) (#.(lispify "GCRYCTL_FAST_POLL" 'enumvalue) 48) (#.(lispify "GCRYCTL_SET_RANDOM_DAEMON_SOCKET" 'enumvalue) 49) (#.(lispify "GCRYCTL_USE_RANDOM_DAEMON" 'enumvalue) 50) (#.(lispify "GCRYCTL_FAKED_RANDOM_P" 'enumvalue) 51) (#.(lispify "GCRYCTL_SET_RNDEGD_SOCKET" 'enumvalue) 52) (#.(lispify "GCRYCTL_PRINT_CONFIG" 'enumvalue) 53) (#.(lispify "GCRYCTL_OPERATIONAL_P" 'enumvalue) 54) (#.(lispify "GCRYCTL_FIPS_MODE_P" 'enumvalue) 55) (#.(lispify "GCRYCTL_FORCE_FIPS_MODE" 'enumvalue) 56) (#.(lispify "GCRYCTL_SELFTEST" 'enumvalue) 57) (#.(lispify "GCRYCTL_DISABLE_HWF" 'enumvalue) 63) (#.(lispify "GCRYCTL_SET_ENFORCED_FIPS_FLAG" 'enumvalue) 64) (#.(lispify "GCRYCTL_SET_PREFERRED_RNG_TYPE" 'enumvalue) 65) (#.(lispify "GCRYCTL_GET_CURRENT_RNG_TYPE" 'enumvalue) 66) (#.(lispify "GCRYCTL_DISABLE_LOCKED_SECMEM" 'enumvalue) 67) (#.(lispify "GCRYCTL_DISABLE_PRIV_DROP" 'enumvalue) 68) (#.(lispify "GCRYCTL_SET_CCM_LENGTHS" 'enumvalue) 69) (#.(lispify "GCRYCTL_CLOSE_RANDOM_DEVICE" 'enumvalue) 70) (#.(lispify "GCRYCTL_INACTIVATE_FIPS_FLAG" 'enumvalue) 71) (#.(lispify "GCRYCTL_REACTIVATE_FIPS_FLAG" 'enumvalue) 72) (#.(lispify "GCRYCTL_SET_SBOX" 'enumvalue) 73) (#.(lispify "GCRYCTL_DRBG_REINIT" 'enumvalue) 74) (#.(lispify "GCRYCTL_SET_TAGLEN" 'enumvalue) 75) (#.(lispify "GCRYCTL_GET_TAGLEN" 'enumvalue) 76) (#.(lispify "GCRYCTL_REINIT_SYSCALL_CLAMP" 'enumvalue) 77) (#.(lispify "GCRYCTL_AUTO_EXPAND_SECMEM" 'enumvalue) 78) (#.(lispify "GCRYCTL_SET_ALLOW_WEAK_KEY" 'enumvalue) 79)) (export '#.(lispify "GCRYCTL_CFB_SYNC" 'enumvalue)) (export '#.(lispify "GCRYCTL_RESET" 'enumvalue)) (export '#.(lispify "GCRYCTL_FINALIZE" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_KEYLEN" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_BLKLEN" 'enumvalue)) (export '#.(lispify "GCRYCTL_TEST_ALGO" 'enumvalue)) (export '#.(lispify "GCRYCTL_IS_SECURE" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ASNOID" 'enumvalue)) (export '#.(lispify "GCRYCTL_ENABLE_ALGO" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_ALGO" 'enumvalue)) (export '#.(lispify "GCRYCTL_DUMP_RANDOM_STATS" 'enumvalue)) (export '#.(lispify "GCRYCTL_DUMP_SECMEM_STATS" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_NPKEY" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_NSKEY" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_NSIGN" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_NENCR" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_VERBOSITY" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_DEBUG_FLAGS" 'enumvalue)) (export '#.(lispify "GCRYCTL_CLEAR_DEBUG_FLAGS" 'enumvalue)) (export '#.(lispify "GCRYCTL_USE_SECURE_RNDPOOL" 'enumvalue)) (export '#.(lispify "GCRYCTL_DUMP_MEMORY_STATS" 'enumvalue)) (export '#.(lispify "GCRYCTL_INIT_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_TERM_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_SECMEM_WARN" 'enumvalue)) (export '#.(lispify "GCRYCTL_SUSPEND_SECMEM_WARN" 'enumvalue)) (export '#.(lispify "GCRYCTL_RESUME_SECMEM_WARN" 'enumvalue)) (export '#.(lispify "GCRYCTL_DROP_PRIVS" 'enumvalue)) (export '#.(lispify "GCRYCTL_ENABLE_M_GUARD" 'enumvalue)) (export '#.(lispify "GCRYCTL_START_DUMP" 'enumvalue)) (export '#.(lispify "GCRYCTL_STOP_DUMP" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_USAGE" 'enumvalue)) (export '#.(lispify "GCRYCTL_IS_ALGO_ENABLED" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_INTERNAL_LOCKING" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_INITIALIZATION_FINISHED" 'enumvalue)) (export '#.(lispify "GCRYCTL_INITIALIZATION_FINISHED_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_ANY_INITIALIZATION_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_CBC_CTS" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_CBC_MAC" 'enumvalue)) (export '#.(lispify "GCRYCTL_ENABLE_QUICK_RANDOM" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_RANDOM_SEED_FILE" 'enumvalue)) (export '#.(lispify "GCRYCTL_UPDATE_RANDOM_SEED_FILE" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_THREAD_CBS" 'enumvalue)) (export '#.(lispify "GCRYCTL_FAST_POLL" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_RANDOM_DAEMON_SOCKET" 'enumvalue)) (export '#.(lispify "GCRYCTL_USE_RANDOM_DAEMON" 'enumvalue)) (export '#.(lispify "GCRYCTL_FAKED_RANDOM_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_RNDEGD_SOCKET" 'enumvalue)) (export '#.(lispify "GCRYCTL_PRINT_CONFIG" 'enumvalue)) (export '#.(lispify "GCRYCTL_OPERATIONAL_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_FIPS_MODE_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_FORCE_FIPS_MODE" 'enumvalue)) (export '#.(lispify "GCRYCTL_SELFTEST" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_HWF" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_ENFORCED_FIPS_FLAG" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_PREFERRED_RNG_TYPE" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_CURRENT_RNG_TYPE" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_LOCKED_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_PRIV_DROP" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_CCM_LENGTHS" 'enumvalue)) (export '#.(lispify "GCRYCTL_CLOSE_RANDOM_DEVICE" 'enumvalue)) (export '#.(lispify "GCRYCTL_INACTIVATE_FIPS_FLAG" 'enumvalue)) (export '#.(lispify "GCRYCTL_REACTIVATE_FIPS_FLAG" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_SBOX" 'enumvalue)) (export '#.(lispify "GCRYCTL_DRBG_REINIT" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_TAGLEN" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_TAGLEN" 'enumvalue)) (export '#.(lispify "GCRYCTL_REINIT_SYSCALL_CLAMP" 'enumvalue)) (export '#.(lispify "GCRYCTL_AUTO_EXPAND_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_ALLOW_WEAK_KEY" 'enumvalue)) (export '#.(lispify "GCRYCTL_CFB_SYNC" 'enumvalue)) (export '#.(lispify "GCRYCTL_RESET" 'enumvalue)) (export '#.(lispify "GCRYCTL_FINALIZE" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_KEYLEN" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_BLKLEN" 'enumvalue)) (export '#.(lispify "GCRYCTL_TEST_ALGO" 'enumvalue)) (export '#.(lispify "GCRYCTL_IS_SECURE" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ASNOID" 'enumvalue)) (export '#.(lispify "GCRYCTL_ENABLE_ALGO" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_ALGO" 'enumvalue)) (export '#.(lispify "GCRYCTL_DUMP_RANDOM_STATS" 'enumvalue)) (export '#.(lispify "GCRYCTL_DUMP_SECMEM_STATS" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_NPKEY" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_NSKEY" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_NSIGN" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_NENCR" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_VERBOSITY" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_DEBUG_FLAGS" 'enumvalue)) (export '#.(lispify "GCRYCTL_CLEAR_DEBUG_FLAGS" 'enumvalue)) (export '#.(lispify "GCRYCTL_USE_SECURE_RNDPOOL" 'enumvalue)) (export '#.(lispify "GCRYCTL_DUMP_MEMORY_STATS" 'enumvalue)) (export '#.(lispify "GCRYCTL_INIT_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_TERM_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_SECMEM_WARN" 'enumvalue)) (export '#.(lispify "GCRYCTL_SUSPEND_SECMEM_WARN" 'enumvalue)) (export '#.(lispify "GCRYCTL_RESUME_SECMEM_WARN" 'enumvalue)) (export '#.(lispify "GCRYCTL_DROP_PRIVS" 'enumvalue)) (export '#.(lispify "GCRYCTL_ENABLE_M_GUARD" 'enumvalue)) (export '#.(lispify "GCRYCTL_START_DUMP" 'enumvalue)) (export '#.(lispify "GCRYCTL_STOP_DUMP" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_ALGO_USAGE" 'enumvalue)) (export '#.(lispify "GCRYCTL_IS_ALGO_ENABLED" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_INTERNAL_LOCKING" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_INITIALIZATION_FINISHED" 'enumvalue)) (export '#.(lispify "GCRYCTL_INITIALIZATION_FINISHED_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_ANY_INITIALIZATION_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_CBC_CTS" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_CBC_MAC" 'enumvalue)) (export '#.(lispify "GCRYCTL_ENABLE_QUICK_RANDOM" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_RANDOM_SEED_FILE" 'enumvalue)) (export '#.(lispify "GCRYCTL_UPDATE_RANDOM_SEED_FILE" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_THREAD_CBS" 'enumvalue)) (export '#.(lispify "GCRYCTL_FAST_POLL" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_RANDOM_DAEMON_SOCKET" 'enumvalue)) (export '#.(lispify "GCRYCTL_USE_RANDOM_DAEMON" 'enumvalue)) (export '#.(lispify "GCRYCTL_FAKED_RANDOM_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_RNDEGD_SOCKET" 'enumvalue)) (export '#.(lispify "GCRYCTL_PRINT_CONFIG" 'enumvalue)) (export '#.(lispify "GCRYCTL_OPERATIONAL_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_FIPS_MODE_P" 'enumvalue)) (export '#.(lispify "GCRYCTL_FORCE_FIPS_MODE" 'enumvalue)) (export '#.(lispify "GCRYCTL_SELFTEST" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_HWF" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_ENFORCED_FIPS_FLAG" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_PREFERRED_RNG_TYPE" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_CURRENT_RNG_TYPE" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_LOCKED_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_DISABLE_PRIV_DROP" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_CCM_LENGTHS" 'enumvalue)) (export '#.(lispify "GCRYCTL_CLOSE_RANDOM_DEVICE" 'enumvalue)) (export '#.(lispify "GCRYCTL_INACTIVATE_FIPS_FLAG" 'enumvalue)) (export '#.(lispify "GCRYCTL_REACTIVATE_FIPS_FLAG" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_SBOX" 'enumvalue)) (export '#.(lispify "GCRYCTL_DRBG_REINIT" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_TAGLEN" 'enumvalue)) (export '#.(lispify "GCRYCTL_GET_TAGLEN" 'enumvalue)) (export '#.(lispify "GCRYCTL_REINIT_SYSCALL_CLAMP" 'enumvalue)) (export '#.(lispify "GCRYCTL_AUTO_EXPAND_SECMEM" 'enumvalue)) (export '#.(lispify "GCRYCTL_SET_ALLOW_WEAK_KEY" 'enumvalue))
16,938
Common Lisp
.lisp
303
53.871287
96
0.712035
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
35ae3fafd295a638d281d4928554d90dd1bf8354047f8c1d3977a72467dde690
24,236
[ -1 ]
24,237
sexp-export.lisp
gorozhin_cl-gcrypt/src/sexp-export.lisp
(in-package #:cl-gcrypt) (export '#.(lispify "gcry_sexp_t" 'type)) (export '#.(Lispify "GCRYSEXP_FMT_DEFAULT" 'enumvalue)) (export '#.(lispify "GCRYSEXP_FMT_CANON" 'enumvalue)) (export '#.(lispify "GCRYSEXP_FMT_BASE64" 'enumvalue)) (export '#.(lispify "GCRYSEXP_FMT_ADVANCED" 'enumvalue)) (export '#.(namify-function "gcry_sexp_new")) (export '#.(namify-function "gcry_sexp_create")) (export '#.(namify-function "gcry_sexp_sscan")) (export '#.(namify-function "gcry_sexp_build")) (export '#.(namify-function "gcry_sexp_build_array")) (export '#.(namify-function "gcry_sexp_release")) (export '#.(namify-function "gcry_sexp_canon_len")) (export '#.(namify-function "gcry_sexp_sprint")) (export '#.(namify-function "gcry_sexp_dump")) ;; Not implemented ;; (export '#.(namify-function "gcry_sexp_cons")) ;; (export '#.(namify-function "gcry_sexp_alist")) ;; (export '#.(namify-function "gcry_sexp_vlist")) ;; (export '#.(namify-function "gcry_sexp_append")) ;; (export '#.(namify-function "gcry_sexp_prepend")) (export '#.(namify-function "gcry_sexp_find_token")) (export '#.(namify-function "gcry_sexp_length")) (export '#.(namify-function "gcry_sexp_nth")) (export '#.(namify-function "gcry_sexp_car")) (export '#.(namify-function "gcry_sexp_cdr")) (export '#.(namify-function "gcry_sexp_cadr")) (export '#.(namify-function "gcry_sexp_nth_data")) (export '#.(namify-function "gcry_sexp_nth_buffer")) (export '#.(namify-function "gcry_sexp_nth_string")) (export '#.(namify-function "gcry_sexp_nth_mpi")) (export '#.(namify-function "gcry_sexp_extract_param"))
1,572
Common Lisp
.lisp
32
47.6875
56
0.699214
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
befeb3269e574abef5b653cd00bfc6ad7a70348c12fdb7addcabd1caf9f93398
24,237
[ -1 ]
24,238
pk-export.lisp
gorozhin_cl-gcrypt/src/pk-export.lisp
(in-package #:cl-gcrypt) (export '#.(lispify "GCRY_PK_RSA" 'enumvalue)) (export '#.(lispify "GCRY_PK_RSA_E" 'enumvalue)) (export '#.(lispify "GCRY_PK_RSA_S" 'enumvalue)) (export '#.(lispify "GCRY_PK_ELG_E" 'enumvalue)) (export '#.(lispify "GCRY_PK_DSA" 'enumvalue)) (export '#.(lispify "GCRY_PK_ECC" 'enumvalue)) (export '#.(lispify "GCRY_PK_ELG" 'enumvalue)) (export '#.(lispify "GCRY_PK_ECDSA" 'enumvalue)) (export '#.(lispify "GCRY_PK_ECDH" 'enumvalue)) (export '#.(lispify "GCRY_PK_EDDSA" 'enumvalue)) (export '#.(lispify "GCRY_PK_USAGE_SIGN" 'enumvalue)) (export '#.(lispify "GCRY_PK_USAGE_ENCR" 'enumvalue)) (export '#.(lispify "GCRY_PK_USAGE_CERT" 'enumvalue)) (export '#.(lispify "GCRY_PK_USAGE_AUTH" 'enumvalue)) (export '#.(lispify "GCRY_PK_USAGE_UNKN" 'enumvalue)) (export '#.(lispify "GCRY_PK_GET_PUBKEY" 'enumvalue)) (export '#.(lispify "GCRY_PK_GET_SECKEY" 'enumvalue)) (export '#.(namify-function "gcry_pk_encrypt")) (export '#.(namify-function "gcry_pk_decrypt")) (export '#.(namify-function "gcry_pk_sign")) (export '#.(namify-function "gcry_pk_verify")) (export '#.(namify-function "gcry_pk_testkey")) (export '#.(namify-function "gcry_pk_genkey")) (export '#.(namify-function "gcry_pk_ctl")) (export '#.(namify-function "gcry_pk_algo_info")) (export '#.(namify-function "gcry_pk_algo_name")) (export '#.(namify-function "gcry_pk_map_name")) (export '#.(namify-function "gcry_pk_get_nbits")) (export '#.(namify-function "gcry_pk_get_keygrip")) (export '#.(namify-function "gcry_pk_get_curve")) (export '#.(namify-function "gcry_pk_get_param")) (export '#.(namify-function "gcry_pk_test_algo")) (export '#.(namify-function "gcry_pubkey_get_sexp"))
1,670
Common Lisp
.lisp
34
47.970588
53
0.690374
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6a02bce03b72ddc157a3ca1027f9e1d6111d2066be176bdc07114bbd59d82557
24,238
[ -1 ]
24,239
cipher-export.lisp
gorozhin_cl-gcrypt/src/cipher-export.lisp
(in-package #:cl-gcrypt) (export '#.(lispify "gcry_cipher_hd_t" 'type)) (export '#.(lispify "GCRY_CIPHER_NONE" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_IDEA" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_3DES" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_CAST5" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_BLOWFISH" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_SAFER_SK128" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_DES_SK" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_AES" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_AES192" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_AES256" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_TWOFISH" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_ARCFOUR" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_DES" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_TWOFISH128" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_SERPENT128" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_SERPENT192" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_SERPENT256" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_RFC2268_40" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_RFC2268_128" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_SEED" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_CAMELLIA128" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_CAMELLIA192" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_CAMELLIA256" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_SALSA20" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_SALSA20R12" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_GOST28147" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_CHACHA20" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_GOST28147_MESH" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_SM4" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_NONE" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_ECB" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_CFB" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_CBC" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_STREAM" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_OFB" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_CTR" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_AESWRAP" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_CCM" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_GCM" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_POLY1305" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_OCB" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_CFB8" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_XTS" 'enumvalue)) (export '#.(lispify "GCRY_CIPHER_MODE_EAX" 'enumvalue)) (export '#.(namify-function "gcry_cipher_open")) (export '#.(namify-function "gcry_cipher_setkey")) (export '#.(namify-function "gcry_cipher_encrypt")) (export '#.(namify-function "gcry_cipher_close")) (export '#.(namify-function "gcry_cipher_decrypt")) (export '#.(namify-function "gcry_cipher_get_algo_keylen")) (export '#.(namify-function "gcry_cipher_get_algo_blklen")) (export '#.(namify-function "gcry_cipher_algo_name")) (export '#.(namify-function "gcry_cipher_map_name")) (export '#.(namify-function "gcry_cipher_mode_from_oid")) (export '#.(namify-function "gcry_cipher_info")) (export '#.(namify-function "gcry_cipher_algo_info")) (export '#.(namify-function "gcry_cipher_test_algo")) (export '#.(namify-function "gcry_cipher_ctl")) (export '#.(namify-function "gcry_cipher_reset")) (export '#.(namify-function "gcry_cipher_setiv")) (export '#.(namify-function "gcry_cipher_gettag")) (export '#.(namify-function "gcry_cipher_authenticate")) (export '#.(namify-function "gcry_cipher_checktag")) (export '#.(namify-function "gcry_cipher_final")) (export '#.(namify-function "gcry_cipher_setctr")) (export '#.(namify-function "gcry_cipher_sync")) (export '#.(namify-function "gcry_cipher_cts")) (export '#.(namify-function "gcry_cipher_set_sbox"))
3,801
Common Lisp
.lisp
70
53.242857
61
0.718272
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
3129047f97e4ac1f8769600b6142ecdb78db22a01bc8687438da63f9954ad8b6
24,239
[ -1 ]
24,240
helper.lisp
gorozhin_cl-gcrypt/src/helper.lisp
(in-package :cl-user) (defpackage cl-gcrypt.helper (:use :cl) (:export :lispify :enumvalue :constant :defenum :namify-function :namify-function-definition)) (in-package :cl-gcrypt.helper) (defmacro defenum (&rest definitions) `(progn ,@(loop for definition in definitions for index = 0 then (1+ index) when (listp definition) do (setf index (second definition) definition (first definition)) collecting `(defconstant ,definition ,index)))) (eval-when (:compile-toplevel :load-toplevel) (defun lispify (name flag &optional (package *package*)) (concatenate 'list name) (labels ((helper (list last accumulator &aux (c (car list))) (cond ((null list) accumulator) ((upper-case-p c) (helper (cdr list) 'upper (case last ((lower digit) (list* c #\- accumulator)) (t (cons c accumulator))))) ((lower-case-p c) (helper (cdr list) 'lower (cons (char-upcase c) accumulator))) ((digit-char-p c) (helper (cdr list) 'digit (case last ((lower upper) (list* c #\- accumulator)) (t (cons c accumulator))))) ((or (char-equal c #\_) (char-equal c #\-)) (helper (cdr list) '_ (case last (_ accumulator) (t (cons #\- accumulator))))) (t (error "Unsupported symbol ~a" c))))) (let ((fix (case flag ((constant enumvalue) "+") (variable "*") (t "")))) (intern (concatenate 'string fix (nreverse (helper (concatenate 'list name) nil nil)) fix) package)))) (defun namify-function (name) (lispify name 'function)) (defun namify-function-definition (name) (list name (namify-function name))))
1,870
Common Lisp
.lisp
74
18.824324
58
0.569514
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
0e667ff44f59bccf07affc94a2268c3c0ee511d2619ba25e2c0fc63fff8a1178
24,240
[ -1 ]
24,241
md.lisp
gorozhin_cl-gcrypt/t/md.lisp
(in-package #:cl-gcrypt-test) (def-suite cl-gcrypt-md-suite :description "Message digest tests") (in-suite cl-gcrypt-md-suite) (defun perform-simple-hash-test (algo expected &key (string "cl-gcrypt") (flags 0)) (let* ((foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (algo-digest-len (gcry-md-get-algo-dlen algo))) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (gcry-md-write handle foreign-string foreign-string-length) (let ((resulting-buffer (gcry-md-read handle algo))) (is (string= (string-downcase expected) (foreign-buffer-to-string resulting-buffer algo-digest-len)))) (gcry-md-close handle))) (foreign-free foreign-string))) (defun perform-buffered-hash-test (algo expected &key (string "cl-gcrypt") (flags 0)) (let* ((foreign-string (convert-to-foreign string :string)) (algo-digest-len (gcry-md-get-algo-dlen algo))) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (loop for character across (string-to-octets string) do (gcry-md-putc handle (convert-to-foreign character :char))) (let ((resulting-buffer (gcry-md-read handle algo))) (is (string= (string-downcase expected) (foreign-buffer-to-string resulting-buffer algo-digest-len)))) (gcry-md-close handle))) (foreign-free foreign-string))) (defmacro perform-simple-hash-test-cases (&rest test-cases) `(progn ,@(loop for (algo expected . others) in test-cases collecting `(perform-simple-hash-test ,algo ,expected ,@others)))) (defmacro perform-buffered-hash-test-cases (&rest test-cases) `(progn ,@(loop for (algo expected . others) in test-cases collecting `(perform-buffered-hash-test ,algo ,expected ,@others)))) (test simple-hash (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (perform-simple-hash-test-cases (+gcry-md-md-5+ "828560813092bf2f8eedf55dd99df999") (+gcry-md-sha-1+ "db3787abcf47c4783f9f520258f3f5cee4c2ddb4") (+gcry-md-rmd-160+ "7dc54aa4a7106b86cb284c140d99f4513aae0833") ;; md-2 is not implemented in libgcrypt, but it is reserved (+gcry-md-tiger+ "02dc0bac07cc64568617d720e180b38dbda3bd3c4f8accb5") ;; haval algo is not implemented in libgcrypt, but it is reserved (+gcry-md-sha-256+ "c293a87cb0c3b41794b535fd80c2936b8ad29e69fed2e2916a69a0324987a7eb") (+gcry-md-sha-384+ "5f5e742ee8df128ba8b642e568a1719c2a45ab6aa8075acde03f13f169a99a34ae32e22f3443621cf07b80b24c576b29") (+gcry-md-sha-512+ "4ec89318c959dae76bbd469fdb3a49dbcf317a1350bcc3241ef1527d674fed3336d63ffc1a495cf1d356cb26cae5edd179edf16319c97dbfc79bfd5135f5e715") (+gcry-md-sha-224+ "4fd270a8f1004e11a64fe45d4e865b62dbb60d4af793094e604187e3") (+gcry-md-md-4+ "9aa45e07068c784ba3f4f7ffcc28d54b") (+gcry-md-crc-32+ "83eb8103") (+gcry-md-crc-32-rfc-1510+ "65e295ad") (+gcry-md-crc-24-rfc-2440+ "2c5ec2") (+gcry-md-whirlpool+ "fcc7281ccd60ec9c00fb80d0ae3288aec877e30a81ced91bb6c4cbbdd4297f283ee557709b4d73724f4a80219c3691e1686879f8547604a85c76e412768faf6b") (+gcry-md-tiger-1+ "5664cc07ac0bdc028db380e120d71786b5cc8a4f3cbda3bd") (+gcry-md-tiger-2+ "352084cc01a42599fbc8f026dcfd83623c4a08862b0b7009") (+gcry-md-gostr-3411-94+ "603c880312dd2bcfcb717de191b6550656ff3b17694a529180c4563794d12fa1") (+gcry-md-stribog-256+ "15cde75f71eda0452087d26623762b8ac37e02902c20fa9621204e0e6428fbce") (+gcry-md-stribog-512+ "177393cbf63b72865f2054205f4b3965e133e5f962addb756c136c07ec7d7b8119c3a7c2c00aaa2ade7a367461c8746cfb3b03087a88eaee3e4d2d781cde953b") (+gcry-md-gostr-3411-cp+ "1e1337a2eafb94ad1e15ea5887859ad3bb637c7fae4b7202dcbb49e5723e0edc") (+gcry-md-sha-3-224+ "07fb67303c9ea811d7f861659b164add1cdc3425b395c8d16ddc5ca8") (+gcry-md-sha-3-256+ "9bf58615b2ad57371ce9bfa42611b614dd2a7174103edc02ceaaf9bc8f1ecdea") (+gcry-md-sha-3-384+ "c4f0810a07d206f2e520203c3a14dc3c2b86bd36cb2546d6bbcd918fa7b4f33d58e6df8fa0cd258f105aa6f1db472794") (+gcry-md-sha-3-512+ "a53945914a089385c7520ad9ea7476aeea02aae9241855252ee8668e2859d8381a480319b959dadf51ca10d71d25e3fd0f0f10b1c605754d6fa610efa31eae2b") (+gcry-md-blake-2-b-512+ "486f5018762362cd9f4fd5c2fc1914e23abe17e2a4f88653de39a45d5a4d437fe57710e5c99b5e74a4d603eb1a3205cdb7388d6d06f6b177b34dafcb2d390f64") (+gcry-md-blake-2-b-384+ "24bf3e0d765c1ba896707b1f911df5a14a695a2bf397c6818949d8f857c8ef941ed8f687d5282d59d3ada4f7703907d1") (+gcry-md-blake-2-b-256+ "b2144a0d9cc93c9ae4f306c75bb36a66e8cae7ae884d4dd53f3da4949911ce65") (+gcry-md-blake-2-b-160+ "3f48945e1f6172fa1bbdaf2931b65ebd2f5758bf") (+gcry-md-blake-2-s-256+ "a6d8c508ae9badf542f646e7cbdd9080946a7417314ee1022e72c997b9d21aaf") (+gcry-md-blake-2-s-224+ "5f297cf66ac5cad9dc3c81b8922a4c6b79f8fd04a0a402054e9a03cf") (+gcry-md-blake-2-s-160+ "6806a27aca24eb897e3608d4744177d3be88990c") (+gcry-md-blake-2-s-128+ "1eb752c0295d7a8d9c7a78745c643c73")) (when (gcry-check-version "1.9.0") (perform-simple-hash-test-cases (+gcry-md-sm-3+ "f072dc24030762ff74aa2cd38a645e7c3f41378814078019ff8ca4e5473ea380") (+gcry-md-sha-512-224+ "b17e9100bd47710919f63881fdc1a7faaefc54a253d3c1948be5d8e6") (+gcry-md-sha-512-256+ "239337abfc8a43300bbb4e17072280c87719a29047b8f0a02ae4b7656be5f1a3")))) (test simple-hash-secure-memory (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (perform-simple-hash-test-cases (+gcry-md-md-5+ "828560813092bf2f8eedf55dd99df999" :flags +gcry-md-flag-secure+) (+gcry-md-sha-1+ "db3787abcf47c4783f9f520258f3f5cee4c2ddb4" :flags +gcry-md-flag-secure+) (+gcry-md-whirlpool+ "fcc7281ccd60ec9c00fb80d0ae3288aec877e30a81ced91bb6c4cbbdd4297f283ee557709b4d73724f4a80219c3691e1686879f8547604a85c76e412768faf6b" :flags +gcry-md-flag-secure+))) (test buffered-hash (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (perform-buffered-hash-test-cases (+gcry-md-md-5+ "828560813092bf2f8eedf55dd99df999") (+gcry-md-sha-1+ "db3787abcf47c4783f9f520258f3f5cee4c2ddb4") (+gcry-md-whirlpool+ "fcc7281ccd60ec9c00fb80d0ae3288aec877e30a81ced91bb6c4cbbdd4297f283ee557709b4d73724f4a80219c3691e1686879f8547604a85c76e412768faf6b"))) (test buffered-hash-secure-memory (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (perform-buffered-hash-test-cases (+gcry-md-md-5+ "828560813092bf2f8eedf55dd99df999" :flags +gcry-md-flag-secure+) (+gcry-md-sha-1+ "db3787abcf47c4783f9f520258f3f5cee4c2ddb4" :flags +gcry-md-flag-secure+) (+gcry-md-whirlpool+ "fcc7281ccd60ec9c00fb80d0ae3288aec877e30a81ced91bb6c4cbbdd4297f283ee557709b4d73724f4a80219c3691e1686879f8547604a85c76e412768faf6b" :flags +gcry-md-flag-secure+))) (test is-enabled-is-secure-test (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (with-foreign-objects ((secure-handle-pointer :pointer) (non-secure-handle-pointer :pointer)) (gcry-md-open secure-handle-pointer +gcry-md-md-5+ +gcry-md-flag-secure+) (gcry-md-open non-secure-handle-pointer +gcry-md-md-5+ 0) (let ((secure-handle (mem-aref secure-handle-pointer 'gcry-md-hd-t)) (non-secure-handle (mem-aref non-secure-handle-pointer 'gcry-md-hd-t))) (is-true (gcry-md-is-secure secure-handle)) (is-false (gcry-md-is-secure non-secure-handle)) (is-true (gcry-md-is-enabled secure-handle +gcry-md-md-5+)) (is-false (gcry-md-is-enabled secure-handle +gcry-md-sha-1+)) (gcry-md-close secure-handle) (gcry-md-close non-secure-handle)))) (test re-enable (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((string "cl-gcrypt") (flags 0) (algo +gcry-md-none+) (later-enabled-algo +gcry-md-md-5+) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (algo-digest-len (gcry-md-get-algo-dlen later-enabled-algo))) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (gcry-md-enable handle +gcry-md-md-5+) (gcry-md-write handle foreign-string foreign-string-length) (let ((resulting-buffer (gcry-md-read handle algo))) (is (string= (string-downcase "828560813092bf2f8eedf55dd99df999") (foreign-buffer-to-string resulting-buffer algo-digest-len)))) (gcry-md-close handle))) (foreign-free foreign-string))) (test multiple-enable (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((string "cl-gcrypt") (flags 0) (algo +gcry-md-md-5+) (second-algo +gcry-md-sha-1+) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (algo-digest-len (gcry-md-get-algo-dlen algo)) (second-algo-digest-len (gcry-md-get-algo-dlen second-algo))) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (gcry-md-enable handle +gcry-md-sha-1+) (is-true (gcry-md-is-enabled handle algo)) (is-true (gcry-md-is-enabled handle second-algo)) (gcry-md-write handle foreign-string foreign-string-length) (let ((resulting-buffer (gcry-md-read handle algo)) (second-resulting-buffer (gcry-md-read handle second-algo))) (is (string= (string-downcase "828560813092bf2f8eedf55dd99df999") (foreign-buffer-to-string resulting-buffer algo-digest-len))) (is (string= (string-downcase "db3787abcf47c4783f9f520258f3f5cee4c2ddb4") (foreign-buffer-to-string second-resulting-buffer second-algo-digest-len)))) (gcry-md-close handle))))) (test algo-name-back-and-forth (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let ((algo +gcry-md-md-5+)) (is (= (gcry-md-map-name (gcry-md-algo-name algo)) algo)))) (test reset (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((some-other-string "some-other-string") (string "cl-gcrypt") (algo +gcry-md-md-5+) (flags 0) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (some-other-foreign-string (convert-to-foreign some-other-string :string)) (some-other-foreign-string-length (foreign-funcall "strlen" :string some-other-foreign-string :int)) (algo-digest-len (gcry-md-get-algo-dlen algo))) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (gcry-md-write handle some-other-foreign-string some-other-foreign-string-length) (gcry-md-reset handle) (gcry-md-write handle foreign-string foreign-string-length) (let ((resulting-buffer (gcry-md-read handle algo))) (is (string= (string-downcase "828560813092bf2f8eedf55dd99df999") (foreign-buffer-to-string resulting-buffer algo-digest-len)))) (gcry-md-close handle))) (foreign-free foreign-string) (foreign-free some-other-foreign-string))) (test algo-available (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (is (= 0 (gcry-md-test-algo +gcry-md-md-5+))) (is (not (= 0 (gcry-md-test-algo +gcry-md-md-2+)))) (is (not (= 0 (gcry-md-test-algo 1000))))) (test hash-buffer (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((algo +gcry-md-md-5+) (string "cl-gcrypt") (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (algo-length (gcry-md-get-algo-dlen algo)) (digest (foreign-alloc :char :initial-element 0 :count algo-length))) (gcry-md-hash-buffer algo digest foreign-string foreign-string-length) (is (string= (string-downcase "828560813092bf2f8eedf55dd99df999") (foreign-buffer-to-string digest algo-length))) (foreign-free foreign-string) (foreign-free digest))) (test get-algo (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((algo +gcry-md-md-5+) (flags 0)) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (is (= +gcry-md-md-5+ (gcry-md-get-algo handle))) (is (not (= +gcry-md-sha-1+ (gcry-md-get-algo handle)))) (gcry-md-close handle))))) (test test-ctl (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((string "cl-gcrypt") (algo +gcry-md-md-5+) (flags 0) (foreign-string (convert-to-foreign string :string)) (algo-digest-len (gcry-md-get-algo-dlen algo))) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (loop for character across (string-to-octets string) for index from 0 if (= index 2) do (gcry-md-final handle) do (gcry-md-putc handle (convert-to-foreign character :char))) (let ((resulting-buffer (gcry-md-read handle algo))) (is (string= (string-downcase "161747ec4dc9f55f1760195593742232") (foreign-buffer-to-string resulting-buffer algo-digest-len)))) (gcry-md-close handle))) (foreign-free foreign-string))) (test hash-buffers (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((algo +gcry-md-md-5+) (str "cl-g") (str1 "crypt") (digest-len (cl-gcrypt:gcry-md-get-algo-dlen algo)) (digest (foreign-alloc :int8 :initial-element 0 :count digest-len)) (iov (foreign-alloc '(:struct gcry-buffer-t) :count 2)) (foreign-string1 (convert-to-foreign str :string)) (foreign-string2 (convert-to-foreign str1 :string)) (len (foreign-funcall "strlen" :string foreign-string1 :int)) (len1 (foreign-funcall "strlen" :string foreign-string2 :int))) (cffi:with-foreign-objects ((iov1 '(:struct gcry-buffer-t)) (iov2 '(:struct gcry-buffer-t))) (setf (foreign-slot-value iov1 '(:struct gcry-buffer-t) 'cl-gcrypt:size) len (foreign-slot-value iov2 '(:struct gcry-buffer-t) 'cl-gcrypt:size) len1 (foreign-slot-value iov1 '(:struct gcry-buffer-t) 'cl-gcrypt:off) 0 (foreign-slot-value iov2 '(:struct gcry-buffer-t) 'cl-gcrypt:off) 0 (foreign-slot-value iov1 '(:struct gcry-buffer-t) 'cl-gcrypt:len) len (foreign-slot-value iov2 '(:struct gcry-buffer-t) 'cl-gcrypt:len) len1 (foreign-slot-value iov1 '(:struct gcry-buffer-t) 'cl-gcrypt:buf) foreign-string1 (foreign-slot-value iov2 '(:struct gcry-buffer-t) 'cl-gcrypt:buf) foreign-string2) (foreign-funcall "memcpy" :pointer (mem-aptr iov '(:struct gcry-buffer-t) 0) :pointer iov1 :int (foreign-type-size '(:struct gcry-buffer-t)) :void) (foreign-funcall "memcpy" :pointer (mem-aptr iov '(:struct gcry-buffer-t) 1) :pointer iov2 :int (foreign-type-size '(:struct gcry-buffer-t)) :void) (gcry-md-hash-buffers algo 0 digest iov 2)) (is (string= "828560813092bf2f8eedf55dd99df999" (foreign-buffer-to-string digest digest-len))) (foreign-free iov) (foreign-free foreign-string1) (foreign-free foreign-string2) (foreign-free digest))) (test get-asnoid (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let ((buffer (cffi:foreign-alloc :uchar :initial-element 0 :count 100)) (size (cffi:foreign-alloc :size :initial-element 100))) (cl-gcrypt:gcry-md-get-asnoid cl-gcrypt:+gcry-md-md-5+ buffer size) (is (string= "3020300c06082a864886f70d020505000410" (foreign-buffer-to-string buffer (mem-aref size :size)))) (cl-gcrypt:gcry-md-get-asnoid cl-gcrypt:+gcry-md-sha-1+ buffer size) (is (string= "3021300906052b0e03021a05000414" (foreign-buffer-to-string buffer (mem-aref size :size)))) (cffi:foreign-free buffer) (cffi:foreign-free size))) (test copy (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((string "cl-gcrypt") (flags 0) (algo +gcry-md-md-5+) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (algo-digest-len (gcry-md-get-algo-dlen algo))) (with-foreign-objects ((handle-pointer :pointer) (copied-handle-pointer :pointer)) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (gcry-md-write handle foreign-string foreign-string-length) (gcry-md-copy copied-handle-pointer handle) (let* ((copied-handle (mem-aref copied-handle-pointer 'gcry-md-hd-t)) (resulting-buffer (gcry-md-read copied-handle algo))) (is (string= (string-downcase "828560813092bf2f8eedf55dd99df999") (foreign-buffer-to-string resulting-buffer algo-digest-len))) (gcry-md-close copied-handle)) (gcry-md-close handle))) (foreign-free foreign-string))) (test extended-output-algo (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((string "cl-gcrypt") (algo +gcry-md-shake-128+) (flags 0) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int))) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (gcry-md-write handle foreign-string foreign-string-length) (let* ((resulting-buffer-length 5) (resulting-buffer (foreign-alloc :uint8 :initial-element 0 :count resulting-buffer-length))) (gcry-md-extract handle algo resulting-buffer resulting-buffer-length) (is (string= (string-downcase "d4a2b45507") (foreign-buffer-to-string resulting-buffer resulting-buffer-length))) (gcry-md-extract handle algo resulting-buffer resulting-buffer-length) (is (string= (string-downcase "409b42c3b6") (foreign-buffer-to-string resulting-buffer resulting-buffer-length)))) (gcry-md-close handle))) (foreign-free foreign-string))) (test hmac (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((string "cl-gcrypt") (algo +gcry-md-md-5+) (flags +gcry-md-flag-hmac+) (secret-key "secret key") (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (foreign-secret-key (convert-to-foreign secret-key :string)) (foreign-secret-key-length (foreign-funcall "strlen" :string foreign-secret-key :int)) (algo-digest-len (gcry-md-get-algo-dlen algo))) (with-foreign-object (handle-pointer :pointer) (gcry-md-open handle-pointer algo flags) (let ((handle (mem-aref handle-pointer 'gcry-md-hd-t))) (gcry-md-setkey handle foreign-secret-key foreign-secret-key-length) (gcry-md-write handle foreign-string foreign-string-length) (let ((resulting-buffer (gcry-md-read handle algo))) (is (string= (string-downcase "69f2f9498714104a591479daebb17337") (foreign-buffer-to-string resulting-buffer algo-digest-len)))) (gcry-md-close handle))) (foreign-free foreign-string) (foreign-free foreign-secret-key))) (test is-secure-via-info (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (with-foreign-objects ((secure-handle-pointer :pointer) (non-secure-handle-pointer :pointer)) (gcry-md-open secure-handle-pointer +gcry-md-md-5+ +gcry-md-flag-secure+) (gcry-md-open non-secure-handle-pointer +gcry-md-md-5+ 0) (let ((secure-handle (mem-aref secure-handle-pointer 'gcry-md-hd-t)) (non-secure-handle (mem-aref non-secure-handle-pointer 'gcry-md-hd-t)) (buffer (foreign-alloc :int :count 10)) (nbytes (foreign-alloc :size))) (gcry-md-info secure-handle +gcryctl-is-secure+ buffer nbytes) (is (= 1 (mem-aref nbytes :int))) (gcry-md-info non-secure-handle +gcryctl-is-secure+ buffer nbytes) (is (= 0 (mem-aref nbytes :int))) (setf (mem-aref buffer :int) +gcry-md-md-5+) (setf (mem-aref nbytes :int) 0) (foreign-free buffer) (foreign-free nbytes) (gcry-md-close secure-handle) (gcry-md-close non-secure-handle))))
22,233
Common Lisp
.lisp
535
36.882243
186
0.717201
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1266d1b2360bd64ddacb62ccf856959b7b957b33385c19f5c66fa71572433425
24,241
[ -1 ]
24,242
cl-gcrypt-test.lisp
gorozhin_cl-gcrypt/t/cl-gcrypt-test.lisp
(in-package #:cl-user) (uiop:define-package #:cl-gcrypt-test (:use #:cl #:cl-gcrypt #:cffi #:fiveam #:alexandria #:babel) (:export #:cl-gcrypt-cipher-suite #:cl-gcrypt-md-suite)) (in-package #:cl-gcrypt-test) (defun foreign-buffer-to-string (buffer length) (unless (null-pointer-p buffer) (let ((stream (make-string-output-stream))) (loop for index below length do (format stream "~2,'0x" (mem-aref buffer :uchar index))) (string-downcase (get-output-stream-string stream))))) (defun split-by-n (string n) (let ((string-length (length string))) (loop for i from 0 to string-length by n as j = (subseq string i (min (+ i n) string-length)) with list = nil when (/= (length j) 0) do (setf list (cons j list)) finally (return (reverse list))))) (defun string-to-foreign-buffer (string) (let* ((n 2) (string-length (length string)) (buffer-length (ceiling (/ string-length n))) (buffer (foreign-alloc :uint8 :initial-element 0 :count buffer-length))) (loop for i in (split-by-n string n) for j below buffer-length do (setf (mem-aref buffer :uint8 j) (parse-integer i :radix 16)) finally (return (values buffer buffer-length)))))
1,232
Common Lisp
.lisp
33
33.090909
62
0.663317
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6a56ad0032221756cf9d9a63a3b3c364649f9065ed9735e7cc27482d5ef0e58c
24,242
[ -1 ]
24,243
pk-test.lisp
gorozhin_cl-gcrypt/t/pk-test.lisp
(in-package #:cl-gcrypt-test) (def-suite cl-gcrypt-pk-suite :description "Assymetric cypto tests") (in-suite cl-gcrypt-pk-suite) (defun free-batch (&rest pointers) (loop for pointer in pointers do (foreign-free pointer))) (defun sexp-free-batch (&rest pointers) (loop for pointer in pointers do (gcry-sexp-release pointer))) (test encrypt-decrypt (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((raw-data "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras convallis egestas metus non dictum.") (data-format "(data (value %s))") (foreign-data (convert-to-foreign data-format :string)) (wrong-data "SOME WRONG DATA") (foreign-wrong-data (convert-to-foreign wrong-data :string)) (keys-request "(genkey (rsa (nbits 4:2048)))") (foreign-keys-request (convert-to-foreign keys-request :string)) (public-key-token "public-key") (foreign-public-key-token (convert-to-foreign public-key-token :string)) (foreign-public-key-token-length (foreign-funcall "strlen" :string foreign-public-key-token :int)) (private-key-token "private-key") (foreign-private-key-token (convert-to-foreign private-key-token :string)) (foreign-private-key-token-length (foreign-funcall "strlen" :string foreign-private-key-token :int)) (error-position (cffi:foreign-alloc :uint :initial-element 0))) (with-foreign-objects ((keys-request-pointer :pointer) (keys-pointer :pointer) (data-pointer :pointer) (encrypted-pointer :pointer) (decrypted-pointer :pointer) (signed-pointer :pointer)) (gcry-sexp-build data-pointer error-position foreign-data :string raw-data) (gcry-sexp-build keys-request-pointer error-position foreign-keys-request) (let ((keys-request (mem-aref keys-request-pointer 'gcry-sexp-t))) (gcry-pk-genkey keys-pointer keys-request) (let* ((keys (mem-aref keys-pointer 'gcry-sexp-t)) (data (mem-aref data-pointer 'gcry-sexp-t)) (public-key (gcry-sexp-find-token keys foreign-public-key-token foreign-public-key-token-length)) (private-key (gcry-sexp-find-token keys foreign-private-key-token foreign-private-key-token-length))) (gcry-pk-sign signed-pointer data private-key) (is (= 0 (gcry-pk-testkey private-key))) (is (= 2048 (gcry-pk-get-nbits private-key))) (gcry-pk-encrypt encrypted-pointer data public-key) (let ((encrypted (mem-aref encrypted-pointer 'gcry-sexp-t)) (signed (mem-aref signed-pointer 'gcry-sexp-t))) (is (= (gcry-pk-verify signed data public-key) 0)) (gcry-pk-decrypt decrypted-pointer encrypted private-key) (let* ((decrypted (mem-aref decrypted-pointer 'gcry-sexp-t)) (decrypted-string (gcry-sexp-nth-string decrypted 0))) (is (string= decrypted-string raw-data)) (sexp-free-batch decrypted)) (sexp-free-batch encrypted signed)) (sexp-free-batch keys data public-key private-key)) (sexp-free-batch keys-request))) (free-batch foreign-data foreign-keys-request foreign-public-key-token foreign-private-key-token error-position foreign-wrong-data))) (test map-name (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let ((cases `(("DSA" ,+gcry-pk-dsa+) ("RSA" ,+gcry-pk-rsa+)))) (loop for (name algo) in cases do (is (= algo (gcry-pk-map-name name))) (is (string= (gcry-pk-algo-name algo) name))))) (test is-available (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let ((cases (list +gcry-pk-dsa+ +gcry-pk-rsa+)) (non-existent-algo 9999)) (loop for algo in cases do (is (= 0 (gcry-pk-test-algo algo)))) (is (/= 0 (gcry-pk-test-algo non-existent-algo))))) (test keygrip (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((public-key-request "(public-key (rsa (n #00EA3769A24D6FD33BA26858E6BCC7EB949D20A42B5C5746626B71F50EAD98EED75583B1BB58DB5439ED897BBE33DE1461065CBD9ED6309F07526A96539904FA42E811CA645DBE8002FAEF768C3FA2C4161F4FD41C78BC1F44FEEE4B8AB2DBA2CB48D0CF8A525F6979CFFF88859458B50028910C34CAF2AE76CAE0BC8C6C5A00CF7A717502A367319A9203049B41D613B75341153BA2ACDF38EC898515784D494EF8F7E16F5177FB7318A5E986675AB90C440DD78D5A2DEA2BBD8881209E093A34407D76BBFC02B2DB53A1B4E6703A0BFEC411F8EBA80E297C6085560A2F9F84EA0409B74BA613954B8FE71FC1CC3159D35CD3F6810F402EBFF23B57F37013ABE7#) (e #010001#) ) )") (foreign-public-key-request (convert-to-foreign public-key-request :string)) (sha1 "74b1dff309444be95e7d026f98047b714505dd68") (error-position (foreign-alloc :uint))) (with-foreign-object (public-key-pointer :pointer) (gcry-sexp-build public-key-pointer error-position foreign-public-key-request) (let ((public-key (mem-aref public-key-pointer 'gcry-sexp-t))) (string= (foreign-buffer-to-string (gcry-pk-get-keygrip public-key (null-pointer)) 20) sha1) (sexp-free-batch public-key))) (free-batch foreign-public-key-request error-position))) (test get-param (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((name "NIST P-224") (sexp (gcry-pk-get-param +gcry-pk-ecc+ name)) (expected-mpi "00ffffffffffffffffffffffffffffffff000000000000000000000001") (mpi-buffer-length 1000) (mpi-buffer (cffi:foreign-alloc :uint :count mpi-buffer-length)) (written (cffi:foreign-alloc :uint)) (nbit (cffi:foreign-alloc :uint))) (with-foreign-object (mpi-pointer :pointer) (let ((extract-param-error (gcry-sexp-extract-param sexp "public-key!ecc" "p" mpi-pointer))) (is (string= (gcry-pk-get-curve sexp 0 nbit) name)) (is (= extract-param-error 0)) (when (= extract-param-error 0) (let ((mpi (mem-aref mpi-pointer 'gcry-mpi-t))) (gcry-mpi-print +gcrympi-fmt-std+ mpi-buffer mpi-buffer-length written mpi) (is (string= expected-mpi (foreign-buffer-to-string mpi-buffer (mem-aref written :uint)))) (gcry-mpi-release mpi))))) (sexp-free-batch sexp) (free-batch mpi-buffer written nbit)))
6,610
Common Lisp
.lisp
163
35.276074
522
0.706425
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
249814142d1a03001457322c796c011a129038066106d32635133b617121538b
24,243
[ -1 ]
24,244
cipher-test.lisp
gorozhin_cl-gcrypt/t/cipher-test.lisp
(in-package #:cl-gcrypt-test) (def-suite cl-gcrypt-cipher-suite :description "Cipher tests") (in-suite cl-gcrypt-cipher-suite) (defun pad-right-with-zeros (buffer actual-buffer-length desired-length-multiplier) (let* ((padding (if (= desired-length-multiplier 1) 0 (- desired-length-multiplier (mod actual-buffer-length desired-length-multiplier)))) (new-length (+ actual-buffer-length padding))) (let ((new-buffer (foreign-alloc :uint8 :initial-element 0 :count new-length))) (foreign-funcall "memcpy" :pointer new-buffer :pointer buffer :int actual-buffer-length :void) (values new-length new-buffer)))) (test simple (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((algo +gcry-cipher-aes+) (flags 0) (string "cl-gcrypt") (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (secret-key "super-secret-key") (foreign-secret-key (convert-to-foreign secret-key :string)) (foreign-secret-key-length (foreign-funcall "strlen" :string foreign-secret-key :int))) (multiple-value-bind (actual-buffer-length actual-buffer) (pad-right-with-zeros foreign-string foreign-string-length 16) (with-foreign-object (handle-pointer :pointer) (gcry-cipher-open handle-pointer algo 1 flags) (let ((handle (mem-aref handle-pointer 'cl-gcrypt:gcry-cipher-hd-t))) (gcry-cipher-setkey handle foreign-secret-key foreign-secret-key-length) (let ((out-buffer (foreign-alloc :int :initial-element 0 :count actual-buffer-length))) (gcry-cipher-encrypt handle out-buffer actual-buffer-length actual-buffer actual-buffer-length) (is (string= "e0f222f7d4e62e30c1f011ad91575af6" (foreign-buffer-to-string out-buffer actual-buffer-length))) (let ((decrypt-buffer (foreign-alloc :int :initial-element 0 :count actual-buffer-length))) (gcry-cipher-decrypt handle decrypt-buffer actual-buffer-length out-buffer actual-buffer-length) (is (string= (convert-from-foreign decrypt-buffer :string) string)) (foreign-free decrypt-buffer)) (foreign-free out-buffer)) (gcry-cipher-close handle))) (foreign-free actual-buffer)) (foreign-free foreign-string) (foreign-free foreign-secret-key))) (defun test-one-algo (algo expected string secret-key cipher-mode) (let* ((block-length (gcry-cipher-get-algo-blklen algo)) (key-length (gcry-cipher-get-algo-keylen algo)) (flags 0) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (foreign-secret-key (convert-to-foreign secret-key :string)) (foreign-secret-key-length (foreign-funcall "strlen" :string foreign-secret-key :int))) (multiple-value-bind (padded-key-length padded-key) (pad-right-with-zeros foreign-secret-key foreign-secret-key-length key-length) (with-foreign-object (pointer :pointer) (gcry-cipher-open pointer algo cipher-mode flags) (let ((handle (mem-aref pointer 'gcry-cipher-hd-t))) (gcry-cipher-setkey handle padded-key padded-key-length) (multiple-value-bind (padded-string-length padded-string) (pad-right-with-zeros foreign-string foreign-string-length block-length) (let ((encrypted-buffer (foreign-alloc :char :initial-element 0 :count padded-string-length)) (decrypted-buffer (foreign-alloc :char :initial-element 0 :count padded-string-length))) (gcry-cipher-encrypt handle encrypted-buffer padded-string-length padded-string padded-string-length) (gcry-cipher-decrypt handle decrypted-buffer padded-string-length encrypted-buffer padded-string-length) (is (string= (foreign-buffer-to-string encrypted-buffer padded-string-length) expected)) (is (string= (foreign-buffer-to-string decrypted-buffer foreign-string-length) (foreign-buffer-to-string foreign-string foreign-string-length))) (foreign-free encrypted-buffer) (foreign-free decrypted-buffer)) (foreign-free padded-string)) (gcry-cipher-close handle))) (foreign-free padded-key)) (foreign-free foreign-string) (foreign-free foreign-secret-key))) (test all (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (loop for (cipher expected string secret-key cipher-mode) in (list `(,+gcry-cipher-3-des+ "9810ddcfda315d83ad2998b8b90c82e5" nil "@U*(Y!@$OFB!HF@*HUS)") `(,+gcry-cipher-aes+ "0b8f6e33e14b0bfe9477fe380702c743") `(,+gcry-cipher-aes-192+ "af7c91211b68d7c7934d0a875ce0e235") `(,+gcry-cipher-aes-256+ "82443d28ac548774f36e6a8cbecf58c8") `(,+gcry-cipher-blowfish+ "cffe62eaf7ac06ccd7a680b72dbaaca9") `(,+gcry-cipher-camellia-128+ "b6cd1bf11434a2030e878a443aff6876") `(,+gcry-cipher-camellia-192+ "f0975f93c073cb361262f59eca58ee5d") `(,+gcry-cipher-camellia-256+ "5281fa4d9b2195274cecd7b0015cfd39") `(,+gcry-cipher-cast-5+ "6faa061299c61b48d8df62c918b516b3") `(,+gcry-cipher-des+ "f80231cca24dbf5e65b7c78833ab7cb9" nil "@U*($") `(,+gcry-cipher-gost-28147+ "55d505738ccf30684e02e9caf33424af") `(,+gcry-cipher-rfc-2268-128+ "fc762181eb3b5eb9f85b55e7b1b0a9f1") `(,+gcry-cipher-rfc-2268-40+ "b82a3e849d9ae1f5a437b0596821a8be") `(,+gcry-cipher-seed+ "75e5ace689f753ed07159605e67bf9e4") `(,+gcry-cipher-serpent-128+ "105720771533c7ee80b25edc398b7fe3") `(,+gcry-cipher-serpent-192+ "d6024543d455e2319473b178a5a98e2c") `(,+gcry-cipher-serpent-256+ "ac1ce037b887e52281c296ab1294163c") `(,+gcry-cipher-twofish+ "bdcff0fdfc623312aee34219b92644e0") `(,+gcry-cipher-twofish-128+ "eca077fd6ab6d03713f3fed003c8248b")) do (let ((string (or string "cl-gcrypt")) (secret-key (or secret-key "secret-key")) (cipher-mode (or cipher-mode +gcry-cipher-mode-ecb+))) (test-one-algo cipher expected string secret-key cipher-mode)))) (test name-id-reversable (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((algo +gcry-cipher-blowfish+) (non-existent-algo 999999) (name-from-algo (gcry-cipher-algo-name algo)) (name-from-non-existent-algo (gcry-cipher-algo-name non-existent-algo))) (is (string= name-from-algo "BLOWFISH")) (is (= algo (gcry-cipher-map-name name-from-algo))) (is (string= name-from-non-existent-algo "?")) (is (= 0 (gcry-cipher-map-name name-from-non-existent-algo))))) (test oid (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (is (= (gcry-cipher-mode-from-oid "1.2.840.113549.3.7") +gcry-cipher-mode-cbc+))) (test algo-available (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (is (= (gcry-cipher-test-algo +gcry-cipher-blowfish+) 0)) (is (not (= (gcry-cipher-test-algo 1231231) 0)))) (test initialization-vector-reset (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((algo +gcry-cipher-aes+) (cipher-mode +gcry-cipher-mode-cfb+) (string "cl-gcrypt") (secret-key "secret-key") (block-length (gcry-cipher-get-algo-blklen algo)) (key-length (gcry-cipher-get-algo-keylen algo)) (flags 0) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (foreign-secret-key (convert-to-foreign secret-key :string)) (foreign-secret-key-length (foreign-funcall "strlen" :string foreign-secret-key :int)) (iv "initvect") (foreign-iv (convert-to-foreign iv :string)) (foreign-iv-length (foreign-funcall "strlen" :string foreign-iv :int))) (multiple-value-bind (padded-key-length padded-key) (pad-right-with-zeros foreign-secret-key foreign-secret-key-length key-length) (with-foreign-object (pointer :pointer) (gcry-cipher-open pointer algo cipher-mode flags) (let ((handle (mem-aref pointer 'gcry-cipher-hd-t))) (gcry-cipher-setkey handle padded-key padded-key-length) (multiple-value-bind (padded-string-length padded-string) (pad-right-with-zeros foreign-string foreign-string-length block-length) (let ((encrypted-buffer (foreign-alloc :char :initial-element 0 :count padded-string-length)) (decrypted-buffer (foreign-alloc :char :initial-element 0 :count padded-string-length))) (gcry-cipher-setiv handle foreign-iv foreign-iv-length) (gcry-cipher-encrypt handle encrypted-buffer padded-string-length padded-string padded-string-length) (gcry-cipher-setiv handle foreign-iv foreign-iv-length) (gcry-cipher-decrypt handle decrypted-buffer padded-string-length encrypted-buffer padded-string-length) (is (string= (foreign-buffer-to-string encrypted-buffer padded-string-length) "0db324cf28f28e00d75ff28b073cc6c2")) (is (string= (foreign-buffer-to-string decrypted-buffer foreign-string-length) (foreign-buffer-to-string foreign-string foreign-string-length))) (gcry-cipher-setiv handle foreign-iv foreign-iv-length) (gcry-cipher-reset handle) (gcry-cipher-encrypt handle encrypted-buffer padded-string-length padded-string padded-string-length) (gcry-cipher-setiv handle foreign-iv foreign-iv-length) (gcry-cipher-reset handle) (gcry-cipher-decrypt handle decrypted-buffer padded-string-length encrypted-buffer padded-string-length) (is (string= (foreign-buffer-to-string encrypted-buffer padded-string-length) "bd6f9922a73efb851b3fc835ec05a9bf")) (is (string= (foreign-buffer-to-string decrypted-buffer foreign-string-length) (foreign-buffer-to-string foreign-string foreign-string-length))) (foreign-free encrypted-buffer) (foreign-free decrypted-buffer)) (foreign-free padded-string)) (gcry-cipher-close handle))) (foreign-free padded-key)) (foreign-free foreign-string) (foreign-free foreign-secret-key) (foreign-free foreign-iv))) (test get-tag (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((algo +gcry-cipher-chacha-20+) (cipher-mode +gcry-cipher-mode-poly-1305+) (string "cl-gcrypt") (secret-key "secret-key") (block-length (gcry-cipher-get-algo-blklen algo)) (key-length (gcry-cipher-get-algo-keylen algo)) (flags 0) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (foreign-secret-key (convert-to-foreign secret-key :string)) (foreign-secret-key-length (foreign-funcall "strlen" :string foreign-secret-key :int)) (tag "3d8cce949681bd185b3d35f8950930f5")) (multiple-value-bind (padded-key-length padded-key) (pad-right-with-zeros foreign-secret-key foreign-secret-key-length key-length) (multiple-value-bind (padded-string-length padded-string) (pad-right-with-zeros foreign-string foreign-string-length block-length) (with-foreign-object (pointer :pointer) (gcry-cipher-open pointer algo cipher-mode flags) (let ((handle (mem-aref pointer 'gcry-cipher-hd-t))) (gcry-cipher-setkey handle padded-key padded-key-length) (let ((encrypted-buffer (foreign-alloc :char :initial-element 0 :count padded-string-length)) (decrypted-buffer (foreign-alloc :char :initial-element 0 :count padded-string-length))) (gcry-cipher-encrypt handle encrypted-buffer padded-string-length padded-string padded-string-length) (let* ((tag-length 16) (tag-buffer (foreign-alloc :uint8 :initial-element 0 :count tag-length))) (multiple-value-bind (foreign-tag foreign-tag-length) (string-to-foreign-buffer tag) (gcry-cipher-gettag handle tag-buffer tag-length) (is (string= (foreign-buffer-to-string tag-buffer tag-length) tag)) (is (= (gcry-cipher-checktag handle foreign-tag foreign-tag-length) 0)) (foreign-free foreign-tag))) (foreign-free encrypted-buffer) (foreign-free decrypted-buffer)) (gcry-cipher-close handle))) (foreign-free padded-string)) (foreign-free padded-key)) (foreign-free foreign-string) (foreign-free foreign-secret-key))) (test authenticate (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((algo +gcry-cipher-chacha-20+) (cipher-mode +gcry-cipher-mode-poly-1305+) (string "cl-gcrypt") (secret-key "secret-key") (block-length (gcry-cipher-get-algo-blklen algo)) (key-length (gcry-cipher-get-algo-keylen algo)) (flags 0) (foreign-string (convert-to-foreign string :string)) (foreign-string-length (foreign-funcall "strlen" :string foreign-string :int)) (foreign-secret-key (convert-to-foreign secret-key :string)) (foreign-secret-key-length (foreign-funcall "strlen" :string foreign-secret-key :int)) (tag "fbb7f3393f47eec221040f1510665732") (additional-info "cl-gcrypt-additional-mesage") (foreign-additional-info (convert-to-foreign additional-info :string)) (foreign-additional-info-length (foreign-funcall "strlen" :string foreign-additional-info :int))) (multiple-value-bind (padded-key-length padded-key) (pad-right-with-zeros foreign-secret-key foreign-secret-key-length key-length) (multiple-value-bind (padded-string-length padded-string) (pad-right-with-zeros foreign-string foreign-string-length block-length) (with-foreign-object (pointer :pointer) (gcry-cipher-open pointer algo cipher-mode flags) (let ((handle (mem-aref pointer 'gcry-cipher-hd-t))) (gcry-cipher-setkey handle padded-key padded-key-length) (let ((encrypted-buffer (foreign-alloc :char :initial-element 0 :count padded-string-length)) (decrypted-buffer (foreign-alloc :char :initial-element 0 :count padded-string-length))) (gcry-cipher-authenticate handle foreign-additional-info foreign-additional-info-length) (gcry-cipher-encrypt handle encrypted-buffer padded-string-length padded-string padded-string-length) (let* ((foreign-tag-size (foreign-alloc :size)) (tag-length-definition (gcry-cipher-info handle +gcryctl-get-taglen+ (null-pointer) foreign-tag-size)) (tag-length (mem-aref foreign-tag-size :size)) (tag-buffer (foreign-alloc :uint8 :initial-element 0 :count tag-length))) (declare (ignore tag-length-definition)) (foreign-free foreign-tag-size) (multiple-value-bind (foreign-tag foreign-tag-length) (string-to-foreign-buffer tag) (gcry-cipher-gettag handle tag-buffer tag-length) (is (string= (foreign-buffer-to-string tag-buffer tag-length) tag)) (is (= (gcry-cipher-checktag handle foreign-tag foreign-tag-length) 0)) (gcry-cipher-reset handle) (gcry-cipher-authenticate handle foreign-additional-info foreign-additional-info-length) (gcry-cipher-decrypt handle decrypted-buffer padded-string-length encrypted-buffer padded-string-length) (is (= (gcry-cipher-checktag handle foreign-tag foreign-tag-length) 0)) (foreign-free foreign-tag))) (foreign-free encrypted-buffer) (foreign-free decrypted-buffer)) (gcry-cipher-close handle))) (foreign-free padded-string)) (foreign-free padded-key)) (foreign-free foreign-string) (foreign-free foreign-secret-key) (foreign-free foreign-additional-info)))
16,899
Common Lisp
.lisp
461
30.62256
73
0.687324
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
ef19716a55f94e25aae3e0369574c33436bd1f03da55c303c96498e6c257a28d
24,244
[ -1 ]
24,245
sexp-test.lisp
gorozhin_cl-gcrypt/t/sexp-test.lisp
(in-package #:cl-gcrypt-test) (def-suite cl-gcrypt-sexp-suite :description "Symbolic expression tests") (in-suite cl-gcrypt-sexp-suite) (let ((was-executed nil)) (cffi:defcallback simple-free :void ((data :pointer)) (setf was-executed t) (cffi:foreign-free data)) (defun callback-executed-p () (prog1 was-executed (setf was-executed nil)))) (test create-with-new (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (b (c) ) ) ") (foreign-buffer (convert-to-foreign buffer :string)) (foreign-buffer-length (foreign-funcall "strlen" :string foreign-buffer :int)) (mode +gcrysexp-fmt-advanced+)) (with-foreign-object (sexp-pointer :pointer) (gcry-sexp-new sexp-pointer foreign-buffer foreign-buffer-length 0) (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (sprintf-buffer-length (gcry-sexp-sprint sexp mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint sexp mode sprintf-buffer sprintf-buffer-length) (is (string= buffer (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp))) (foreign-free foreign-buffer))) (test create-with-callback (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (b (c) ) ) ") (foreign-buffer (convert-to-foreign buffer :string)) (foreign-buffer-length (foreign-funcall "strlen" :string foreign-buffer :int)) (mode +gcrysexp-fmt-advanced+)) (with-foreign-object (sexp-pointer :pointer) (gcry-sexp-create sexp-pointer foreign-buffer foreign-buffer-length 0 (cffi:callback simple-free)) (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (sprintf-buffer-length (gcry-sexp-sprint sexp mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint sexp mode sprintf-buffer sprintf-buffer-length) (is (string= buffer (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp))) (foreign-free foreign-buffer)) (is (callback-executed-p))) (test create-with-sscan (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (b c) ) ") (foreign-buffer (convert-to-foreign buffer :string)) (foreign-buffer-length (foreign-funcall "strlen" :string foreign-buffer :int)) (mode +gcrysexp-fmt-advanced+) (error-position (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-sscan sexp-pointer error-position foreign-buffer foreign-buffer-length) (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (sprintf-buffer-length (gcry-sexp-sprint sexp mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint sexp mode sprintf-buffer sprintf-buffer-length) (is (string= buffer (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp))) (foreign-free foreign-buffer) (foreign-free error-position))) (test create-with-build (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (%s %s c) ) ") (expected-string "(a (asdf qwer c) ) ") (foreign-buffer (convert-to-foreign buffer :string)) (mode +gcrysexp-fmt-advanced+) (error-position (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "qwer") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (sprintf-buffer-length (gcry-sexp-sprint sexp mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint sexp mode sprintf-buffer sprintf-buffer-length) (is (string= expected-string (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp))) (foreign-free foreign-buffer) (foreign-free error-position))) (test create-with-build-array (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (%s %s c) ) ") (expected-string "(a (asdf qwer c) ) ") (foreign-buffer (convert-to-foreign buffer :string)) (mode +gcrysexp-fmt-advanced+) (error-position (cffi:foreign-alloc :uint)) (array-parameters (cffi:foreign-alloc :pointer :count 2)) (foreign-string-1 (convert-to-foreign "asdf" :string)) (foreign-string-2 (convert-to-foreign "qwer" :string))) (with-foreign-objects ((sexp-pointer :pointer) (string-1 :pointer) (string-2 :pointer)) (setf (mem-aref string-1 :pointer) foreign-string-1) (setf (mem-aref string-2 :pointer) foreign-string-2) (setf (mem-aref array-parameters :pointer 0) string-1) (setf (mem-aref array-parameters :pointer 1) string-2) (gcry-sexp-build-array sexp-pointer error-position foreign-buffer array-parameters) (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (sprintf-buffer-length (gcry-sexp-sprint sexp mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint sexp mode sprintf-buffer sprintf-buffer-length) (is (string= expected-string (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp))) (foreign-free foreign-buffer) (foreign-free error-position) (foreign-free foreign-string-1) (foreign-free foreign-string-2) (foreign-free array-parameters))) (test create-canon-len (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(4:qwer(4:asdf))") (foreign-buffer (convert-to-foreign buffer :string)) (foreign-buffer-length (foreign-funcall "strlen" :string foreign-buffer :int)) (error-position (cffi:foreign-alloc :uint)) (gcry-error (cffi:foreign-alloc 'gcry-error-t))) (is (= foreign-buffer-length (gcry-sexp-canon-len foreign-buffer foreign-buffer-length error-position gcry-error))) (foreign-free foreign-buffer) (foreign-free error-position))) (test find-token (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (%s %s c) ) ") (expected-string "(asdf qwer c) ") (token "asdf") (token-buffer (convert-to-foreign token :string)) (token-buffer-length (foreign-funcall "strlen" :string token-buffer :int)) (foreign-buffer (convert-to-foreign buffer :string)) (mode +gcrysexp-fmt-advanced+) (error-position (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string token :string "qwer") (let* ( (sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (token-list (gcry-sexp-find-token sexp token-buffer token-buffer-length)) (sprintf-buffer-length (gcry-sexp-sprint token-list mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint token-list mode sprintf-buffer sprintf-buffer-length) (is (string= expected-string (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp))) (foreign-free foreign-buffer) (foreign-free error-position))) (test length (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (%s %s c) (%s %s))") (foreign-buffer (convert-to-foreign buffer :string)) (error-position (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "qwer" :string "1234" :string "4321") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (length (gcry-sexp-length sexp))) (is (= length 3)) (gcry-sexp-release sexp))) (foreign-free foreign-buffer) (foreign-free error-position))) (test nth (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (%s %s c) (%s %s))") (expected-string "(asdf qwer c) ") (foreign-buffer (convert-to-foreign buffer :string)) (mode +gcrysexp-fmt-advanced+) (error-position (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "qwer" :string "1234" :string "4321") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (nth (gcry-sexp-nth sexp 1)) (sprintf-buffer-length (gcry-sexp-sprint nth mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint nth mode sprintf-buffer sprintf-buffer-length) (is (string= expected-string (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp) (gcry-sexp-release nth) (foreign-free sprintf-buffer))) (foreign-free foreign-buffer) (foreign-free error-position))) (test car (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (%s %s c) (%s %s))") (expected-string "(a) ") (foreign-buffer (convert-to-foreign buffer :string)) (mode +gcrysexp-fmt-advanced+) (error-position (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "qwer" :string "1234" :string "4321") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (car (gcry-sexp-car sexp)) (sprintf-buffer-length (gcry-sexp-sprint car mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint car mode sprintf-buffer sprintf-buffer-length) (is (string= expected-string (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp) (gcry-sexp-release car) (foreign-free sprintf-buffer))) (foreign-free foreign-buffer) (foreign-free error-position))) (test car (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (%s %s c) (%s %s))") (expected-string "( (asdf qwer c) ) ") (foreign-buffer (convert-to-foreign buffer :string)) (mode +gcrysexp-fmt-advanced+) (error-position (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "qwer" :string "1234" :string "4321") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (cdr (gcry-sexp-cdr sexp)) (sprintf-buffer-length (gcry-sexp-sprint cdr mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint cdr mode sprintf-buffer sprintf-buffer-length) (is (string= expected-string (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp) (gcry-sexp-release cdr) (foreign-free sprintf-buffer))) (foreign-free foreign-buffer) (foreign-free error-position))) (test cadr (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a (%s %s c) (%s %s))") (expected-string "(asdf qwer c) ") (foreign-buffer (convert-to-foreign buffer :string)) (mode +gcrysexp-fmt-advanced+) (error-position (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "qwer" :string "1234" :string "4321") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (cadr (gcry-sexp-cadr sexp)) (sprintf-buffer-length (gcry-sexp-sprint cadr mode (null-pointer) 0)) (sprintf-buffer (foreign-alloc :uint8 :initial-element 0 :count sprintf-buffer-length))) (gcry-sexp-sprint cadr mode sprintf-buffer sprintf-buffer-length) (is (string= expected-string (convert-from-foreign sprintf-buffer :string))) (gcry-sexp-release sexp) (gcry-sexp-release cadr) (foreign-free sprintf-buffer))) (foreign-free foreign-buffer) (foreign-free error-position))) (test nth-data (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a %s %s c %s %s)") (expected-string "qwer") (foreign-buffer (convert-to-foreign buffer :string)) (error-position (cffi:foreign-alloc :uint)) (data-length (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "qwer" :string "1234" :string "4321") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (nth-data (gcry-sexp-nth-data sexp 2 data-length))) (is (string= expected-string (cffi:foreign-string-to-lisp nth-data :count (mem-aref data-length :uint)))) (gcry-sexp-release sexp))) (foreign-free foreign-buffer) (foreign-free error-position) (foreign-free data-length))) (test nth-buffer (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((buffer "(a %s %s c %s %s)") (expected-string "qwer") (foreign-buffer (convert-to-foreign buffer :string)) (error-position (cffi:foreign-alloc :uint)) (data-length (cffi:foreign-alloc :uint))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "qwer" :string "1234" :string "4321") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (nth-data (gcry-sexp-nth-buffer sexp 2 data-length))) (is (string= expected-string (cffi:foreign-string-to-lisp nth-data :count (mem-aref data-length :uint)))) (gcry-sexp-release sexp))) (foreign-free foreign-buffer) (foreign-free error-position) (foreign-free data-length))) (test nth-mpi (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((mpi-hex-representation "12de0a") (buffer (format nil "(a %s #~a# c %s %s)" mpi-hex-representation)) (foreign-buffer (convert-to-foreign buffer :string)) (error-position (cffi:foreign-alloc :uint)) (written (cffi:foreign-alloc :uint)) (mpi-buffer-length 1000) (mpi-buffer (cffi:foreign-alloc :uint :count mpi-buffer-length))) (with-foreign-objects ((sexp-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer :string "asdf" :string "1234" :string "4321") (let* ((sexp (mem-aref sexp-pointer 'gcry-sexp-t)) (nth-data (gcry-sexp-nth-mpi sexp 2 1))) (gcry-mpi-print +gcrympi-fmt-std+ mpi-buffer mpi-buffer-length written nth-data) (is (string= (foreign-buffer-to-string mpi-buffer (mem-aref written :uint)) mpi-hex-representation)) (gcry-sexp-release sexp))) (foreign-free foreign-buffer) (foreign-free error-position) (foreign-free written) (foreign-free mpi-buffer))) (test nth-extract (unless (gcry-check-version "1.8.0") (error "Unsupported gcrypt version")) (gcry-control +gcryctl-initialization-finished+ :int 0) (let* ((mpi-1-hex-representation "12de0a") (mpi-2-hex-representation "00cafebabe") (mpi-3-hex-representation "18") (buffer (format nil "(a (long (path (to (a #~a#) (b #~a#) (c #~a#)))))" mpi-1-hex-representation mpi-2-hex-representation mpi-3-hex-representation)) (foreign-buffer (convert-to-foreign buffer :string)) (error-position (cffi:foreign-alloc :uint)) (written (cffi:foreign-alloc :uint)) (path "a!long!path!to") (param-list "abc") (mpi-buffer-length 1000) (mpi-buffer (cffi:foreign-alloc :uint :count mpi-buffer-length))) (with-foreign-objects ((sexp-pointer :pointer) (mpi-1-pointer :pointer) (mpi-2-pointer :pointer) (mpi-3-pointer :pointer)) (gcry-sexp-build sexp-pointer error-position foreign-buffer) (let ((sexp (mem-aref sexp-pointer 'gcry-sexp-t))) (gcry-sexp-extract-param sexp path param-list mpi-1-pointer mpi-2-pointer mpi-3-pointer) (let* ((mpi-1 (mem-aref mpi-1-pointer 'gcry-sexp-t)) (mpi-2 (mem-aref mpi-2-pointer 'gcry-sexp-t)) (mpi-3 (mem-aref mpi-3-pointer 'gcry-sexp-t))) (gcry-mpi-print +gcrympi-fmt-std+ mpi-buffer mpi-buffer-length written mpi-1) (is (string= (foreign-buffer-to-string mpi-buffer (mem-aref written :uint)) mpi-1-hex-representation)) (gcry-mpi-print +gcrympi-fmt-std+ mpi-buffer mpi-buffer-length written mpi-2) (is (string= (foreign-buffer-to-string mpi-buffer (mem-aref written :uint)) mpi-2-hex-representation)) (gcry-mpi-print +gcrympi-fmt-std+ mpi-buffer mpi-buffer-length written mpi-3) (is (string= (foreign-buffer-to-string mpi-buffer (mem-aref written :uint)) mpi-3-hex-representation)) (gcry-mpi-release mpi-1) (gcry-mpi-release mpi-2) (gcry-mpi-release mpi-3)))) (foreign-free foreign-buffer) (foreign-free error-position) (foreign-free written) (foreign-free mpi-buffer)))
19,742
Common Lisp
.lisp
657
24.313546
79
0.644092
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1309155e99b57c420947dba9667bf2a473979289738408b7e1472f705a61e700
24,245
[ -1 ]
24,246
cl-gcrypt.asd
gorozhin_cl-gcrypt/cl-gcrypt.asd
(in-package #:cl-user) (defpackage cl-gcrypt-asd (:use #:cl #:asdf)) (in-package #:cl-gcrypt-asd) (defsystem cl-gcrypt :version "0.0.1" :author "Mikhail Gorozhin <m.gorozhin at gmail.com>" :license "LGPLv2.1" :depends-on (#:cffi) :components ((:module "src" :components ((:file "md-binding" :depends-on ("cl-gcrypt" "helper")) (:file "md-export" :depends-on ("md-binding" "helper")) (:file "cipher-binding" :depends-on ("cl-gcrypt" "helper")) (:file "cipher-export" :depends-on ("cipher-binding" "helper")) (:file "mpi-binding" :depends-on ("cl-gcrypt" "helper")) (:file "mpi-export" :depends-on ("mpi-binding" "helper")) (:file "sexp-binding" :depends-on ("mpi-binding" "cl-gcrypt" "helper")) (:file "sexp-export" :depends-on ("sexp-binding" "helper")) (:file "pk-binding" :depends-on ("sexp-binding" "cl-gcrypt" "helper")) (:file "pk-export" :depends-on ("pk-binding" "helper")) (:file "cl-gcrypt" :depends-on ("helper")) (:file "helper")))) :description "Common Lisp bindings for libgcrypt")
1,081
Common Lisp
.asd
27
35.851852
66
0.634378
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
53f6202c9430db7f1a7e87ee2f6072001df840d612eedb869ae06603347b6e60
24,246
[ -1 ]
24,247
cl-gcrypt-test.asd
gorozhin_cl-gcrypt/cl-gcrypt-test.asd
(in-package #:cl-user) (uiop:define-package #:cl-gcrypt-test-asd (:use #:cl #:asdf #:uiop)) (in-package #:cl-gcrypt-test-asd) (defun run-tests () (let ((suites (list (intern* 'cl-gcrypt-cipher-suite '#:cl-gcrypt-test) (intern* 'cl-gcrypt-md-suite '#:cl-gcrypt-test) (intern* 'cl-gcrypt-sexp-suite '#:cl-gcrypt-test) (intern* 'cl-gcrypt-pk-suite '#:cl-gcrypt-test)))) (when (not (reduce #'(lambda (x y) (and x y)) (loop for suite in suites collecting (symbol-call :fiveam '#:run! suite)) :initial-value t)) (and (uiop:getenvp "CL_GCRYPT_EXIT_ON_FAIL") (uiop:quit 123))))) (defsystem cl-gcrypt-test :version "0.0.1" :author "Mikhail Gorozhin <m.gorozhin at gmail.com>" :license "LGPLv2.1" :depends-on (#:cl-gcrypt #:cffi #:fiveam #:alexandria #:babel) :description "Common Lisp bindings for libgcrypt test suite" :components((:module "t" :components ((:file "cl-gcrypt-test") (:file "md" :depends-on ("cl-gcrypt-test")) (:file "cipher-test" :depends-on ("cl-gcrypt-test")) (:file "sexp-test" :depends-on ("cl-gcrypt-test")) (:file "pk-test" :depends-on ("cl-gcrypt-test"))))) :perform (test-op (o c) (run-tests)))
1,210
Common Lisp
.asd
33
32.69697
64
0.642491
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
51bd0323dc2dec413d430cdead46cda6c498706ca1edb2ea635c302e9b5933ed
24,247
[ -1 ]
24,268
tests.yml
gorozhin_cl-gcrypt/.github/workflows/tests.yml
name: Tests on: push: branches: pull_request: branches: jobs: test: name: ${{ matrix.lisp }} on ${{ matrix.os }} strategy: matrix: lisp: [sbcl-bin, ccl] os: [ ubuntu-latest, macos-latest ] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - name: Cache .roswell id: cache-dot-roswell uses: actions/cache@v1 with: path: ~/.roswell key: ${{ runner.os }}-dot-roswell-${{ matrix.lisp }}-${{ hashFiles('**/*.asd') }} restore-keys: | ${{ runner.os }}-dot-roswell-${{ matrix.lisp }}- ${{ runner.os }}-dot-roswell- - name: install roswell shell: bash env: LISP: ${{ matrix.lisp }} run: curl -L https://raw.githubusercontent.com/roswell/roswell/master/scripts/install-for-ci.sh | sh - name: run lisp continue-on-error: false shell: bash run: | ros -e '(format t "~a:~a on ~a~%...~%~%" (lisp-implementation-type) (lisp-implementation-version) (machine-type))' ros -e '(format t " fixnum bits:~a~%" (integer-length most-positive-fixnum))' ros -e "(ql:quickload 'trivial-features)" -e '(format t "features = ~s~%" *features*)' - name: Install dependencies ubuntu if: matrix.os == 'ubuntu-latest' shell: bash run: | sudo apt-get update -qq sudo apt-get install -y libgcrypt20 - name: Install dependencies macos if: matrix.os == 'macos-latest' shell: bash run: | brew install libgcrypt - name: load code and run tests shell: bash env: CL_GCRYPT_EXIT_ON_FAIL: true run: | ros -e '(handler-bind (#+asdf3.2(asdf:bad-SYSTEM-NAME (function MUFFLE-WARNING))) (handler-case (ql:quickload :cl-gcrypt-test) (error (a) (format t "caught error ~s~%~a~%" a a) (uiop:quit 123))))' -e '(asdf:test-system "cl-gcrypt-test")'
1,997
Common Lisp
.l
54
28.740741
247
0.564116
gorozhin/cl-gcrypt
1
0
0
LGPL-2.1
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
93a372a17affb3e38b510a12d75d3427b8c7df27a3610fa8da55b1e96de2726e
24,268
[ -1 ]
24,283
documentation-EN.lisp
JMC-design_turtle-graphics/documentation-EN.lisp
(in-package :turtle) #-life (defun document (doc-strings) (dolist (doc-string doc-strings) (destructuring-bind (fn . doc) doc-string (setf (documentation (find-symbol (symbol-name fn)) 'function) doc)))) (document '((forward . "Move forward UNITS amount. Draws line if TURTLE-DRAWP is T.") (back . "Move backwards UNITS amount. Draws line if TURTLE-DRAWP is T.") (right . "Turns to the right by DEGREES.") (left . "Turns to the left by DEGREES.") (repeat . "Exposes REPEAT-COUNTER to the contents of the macro.") (center . "Resets turtles starting location and heading, leaving surface intact.") (move-to . "Moves turtle to given location without drawing or changing heading.") (heading . "Returns the turtles heading in degrees.") (location . "Returns the absolute coordinates of turtles location.") (clear . "Clears the surface to background colour. Does not change location or heading.") (reset . "Clears surface, recenters turtle and zeros heading.") (pen-up . "Removes pen from the surface no further drawing takes place until PEN-DOWN.") (pen-down . "Sets pen to surface so further commands will draw.") (pen-colour . "Sets pen to the given colour, premultiplying alpha for xrender.") (pen-width . "Sets pen to WIDTH which accepts pixel fractions.") (repeat . "TIMES may be an integer or :FOREVER.") (to . "Defines a new turtle procedure. VARS is a regular lambda list.") (save . "Saves the surface to NAME.")))
1,485
Common Lisp
.lisp
25
55.76
92
0.714678
JMC-design/turtle-graphics
1
0
0
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
50d53179525418e42c1567aea3b6c768ea4710868a57e119ec1219eba0db5164
24,283
[ -1 ]
24,284
turtle.lisp
JMC-design_turtle-graphics/turtle.lisp
(defpackage :turtle-graphics (:use :cl) (:nicknames :turtle)) (in-package :turtle) (defconstant +half-pi+ (/ pi 2)) (defconstant +2pi+ (* pi 2)) (defparameter *composite-p* t "When True composites lines onto final drawing.") (defparameter *always-flush* nil "When False only flushes the clx display buffer in TO functions.") (defparameter *stroke-width* 1.0) (defparameter *turtle* nil) (defparameter *surface* nil) (defparameter *cursor* (make-array 117 :element-type '(unsigned-byte 8) :initial-contents '(00 00 00 00 #xFF 00 00 00 00 00 00 00 00 #xFF 00 00 00 00 00 00 00 #xAF #xFF #xAF 00 00 00 00 00 00 #xFF 00 #xFF 00 00 00 00 00 00 #xFF 00 #xFF 00 00 00 00 00 #xAF #xFF 00 #xFF #xAF 00 00 00 00 #xFF 00 00 00 #xFF 00 00 00 00 #xFF 00 00 00 #xFF 00 00 00 #xAF #xFF 00 #xFF 00 #xFF #xAF 00 00 #xFF 00 00 00 00 00 #xFF 00 00 #xFF 00 00 00 00 00 #xFF 00 #xAF #xFF 00 00 #xAF 00 00 #xFF #xAF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF))) (defun init (&optional (width 600) (height 600) (colour #(#xFFFF #xFFFF #xFFFF #xFFFF))) (unless xwindows:*display* (xwindows::init-default-display)) ;FIXME i'm a hack. (setf *surface* (surface:get-surface :width width :height height :depth 32 :override :off) *turtle* (make-turtle :location (cons (floor width 2) (floor height 2)) :angle 0 :pen (make-pen colour) :drawp t)) (surface:prepare-surface *surface*) (surface:map-surface *surface*)) (defun stop () (surface:destroy-surface *surface*) (xlib:render-free-picture (turtle-pen *turtle*)) (setf *turtle* nil *surface* nil)) (defmacro with-turtle (turtle &rest body) `(with-slots (location angle pen drawp representation) ,turtle ,@body)) (defstruct turtle location angle pen drawp representation) ;;;; Utils (declaim (inline calc-destination deg->rad rad->deg)) (defun calc-destination (location angle units) (declare (optimize speed)) (let ((rads (deg->rad angle))) (destructuring-bind (x . y) location (cons (the double-float (+ x (* units (sin rads)))) (the double-float (+ y (* units (cos rads)))))))) (defun deg->rad (degrees) (* pi (/ degrees 180.0))) (defun rad->deg (rads) (* (/ rads 2 pi) 360)) ;;;; The workhorse, no butts. (defun draw-line (surface pen x1 y1 x2 y2 &optional (thickness *stroke-width*)) (declare (optimize speed) (type (or integer double-float) thickness x1 x2 y1 y2)) (let ((delta (/ thickness 2)) (angle (- (turtle-angle *turtle*) 90)) p1x p1y p2x p2y p3x p3y p4x p4y) (cond ;;Vertical line ((= x1 x2) (setf p1x (- x1 delta) p1y y1 p2x (+ x1 delta) p2y y1 p3x (- x2 delta) p3y y2 p4x (+ x2 delta) p4y y2)) ;;Horizontal line ((= y1 y2)(setf p1x x1 p1y (- y1 delta) p2x x1 p2y (+ y1 delta) p3x x2 p3y (- y2 delta) p4x x2 p4y (+ y2 delta))) (t (let ((p1 (calc-destination (cons x1 y1) angle delta)) (p2 (calc-destination (cons x1 y1) angle (- delta))) (p3 (calc-destination (cons x2 y2) angle delta)) (p4 (calc-destination (cons x2 y2) angle (- delta)))) (setf p1x (car p1) p1y (cdr p1) p2x (car p2) p2y (cdr p2) p3x (car p3) p3y (cdr p3) p4x (car p4) p4y (cdr p4))))) (xlib:render-triangle-strip (xlib:render-create-picture surface) :over pen 0 0 :none (mapcar (lambda (x) (coerce (realpart x) 'double-float)) (list p1x p1y p2x p2y p3x p3y p4x p4y)))) (when *always-flush* (surface:update *surface*))) ;;;; Basic Relative Turtle commands (defun forward (units) (with-turtle *turtle* (let ((destination (calc-destination location angle units))) (when drawp (draw-line *surface* pen (car location) (cdr location) (car destination) (cdr destination))) (setf location destination)))) (defun back (units) (forward (- units))) (defun right (degrees) (with-turtle *turtle* (setf angle (mod (- angle degrees) 360)))) (defun left (degrees) (right (- degrees))) ;;;; Pen Basics (defun pen-up () (setf (turtle-drawp *turtle*) nil)) (defun pen-down () (setf (turtle-drawp *turtle*) t)) (defun pen-colour (r g b a) (set-pen (turtle-pen *turtle*) (make-array 4 :initial-contents (mapcar (lambda (x) (* x a)) (list r g b a) )))) (defun pen-width (width) (setf *stroke-width* width)) ;;;; Absolute basics (defun center () (destructuring-bind (w . h) (surface:size *surface*) (setf (turtle-location *turtle*) (cons (floor w 2) (floor h 2)) (turtle-angle *turtle*) 0))) (defun move-to (x y) (setf (turtle-location *turtle*) (cons x y))) (defun location () (turtle-location *turtle*)) (defun heading () (turtle-angle *turtle*)) (defun clear () (xlib:clear-area *surface* ) (xlib:display-finish-output xwindows:*display*)) (defun reset () (center) (clear)) ;;;; Procedure macros (defmacro repeat (times &rest rest) (typecase times (keyword (case :forever `(loop :for repeat-counter :from 0 :do (progn ,@rest)))) (t `(dotimes (repeat-counter ,times) ,@rest)))) (defmacro to (name vars &rest body) `(defun ,name ,vars ,@body (unless *always-flush* (xlib:display-finish-output xwindows:*display*) ))) ;;;;RGBA Colour helpers (defun make-pen (colour) (let ((pic (xlib:render-create-picture (surface:get-surface :width 1 :height 1 :type :x-pixmap :depth 32) :format (xlib:find-window-picture-format *surface*) :repeat :on))) (xlib:render-fill-rectangle pic :over colour 0 0 1 1) pic)) (defun set-pen (pen colour) (xlib:render-fill-rectangle pen :src #(0 0 0 0) 0 0 1 1) (xlib:render-fill-rectangle pen :over colour 0 0 1 1)) (defun random-colour (&optional (min 128)) (colour (+ min (random (- 255 min))) (+ min (random (- 255 min))) (+ min (random (- 255 min))) 255)) (defun background-colour (r g b a) ()) #-LIFE (progn (defun swap-rb-flat (array) (let ((size (car (array-dimensions array)))) (loop :for r fixnum :from 0 :upto size :by 4 :for b fixnum :from 2 :upto size :by 4 :do (rotatef (aref array r) (aref array b))))) (defun save (filename) (let ((data (surface:get-data *surface*))) (swap-rb-flat data) (destructuring-bind (width . height) (surface:size *surface*) (zpng:write-png (make-instance 'zpng:png :color-type :truecolor-alpha :width width :height height :image-data data) filename)))) (defun load-documentation (system lang-code) "Loads the appropriate language documentation according to two char language code." (let* ((dir (asdf:system-source-directory system)) (file (probe-file (merge-pathnames (concatenate 'string "documentation-" (symbol-name lang-code) ".lisp") dir)))) (when file (load file))))) (load-documentation :turtle-graphics :en) ;;;; examples (defun ldragon (size level) (random-colour 20) (if (= level 0) (forward size) (progn (ldragon size (- level 1))(if (< size 1) 10 (random size)) (left 90) (rdragon size (- level 1))))) (defun rdragon (size level) (if (= level 0) (forward size) (progn (ldragon size (- level 1)) (right 90) (rdragon size (- level 1)))))
7,289
Common Lisp
.lisp
193
33.181347
187
0.63991
JMC-design/turtle-graphics
1
0
0
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
40863053fff78ad14bd8a405fb4760f51769087b6b85df38ca27e0a973a767d6
24,284
[ -1 ]
24,285
turtle-graphics.asd
JMC-design_turtle-graphics/turtle-graphics.asd
(in-package :asdf-user) (defsystem "turtle-graphics" :description "Turtle graphics for lisp supporting rgba32." :version "0.1" :author "Johannes Martinez Calzada" :licence "LGPL" :depends-on ("tag" "surface-x11") :components ((:file "turtle")))
257
Common Lisp
.asd
8
29.625
60
0.718876
JMC-design/turtle-graphics
1
0
0
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f490220fee5f99b80e8013054a88c31bc2286c5a2a74836ef72a0a796bc8e0c4
24,285
[ -1 ]
24,304
gmsk-transfer.lisp
glv2_cl-gmsk-transfer/gmsk-transfer.lisp
;;; This file is part of cl-gmsk-transfer ;;; Copyright 2021-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defpackage :gmsk-transfer (:use :cl) (:import-from :cffi #:callback #:defcallback #:defcfun #:define-foreign-library #:mem-aref #:null-pointer #:null-pointer-p #:use-foreign-library) (:import-from :cl-octet-streams #:with-octet-input-stream #:with-octet-output-stream) (:export #:free-transfer #:make-transfer #:start-transfer #:stop-all-transfers #:stop-transfer #:transmit-buffer #:transmit-file #:transmit-stream #:receive-buffer #:receive-callback #:receive-file #:receive-stream #:verbosity)) (in-package :gmsk-transfer) ;;; ;;; Bindings to libgmsk-transfer ;;; (define-foreign-library gmsk-transfer (:unix (:or "libgmsk-transfer.so" "libgmsk-transfer.so.1")) (t (:default "libgmsk-transfer"))) (use-foreign-library gmsk-transfer) (defcfun ("gmsk_transfer_set_verbose" gmsk-transfer-set-verbose) :void "Set the verbosity level." (v :unsigned-char)) (defcfun ("gmsk_transfer_is_verbose" gmsk-transfer-is-verbose) :unsigned-char "Get the verbosity level.") (defcfun ("gmsk_transfer_create" gmsk-transfer-create) :pointer "Initialize a new transfer." (radio-driver :string) (emit :unsigned-char) (file :string) (sample-rate :unsigned-long) (bit-rate :unsigned-int) (frequency :unsigned-long) (frequency-offset :long) (maximum-deviation :unsigned-int) (gain :string) (ppm :float) (bt :float) (inner-fec :string) (outer-fec :string) (id :string) (dump :string) (timeout :unsigned-int) (audio :unsigned-char)) (defcfun ("gmsk_transfer_create_callback" gmsk-transfer-create-callback) :pointer "Initialize a new transfer using a callback." (radio-driver :string) (emit :unsigned-char) (data-callback :pointer) (callback-context :pointer) (sample-rate :unsigned-long) (bit-rate :unsigned-int) (frequency :unsigned-long) (frequency-offset :long) (maximum-deviation :unsigned-int) (gain :string) (ppm :float) (bt :float) (inner-fec :string) (outer-fec :string) (id :string) (dump :string) (timeout :unsigned-int) (audio :unsigned-char)) (defcfun ("gmsk_transfer_free" gmsk-transfer-free) :void "Cleanup after a finished transfer." (transfer :pointer)) (defcfun ("gmsk_transfer_start" gmsk-transfer-start) :void "Start a transfer and return when finished." (transfer :pointer)) (defcfun ("gmsk_transfer_stop" gmsk-transfer-stop) :void "Interrupt a transfer." (transfer :pointer)) (defcfun ("gmsk_transfer_stop_all" gmsk-transfer-stop-all) :void "Interrupt a transfer.") (defcfun ("gmsk_transfer_print_available_radios" gmsk-transfer-print-available-radios) :void "Print list of detected software defined radios.") (defcfun ("gmsk_transfer_print_available_forward_error_codes" gmsk-transfer-print-available-forward-error-codes) :void "Print list of supported forward error codes.") ;;; ;;; Lisp API ;;; (defun verbosity () "Get the verbosity level." (gmsk-transfer-is-verbose)) (defun (setf verbosity) (value) "Set the verbosity level." (gmsk-transfer-set-verbose value) value) (defun make-transfer (&key (radio-driver "") emit file data-callback callback-context (sample-rate 2000000) (bit-rate 9600) (frequency 434000000) (frequency-offset 0) (gain 0) (maximum-deviation (ceiling bit-rate 100)) (ppm 0.0) (bt 0.5) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Initialize a transfer." (when (or (and file data-callback) (and (not file) (not data-callback))) (error "Either FILE or DATA-CALLBACK must be specified.")) (let ((transfer (if file (gmsk-transfer-create radio-driver (if emit 1 0) (namestring file) sample-rate bit-rate frequency frequency-offset maximum-deviation (if (stringp gain) gain (format nil "~d" gain)) ppm bt inner-fec outer-fec id (if dump (namestring dump) (null-pointer)) (or timeout 0) (if audio 1 0)) (gmsk-transfer-create-callback radio-driver (if emit 1 0) data-callback (or callback-context (null-pointer)) sample-rate bit-rate frequency frequency-offset maximum-deviation (if (stringp gain) gain (format nil "~d" gain)) ppm bt inner-fec outer-fec id (if dump (namestring dump) (null-pointer)) (or timeout 0) (if audio 1 0))))) (if (null-pointer-p transfer) (error "Failed to initialize transfer.") transfer))) (defun free-transfer (transfer) "Cleanup after a finished transfer." (gmsk-transfer-free transfer)) (defun start-transfer (transfer) "Start a transfer and return when finished." (float-features:with-float-traps-masked t (gmsk-transfer-start transfer))) (defun stop-transfer (transfer) "Interrupt a transfer." (gmsk-transfer-stop transfer)) (defun stop-all-transfers () "Interrupt all transfers." (gmsk-transfer-stop-all)) (defun transmit-file (file &key (radio-driver "") (sample-rate 2000000) (bit-rate 9600) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (bt 0.5) (inner-fec "h128") (outer-fec "none") (id "") dump audio (final-delay 0.0)) "Transmit the data from FILE." (let ((transfer (make-transfer :emit t :file file :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :bt bt :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :audio audio))) (unwind-protect (progn (start-transfer transfer) (unless (zerop final-delay) (sleep final-delay))) (free-transfer transfer)) t)) (defun receive-file (file &key (radio-driver "") (sample-rate 2000000) (bit-rate 9600) (frequency 434000000) (frequency-offset 0) (gain 0) (maximum-deviation (ceiling bit-rate 100)) (ppm 0.0) (bt 0.5) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Receive data into FILE." (let ((transfer (make-transfer :emit nil :file file :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :maximum-deviation maximum-deviation :gain gain :ppm ppm :bt bt :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :timeout timeout :audio audio))) (unwind-protect (start-transfer transfer) (free-transfer transfer)) t)) (defparameter *data-stream* nil) (defparameter *buffer* nil) (defcallback read-data-from-stream :int ((context :pointer) (payload :pointer) (payload-size :unsigned-int)) (declare (ignore context)) (handler-case (labels ((copy-data (total) (let* ((size (min (length *buffer*) (- payload-size total))) (n (read-sequence *buffer* *data-stream* :end size))) (cond ((zerop n) (if (zerop total) -1 total)) (t (dotimes (i n) (setf (mem-aref payload :unsigned-char (+ total i)) (aref *buffer* i))) (copy-data (+ total n))))))) (copy-data 0)) (error () -1))) (defcallback write-data-to-stream :int ((context :pointer) (payload :pointer) (payload-size :unsigned-int)) (declare (ignore context)) (handler-case (labels ((copy-data (total) (let ((size (min (length *buffer*) (- payload-size total)))) (cond ((zerop size) payload-size) (t (dotimes (i size) (setf (aref *buffer* i) (mem-aref payload :unsigned-char (+ total i)))) (write-sequence *buffer* *data-stream* :end size) (copy-data (+ total size))))))) (copy-data 0)) (error () -1))) (defun transmit-stream (stream &key (radio-driver "") (sample-rate 2000000) (bit-rate 9600) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (bt 0.5) (inner-fec "h128") (outer-fec "none") (id "") dump audio (final-delay 0.0)) "Transmit the data from STREAM." (let* ((*data-stream* stream) (*buffer* (make-array 1024 :element-type '(unsigned-byte 8))) (transfer (make-transfer :emit t :data-callback (callback read-data-from-stream) :callback-context (null-pointer) :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :bt bt :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :audio audio))) (unwind-protect (progn (start-transfer transfer) (unless (zerop final-delay) (sleep final-delay))) (free-transfer transfer)) t)) (defun receive-stream (stream &key (radio-driver "") (sample-rate 2000000) (bit-rate 9600) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (bt 0.5) (maximum-deviation (ceiling bit-rate 100)) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Receive data to STREAM." (let* ((*data-stream* stream) (*buffer* (make-array 1024 :element-type '(unsigned-byte 8))) (transfer (make-transfer :emit nil :data-callback (callback write-data-to-stream) :callback-context (null-pointer) :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :maximum-deviation maximum-deviation :gain gain :ppm ppm :bt bt :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :timeout timeout :audio audio))) (unwind-protect (start-transfer transfer) (free-transfer transfer)) t)) (defun transmit-buffer (buffer &key (start 0) end (radio-driver "") (sample-rate 2000000) (bit-rate 9600) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (bt 0.5) (inner-fec "h128") (outer-fec "none") (id "") dump audio (final-delay 0.0)) "Transmit the data between START and END in BUFFER." (with-octet-input-stream (stream buffer start (or end (length buffer))) (transmit-stream stream :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :bt bt :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :audio audio :final-delay final-delay))) (defun receive-buffer (&key (radio-driver "") (sample-rate 2000000) (bit-rate 9600) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (bt 0.5) (maximum-deviation (ceiling bit-rate 100)) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Receive data into a new octet vector and return it." (with-octet-output-stream (stream) (receive-stream stream :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :maximum-deviation maximum-deviation :gain gain :ppm ppm :bt bt :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :timeout timeout :audio audio))) (defparameter *user-function* nil) (defcallback call-user-function :int ((context :pointer) (payload :pointer) (payload-size :unsigned-int)) (declare (ignore context)) (handler-case (let ((data (make-array payload-size :element-type '(unsigned-byte 8)))) (dotimes (i payload-size) (setf (aref data i) (mem-aref payload :unsigned-char i))) (funcall *user-function* data) payload-size) (error () -1))) (defun receive-callback (function &key (radio-driver "") (sample-rate 2000000) (bit-rate 9600) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (bt 0.5) (maximum-deviation (ceiling bit-rate 100)) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Receive data and call a FUNCTION on it. The FUNCTION must take one octet vector as argument." (let* ((*user-function* function) (transfer (make-transfer :emit nil :data-callback (callback call-user-function) :callback-context (null-pointer) :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :maximum-deviation maximum-deviation :gain gain :ppm ppm :bt bt :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :timeout timeout :audio audio))) (unwind-protect (start-transfer transfer) (free-transfer transfer)) t))
19,319
Common Lisp
.lisp
441
24.76644
81
0.442439
glv2/cl-gmsk-transfer
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a3be6b124a803f60c934bfab5c38ed43d75e2de0515a4620f7eac3c4ce88a213
24,304
[ -1 ]
24,305
tests.lisp
glv2_cl-gmsk-transfer/tests.lisp
;;; This file is part of cl-gmsk-transfer ;;; Copyright 2021-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defpackage :gmsk-transfer-tests (:use :cl :fiveam :gmsk-transfer) (:import-from :uiop #:with-temporary-file)) (in-package :gmsk-transfer-tests) (def-suite gmsk-transfer-tests :description "Tests for gmsk-transfer.") (in-suite gmsk-transfer-tests) (defparameter *message* (asdf:system-relative-pathname "gmsk-transfer" "LICENSE")) (defun same-files-p (path-1 path-2) (with-open-file (file-1 path-1 :element-type '(unsigned-byte 8)) (with-open-file (file-2 path-2 :element-type '(unsigned-byte 8)) (let ((buffer-1 (make-array 1024 :element-type '(unsigned-byte 8))) (buffer-2 (make-array 1024 :element-type '(unsigned-byte 8)))) (labels ((same-p () (let ((i (read-sequence buffer-1 file-1)) (j (read-sequence buffer-2 file-2))) (cond ((not (= i j)) nil) ((zerop i) t) ((mismatch buffer-1 buffer-2 :end1 i :end2 i) nil) (t (same-p)))))) (same-p)))))) (test transmit-and-receive-file (with-temporary-file (:pathname samples) (with-temporary-file (:pathname decoded) (let ((radio (format nil "file=~a" (namestring samples)))) (transmit-file (namestring *message*) :radio-driver radio) (receive-file (namestring decoded) :radio-driver radio) (is (same-files-p *message* decoded)))))) (test transmit-and-receive-file-audio (with-temporary-file (:pathname samples) (with-temporary-file (:pathname decoded) (let ((radio (format nil "file=~a" (namestring samples)))) (transmit-file (namestring *message*) :radio-driver radio :audio t :sample-rate 48000 :frequency 1500 :bit-rate 2400) (receive-file (namestring decoded) :radio-driver radio :audio t :sample-rate 48000 :frequency 1500 :bit-rate 2400) (is (same-files-p *message* decoded)))))) (test transmit-and-receive-stream (with-temporary-file (:pathname samples) (with-temporary-file (:pathname decoded :stream decoded-stream :direction :output :element-type '(unsigned-byte 8)) (with-open-file (message-stream *message* :element-type '(unsigned-byte 8)) (let ((radio (format nil "file=~a" (namestring samples)))) (transmit-stream message-stream :radio-driver radio) (receive-stream decoded-stream :radio-driver radio))) :close-stream (is (same-files-p *message* decoded))))) (test transmit-and-receive-buffer (with-temporary-file (:pathname samples) (let ((data #(0 1 2 4 9 16 25 36 49 64 81 100 121 144 169 196 225)) (radio (format nil "file=~a" (namestring samples)))) (transmit-buffer data :radio-driver radio) (let ((decoded (receive-buffer :radio-driver radio))) (is (equalp data decoded)))))) (test receive-callback (with-temporary-file (:pathname samples) (let ((data #(0 1 2 4 9 16 25 36 49 64 81 100 121 144 169 196 225)) (radio (format nil "file=~a" (namestring samples))) (decoded nil)) (transmit-buffer data :radio-driver radio) (receive-callback (lambda (data) (setf decoded (concatenate 'vector decoded data))) :radio-driver radio) (is (equalp data decoded)))))
3,923
Common Lisp
.lisp
77
38.181818
78
0.569752
glv2/cl-gmsk-transfer
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a92d36426e72f6b6c2f7b59e2a9e0ec7743646bd1e5a0a76a2fe31c3d497734c
24,305
[ -1 ]
24,306
echo-server.lisp
glv2_cl-gmsk-transfer/examples/echo-server.lisp
;;; Example of use of cl-gmsk-transfer's API to make a server receiving ;;; messages from clients and sending them back in reverse order. ;;; ;;; Copyright 2021 Guillaume LE VAILLANT ;;; ;;; 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/>. (asdf:load-system "gmsk-transfer") (defpackage :echo-server (:use :cl) (:export #:client #:server)) (in-package :echo-server) (defparameter *radio-driver* "driver=hackrf") (defparameter *sample-rate* 4000000) (defparameter *transmission-gain* 30) (defparameter *reception-gain* 60) (defparameter *frequency-offset* 100000) (defparameter *bit-rate* 9600) (defparameter *bt* 0.5) (defparameter *inner-fec* "rs8") (defparameter *outer-fec* "rs8") (defun transmit (data frequency) (gmsk-transfer:transmit-buffer data :radio-driver *radio-driver* :sample-rate *sample-rate* :gain *transmission-gain* :frequency frequency :frequency-offset *frequency-offset* :bit-rate *bit-rate* :bt *bt* :inner-fec *inner-fec* :outer-fec *outer-fec* :final-delay 1)) (defun receive (callback frequency) (gmsk-transfer:receive-callback callback :radio-driver *radio-driver* :sample-rate *sample-rate* :gain *reception-gain* :frequency frequency :frequency-offset *frequency-offset* :bit-rate *bit-rate* :bt *bt* :inner-fec *inner-fec* :outer-fec *outer-fec*)) (defun receive-1 (frequency) (let* ((received nil) (callback (lambda (data) (setf received data) (gmsk-transfer:stop-all-transfers)))) (receive callback frequency) received)) (defun process-request (data) (reverse data)) (defun server (frequency) (unwind-protect (loop :do (let* ((data (receive-1 frequency)) (processed (process-request data))) (format t "~%Received: ~a~%" data) (sleep 1) (format t "Sending: ~a~%" processed) (transmit processed frequency))) (gmsk-transfer:stop-all-transfers))) (defun client (frequency data) (unwind-protect (progn (format t "~%Sending: ~a~%" data) (transmit data frequency) (let ((data (receive-1 frequency))) (format t "Received: ~a~%" data) data)) (gmsk-transfer:stop-all-transfers)))
3,478
Common Lisp
.lisp
83
30.409639
73
0.565269
glv2/cl-gmsk-transfer
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
66d9a42e9f736e997538404308c25184a742481ccd59e2dd5ed65e5623cf1815
24,306
[ -1 ]
24,307
gmsk-transfer.asd
glv2_cl-gmsk-transfer/gmsk-transfer.asd
;;; This file is part of cl-gmsk-transfer ;;; Copyright 2021-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defsystem "gmsk-transfer" :name "gmsk-transfer" :description "Send and receive data with SDRs using GMSK modulation" :version "1.6" :author "Guillaume LE VAILLANT" :license "GPL-3" :depends-on ("cffi" "cl-octet-streams" "float-features") :in-order-to ((test-op (test-op "gmsk-transfer/tests"))) :components ((:file "gmsk-transfer"))) (defsystem "gmsk-transfer/tests" :name "gmsk-transfer/tests" :description "Tests fot gmsk-transfer" :version "1.6" :author "Guillaume LE VAILLANT" :license "GPL-3" :depends-on ("fiveam" "gmsk-transfer" "uiop") :in-order-to ((test-op (load-op "gmsk-transfer/tests"))) :perform (test-op (o s) (let ((tests (uiop:find-symbol* 'gmsk-transfer-tests :gmsk-transfer-tests))) (uiop:symbol-call :fiveam 'run! tests))) :components ((:file "tests")))
1,079
Common Lisp
.asd
26
36.307692
70
0.663178
glv2/cl-gmsk-transfer
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
756de384b26a6aad71dcade5284f7a10abc4e2bcf4e50fc3a0bc9d7ab94eb8d9
24,307
[ -1 ]
24,326
ofdm-transfer.lisp
glv2_cl-ofdm-transfer/ofdm-transfer.lisp
;;; This file is part of cl-ofdm-transfer ;;; Copyright 2021-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defpackage :ofdm-transfer (:use :cl) (:import-from :cffi #:callback #:defcallback #:defcfun #:define-foreign-library #:mem-aref #:null-pointer #:null-pointer-p #:use-foreign-library) (:import-from :cl-octet-streams #:with-octet-input-stream #:with-octet-output-stream) (:export #:free-transfer #:make-transfer #:start-transfer #:stop-all-transfers #:stop-transfer #:transmit-buffer #:transmit-file #:transmit-stream #:receive-buffer #:receive-callback #:receive-file #:receive-stream #:verbosity)) (in-package :ofdm-transfer) ;;; ;;; Bindings to libofdm-transfer ;;; (define-foreign-library ofdm-transfer (:unix (:or "libofdm-transfer.so" "libofdm-transfer.so.1")) (t (:default "libofdm-transfer"))) (use-foreign-library ofdm-transfer) (defcfun ("ofdm_transfer_set_verbose" ofdm-transfer-set-verbose) :void "Set the verbosity level." (v :unsigned-char)) (defcfun ("ofdm_transfer_is_verbose" ofdm-transfer-is-verbose) :unsigned-char "Get the verbosity level.") (defcfun ("ofdm_transfer_create" ofdm-transfer-create) :pointer "Initialize a new transfer." (radio-driver :string) (emit :unsigned-char) (file :string) (sample-rate :unsigned-long) (bit-rate :unsigned-int) (frequency :unsigned-long) (frequency-offset :long) (gain :string) (ppm :float) (subcarrier-modulation :string) (subcarriers :unsigned-int) (cyclic-prefix-length :unsigned-int) (taper-length :unsigned-int) (inner-fec :string) (outer-fec :string) (id :string) (dump :string) (timeout :unsigned-int) (audio :unsigned-char)) (defcfun ("ofdm_transfer_create_callback" ofdm-transfer-create-callback) :pointer "Initialize a new transfer using a callback." (radio-driver :string) (emit :unsigned-char) (data-callback :pointer) (callback-context :pointer) (sample-rate :unsigned-long) (bit-rate :unsigned-int) (frequency :unsigned-long) (frequency-offset :long) (gain :string) (ppm :float) (subcarrier-modulation :string) (subcarriers :unsigned-int) (cyclic-prefix-length :unsigned-int) (taper-length :unsigned-int) (inner-fec :string) (outer-fec :string) (id :string) (dump :string) (timeout :unsigned-int) (audio :unsigned-char)) (defcfun ("ofdm_transfer_free" ofdm-transfer-free) :void "Cleanup after a finished transfer." (transfer :pointer)) (defcfun ("ofdm_transfer_start" ofdm-transfer-start) :void "Start a transfer and return when finished." (transfer :pointer)) (defcfun ("ofdm_transfer_stop" ofdm-transfer-stop) :void "Interrupt a transfer." (transfer :pointer)) (defcfun ("ofdm_transfer_stop_all" ofdm-transfer-stop-all) :void "Interrupt a transfer.") (defcfun ("ofdm_transfer_print_available_radios" ofdm-transfer-print-available-radios) :void "Print list of detected software defined radios.") (defcfun ("ofdm_transfer_print_available_subcarrier_modulations" ofdm-transfer-print-available-subcarrier-modulations) :void "Print list of supported subcarrier modulations.") (defcfun ("ofdm_transfer_print_available_forward_error_codes" ofdm-transfer-print-available-forward-error-codes) :void "Print list of supported forward error codes.") ;;; ;;; Lisp API ;;; (defun verbosity () "Get the verbosity level." (ofdm-transfer-is-verbose)) (defun (setf verbosity) (value) "Set the verbosity level." (ofdm-transfer-set-verbose value) value) (defun make-transfer (&key (radio-driver "") emit file data-callback callback-context (sample-rate 2000000) (bit-rate 38400) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (subcarrier-modulation "qpsk") (subcarriers 64) (cyclic-prefix-length 16) (taper-length 4) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Initialize a transfer." (when (or (and file data-callback) (and (not file) (not data-callback))) (error "Either FILE or DATA-CALLBACK must be specified.")) (let ((transfer (if file (ofdm-transfer-create radio-driver (if emit 1 0) (namestring file) sample-rate bit-rate frequency frequency-offset (if (stringp gain) gain (format nil "~d" gain)) ppm subcarrier-modulation subcarriers cyclic-prefix-length taper-length inner-fec outer-fec id (if dump (namestring dump) (null-pointer)) (or timeout 0) (if audio 1 0)) (ofdm-transfer-create-callback radio-driver (if emit 1 0) data-callback (or callback-context (null-pointer)) sample-rate bit-rate frequency frequency-offset (if (stringp gain) gain (format nil "~d" gain)) ppm subcarrier-modulation subcarriers cyclic-prefix-length taper-length inner-fec outer-fec id (if dump (namestring dump) (null-pointer)) (or timeout 0) (if audio 1 0))))) (if (null-pointer-p transfer) (error "Failed to initialize transfer.") transfer))) (defun free-transfer (transfer) "Cleanup after a finished transfer." (ofdm-transfer-free transfer)) (defun start-transfer (transfer) "Start a transfer and return when finished." (float-features:with-float-traps-masked t (ofdm-transfer-start transfer))) (defun stop-transfer (transfer) "Interrupt a transfer." (ofdm-transfer-stop transfer)) (defun stop-all-transfers () "Interrupt all transfers." (ofdm-transfer-stop-all)) (defun transmit-file (file &key (radio-driver "") (sample-rate 2000000) (bit-rate 38400) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (subcarrier-modulation "qpsk") (subcarriers 64) (cyclic-prefix-length 16) (taper-length 4) (inner-fec "h128") (outer-fec "none") (id "") dump audio (final-delay 0.0)) "Transmit the data from FILE." (let ((transfer (make-transfer :emit t :file file :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :subcarrier-modulation subcarrier-modulation :subcarriers subcarriers :cyclic-prefix-length cyclic-prefix-length :taper-length taper-length :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :audio audio))) (unwind-protect (progn (start-transfer transfer) (unless (zerop final-delay) (sleep final-delay))) (free-transfer transfer)) t)) (defun receive-file (file &key (radio-driver "") (sample-rate 2000000) (bit-rate 38400) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (subcarrier-modulation "qpsk") (subcarriers 64) (cyclic-prefix-length 16) (taper-length 4) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Receive data into FILE." (let ((transfer (make-transfer :emit nil :file file :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :subcarrier-modulation subcarrier-modulation :subcarriers subcarriers :cyclic-prefix-length cyclic-prefix-length :taper-length taper-length :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :timeout timeout :audio audio))) (unwind-protect (start-transfer transfer) (free-transfer transfer)) t)) (defparameter *data-stream* nil) (defparameter *buffer* nil) (defcallback read-data-from-stream :int ((context :pointer) (payload :pointer) (payload-size :unsigned-int)) (declare (ignore context)) (handler-case (labels ((copy-data (total) (let* ((size (min (length *buffer*) (- payload-size total))) (n (read-sequence *buffer* *data-stream* :end size))) (cond ((zerop n) (if (zerop total) -1 total)) (t (dotimes (i n) (setf (mem-aref payload :unsigned-char (+ total i)) (aref *buffer* i))) (copy-data (+ total n))))))) (copy-data 0)) (error () -1))) (defcallback write-data-to-stream :int ((context :pointer) (payload :pointer) (payload-size :unsigned-int)) (declare (ignore context)) (handler-case (labels ((copy-data (total) (let ((size (min (length *buffer*) (- payload-size total)))) (cond ((zerop size) payload-size) (t (dotimes (i size) (setf (aref *buffer* i) (mem-aref payload :unsigned-char (+ total i)))) (write-sequence *buffer* *data-stream* :end size) (copy-data (+ total size))))))) (copy-data 0)) (error () -1))) (defun transmit-stream (stream &key (radio-driver "") (sample-rate 2000000) (bit-rate 38400) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (subcarrier-modulation "qpsk") (subcarriers 64) (cyclic-prefix-length 16) (taper-length 4) (inner-fec "h128") (outer-fec "none") (id "") dump audio (final-delay 0.0)) "Transmit the data from STREAM." (let* ((*data-stream* stream) (*buffer* (make-array 1024 :element-type '(unsigned-byte 8))) (transfer (make-transfer :emit t :data-callback (callback read-data-from-stream) :callback-context (null-pointer) :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :subcarrier-modulation subcarrier-modulation :subcarriers subcarriers :cyclic-prefix-length cyclic-prefix-length :taper-length taper-length :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :audio audio))) (unwind-protect (progn (start-transfer transfer) (unless (zerop final-delay) (sleep final-delay))) (free-transfer transfer)) t)) (defun receive-stream (stream &key (radio-driver "") (sample-rate 2000000) (bit-rate 38400) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (subcarrier-modulation "qpsk") (subcarriers 64) (cyclic-prefix-length 16) (taper-length 4) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Receive data to STREAM." (let* ((*data-stream* stream) (*buffer* (make-array 1024 :element-type '(unsigned-byte 8))) (transfer (make-transfer :emit nil :data-callback (callback write-data-to-stream) :callback-context (null-pointer) :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :subcarrier-modulation subcarrier-modulation :subcarriers subcarriers :cyclic-prefix-length cyclic-prefix-length :taper-length taper-length :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :timeout timeout :audio audio))) (unwind-protect (start-transfer transfer) (free-transfer transfer)) t)) (defun transmit-buffer (buffer &key (start 0) end (radio-driver "") (sample-rate 2000000) (bit-rate 38400) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (subcarrier-modulation "qpsk") (subcarriers 64) (cyclic-prefix-length 16) (taper-length 4) (inner-fec "h128") (outer-fec "none") (id "") dump audio (final-delay 0.0)) "Transmit the data between START and END in BUFFER." (with-octet-input-stream (stream buffer start (or end (length buffer))) (transmit-stream stream :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :subcarrier-modulation subcarrier-modulation :subcarriers subcarriers :cyclic-prefix-length cyclic-prefix-length :taper-length taper-length :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :audio audio :final-delay final-delay))) (defun receive-buffer (&key (radio-driver "") (sample-rate 2000000) (bit-rate 38400) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (subcarrier-modulation "qpsk") (subcarriers 64) (cyclic-prefix-length 16) (taper-length 4) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Receive data into a new octet vector and return it." (with-octet-output-stream (stream) (receive-stream stream :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :subcarrier-modulation subcarrier-modulation :subcarriers subcarriers :cyclic-prefix-length cyclic-prefix-length :taper-length taper-length :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :timeout timeout :audio audio))) (defparameter *user-function* nil) (defcallback call-user-function :int ((context :pointer) (payload :pointer) (payload-size :unsigned-int)) (declare (ignore context)) (handler-case (let ((data (make-array payload-size :element-type '(unsigned-byte 8)))) (dotimes (i payload-size) (setf (aref data i) (mem-aref payload :unsigned-char i))) (funcall *user-function* data) payload-size) (error () -1))) (defun receive-callback (function &key (radio-driver "") (sample-rate 2000000) (bit-rate 38400) (frequency 434000000) (frequency-offset 0) (gain 0) (ppm 0.0) (subcarrier-modulation "qpsk") (subcarriers 64) (cyclic-prefix-length 16) (taper-length 4) (inner-fec "h128") (outer-fec "none") (id "") dump timeout audio) "Receive data and call a FUNCTION on it. The FUNCTION must take one octet vector as argument." (let* ((*user-function* function) (transfer (make-transfer :emit nil :data-callback (callback call-user-function) :callback-context (null-pointer) :radio-driver radio-driver :sample-rate sample-rate :bit-rate bit-rate :frequency frequency :frequency-offset frequency-offset :gain gain :ppm ppm :subcarrier-modulation subcarrier-modulation :subcarriers subcarriers :cyclic-prefix-length cyclic-prefix-length :taper-length taper-length :inner-fec inner-fec :outer-fec outer-fec :id id :dump dump :timeout timeout :audio audio))) (unwind-protect (start-transfer transfer) (free-transfer transfer)) t))
21,980
Common Lisp
.lisp
481
26.079002
81
0.453986
glv2/cl-ofdm-transfer
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
8da172023e2ebaaa799a53c8024ad3e52a9ec1535d2c2ad308bce1a555005cc1
24,326
[ -1 ]
24,327
tests.lisp
glv2_cl-ofdm-transfer/tests.lisp
;;; This file is part of cl-ofdm-transfer ;;; Copyright 2021-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defpackage :ofdm-transfer-tests (:use :cl :fiveam :ofdm-transfer) (:import-from :uiop #:with-temporary-file)) (in-package :ofdm-transfer-tests) (def-suite ofdm-transfer-tests :description "Tests for ofdm-transfer.") (in-suite ofdm-transfer-tests) (defparameter *message* (asdf:system-relative-pathname "ofdm-transfer" "LICENSE")) (defun same-files-p (path-1 path-2) (with-open-file (file-1 path-1 :element-type '(unsigned-byte 8)) (with-open-file (file-2 path-2 :element-type '(unsigned-byte 8)) (let ((buffer-1 (make-array 1024 :element-type '(unsigned-byte 8))) (buffer-2 (make-array 1024 :element-type '(unsigned-byte 8)))) (labels ((same-p () (let ((i (read-sequence buffer-1 file-1)) (j (read-sequence buffer-2 file-2))) (cond ((not (= i j)) nil) ((zerop i) t) ((mismatch buffer-1 buffer-2 :end1 i :end2 i) nil) (t (same-p)))))) (same-p)))))) (test transmit-and-receive-file (with-temporary-file (:pathname samples) (with-temporary-file (:pathname decoded) (let ((radio (format nil "file=~a" (namestring samples)))) (transmit-file (namestring *message*) :radio-driver radio) (receive-file (namestring decoded) :radio-driver radio) (is (same-files-p *message* decoded)))))) (test transmit-and-receive-file-audio (with-temporary-file (:pathname samples) (with-temporary-file (:pathname decoded) (let ((radio (format nil "file=~a" (namestring samples)))) (transmit-file (namestring *message*) :radio-driver radio :audio t :sample-rate 48000 :frequency 1500 :bit-rate 2400) (receive-file (namestring decoded) :radio-driver radio :audio t :sample-rate 48000 :frequency 1500 :bit-rate 2400) (is (same-files-p *message* decoded)))))) (test transmit-and-receive-stream (with-temporary-file (:pathname samples) (with-temporary-file (:pathname decoded :stream decoded-stream :direction :output :element-type '(unsigned-byte 8)) (with-open-file (message-stream *message* :element-type '(unsigned-byte 8)) (let ((radio (format nil "file=~a" (namestring samples)))) (transmit-stream message-stream :radio-driver radio) (receive-stream decoded-stream :radio-driver radio))) :close-stream (is (same-files-p *message* decoded))))) (test transmit-and-receive-buffer (with-temporary-file (:pathname samples) (let ((data #(0 1 2 4 9 16 25 36 49 64 81 100 121 144 169 196 225)) (radio (format nil "file=~a" (namestring samples)))) (transmit-buffer data :radio-driver radio) (let ((decoded (receive-buffer :radio-driver radio))) (is (equalp data decoded)))))) (test receive-callback (with-temporary-file (:pathname samples) (let ((data #(0 1 2 4 9 16 25 36 49 64 81 100 121 144 169 196 225)) (radio (format nil "file=~a" (namestring samples))) (decoded nil)) (transmit-buffer data :radio-driver radio) (receive-callback (lambda (data) (setf decoded (concatenate 'vector decoded data))) :radio-driver radio) (is (equalp data decoded)))))
3,923
Common Lisp
.lisp
77
38.181818
78
0.569752
glv2/cl-ofdm-transfer
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d480ce9585fcd7d1bd7fcfcbf7314cc7d11e8ca1856aea96c560501170330942
24,327
[ -1 ]
24,328
echo-server.lisp
glv2_cl-ofdm-transfer/examples/echo-server.lisp
;;; Example of use of cl-ofdm-transfer's API to make a server receiving ;;; messages from clients and sending them back in reverse order. ;;; ;;; Copyright 2021 Guillaume LE VAILLANT ;;; ;;; 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/>. (asdf:load-system "ofdm-transfer") (defpackage :echo-server (:use :cl) (:export #:client #:server)) (in-package :echo-server) (defparameter *radio-driver* "driver=hackrf") (defparameter *sample-rate* 4000000) (defparameter *transmission-gain* 36) (defparameter *reception-gain* 60) (defparameter *frequency-offset* 100000) (defparameter *bit-rate* 9600) (defparameter *subcarrier-modulation* "qpsk") (defparameter *subcarriers* 64) (defparameter *cyclic-prefix-length* 16) (defparameter *taper-length* 4) (defparameter *inner-fec* "rs8") (defparameter *outer-fec* "rs8") (defun transmit (data frequency) (ofdm-transfer:transmit-buffer data :radio-driver *radio-driver* :sample-rate *sample-rate* :gain *transmission-gain* :frequency frequency :frequency-offset *frequency-offset* :bit-rate *bit-rate* :subcarrier-modulation *subcarrier-modulation* :subcarriers *subcarriers* :cyclic-prefix-length *cyclic-prefix-length* :taper-length *taper-length* :inner-fec *inner-fec* :outer-fec *outer-fec* :final-delay 1)) (defun receive (callback frequency) (ofdm-transfer:receive-callback callback :radio-driver *radio-driver* :sample-rate *sample-rate* :gain *reception-gain* :frequency frequency :frequency-offset *frequency-offset* :bit-rate *bit-rate* :subcarrier-modulation *subcarrier-modulation* :subcarriers *subcarriers* :cyclic-prefix-length *cyclic-prefix-length* :taper-length *taper-length* :inner-fec *inner-fec* :outer-fec *outer-fec*)) (defun receive-1 (frequency) (let* ((received nil) (callback (lambda (data) (setf received data) (ofdm-transfer:stop-all-transfers)))) (receive callback frequency) received)) (defun process-request (data) (reverse data)) (defun server (frequency) (unwind-protect (loop :do (let* ((data (receive-1 frequency)) (processed (process-request data))) (format t "~%Received: ~a~%" data) (sleep 1) (format t "Sending: ~a~%" processed) (transmit processed frequency))) (ofdm-transfer:stop-all-transfers))) (defun client (frequency data) (unwind-protect (progn (format t "~%Sending: ~a~%" data) (transmit data frequency) (let ((data (receive-1 frequency))) (format t "Received: ~a~%" data) data)) (ofdm-transfer:stop-all-transfers)))
4,084
Common Lisp
.lisp
92
31.73913
80
0.564148
glv2/cl-ofdm-transfer
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
76d863d4cc1dbdba6255c6092751fe76e9689f206f03d67c0ef7ad970d061b94
24,328
[ -1 ]
24,329
ofdm-transfer.asd
glv2_cl-ofdm-transfer/ofdm-transfer.asd
;;; This file is part of cl-ofdm-transfer ;;; Copyright 2021-2022 Guillaume LE VAILLANT ;;; Distributed under the GNU GPL v3 or later. ;;; See the file LICENSE for terms of use and distribution. (defsystem "ofdm-transfer" :name "ofdm-transfer" :description "Send and receive data with SDRs using OFDM modulation" :version "1.6" :author "Guillaume LE VAILLANT" :license "GPL-3" :depends-on ("cffi" "cl-octet-streams" "float-features") :in-order-to ((test-op (test-op "ofdm-transfer/tests"))) :components ((:file "ofdm-transfer"))) (defsystem "ofdm-transfer/tests" :name "ofdm-transfer/tests" :description "Tests fot ofdm-transfer" :version "1.6" :author "Guillaume LE VAILLANT" :license "GPL-3" :depends-on ("fiveam" "ofdm-transfer" "uiop") :in-order-to ((test-op (load-op "ofdm-transfer/tests"))) :perform (test-op (o s) (let ((tests (uiop:find-symbol* 'ofdm-transfer-tests :ofdm-transfer-tests))) (uiop:symbol-call :fiveam 'run! tests))) :components ((:file "tests")))
1,079
Common Lisp
.asd
26
36.307692
70
0.663178
glv2/cl-ofdm-transfer
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
7ecbe3f6da56e9695ded1784078b1db79369cf9a3f2c4bc745f3627a68c2fa97
24,329
[ -1 ]
24,348
doit.lisp
shepherdjerred-homework_simplify-function/test/doit.lisp
(load "../src/simplify.lisp") (load "rules.lisp") (setq term0 '(+ Mary (+ Sue (- Sue)))) (pprint (setq a0 (simplify term0 r))) (setq term1 '(+ saw (+ (+ had (+ heard (- heard))) (- had)))) (pprint (setq a1 (simplify term1 r))) (setq term2 '(+ (+ (- (* a b)) (* a b)) a)) (pprint (setq a2 (simplify term2 r))) (setq term3 '(* big (/ little little))) (pprint (setq a3 (simplify term3 r))) (setq term4 '(+ (* 1 (/ 0 (+ ludicrous bright (* invisible dangerous)))) silly)) (pprint (setq a4 (simplify term4 r))) (setq term5 '(+ (+ (- tempermental) tempermental) (- (- lovable)))) (pprint (setq a5 (simplify term5 r))) (setq term6 '(+ (- ugly (* (/ big big) ugly)) cute)) (pprint (setq a6 (simplify term6 r))) (setq term7 '(+ (* (+ (- pig) pig)(- dog))(/ (* pig (+ dog cat))(+ dog cat)))) (pprint (setq a7 (simplify term7 r))) (pprint (setq ans (list a0 a1 a2 a3 a4 a5 a6 a7)))
873
Common Lisp
.lisp
19
44.894737
80
0.594373
shepherdjerred-homework/simplify-function
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
5e8c1861585db5fc77bf314f915c2d00905c10c1ea69a37e860581eb78881a01
24,348
[ -1 ]
24,349
rules.lisp
shepherdjerred-homework_simplify-function/test/rules.lisp
(setq r1 '((+ x (- x)) 0)) (setq r2 '((+ 0 x) x)) (setq r3 '((+ x 0) x)) (setq r4 '((/ x x) 1)) (setq r5 '((* x 1) x)) (setq r6 '((+ (- x) x) 0)) (setq r7 '((- (- x)) x)) (setq r8 '((* 1 x) x)) (setq r9 '((- x x) 0)) (setq r10 '((/ 0 x) 0)) (setq r11 '((* 0 x) 0)) (setq r12 '((/ (* y x) x) y)) (setq r (list r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12))
351
Common Lisp
.lisp
13
25.923077
54
0.436202
shepherdjerred-homework/simplify-function
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6b3b15bc9464ab926a4dd642f5e4144a0051c69a80534999358e46cd41f9bfb5
24,349
[ -1 ]
24,350
test.lisp
shepherdjerred-homework_simplify-function/test/test.lisp
(progn (load "../src/match.lisp") (load "../src/simplify.lisp") ; (trace simplify) ; (trace simplify-term) ; (trace match) ; (trace find-matching-reduction) ; (trace apply-reduction) ; (trace apply-match) ; (trace apply-matches) (setq r '( ((+ x (- x)) 0) ((+ (- x) x) 0) ((+ x 0) x) ((+ 0 x) x) ((/ (* x y) x) y) ((/ (* y x) x) y) ((* x 0) 0) ((* 0 x) 0)))) (load "doit.lisp") (and (equal (simplify '(+ c (+ (+ a (+ b (- b))) (- a))) r) 'C) (equal (simplify '(+ (- (* a b)) (* a b)) r) '0) (equal (simplify '(+ (* (+ (- a) a) (- b)) (/ (* a (+ b c)) (+ b c))) r) 'A))
848
Common Lisp
.lisp
37
14.378378
64
0.32797
shepherdjerred-homework/simplify-function
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f2d4949552a2dcb5adbf47b626a2fec3c075f31d65ee0fd479389b7763dbfc72
24,350
[ -1 ]
24,351
match.lisp
shepherdjerred-homework_simplify-function/src/match.lisp
;************************************************************************ ; isvar ; ; return true or false to indicate whether or not argument is a variable ; ; (isvar 'u) => non-nil ; (isvar 'a) => nil (defun isvar (x) (member x '(u v w x y z))) ;************************************************************************ ; applyone ; ; apply one substitution pair (called for each pair by applysub) ; ; (applyone '(x . a) '(+ x x)) => (+ a a) (defun applyone (sub patt) (cond ((null patt) nil) ((atom patt) (if (eq patt (car sub)) (cdr sub) patt)) (t (cons (applyone sub (car patt)) (applyone sub (cdr patt)))))) ;************************************************************************ ; applysub ; ; apply an entire substitution to a term (calls applyone to do the work) ; ; (applysub '((x . a)(y . b)) '(+ x y)) => (+ a b) ; (applysub '((x . a)) 'x) => a ; (applysub '(nil) '(+ x y)) => (+ x y) (defun applysub (subst patt) (if (equal subst '(nil)) patt (do* ((subs subst (cdr subs)) (sub (car subs) (car subs))) ((null subs) patt) (setq patt (applyone sub patt))))) ;************************************************************************ ; combine ; ; combine two substitutions into one ; note: if either is the "do nothing" substitution, it has no effect ; ; (combine '((x . a)(y . b)) '((v . c)(w . d))) => ((x . a)(y . b)(v . c)(w . d)) ; (combine '(nil) '((x . a))) => ((x . a)) (defun combine (sub1 sub2) (cond ((equal sub1 '(nil)) sub2) ((equal sub2 '(nil)) sub1) (t (append sub1 sub2)))) ;************************************************************************ ; match ; ; find the substitution which makes pattern identical to term ; note: nil means they cannot be made identical ; (nil) means they are already identical ; ((x.a)(y + b c)) means replace x with a and y with (+ b c) ; ; (match '(+ a b) '(+ x y)) => ((x . a)(y . b)) ; (match '(+ a b) '(+ a b)) => (nil) ; (match '(+ a b) '(+ x x)) => nil ; ; this functions calls match1 to give an initial substition of '(nil) ; match1 does all of the work (defun match(term patt) (match1 term patt '(nil))) ;************************************************************************ ; match1 ; ; implements the match function described above ; ; the initial call is as for match, but with an initial substituion of '(nil) ; ; the following cases are handled: ; 1. both term and pattern are nil - match has completed successfully ; 2. pattern is a variable - it can be replaced by term and added to subst ; 3. both are atoms - if equal, match is done, otherwise they cannot match ; 4. either is an atom - since not equal and no variable present, no match ; 5. they are both lists - match the cars, if ok, add resulting subst to ; the subst in progress and match the cdrs (after ; applying the car subst to the cdr of the pattern) (defun match1 (term patt subst) (cond ((and (null patt) (null term)) subst) ((isvar patt) (combine (list (cons patt term)) subst)) ((and (atom patt) (atom term)) (if (eq patt term) subst nil)) ((or (atom term) (atom patt)) nil) (t (let* ((sub (match (car term) (car patt)))) (cond ((null sub) nil) ((equal sub '(nil)) (match1 (cdr term) (cdr patt) subst)) (t (match1 (cdr term) (applysub sub (cdr patt)) (combine sub subst))))))))
3,900
Common Lisp
.lisp
88
36.443182
109
0.464729
shepherdjerred-homework/simplify-function
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a1b927a768dfb896db7b5f375b9faff113913d91b0b93948a697685a08bf1093
24,351
[ -1 ]
24,352
simplify.lisp
shepherdjerred-homework_simplify-function/src/simplify.lisp
; simplify ; Jerred Shepherd ; match = ((X . A)) ; reduction = ((+ X 0) (X)) ; term = (+ A 0) ; Given a list of reductions, this function will return the reduction whose pattern matches the term. ; If no reduction matches the term, it will return nil ; Term: (+ A 0) ; Reductions: (((+ X 0) X)) (defun find-matching-reduction (term reductions) (if (null reductions) nil (let* ( (current-reduction (car reductions)) (next-reduction (cdr reductions)) (reduction-pattern (car current-reduction)) (match-result (match term reduction-pattern))) (if (null match-result) (find-matching-reduction term next-reduction) (cons current-reduction match-result))))) ; Applies a match to a term ; Term: (X) ; Match: (X . A) (defun apply-match (term match) (if (null term) nil (let ( (curr-reduction-term (car term)) (next-reduction-term (cdr term)) (match-key (car match)) (match-value (cdr match))) (if (equal curr-reduction-term match-key) (cons match-value (apply-match next-reduction-term match)) (cons curr-reduction-term (apply-match next-reduction-term match)))))) ; Applies matches to a term ; Term: (X) ; Matches: ((X . A)) (defun apply-matches (term matches) (let ( (curr-match (car matches)) (next-match (cdr matches))) (if (null next-match) (apply-match term curr-match) (apply-match (apply-matches term next-match) curr-match)))) ; Applies a reduction to a term, and then applies any matches to the reduction ; Reduction: ((+ X 0) X) ; Matches: ((X . A)) (defun apply-reduction (reduction matches) (let ( (reduction-result (cdr reduction))) (list-to-atom (apply-matches reduction-result matches)))) ; Converts a list of a single atom to an atom (defun list-to-atom (term) (if (null (cdr term)) (car term) term)) (defun not-equal (l r) (not (equal l r))) ; Reductions should also be a list ; Term: (+ A 0) ; Reductions: (((+ X 0) X)) (defun simplify-term (term reductions) (if (null term) nil (let* ( (matched-reduction (find-matching-reduction term reductions))) (if (null matched-reduction) (if (atom term) term (let* ( (curr-car (car term)) (curr-cdr (cdr term)) (new-car (simplify-term curr-car reductions)) (new-cdr (simplify-term curr-cdr reductions)) (new-term (cons new-car new-cdr))) (if (or (not-equal new-car curr-car) (not-equal new-cdr curr-cdr)) (simplify-term new-term reductions) new-term))) (let* ( (term-after-reduction (apply-reduction (car matched-reduction) (cdr matched-reduction))) (new-term (simplify-term term-after-reduction reductions))) (if (equal term-after-reduction new-term) new-term (simplify-term new-term reductions))))))) (defun simplify (term reductions) (simplify-term term reductions))
3,275
Common Lisp
.lisp
114
22.236842
101
0.588832
shepherdjerred-homework/simplify-function
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d98fed6f5821ab67f3fc6fcea282f88aa2524a0a6af503b4caa3dde7da09cbd6
24,352
[ -1 ]
24,373
package.lisp
ibawt_cl-swagger/package.lisp
;;;; package.lisp ;;;; ;;;; Copyright (c) 2016 Ian Quick (defpackage #:cl-swagger (:use #:cl #:alexandria #:drakma) (:nicknames #:swagger) (:export #:generate-client #:swagger-object #:unknown-response-content-type-error #:unhandled-response-code-error))
290
Common Lisp
.lisp
13
18.615385
40
0.648551
ibawt/cl-swagger
1
1
1
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
82f1cd2d33332698d4d62c33b912f89fcb18ce276e7d6c145ad8cfd1f6185dab
24,373
[ -1 ]
24,374
test.lisp
ibawt_cl-swagger/test.lisp
(defpackage :test (:use :cl :cl-swagger)) (in-package :test) (defparameter *petstore-url* "http://localhost/v2/swagger.json") (defvar *petstore-json* (let* ((cl-json:*json-identifier-name-to-lisp* #'identity)) (fetch-json *petstore-url*))) (time (generate-client :test *k8s-json*)) (defvar *k8s-json* (fetch-json "https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json")) (defvar *foo*) (setf *foo* (generate-client :test *petstore-json*)) (defmacro foobar () (let ((x (generate-client :test *petstore-json*))) x)) (defmacro foobar-2 () (let ((x (generate-client :test *k8s-json*))) x)) (foobar) (foobar-2) (setf swagger:*api-host* "localhost")
732
Common Lisp
.lisp
19
34.947368
127
0.681366
ibawt/cl-swagger
1
1
1
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
35a2cc0eb39145bd231dc324a766763ec5d735a5bb35f4a9d6b6fc6cd8cca1a7
24,374
[ -1 ]
24,375
cl-swagger.asd
ibawt_cl-swagger/cl-swagger.asd
;;;; cl-swagger.asd ;;;; ;;;; Copyright (c) 2016 Ian Quick (asdf:defsystem #:cl-swagger :description "Describe cl-swagger here" :author "Ian Quick <[email protected]>" :license "AGPL" :serial t :depends-on (:alexandria :cl-json :drakma) :components ((:file "package") (:file "cl-swagger")))
351
Common Lisp
.asd
13
21.538462
43
0.596439
ibawt/cl-swagger
1
1
1
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
eff5ba44da11aea8bc1897e50d4c3530e2c81aac8e73baeb804eab548581cc15
24,375
[ -1 ]
24,394
hackmode.lisp
lost-rob0t_hackmode/hackmode.lisp
(declaim (optimize (speed 3) (safety 0))) (defpackage :hackmode-user (:export :main) (:use :cl #:hackmode) (:documentation "top level entry function")) ;; I dont really use hackmode-user (in-package :hackmode-user) (defun main () (in-package :cl-user) (use-package :hackmode) (use-package :hackmode-tools) (setq hackmode::*interactive* t) (load hackmode-init-file) (shellpool:start) (nhooks:run-hook *startup-hook*) (lish:lish))
455
Common Lisp
.lisp
16
25.9375
46
0.707094
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f4ded435f7c73fd60734b6b1c96b8f5c6492af0b9e5931e7f41bd4388c8f0a2b
24,394
[ -1 ]
24,395
certsh.lisp
lost-rob0t_hackmode/source/hackmode-tools/recon/recon-dns/certsh.lisp
(in-package :recon.dns) (defun cert.sh (domain) (remove-duplicates (flatten (loop for result in (jsown:parse (dex:get (format nil "https://crt.sh/?q=~a&output=json" domain) :headers '(("User-Agent" . "Hackmode") ("Accept" . "Application/json")))) for domain = (jsown:val result "name_value") if (not (str:containsp "@" domain)) collect (str:words (cl-ppcre:regex-replace-all "\\*\\." domain "")))) :test #'string=)) (defvar *cert.sh-setup-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called before cert.sh is ran.") (defvar *cert.sh-finish-hook* (make-instance 'nhooks:hook-any :handlers nil) "Hook That is called after cert.sh is finished. Argument must accept list of DOMAIN objects.") (defun cert.sh* (domain) (nhooks:run-hook *cert.sh-setup-hook*) (let ((resp (loop for domain in (cert.sh domain) for result = (make-instance 'domain :id (format nil "~a" (sxhash domain)) :record domain :tool "cert.sh" :tags '("crt.sh" "domain")) do (nhooks:run-hook *domain-hook* result) collect result))) (nhooks:run-hook *cert.sh-finish-hook* resp) resp)) (lish:defcommand cert.sh ((domain string)) (loop for domain in (cert.sh* domain) do (format t "~a~%" (domain-name domain))))
1,495
Common Lisp
.lisp
23
51.086957
201
0.570451
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
58b46ee215387a2c76c094cfeef0fd59061e93c0a4089d7b79c449f17f32cee7
24,395
[ -1 ]
24,396
package.lisp
lost-rob0t_hackmode/source/hackmode-tools/recon/recon-dns/package.lisp
(uiop:define-package :recon-dns (:use :cl :hackmode) (:nicknames :recon.dns) (:export :dns-recon :subfinder :subfinder* :dnsrecon :check-mdi :*subfinder-finish-hook* :*subfinder-setup-hook* :*cert.sh-finish-hook* :*cert.sh-setup-hook* :*oam-subs-setup-hook* :*oam-subs-finish-hook* :oam-subs :oam-subs* :cert.sh* :cert.sh :check-mdi* :*check-mdi-finish-hook* :*check-mdi-setup-hook*) (:documentation "DNS recon tooling"))
487
Common Lisp
.lisp
23
17.434783
39
0.650108
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
93f72f191254e213c092a7557a72fb046c9ef8c20db5900df5c8126e6dbeee48
24,396
[ -1 ]
24,397
dns.lisp
lost-rob0t_hackmode/source/hackmode-tools/recon/recon-dns/dns.lisp
(in-package :recon-dns) ;; TODO wrape up shell tool creation into a macro since its just calling it from the shell (defun subfinder (&rest args) "run subfinder" (nth 0 (apply #'make-command "subfinder" "-silent" args))) (defvar *subfinder-setup-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called before subfinder is ran.") (defvar *subfinder-finish-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called after subfinder is finished.") (defvar *oam-subs-setup-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called before oam-subs is ran.") (defvar *oam-subs-finish-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called after oam-subs is finished.") (defun subfinder* (&rest args) "run subfinder and save output to database" (nhooks:run-hook *subfinder-setup-hook*) (let* ((output (uiop:split-string (apply #'subfinder args) :separator "\n")) (docs (loop for domain in output for record = (make-instance 'domain :id (format nil "~a" (sxhash domain)) :tags '("dns" "subfinder") :dtype "domain" :record domain) do (nhooks:run-hook *domain-hook* record) collect record))) (nhooks:run-hook *subfinder-finish-hook*) docs)) (defun oam-subs (&rest args) (uiop:split-string (nth 0 (shellpool:run (apply #'make-command "oam_subs" "-o /dev/stdout -names" args))) :separator "\n")) ;; TODO fix gopath and test this (defun oam-subs* (&rest args) (nhooks:run-hook *oam-subs-setup-hook*) (let* ((output (apply 'oam-subs args)) (domains (loop for domain in output for record = (make-instance 'domain :id (format nil "~a" (sxhash domain)) :tags '("dns" "oam-subs") :dtype "domain" :record domain) do (nhooks:run-hook *domain-hook* record)))) (nhooks:run-hook *oam-subs-finish-hook* domains) domains)) (defun dnsrecon (&rest args) (nth 0 (apply #'make-command "dnsrecon" args)))
2,219
Common Lisp
.lisp
41
44.073171
153
0.616489
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
26e058b37986389993874e8979b177a993a3f925257090d1e969d55b40f60c46
24,397
[ -1 ]
24,398
mdi.lisp
lost-rob0t_hackmode/source/hackmode-tools/recon/recon-dns/mdi.lisp
(in-package :recon.dns) (defvar *check-mdi-setup-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called before check-mdi is ran.") (defvar *check-mdi-finish-hook* (make-instance 'nhooks:hook-any :handlers nil) "Hook That is called after check-mdi is finished. Argument must accept list of DOMAIN objects.") (defun make-mdi-body (domain) (format nil "<?xml version=\"1.0\" encoding=\"utf-8\"?> <soap:Envelope xmlns:exm=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:ext=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <soap:Header> <a:RequestedServerVersion>Exchange2010</a:RequestedServerVersion> <a:MessageID>urn:uuid:6389558d-9e05-465e-ade9-aae14c4bcd10</a:MessageID> <a:Action soap:mustUnderstand=\"1\">http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetFederationInformation</a:Action> <a:To soap:mustUnderstand=\"1\">https://autodiscover.byfcxu-dom.extest.microsoft.com/autodiscover/autodiscover.svc</a:To> <a:ReplyTo> <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address> </a:ReplyTo> </soap:Header> <soap:Body> <GetFederationInformationRequestMessage xmlns=\"http://schemas.microsoft.com/exchange/2010/Autodiscover\"> <Request> <Domain>~a</Domain> </Request> </GetFederationInformationRequestMessage> </soap:Body> </soap:Envelope>" domain)) (defun make-mdi-request (domain) (let* ((body (make-mdi-body domain)) (headers '(("Content-type" . "text/xml; charset=utf-8") ("User-agent" . "AutodiscoverClient"))) (resp (dex:post "https://autodiscover-s.outlook.com/autodiscover/autodiscover.svc" :headers headers :content body))) resp)) (defun parse-mdi-resp (resp) (loop for domain in (cdr (xmls:node->nodelist (xmls:xmlrep-find-child-tag "Domains" (xmls:xmlrep-find-child-tag "response" (xmls:xmlrep-find-child-tag "getfederationinformationresponsemessage" (xmls:xmlrep-find-child-tag "Body" (xmls:parse resp))))))) if domain collect (nth 2 domain))) (defun check-mdi (domain) (remove-duplicates (parse-mdi-resp (make-mdi-request domain)) :test #'string=)) (defun check-mdi* (domain) (nhooks:run-hook *check-mdi-setup-hook*) (let ((records (loop for domain in (check-mdi domain) for record = (make-instance 'domain :id (format nil "~a" (sxhash domain)) :dtype "domain" :record domain :tags (list "domain" "cert.sh")) do (if (str:containsp "onmicrosoft.com" domain) (push "azure-tenet" (doc-tags record))) do (nhooks:run-hook *domain-hook* record) collect record))) (nhooks:run-hook *check-mdi-finish-hook* records) records))
3,438
Common Lisp
.lisp
58
46.137931
163
0.60761
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b9a732ddf2d0fbf3cf11c6b007df11c2c68e43844ea5e982bb1eeb23ab1b3b37
24,398
[ -1 ]
24,399
package.lisp
lost-rob0t_hackmode/source/hackmode-core/package.lisp
(uiop:define-package :hackmode (:import-from :serapeum :dict :@) (:documentation "Core hackmode internalls.") (:export :EXPLOIT-OPTION-DOCUMENTATION :EXPLOIT-NAME :USE :EXPLOIT-OPTIONS :EXPLOIT-OPTION-NAME :EXPLOIT-SETUP :UNIX-NOW :RUN-EXPLOIT :EXPLOIT-FUNC :EXPLOIT-HELP :EXPLOIT-PLATFORM :EXPLOIT-OPTION-TYPE :hackmode-init-file :hackmode-operations-database :RHOST :payloads :config-dir :wordlist-dir :wordlist-alist :wordlist :target-platform :socks5-proxy-list :http-proxy-list :exploits-dir :history-path :prompt :*startup-hook* :init-database :put-doc :put-docs :*db* :*operations-database* :meta :output :host :port :finding :url :*api-common-patterns* :find-api :find-apis :*exploits* :*current-exploit* :exploit-option :exploit :operation :operation-dir :domain :domain-name :domain-type :doman-zone :use-operation :parse-url :url-query :url-path :url-port :url-host :url-scheme :*interactive* :*finding-hook* :*domain-hook* :flatten :*current-operation* :new-operation :select-operation :make-command :doc-tags :doc-type :doc-operation :doc-date-updated :doc-date-added :doc-output :doc-tool :doc-host :doc-ip :doc-port :doc-services :finding-id :finding-doc :finding-finding-type :finding-data :cert-not-before :cert-not-after :cert-common-name :cert-org-unit-name :cert-locality :cert-country :cert-province)) (in-package :hackmode)
1,619
Common Lisp
.lisp
93
13.473118
46
0.673014
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
12e065a4ca5062a9e93ea0517e8b32382f6cadbc53fcd75269675b840631a96b
24,399
[ -1 ]
24,400
database.lisp
lost-rob0t_hackmode/source/hackmode-core/database.lisp
(in-package :hackmode) (conspack:defencoding meta doc-id tags dtype date-added date-updated operation) (conspack:defencoding output doc-id tags dtype date-added date-updated operation tool output) (conspack:defencoding host doc-id tags dtype date-added date-updated operation hostname ip) (conspack:defencoding port doc-id tags dtype date-added date-updated operation number services) (defvar *db* nil "The hackmode database object") ;; default to the one from tek9 ;; This is effectivly just a wrapper around "put" (defun put-doc (document &key (database-name "std") (database *db*)) (when (not (doc-id document)) (setf (doc-id document) (sxhash document))) (tek9:put* database document :id (doc-id document))) (defun put-docs (documents &key (database-name "std") (database *db*)) (tek9:put-bulk database (loop for doc in documents collect (progn (let ((id (or (doc-id doc) (format nil "~a" (sxhash doc))))) (tek9:new-document :id id :value doc))))))
1,102
Common Lisp
.lisp
21
44.380952
102
0.66573
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
503ca78c42c1848cd36ddd39c99be028638205021154f3a995cebeadf0c8d073
24,400
[ -1 ]
24,401
objects.lisp
lost-rob0t_hackmode/source/hackmode-core/objects.lisp
(in-package :hackmode) (defclass meta () ((date-added :initarg :date-added :initform (unix-now) :type integer :accessor doc-date-added :allocation :class) (date-updated :initarg :date-updated :initform (unix-now) :type integer :accessor doc-date-updated :allocation :class) (operation :initarg :operation :initform "" :type string :accessor doc-operation :allocation :class) (dtype :initarg :dtype :initform nil :accessor doc-type :allocation :class) (tags :initarg :tags :type list :initform () :accessor doc-tags :allocation :class) (tool :initarg :tool :type string :initform "hackmode" :accessor doc-tool :allocation :class) (doc-id :initarg :id :type string :initform (tek9:make-key-id) :allocation :class :accessor doc-id))) (defclass output (meta) ((tool :initarg :tool :initform "" :type string :accessor doc-tool :allocation :class) (output :initarg :output :initform "" :type string :accessor doc-output :allocation :class))) (defclass domain (meta) ((ips :initarg :ips :initform nil :type list :accessor domain-ips) (record :initarg :record :initform "" :type string :accessor domain-name) (record-type :initarg :record-type :initform "" :type string :accessor domain-type) (zone :initarg :zone :initform "" :accessor doman-zone :type string))) (defclass host (meta) ((hostname :initarg :hostname :type string :accessor doc-host :allocation :class) (ip :initarg :ip :type string :accessor doc-ip :allocation :class))) (defclass port (meta) ((number :initarg :number :type integer :accessor doc-port :allocation :class) (services :initarg :services :type list :accessor doc-services :allocation :class))) (defclass finding (meta) ((id :initarg :id :type string :initform "" :accessor finding-id :allocation :class) (doc-id :initarg :host :type string :initform "" :accessor finding-doc :allocation :class) (finding-type :initarg :finding-type :type string :initform "Bug" :accessor finding-finding-type :allocation :class) (data :initarg :data :type string :initform "" :accessor finding-data))) (defclass url (meta) ((scheme :initarg :scheme :type string :reader url-scheme :allocation :class) (host :initarg :host :type string :reader url-host :allocation :class) (port :initarg :port :type integer :reader url-port :allocation :class) (path :initarg :path :type string :reader url-path :allocation :class) (query :initarg :query :type string :reader url-query :allocation :class))) (defclass cert (meta) ((not-before :initarg :not-before :type integer :accessor cert-not-before :initform (unix-now) :allocation :class) (not-after :initarg :not-after :type integer :accessor cert-not-after :initform (unix-now) :allocation :class) (common-name :initarg :common-name :type string :accessor cert-common-name :initform "" :allocation :class) (org-unit-name :initarg :org-unit-name :type string :accessor cert-org-unit-name :initform "" :allocation :class) (locality :initarg :locality :type string :accessor cert-locality :initform "" :allocation :class) (country-name :initarg :country :type string :accessor cert-country :initform "" :allocation :class) (province :initarg :province :type string :accessor cert-province :initform "" :allocation :class)))
3,277
Common Lisp
.lisp
42
74.428571
121
0.735157
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d023caf9228f8fc4aedb1e18af01e23868b0c21d9fcae35eee450046d0d2860a
24,401
[ -1 ]
24,402
operations.lisp
lost-rob0t_hackmode/source/hackmode-core/operations.lisp
(in-package :hackmode) ;;; This file is ment to handle the handling of operation, which put simply is just a current working directory ;;; This is the common pattern when doing hacking i find myself in (defvar *operations-database* (tek9:new-database "operations" :path hackmode-operations-database)) (nhooks:add-hook *startup-hook* #'(lambda () (tek9:open-database *operations-database*))) (defclass operation (meta) ((working-dir :initarg :dir :accessor operation-dir :initform (uiop/os:getcwd) :allocation :class) (name :initarg :name :accessor operation-name :initform "" :allocation :class) (description :initarg :description :accessor operation-description :initform "" :allocation :class))) (defvar *current-operation* nil "The current operation") (defun new-operation (name &optional (path (uiop:merge-pathnames* ".hackmode/" (uiop:getcwd)) ) (description "Hackmode operation")) (let ((doc (make-instance 'operation :name name :description description :dir path :dtype "operation"))) (tek9:put* *operations-database* doc :id (operation-name doc)))) ;; TODO A function/helper should do this! ;; NOTE For others reading the source code of hackmode this is a good example ;; On how to query tek9 (defun select-operation (name) "Selection query for tek9." (tek9:fetch* *operations-database* name)) (defun use-operation (name) "Select a operation by name to be the current operation." (let* ((op (select-operation name)) (dir (if op (operation-dir op) (error (format nil "No Such Operation exist. Use (hackmode:new-operation \"~a\") to create one" name))))) (setq *current-operation* op) (uiop:ensure-all-directories-exist (list dir)) (when *db* (tek9:close-database *db*)) (setq *db* (tek9:new-database name :path (uiop:merge-pathnames* (uiop:parse-unix-namestring dir) (format nil ".hackmode/")))) (tek9:open-database *db*) (uiop:chdir dir)))
1,965
Common Lisp
.lisp
31
58.741935
146
0.714286
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e553f0fb9ca90ff26535cb407048f2c507348e2b237c467fa4e9861720393cec
24,402
[ -1 ]
24,403
functions.lisp
lost-rob0t_hackmode/source/hackmode-core/functions.lisp
(in-package :hackmode) (defvar *api-common-patterns* (list "/api/" "/v1/" "/v2/" "/rest/" "/rest/v1/" "/rest/v2/" "/rpc/" "/rpc/v1/" "/rpc/v2/" "/services/" "/services/api/" "/services/v1/" "/services/v2/" "/public/api/" "/public/v1/" "/public/v2/" "/app/api/" "/app/v1/" "/app/v2/" "/api/v1/" "/api/v2/" "/api/rest/" "/api/rest/v1/" "/api/rest/v2/" "/api/rpc/" "/api/rpc/v1/" "/api/rpc/v2/" "/api/services/" "/api/services/v1/" "/api/services/v2/" "/api/public/" "/api/public/v1/" "/api/public/v2/" "/api/app/" "/api/app/v1/" "/api/app/v2/" "/restful/" "/restful/v1/" "/restful/v2/" "/rest/v1/endpoints/" "/rest/v2/endpoints/" "/graphql/" "/graphql/v1/" "/graphql/v2/" "/v1/endpoints/" "/v2/endpoints/" "/public/v1/endpoints/" "/public/v2/endpoints/" "/app/v1/endpoints/" "/app/v2/endpoints/" "/api/v1/endpoints/" "/api/v2/endpoints/" "/restful/endpoints/" "/restful/v1/endpoints/" "/restful/v2/endpoints/" "/rest/v1/methods/" "/rest/v2/methods/" "/graphql/methods/" "/v1/methods/" "/v2/methods/" "/public/v1/methods/" "/public/v2/methods/" "/app/v1/methods/" "/app/v2/methods/" "/api/v1/methods/" "/api/v2/methods/" "/restful/methods/" "/restful/v1/methods/" "/restful/v2/methods/" "/rest/methods/" "/rest/v1/actions/" "/rest/v2/actions/" "/graphql/actions/" "/v1/actions/" "/v2/actions/" "/public/v1/actions/" "/public/v2/actions/" "/app/v1/actions/" "/app/v2/actions/" "/api/v1/actions/" "/api/v2/actions/" "/restful/actions/" "/restful/v1/actions/" "/restful/v2/actions/" "/rest/actions/" "/rest/v1/tasks/" "/rest/v2/tasks/" "/graphql/tasks/" "/v1/tasks/" "/v2/tasks/" "/public/v1/tasks/" "/public/v2/tasks/" "/app/v1/tasks/" "/app/v2/tasks/" "/api/v1/tasks/" "/api/v2/tasks/" "/restful/tasks/" "/restful/v1/tasks/" "/restful/v2/tasks/" "/rest/tasks/")) ;; TODO figure out how to set current operation? (defun parse-url (url) (multiple-value-bind (scheme unknown host port path query) (quri:parse-uri url) (make-instance 'url :scheme scheme :host host :port (or port 80) ; Use 80 as default port if not specified :path path :query query :dtype "url" :tags '("url")))) (defun find-api (url-object &optional (patterns *api-common-patterns*)) "find api urls based on the given pattern in the :path field of the url-object. adds 'api' tag to the url-object if it matches the pattern." (let ((path (url-path url-object))) (car (loop for pattern in patterns if (and path (cl-ppcre:scan pattern path)) collect (progn (setf (doc-tags url-object) (push "api" (doc-tags url-object))) url-object))))) (defun find-apis (url-objects &optional (common-api-urls *api-common-patterns*)) "find api urls in a list of url-objects based on the given pattern. adds 'api' tag to each url-object if it matches the pattern." (mapcar (lambda (url-object) (find-api pattern url-object common-api-urls)) url-objects))
3,754
Common Lisp
.lisp
45
61.2
129
0.502434
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
140e3488ef5cd1ba59bad9aa23659321b41557da3ca8e43b49493bc14fc3ebcb
24,403
[ -1 ]
24,404
exploits.lisp
lost-rob0t_hackmode/source/hackmode-core/exploits.lisp
(in-package :hackmode) (defclass exploit () ((name :initarg :name :accessor exploit-name :initform (error "Invalid exploit Error: exploit requires a name")) (platform :initarg :platform :accessor exploit-platform :initform (error "Invalid exploit Error: exploit requires a platform")) (help :initarg :help :accessor exploit-help :initform nil) (options :initarg :options :accessor exploit-options :initform nil) (func :initarg :func :accessor exploit-func :initform (lambda () (format t "Its an exploit!"))) (setup :initarg :exploit-setup :accessor exploit-setup :initform (lambda () (format t "Exploit setup function!"))))) (defclass exploit-option () ((name :initarg :name :accessor exploit-option-name :initform (error 'invalid-object-error :slot :name)) (option-type :initarg :option-type :accessor exploit-option-type :initform (error 'invalid-object-error :slot :option-type)) (documentation :initarg :documentation :accessor exploit-option-documentation :initform (progn (warn "You Should document your exploit options.") "option for exploit.")))) (defvar *current-exploit* (make-instance 'exploit :name "Hackmode" :platform "hackmode") "The Current package to be ran. this may be a exploit, a tool, ect.") (defvar *exploits* (dict) "The current list of loaded exploits in hackmode.") (defmethod use ((exploit exploit)) (setq *current-exploit* exdploit)) (defmethod run-exploit ((exploit exploit)) (funcall (exploit-setup exploit)) (funcall (exploit-func exploit))) ;; (nhooks:run-hook '*history-hook* (make-history (format nil "run ~a" (exploit-name exploit))))
1,613
Common Lisp
.lisp
20
77.6
174
0.744788
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
667d352a4f406e73e5d08cf2ffdc8414063dbc22c9db0b0d54d01a431979db4f
24,404
[ -1 ]
24,405
settings.lisp
lost-rob0t_hackmode/source/hackmode-core/settings.lisp
;;;; This file is ment to be a user facing config options that is ment to be changed, ;;;; although everything can be, just these are explitit options (in-package :hackmode) (defvar config-dir (nfiles:expand (make-instance 'nfiles:config-file :base-path #p"hackmode/")) "A Path to user configuration") (defvar hackmode-init-file (nfiles:expand (make-instance 'nfiles:config-file :base-path (uiop:merge-pathnames* config-dir #p"init.lisp"))) "The path to the init file for hackmode. Defaults to ~/.config/hackmode/init.lisp") (defvar data-dir (nfiles:expand (make-instance 'nfiles:data-file :base-path #p"hackmode/")) "The local data path, defaults to ~/.local/share/hackmode") (defvar hackmode-operations-database (nfiles:expand (make-instance 'nfiles:data-file :base-path (uiop:merge-pathnames* ".db/" data-dir ))) "The Path to database file that maintains paths to operations.") (defvar RHOST nil "The target host address for a payload") (defvar LHOST nil "The target Listen Address for payload") (defvar payloads nil "A List of payloads.") (defvar wordlist-dir (nfiles:expand (make-instance 'nfiles:data-file :base-path (uiop:merge-pathnames* "wordlists/" data-dir))) "The Path to user directory of wordlists, defaults to data-dir/wordlists/") (defvar wordlist-alist nil "An Alist of tasks/tools to default wordlists to be used.") (defvar wordlist nil "The current wordlist to use, it has the highest priority") (defvar target-platform nil "The target platform Operating system.") ;; NOTE Platforms are represented as a symbol ;; TODO Use a scheme://ip:port proxy system (defvar socks5-proxy-list nil "List of socks5 proxy addresses. Must be in the format of socks5://ip:port") (defvar http-proxy-list nil "List of http proxy addresses. Must be in the format of http://ip:port") (defvar exploits-dir (nfiles:expand (make-instance 'nfiles:data-file :base-path (uiop:merge-pathnames* "exploits/" data-dir))) "Path to exploit dir where exploits are stored.") (defvar exploits-dependency-dir (nfiles:expand (make-instance 'nfiles:data-file :base-path (uiop:merge-pathnames* "exploits/" data-dir))) "Path to exploit dir where exploit dependencies are stored.") (defvar history-dir (nfiles:expand (make-instance 'nfiles:data-file :base-path (uiop:merge-pathnames* data-dir "history.lisp"))) "The history File, defaults to data-dir/history.lisp") ;; Ricing related (defvar prompt "HACK$> " "The prompt to be used for command inputs.") (defvar dependency-dir (nfiles:expand (make-instance 'nfiles:data-file :base-path (uiop:merge-pathnames* "deps/" data-dir))) "The Path for where dependency of tools will be downloaded. ") ;; hackmode internals (defvar *startup-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called when hackmode-user is started.") (defvar *finding-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called when a finding is found. Takes the finding object as the argument") (defvar *domain-hook* (make-instance 'nhooks:hook-void :handlers nil) "Hook That is called when a domain is found. Takes the domain object as the argument") (defvar *interactive* nil "Is hackmode being run from a repl/shell?")
3,297
Common Lisp
.lisp
35
89.142857
222
0.737882
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b2db557d5ebff978d7ba4cc64b9ec79b9d0fc4e53ca347f98e7e542338bdeec3
24,405
[ -1 ]
24,406
db.lisp
lost-rob0t_hackmode/source/hackmode-database/db.lisp
(in-package :hackmode-database) (defvar *db* nil "The hackmode database object") (defun make-document (data &key (id (make-ke)))) ;; default to the one from tek9 ;; This is effectivly just a wrapper around "put" (defun put-doc (database document &key (database-name "std")) (tek9:put* database document :key (sxhash))) (defun put-docs (database documents &key (database-name "std")) (loop for))
405
Common Lisp
.lisp
9
42.888889
63
0.728205
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a164b3eac366dc715efd426f6385d695683718ac50f8b37ad664716dc891907f
24,406
[ -1 ]
24,407
package.lisp
lost-rob0t_hackmode/source/hackmode-database/package.lisp
(uiop:define-package :hackmode-database (:nicknames :hack-db) (:use :tek9 :cl) (:documentation "the database for starintel"))
135
Common Lisp
.lisp
4
31.25
48
0.709924
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
dbf6c274f4e696a430ef8c85676a07581ae706e2eebb7674f6b558786c4e1efa
24,407
[ -1 ]
24,408
hackmode-user.asd
lost-rob0t_hackmode/hackmode-user.asd
(asdf:defsystem :hackmode-user :version "0.1.0" :description "description" :author "[email protected]" :serial t :license "LGPLv3" :components ((:file "hackmode")) :depends-on (#:hackmode #:lish #:hackmode-tools #:shellpool))
267
Common Lisp
.asd
8
30.625
65
0.629344
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
239e5c89ea6930aaf4a21a2f0c377d929965bd87c8f600e9a3ad6fdce6f5b5b2
24,408
[ -1 ]
24,409
recon-dns.asd
lost-rob0t_hackmode/source/hackmode-tools/recon/recon-dns/recon-dns.asd
(asdf:defsystem :recon-dns :version "0.1.0" :description "DNS recon tooling." :author "[email protected]" :serial t :license "LGPLV3" :components ((:file "package") (:file "dns") (:file "mdi") (:file "certsh")) :depends-on (#:hackmode #:lish #:str #:shellpool #:dexador #:lquery #:lparallel #:xmls))
392
Common Lisp
.asd
11
28.727273
92
0.530184
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
576a172ddda412d8b420ebf72148a9077736378f635640850a305b1ff6ef8e1f
24,409
[ -1 ]
24,410
hackmode.asd
lost-rob0t_hackmode/source/hackmode-core/hackmode.asd
(asdf:defsystem :hackmode :description "Core Systems for hackmode" :author "nsaspy" :license "LGLV3" :version "0.1.0" :serial t :depends-on (#:serapeum :local-time :nfiles :nhooks #:tek9 #:cl-ppcre #:dexador #:shellpool) :components ((:file "package") (:file "utils") (:file "settings") (:file "objects") (:file "database") (:file "operations") (:file "functions") (:file "exploits") (:file "hackmode")))
539
Common Lisp
.asd
16
24.3125
94
0.527725
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9c83c3123cd3aa975116945dc6b713a4c73ad44c02b3c4ed5ad141448e8ff343
24,410
[ -1 ]
24,411
hackmode-database.asd
lost-rob0t_hackmode/source/hackmode-database/hackmode-database.asd
(asdf:defsystem :hackmode-database :description "Database for hackmode" :author "nsaspy" :license "MIT" :version "0.1.0" :serial t :depends-on (#:tek9 #:cl-conspack) :components ((:file "package") (:file "objects") (:file "encoding") (:file "db")))
309
Common Lisp
.asd
11
21.636364
38
0.575758
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
05faa01343a825621bebb9516e95ba0c60ae89fc0b848b9166e83762f2fe4722
24,411
[ -1 ]
24,414
flake.lock
lost-rob0t_hackmode/flake.lock
{ "nodes": { "nixpkgs": { "locked": { "lastModified": 1699580828, "narHash": "sha256-SQT+801NjseVMQCr0ZVJVsdL9AN4CKxSU2Zf3oIbj+Q=", "owner": "nixos", "repo": "nixpkgs", "rev": "7c19f30a07d07d3fceaa2f6fced02c42c43563a8", "type": "github" }, "original": { "owner": "nixos", "repo": "nixpkgs", "type": "github" } }, "root": { "inputs": { "nixpkgs": "nixpkgs" } } }, "root": "root", "version": 7 }
534
Common Lisp
.l
26
14.153846
73
0.48622
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
ad6f044665d110ba4f4f2263fa11d7e28c3985805cdb4d910f03462b9835d018
24,414
[ -1 ]
24,415
.gitmodules
lost-rob0t_hackmode/.gitmodules
[submodule "deps/yew"] path = deps/yew url = https://github.com/lost-rob0t/yew-for-hackmode.git [submodule "deps/cl-cidr-notation"] path = deps/cl-cidr-notation url = https://github.com/AccelerationNet/cl-cidr-notation.git
227
Common Lisp
.l
6
36.166667
62
0.760181
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d63b0a435abe97a16999847be5a7bce00111f20dc8d2ac5523a209a683cffbf0
24,415
[ -1 ]
24,416
Makefile
lost-rob0t_hackmode/Makefile
## # Hackmode # # @file # @version 0.1 LISP ?= sbcl all: test run: $(LISP) --load run.lisp build: $(LISP) --non-interactive \ --load hackmode-user.asd \ --eval '(ql:quickload :hackmode-user)' \ --load 'hackmode.lisp' \ --eval "(sb-ext:save-lisp-and-die \"hm\" :toplevel 'hackmode-user::main :executable t :compression t)" install: cp hm /usr/local/bin clean: rm -f hm
385
Common Lisp
.l
19
18.368421
104
0.67313
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c0e1bcf06af885bec29e5e0889dc9d67d46d7434b68a88a2ac0ac8a6577e3b2d
24,416
[ -1 ]
24,417
flake.nix
lost-rob0t_hackmode/flake.nix
{ description = "Hackmode is a red teaming toolkit/exploit framework for common lisp"; inputs = { nixpkgs.url = "github:nixos/nixpkgs"; }; outputs = { self, nixpkgs }: let pkgs = nixpkgs.legacyPackages.x86_64-linux; in { devShell.x86_64-linux = pkgs.mkShell { buildInputs = with pkgs; [ pkg-config sbcl sbclPackages.mcclim glib openssl # Hacking tools used subfinder amass dnsrecon fierce asn whatweb nmap nuclei zap gospider ]; shellHook = '' export LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath([pkgs.openssl])}:${pkgs.lib.makeLibraryPath([pkgs.libedit])}:${pkgs.lib.makeLibraryPath([pkgs.libev])}:${pkgs.lib.makeLibraryPath([pkgs.lmdb])} ''; }; }; }
950
Common Lisp
.l
36
17.055556
204
0.526894
lost-rob0t/hackmode
1
0
3
LGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
93456ac417ce865a42f213fbce394331ded14e565119e4c9dc01d5cdda28f088
24,417
[ -1 ]
24,445
mandelbrot.lisp
sebity_mandelbrot/mandelbrot.lisp
;;;; mandelbrot.lisp (in-package #:mandelbrot) ;;; "mandelbrot" goes here. Hacks and glory await! (defparameter *width* 800) (defparameter *height* 600) (defparameter *zoom* 0.35) (defparameter *move-x* 1.5) (defparameter *move-y* 1.4) (defparameter *max-iterations* 300) (defun square (x) (* x x)) (defun draw-fractal (width height zoom move-x move-y iter max-iter) (declare (type fixnum width height iter max-iter) (type single-float zoom move-x move-y) (optimize (speed 3) (safety 0) (debug 0))) (let* ((px-real 0.0) (px-imag 0.0) (new-real nil) (new-imag nil) (old-real nil) (old-imag nil)) (loop for dx fixnum below *width* do (loop for dy fixnum below *height* do (setf px-real (+ (/ (* 1.5 (/ (float (- dx width)) 2.0)) (* 0.5 zoom (float width))) move-x)) (setf px-imag (+ (/ (/ (float (- dy height)) 2.0) (* 0.5 zoom height)) move-y)) (setf new-real 0.0) (setf new-imag 0.0) (setf old-real 0.0) (setf old-imag 0.0) (setf iter 0) (loop do (setf old-real new-real) (setf old-imag new-imag) (setf new-real (+ (- (the single-float (square old-real)) (the single-float(square old-imag))) px-real)) (setf new-imag (+ (the single-float (* 2.0 old-real old-imag)) (the single-float px-imag))) (setf iter (incf iter)) while (and (< (+ (the single-float (square new-real)) (the single-float (square new-imag))) 4) (< iter max-iter))) (cond ((= iter max-iter) (draw-pixel dx dy 0 0 0)) ((< iter 16) (draw-pixel dx dy (* iter 8.0) (* iter 8.0) (+ (* iter 4.0) 128))) ((and (> iter 16) (< iter 64)) (draw-pixel dx dy (- (+ 128 iter) 16) (- (+ 128 iter) 16) (- (+ 192 iter) 16))) ((> iter 64) (draw-pixel dx dy (the fixnum (- max-iter iter)) (the fixnum (+ (- max-iter iter) 128)) (the fixnum (- max-iter iter))))))))) (defun draw-pixel (x y r g b) (declare (fixnum x y r g b) (optimize (speed 3) (safety 0))) (sdl:draw-pixel-* x y :color (sdl:color :r r :g g :b b))) (defun update-movement () (setf *zoom* (* 1.001 *zoom*))) (defun render () ;(update-movement) (draw-fractal *width* *height* *zoom* *move-x* *move-y* 0 *max-iterations*) (sdl:update-display)) (defun start () (sdl:with-init (sdl:sdl-init-video) (sdl:window *width* *height* :title-caption "Mandelbrot") (setf (sdl:frame-rate) 30) (sdl:clear-display sdl:*black*) (sdl:with-events () (:quit-event () t) (:key-down-event (:key key) (case key (:sdl-key-escape (sdl:push-quit-event)))) (:key-up-event (:key key) (case key)) (:idle () (render)))))
2,873
Common Lisp
.lisp
85
27.282353
77
0.568838
sebity/mandelbrot
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
12f1a611577eabfe69a40d4aab2fa23e2fc0ce3f96ed934080e7f37a50fc0e5a
24,445
[ -1 ]
24,446
mandelbrot.asd
sebity_mandelbrot/mandelbrot.asd
;;;; mandelbrot.asd (asdf:defsystem #:mandelbrot :description "A Mandelbrot Set in Common Lisp" :author "Jan Tatham <[email protected]>" :license "GPL v2" :depends-on (#:lispbuilder-sdl) :serial t :components ((:file "package") (:file "mandelbrot")))
277
Common Lisp
.asd
9
26.555556
48
0.665414
sebity/mandelbrot
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c27b42e82d62bcda75064ece965cfb6e2a1a487241981f2d4127c9375af86ba3
24,446
[ -1 ]
24,464
packages.lisp
jnjcc_cl-nlp/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Natural Language Processing in Common Lisp (in-package #:cl-user) (defpackage #:cl-nlp (:nicknames #:nlp) (:use #:cl #:cl-ml/probs #:cl-ml/algo #:cl-ml/linalg #:cl-ml/graph #:cl-ml/io #:cl-ml #:cl-nlp/algo) (:export #:fit #:transform ;;; Probabilistic Graphical Models #:hmm-model #:hmm-states #:hmm-symbols #:hmm-start-prob #:hmm-trans-prob #:hmm-emiss-prob #:hmm-forward #:hmm-backward #:hmm-decode #:hmm-learn ;;; Language Modeling ;; word frequency, from text stream #:word-frequency ;; word id vocab, from word frequency, or from file stream #:wfreq-idvocab #:read-idvocab ;; ngram (wngram or idngram), from text stream (and idvocab) #:wngram-count #:idngram-count #:wngram-idngram ;; reduce n-gram to m-gram #:ngram-mgram #:sorted-wngram #:sorted-idngram ;; frequency of frequency for 1-, 2-, ..., n-gram #:fof-from-ngram #:fof-ref #:write-ngram #:read-ngram #:idngram-lm #:ngram-lm ;;; Segment words #:segment-chars ;;; Part-of-Speech tagging #:pos-tagger #:hmm-tagger #:pos-tag-sent #:pos-tag-corpus #:pos-evaluate ;;; Embedding #:word2vec #:fit-from-string #:fit-from-list #:has-embedding #:node2vec ))
1,526
Common Lisp
.lisp
38
30.289474
82
0.558406
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4002e91b11dd76ef641c509a16bb0c0cfec3d22b8024a2e74d6690e5d46a68a9
24,464
[ -1 ]
24,465
word2vec-test.lisp
jnjcc_cl-nlp/test/word2vec-test.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (define-test w2v-vocab-test "Huffman tree of the form: 8 / \ 6 7 / \ / \ 5 B D A / \ 2 3 4 E C 0 1 where inner node being index, which should subtract length(leafs)" (let ((text "a a b c c b b a d e d d a a d") (vocab nil) (vocsz nil) (winfo nil)) (setf vocab (cl-nlp::learn-vocab-from-string text)) (cl-nlp::create-huffman vocab) (setf vocsz (cl-nlp::vocab-size vocab)) (assert-eq 5 vocsz) (setf winfo (cl-nlp::get-word-info vocab "e")) ;; list of index of parents ;; (assert-true (equal '(8 6 5) (cl-nlp::winfo-path winfo))) (assert-true (equal '(3 1 0) (cl-nlp::winfo-path winfo))) ;; left child (assert-true (equal 0 (cl-nlp::winfo-code winfo))) (setf winfo (cl-nlp::get-word-info vocab "b")) ;; (assert-true (equal '(8 6) (cl-nlp::winfo-path winfo))) (assert-true (equal '(3 1) (cl-nlp::winfo-path winfo))) (assert-true (equal 1 (cl-nlp::winfo-code winfo))))) (define-test word2vec-test (let ((text "a a b c c b b a d e d d a a d") ;; CBOW with Hierarchical Softmax (cbowhs (make-instance 'word2vec :dimensions 10 :epochs 50 :algo :cbow :hsoftmax t :window 3)) ;; CBOW with Negative Sampling (cbowneg (make-instance 'word2vec :dimensions 10 :epochs 50 :algo :cbow :negsample 3 :window 3)) ;; Skip-gram with Hierarchical Softmax (sghs (make-instance 'word2vec :dimensions 10 :epochs 50 :algo :skip-gram :hsoftmax t :window 3)) ;; Skip-gram with Negative Sampling (sgneg (make-instance 'word2vec :dimensions 10 :epochs 50 :algo :skip-gram :negsample 3 :window 3))) (fit-from-string cbowhs text) ;; TODO: (assert-true (equal)) (format *test-stream* "cbowhs a: ~A~%" (transform cbowhs "a")) (fit-from-string cbowneg text) (format *test-stream* "cbowneg a: ~A~%" (transform cbowneg "a")) (fit-from-string sghs text) (format *test-stream* "a: ~A~%" (transform sghs "a")) (fit-from-string sgneg text) (format *test-stream* "a: ~A~%" (transform sgneg "a"))))
2,230
Common Lisp
.lisp
51
37.764706
108
0.611034
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c405d2ab6d030f9309f053e9ab60d5c4bdbaf174ce80aa537569ad2db6ac06d4
24,465
[ -1 ]
24,466
pgm-test.lisp
jnjcc_cl-nlp/test/pgm-test.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (define-test hmm-model-test (let ((states '("bull" "bear" "static")) (symbls '("up" "down" "unchanged")) (startp '(0.5 0.2 0.3)) (transp '((0.6 0.2 0.2) (0.5 0.3 0.2) (0.4 0.1 0.5))) (emissp '((0.7 0.1 0.2) (0.1 0.6 0.3) (0.3 0.3 0.4))) (hmm (make-instance 'hmm-model))) (cl-nlp::hmm-literal hmm states symbls startp transp emissp) (let ((obscorpus '(("up" "down" "up") ("unchanged" "unchanged" "unchanged" "unchanged" "unchanged" "up"))) (probs '(0.0509 0.0008)) (statcorpus '(("bull" "bear" "bull") ("static" "static" "static" "static" "static" "bull"))) (*float-zero-epsilon* 0.0001)) (dotimes (i (length obscorpus)) (assert-true (float= (nth i probs) (hmm-forward hmm (nth i obscorpus)))) (assert-true (float= (nth i probs) (hmm-backward hmm (nth i obscorpus)))) (assert-true (equal (nth i statcorpus) (mapcar #'cdr (hmm-decode hmm (nth i obscorpus)))))) )))
1,155
Common Lisp
.lisp
23
40.826087
91
0.538053
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
17641aa54e71f8ba19fd44a3e6d808e35146132d1037d5c11906df73a7ef6302
24,466
[ -1 ]
24,467
algo-test.lisp
jnjcc_cl-nlp/test/algo-test.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (define-test algo-dict-test (let* ((keys '("A" "B" "C")) (vals '( 1 2 3)) (badict (zip-badict keys vals)) (bhdict (zip-bhdict keys vals))) (assert-eq 1 (badict-ref badict "A")) (assert-eq 2 (badict-ref badict "B")) (assert-true (string= "C" (badict-bref badict 3))) (assert-eq nil (badict-ref badict "D")) (assert-eq nil (badict-bref badict 5)) (badict-add badict "A" 10) (assert-eq 10 (badict-ref badict "A")) (assert-true (string= "A" (badict-bref badict 10))) (assert-eq 3 (bhdict-ref bhdict "C")) (assert-true (string= "A" (bhdict-bref bhdict 1))) (assert-true (string= "B" (bhdict-bref bhdict 2))) (assert-eq nil (bhdict-ref bhdict "D")) (assert-eq nil (bhdict-bref bhdict 5)) (bhdict-add bhdict "B" 20) (assert-eq 20 (bhdict-ref bhdict "B")) (assert-true (string= "B" (bhdict-bref bhdict 20)))))
1,003
Common Lisp
.lisp
24
36.708333
66
0.610883
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
23112ffff9c980e262591cd53a02df623943e0412eef04444580d525889f5b47
24,467
[ -1 ]
24,468
tests.lisp
jnjcc_cl-nlp/test/tests.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (defun run-all-tests () (let ((result (run-tests :all :cl-nlp/test))) (test-names result) result))
210
Common Lisp
.lisp
7
27.285714
66
0.651741
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9a7ea3ffd29a044f2355bfaf1491e6178cf8a61211c3fa9c179d5c01a8215879
24,468
[ -1 ]
24,469
postag-test.lisp
jnjcc_cl-nlp/test/postag-test.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (define-test hmm-tagger-test (if (probe-file *treebank-dir*) (let* ((treebank (cl-nlp::load-treebank-dir *treebank-dir*)) (tagcorpus (cl-nlp::parse-treebank treebank)) (trains (subseq tagcorpus 0 3000)) (validation (subseq tagcorpus 0 100)) (sent nil) (hmmtag (make-instance 'hmm-tagger))) (hmm-learn hmmtag trains) (assert-eq 46 (length (hmm-states hmmtag))) (assert-eq 10767 (length (hmm-symbols hmmtag))) (let ((*float-zero-epsilon* 0.0001)) (assert-true (float= 0.1793 (hmm-start-prob hmmtag "NNP"))) (assert-true (float= 0.0000 (hmm-start-prob hmmtag "WP$"))) (assert-true (float= 0.0243 (hmm-start-prob hmmtag "-NONE-"))) (assert-true (float= 0.3901 (hmm-trans-prob hmmtag "NNP" "NNP"))) (assert-true (float= 0.0000 (hmm-trans-prob hmmtag "WP$" "NNP"))) (assert-true (float= 0.0061 (hmm-trans-prob hmmtag "NNP" "-NONE-"))) (assert-true (float= 0.0432 (hmm-emiss-prob hmmtag "NNP" "Mr."))) (assert-true (float= 0.9855 (hmm-emiss-prob hmmtag "." "."))) (assert-true (float= 0.1623 (hmm-emiss-prob hmmtag "-NONE-" "0")))) (setf sent (cl-nlp::untag-sentence (car trains))) (assert-true (equal (car trains) (hmm-decode hmmtag sent))) (assert-true (> (pos-evaluate hmmtag validation) 0.98)) (hmm-learn hmmtag trains :lidstone) (let ((*float-zero-epsilon* 0.0001)) ;; `SYM' only transition to `NNP' in train data, smooth with :lidstone (assert-true (float= 0.0178 (hmm-trans-prob hmmtag "SYM" "SYM")))) ) (error "treebank corpus needed (https://github.com/nltk/nltk)")))
1,842
Common Lisp
.lisp
33
46.545455
80
0.596676
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d3c06a7ecff7032856bdfddab70aa48d456be2c9ebbb05696c85eeeac9c13214
24,469
[ -1 ]
24,470
corpora-test.lisp
jnjcc_cl-nlp/test/corpora-test.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (define-test treebank-test (if (probe-file *treebank-dir*) (let* ((treebank (cl-nlp::load-treebank-dir *treebank-dir*)) (tagged (cl-nlp::parse-treebank treebank)) (tagone nil)) (assert-eq 3884 (length treebank)) (assert-eq 3884 (length tagged)) (setf tagone (nth 0 tagged)) (assert-true (equal '("Pierre" . "NNP") (first tagone))) (assert-true (equal '("." . ".") (car (last tagone)))) (setf tagone (nth 99 tagged)) (assert-true (equal '("Northeast" . "NNP") (first tagone))) (assert-true (equal '("0" . "-NONE-") (third tagone))) (assert-true (equal '("." . ".") (car (last tagone))))) (error "treebank corpus needed (https://github.com/nltk/nltk)"))) (define-test conll-chunk-test (with-open-file (conll-fp (merge-pathnames "conll/head.txt" *dataset-path*)) (let ((chunkt (read-file-content (merge-pathnames "conll/chunk.txt" *dataset-path*))) (postag (read-file-content (merge-pathnames "conll/pos.txt" *dataset-path*))) (output (make-adjustable-string))) (with-output-to-string (out-fp output) (cl-nlp::write-conll-chunk conll-fp out-fp)) (assert-true (string= chunkt output)) (setf output (make-adjustable-string)) (with-output-to-string (out-fp output) (file-position conll-fp 0) (cl-nlp::write-conll-pos conll-fp out-fp)) (assert-true (string= postag output))))) (define-test crfsuite-test (with-open-file (pos-fp (merge-pathnames "conll/pos.txt" *dataset-path*)) (let ((inst (cl-nlp::read-crf-instance pos-fp))) (assert-eq 37 (length inst)) (setf inst (cl-nlp::read-crf-instance pos-fp)) (assert-eq 23 (length inst)))))
1,850
Common Lisp
.lisp
37
42.972973
89
0.620709
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
fb44689a094fbc08b1dfda3e6abc4c4e4d5535d91b5c70e6ccd1d1ff76c45c44
24,470
[ -1 ]
24,471
common.lisp
jnjcc_cl-nlp/test/common.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (defvar *test-stream* nil) (defvar *float-zero-epsilon* 1.0e-10) (defun float= (a b) (<= (abs (- a b)) *float-zero-epsilon*)) (defun float/= (a b) (> (abs (- a b)) *float-zero-epsilon*)) (defun float< (a b) (and (float/= a b) (< (- a b) 0))) (defun make-adjustable-string () (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t))
470
Common Lisp
.lisp
14
31
75
0.621381
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
cb5eeb4738bc90859854a0793b53608f10340df9b5536809a8cfb6bda885619c
24,471
[ -1 ]
24,472
lm-test.lisp
jnjcc_cl-nlp/test/lm-test.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (define-test ngram-count-test (let ((text (format nil "~A~%~A~%~A~%~A" "One Ring to rule them all" "One Ring to find them" "One Ring to bring them all" "and in the darkness bind them")) wfreq wngram wmgram sorted idvocab idngram idngram2) (with-input-from-string (stream text) (setf wfreq (word-frequency stream)) (file-position stream 0) (setf wngram (wngram-count stream 2)) (assert-eq 3 (gethash "Ring" wfreq)) (assert-eq 2 (gethash "all" wfreq)) (assert-eq 1 (gethash "darkness" wfreq)) (assert-eq 3 (gethash "<BOS> One" wngram)) (assert-eq 2 (gethash "them <EOS>" wngram)) (assert-eq 1 (gethash "to rule" wngram)) (setf wmgram (ngram-mgram wngram 2 1)) (assert-true 3 (gethash "Ring" wmgram)) (assert-true 2 (gethash "all" wmgram)) (setf sorted (sorted-wngram wngram 2 1)) (assert-true (string= "Ring 3" (nth 1 sorted))) (assert-true (string= "all 2" (nth 2 sorted))) (setf idvocab (wfreq-idvocab wfreq)) (file-position stream 0) (setf idngram (idngram-count stream 2 idvocab)) ;; <BOS> One (assert-eq 3 (gethash "-1 1" idngram)) ;; them <EOS> (assert-eq 2 (gethash "3 -2" idngram)) (setf idngram2 (wngram-idngram wngram idvocab)) ;; <BOS> One (assert-eq 3 (gethash "-1 1" idngram2)) (assert-eq 2 (gethash "3 -2" idngram2)) ))) (define-test frequency-of-frequency-test (let ((text (format nil "One Ring to rule them all them all")) (bos "<BOS>") (eos "<EOS>") wngram fof) (with-input-from-string (stream text) ;;; trigram: ;; <One Ring to 1>, <Ring to rule 1>, <to rule them 1>, <rule them all 1>, <them all them 1>, <all them all 1>, ;; <BOS BOS One 1>, <BOS One Ring 1>, <them all EOS 1> ;;; biggram: ;; <One Ring 1>, <Ring to 1>, <to rule 1>, <rule them 1>, <all them 1>, <them all 2> ;; <BOS One 1>, <all EOS 1> ;;; unigram: ;; <One 1>, <Ring 1>, <to 1>, <rule 1>, <them 2>, <all 2> (setf wngram (wngram-count stream 3 :bos bos :eos eos)) (setf fof (fof-from-ngram wngram 3 :disc 7 :uni 3 :bos bos :eos eos)) ;; bigram (assert-eq 7 (fof-ref fof 2 1)) (assert-eq 1 (fof-ref fof 2 2)) ;; we also recorded frequency of frequency-(disc+1) (assert-eq 0 (fof-ref fof 2 8)) ;; unigram (assert-eq 4 (fof-ref fof 1 1)) (assert-eq 2 (fof-ref fof 1 2)) (file-position stream 0) (setf wngram (wngram-count stream 3 :bos nil :eos nil)) (setf fof (fof-from-ngram wngram 3 :disc 7 :uni 3)) ;; unigram (assert-eq 6 (fof-ref fof 1 1)) ;; NOTICE: without `eos', the last two word `them' and `all' are lost... (assert-eq 0 (fof-ref fof 1 2))))) (define-test idngram-tree-test ;; idngram contents: ;; 1 1 2 1 ;; 1 2 1 1 ;; 1 2 3 1 ;; 2 1 1 1 ;; 2 3 4 1 ;; 3 4 5 1 ;; 4 5 6 1 ;; 5 6 7 1 (with-open-file (idfp (merge-pathnames "lm/idngram.tree" *dataset-path*)) (let* ((idmax 7) ;; 7 words in idngram file (idinfo (cl-nlp::idngram-tree (read-ngram idfp) 3 idmax :disc 7 :uni 3))) (assert-eq 3 (cl-nlp::idm-get-fof idinfo 1 1)) ;; NOTICE: there should have been 8 bigrams, without <EOS> extending, we lost "6 7" (assert-true (equalp '(0 7 7 8) (cl-nlp::mgram-nums idinfo))) (assert-eq 2 (cl-nlp::idm-get-freq idinfo 2 2)) (assert-eq 3 (cl-nlp::idm-get-wdid idinfo 2 4)) (assert-eq 1.0 (cl-nlp::idm-get-alpha idinfo 2 2)) ;; the 1-th unigram ("1") points to the 2-th bigram ("1 2") ;; thus "1" spans 1-th to 2-th bigram ("1 1" and "1 2") (assert-eq 2 (cl-nlp::idm-get-ptrs idinfo 1 1)) ;; the 2-th unigram ("2") points to the 4-th bigram ("2 3") ;; thus "2" spans 3-th to 4-th bigram ("2 1" and "2 3") (assert-eq 4 (cl-nlp::idm-get-ptrs idinfo 1 2)) ;; the 5-th unigram ("5") points to the 7-th bigram ("5 6") ;; as well as the 6-th and 7-th unigram (assert-eq 7 (cl-nlp::idm-get-ptrs idinfo 1 5)) (assert-eq 7 (cl-nlp::idm-get-ptrs idinfo 1 6)) (assert-eq 7 (cl-nlp::idm-get-ptrs idinfo 1 7)) ;; the 1-th bigram ("1 1") points to the 1-th trigram ("1 1 2") (assert-eq 1 (cl-nlp::idm-get-ptrs idinfo 2 1)) ;; the 2-th bigram ("1 2") points to the 3-th trigram ("1 2 3") ;; thus "1 2" spans 2-th to 3-th trigram ("1 2 1" and "1 2 3") (assert-eq 3 (cl-nlp::idm-get-ptrs idinfo 2 2))))) (define-test idngram-lm-test (with-open-file (fcorpus (merge-pathnames "lm/corpus.lm" *dataset-path*)) (let ((n 3) (disc-type :good-turing) (disc-range 2) (uni-range 1) (oov :open) (unk "<UNK>") wfreq idvocab idngram) (setf wfreq (word-frequency fcorpus)) (setf idvocab (wfreq-idvocab wfreq)) (file-position fcorpus 0) (setf idngram (idngram-count fcorpus n idvocab :bos nil :eos nil)) (multiple-value-bind (idminfo id2word idmin idmax) (cl-nlp::idngram-lm idngram n idvocab :disc-type disc-type :disc-range disc-range :uni-range uni-range :oov oov :unk unk :bos nil :eos nil) (declare (ignore id2word idmin idmax)) (let ((*float-zero-epsilon* 1.0e-4)) (assert-true (float= 0.0134 (cl-nlp::idm-get-uprob idminfo 1))) (assert-true (float= 0.0278 (cl-nlp::idm-get-uprob idminfo 5))) (assert-true (float= 0.0556 (cl-nlp::idm-get-uprob idminfo 11))) (assert-true (float= 0.1250 (cl-nlp::idm-get-uprob idminfo 36))) ) )))) (define-test ngram-lm-test (with-open-file (corpus-fp (merge-pathnames "lm/corpus.lm" *dataset-path*)) (let ((n 3) (disc-range 2) (uni-range 1) (lmarpa (read-file-content (merge-pathnames "lm/arpa.lm" *dataset-path*))) (lmstring (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t))) (with-output-to-string (lm-fp lmstring) (ngram-lm corpus-fp n lm-fp :disc-range disc-range :uni-range uni-range :bos nil :eos nil)) (assert-true (string= lmarpa lmstring)))))
6,393
Common Lisp
.lisp
138
38.775362
117
0.582986
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
85497826ee113e9cd2e9cd4b87edafbdc6b6b95b748245adfd80fe3da989f2b3
24,472
[ -1 ]
24,473
packages.lisp
jnjcc_cl-nlp/test/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-user) (defpackage #:cl-nlp/test (:nicknames #:nlp/test) (:use #:cl #:lisp-unit #:cl-nlp/algo #:cl-nlp #:cl-ml/io) (:export #:run-all-tests))
246
Common Lisp
.lisp
8
27.75
66
0.622881
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
fd7486f90be8411a54cfd1c9933bd3e6e5ba504db6c78b6fb220a69dca5ff92b
24,473
[ -1 ]
24,474
dataset.lisp
jnjcc_cl-nlp/test/dataset.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp/test) (defvar *dataset-path* (merge-pathnames "test/dataset/" (asdf:system-source-directory :cl-nlp-test))) (defvar *nltk-path* (merge-pathnames "nltk_data/" (user-homedir-pathname))) (defvar *treebank-dir* (merge-pathnames "corpora/treebank/combined/" *nltk-path*))
404
Common Lisp
.lisp
7
50.428571
85
0.656489
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9c618cd07bac9612286777e255ca9e7b4da6831b32a3b2c3a40cbff292ff354c
24,474
[ -1 ]
24,475
csgd.lisp
jnjcc_cl-nlp/pgm/csgd.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; SGD for CRF (in-package #:cl-nlp) (defmethod crf-learn-sgd ((crf crf-model) crfdata) ) ;;; Given `inst', expectation of feature function under empirical distribution ;;; w[k] <- w[k] + eta * \sum_{t=1}^{T}f[k](y', y, x, t) ;;; or in vector form: ;;; w <- w + eta * F(y, x) (defmethod csgd-emp-exp ((crf crf-model) inst eta) (with-slots (statef transf sweigt tweigt) crf (let ((plid nil)) (do-crf-item (lid attrs inst) ;; `lid' -> `aid': state feature (do-crf-attr (aid scale attrs) (fdist-cond-incf sweigt lid aid (* eta scale))) ;; `plid' -> `lid': transition feature (when plid (fdist-cond-incf tweigt plid lid eta)) (setf plid lid) )))) ;;; Given `inst', expectation of feature function under model distribution ;;; w <- w + eta * (-P(y|x)) * F(y, x) (defmethod csgd-mod-exp ((crf crf-model) inst eta) ) (defmethod csgd-gradient ((crf crf-model) inst eta) )
1,035
Common Lisp
.lisp
28
32.714286
78
0.605788
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f6dcc26de28f21a4da353eaf932a7e75c241385b3ba1b0c8560cc428431ba1a1
24,475
[ -1 ]
24,476
hmm.lisp
jnjcc_cl-nlp/pgm/hmm.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; (First-order) Hidden Markov Model $\lambda = (S, V, \pi, A, B)$: ;;;; - The Evaluation Problem and the Forward / Backward Algorithm ;;;; - The Decoding Problem and the Viterbi Algorithm ;;;; - The Learning Problem and the MLE / Baum-Welch Algorithm (in-package #:cl-nlp) ;;; states: a set of hidden states ;;; - stateseq: state sequence, (state state ...) ;;; - statecorpus: a collection of state sequence, (stateseq stateseq ...) ;;; observation symbols: a set of symbols ;;; - obsseq: observation sequence, (symbol symbol ...) ;;; - obscorpus: a collection of observation sequence, (obsseq obsseq ...) ;;; - compseq: complete-data, observation with associated state, ((symbol . state) ...) ;;; - compcorpus: complete-data, (compseq compseq ...) (defclass hmm-model () ((testfn :initform 'equal :initarg :test :documentation "hash key test function") (states :initform nil :documentation "HMM states S as a list") (symbls :initform nil :documentation "HMM symbols V as a list") (startp :initform nil :documentation "HMM start probability \pi") (transp :initform nil :documentation "HMM transition probability A") (emissp :initform nil :documentation "HMM emission probability B"))) (defmethod reset-states ((hmm hmm-model)) (with-slots (testfn states symbls startp transp emissp) hmm (setf states (make-freq-dist :hash :test testfn)) (setf symbls (make-freq-dist :hash :test testfn)) (setf startp (make-freq-dist :hash :test testfn)) (setf transp (make-cond-freq :test testfn)) (setf emissp (make-cond-freq :test testfn)))) (defmethod hmm-states ((hmm hmm-model)) (with-slots (states) hmm states)) (defmethod hmm-symbols ((hmm hmm-model)) (with-slots (symbls) hmm symbls)) (defmethod hmm-start-prob ((hmm hmm-model) state) (with-slots (startp) hmm (pdist-prob startp state))) (defmethod hmm-start-probi ((hmm hmm-model) is) "start probability for `is'-th state" (with-slots (states) hmm (hmm-start-prob hmm (nth is states)))) (defmethod hmm-trans-prob ((hmm hmm-model) state1 state2) (with-slots (transp) hmm (pdist-cond-prob transp state1 state2))) (defmethod hmm-trans-probi ((hmm hmm-model) is1 is2) "transition probability from `is1'-th state to `is2'-th state" (with-slots (states) hmm (hmm-trans-prob hmm (nth is1 states) (nth is2 states)))) (defmethod hmm-emiss-prob ((hmm hmm-model) state symbl) (with-slots (emissp) hmm (pdist-cond-prob emissp state symbl))) (defmethod hmm-emiss-probi ((hmm hmm-model) is symbl) (with-slots (states) hmm (hmm-emiss-prob hmm (nth is states) symbl))) ;;; The Evaluation Problem and the Forward / Backward Algorithm (defmethod hmm-forward-alpha ((hmm hmm-model) obsseq) "T by N array of probabilities, with T being length of the sequence and N being number of states. `alpha[t][s]': the probability of being in state s at time t after observing the partial symbol sequence up to and including t" (with-slots (states symbls) hmm (let* ((symT (length obsseq)) (statN (length states)) (alpha (make-array `(,symT ,statN) :initial-element 0))) (let ((symbl (nth 0 obsseq))) (dotimes (i statN) (setf (aref alpha 0 i) (* (hmm-start-probi hmm i) (hmm-emiss-probi hmm i symbl))))) (loop for ts from 1 below symT do (dotimes (i statN) (dotimes (j statN) (incf (aref alpha ts i) (* (aref alpha (- ts 1) j) (hmm-trans-probi hmm j i) (hmm-emiss-probi hmm i (nth ts obsseq))))))) alpha))) (defmethod hmm-forward ((hmm hmm-model) obsseq) (with-slots (states symbls) hmm (let ((prob 0.0) (symT (length obsseq)) (statN (length states)) (alpha (hmm-forward-alpha hmm obsseq))) (dotimes (i statN) (incf prob (aref alpha (- symT 1) i))) (values prob alpha)))) (defmethod hmm-backward-beta ((hmm hmm-model) obsseq) "T by N array of probabilities. `beta[t][s]': the probability of being in state s at time t after observing the partial symbol sequence from t ... T" (with-slots (states symbls) hmm (let* ((symT (length obsseq)) (statN (length states)) (beta (make-array `(,symT ,statN) :initial-element 0))) (dotimes (i statN) (setf (aref beta (- symT 1) i) 1)) (loop for ts from (- symT 2) downto 0 do (dotimes (i statN) (dotimes (j statN) (incf (aref beta ts i) (* (aref beta (+ ts 1) j) (hmm-trans-probi hmm i j) (hmm-emiss-probi hmm j (nth (+ ts 1) obsseq))))))) beta))) (defmethod hmm-backward ((hmm hmm-model) obsseq) "T by N array of probabilities. `beta[t][s]': the probability of being in state s at time t after observing the partial symbol sequence from t ... T" (with-slots (states symbls) hmm (let ((statN (length states)) (beta (hmm-backward-beta hmm obsseq)) (prob 0.0)) (let ((symbl (nth 0 obsseq))) (dotimes (i statN) (incf prob (* (hmm-start-probi hmm i) (hmm-emiss-probi hmm i symbl) (aref beta 0 i))))) (values prob beta)))) ;;; The Decoding Problem and the Viterbi Problem (defmethod %fill-symbol-index ((hmm hmm-model) obsseq) (with-slots (symbls) hmm (let ((symidx (make-hash-table :test 'equal))) (let ((idx 0)) (dolist (symbl obsseq) (setf (gethash symbl symidx) idx) (incf idx)) (dolist (symbl obsseq) ;; we know for sure `nil' means not exist in this context (unless (gethash symbl symidx) (setf (gethash symbl symidx) idx) (incf idx)))) symidx))) (defmethod hmm-decode ((hmm hmm-model) obsseq) "decode hidden states for symbol sequence `obsseq' using Viterbi algorithm" (with-slots (states symbls) hmm (let* (;; length of test `obsseq' (symT (length obsseq)) ;; number of states (statN (length states)) ;; records max probability leading to each possible state at time step t (delta (make-array `(,symT ,statN) :initial-element 0)) ;; backtrace (backtrace (make-array `(,symT ,statN) :initial-element -1))) (let ((symbl (nth 0 obsseq))) (dotimes (i statN) (setf (aref delta 0 i) ;; delta[1][i] (logprod (hmm-start-probi hmm i) (hmm-emiss-probi hmm i symbl))))) ;; t = 2, 3, ..., T (loop for ts from 1 below symT do (dotimes (i statN) (let (best argbest curr) (dotimes (j statN) (setf curr (rlogprod (aref delta (- ts 1) j) (hmm-trans-probi hmm j i))) (when (or (null best) (> curr best)) (setf best curr) (setf argbest j))) (setf (aref delta ts i) (rlogprod best (hmm-emiss-probi hmm i (nth ts obsseq)))) (setf (aref backtrace ts i) argbest)))) (let (best argbest curr tags) (dotimes (i statN) (setf curr (aref delta (- symT 1) i)) (when (or (null best) (> curr best)) (setf best curr) (setf argbest i))) (push (cons (car (last obsseq)) (nth argbest states)) tags) (loop for ts from (- symT 1) downto 1 do (setf argbest (aref backtrace ts argbest)) (push (cons (nth (- ts 1) obsseq) (nth argbest states)) tags)) tags)))) ;;; The Learning Problem - 1: ;;; HMM model from probability literal (defmethod hmm-literal ((hmm hmm-model) Slst Vlst pilst Amat Bmat) (with-slots (states symbls startp transp emissp) hmm (setf states Slst) (setf symbls Vlst) (setf startp (derive-literal states pilst)) (setf transp (derive-cond-literal states states Amat)) (setf emissp (derive-cond-literal states symbls Bmat)))) ;;; The Learning Problem - 2: ;;; MLE from complete corpus (defmethod hmm-learn ((hmm hmm-model) compcorpus &optional etype) (reset-states hmm) (with-slots (states symbls startp transp emissp) hmm (unless etype (setf etype :mle)) (dolist (compseq compcorpus) (let ((pre-stat nil) symb stat) (dolist (pair compseq) (setf symb (car pair)) (fdist-incf symbls symb) (setf stat (cdr pair)) (fdist-incf states stat) (if pre-stat (fdist-cond-incf transp pre-stat stat) (fdist-incf startp stat)) (fdist-cond-incf emissp stat symb) (setf pre-stat stat)))) (setf states (fdist-keys states)) (setf symbls (fdist-keys symbls)) (setf startp (derive-prob startp (length states) etype)) (setf transp (derive-cond-prob transp (length states) etype)) (setf emissp (derive-cond-prob emissp (length symbls) etype)))) ;;; The Learning Problem - 3: ;;; Baum-Welch algorithm from incomplete corpus (defmethod hmm-init-random ((hmm hmm-model) stats syms) (let* ((statN (length stats)) (symM (length syms)) (pilst (randprob1d statN)) (Amat (randprob2d statN statN)) (Bmat (randprob2d statN symM))) (hmm-literal hmm stats syms pilst Amat Bmat))) (defmethod hmm-fb-arrays ((hmm hmm-model) obsseq) "forward and backward arrays" (multiple-value-bind (fzprob alpha) (hmm-forward hmm obsseq) (multiple-value-bind (bzprob beta) (hmm-backward hmm obsseq) (values fzprob alpha beta bzprob)))) (defmethod hmm-bw-arrays ((hmm hmm-model) symT statN obsseq alpha beta zprob) "gamma[t][i]: P(s[t] = i); xi[t][i][j]: P(s[t+1] = j | s[t] = i)" (let ((gamma (make-array (list symT statN) :initial-element 0.0)) (xi (make-array (list (- symT 1) statN statN) :initial-element 0.0))) (dotimes (ts symT) (dotimes (i statN) (setf (aref gamma ts i) (/ (* (aref alpha ts i) (aref beta ts i)) zprob)) (unless (= ts (- symT 1)) (dotimes (j statN) (setf (aref xi ts i j) (/ (* (aref alpha ts i) (hmm-trans-probi hmm i j) (hmm-emiss-probi hmm j (nth (+ ts 1) obsseq)) (aref beta (+ ts 1) j)) zprob)))))) (values gamma xi))) (defmethod hmm-baum-welch ((hmm hmm-model) incomplete) (with-slots (states symbls startp transp emissp) hmm (let ((statN (length states)) (symT nil)) (dolist (obsseq incomplete) (setf symT (length obsseq)) (multiple-value-bind (fzprob alpha beta bzprob) (hmm-fb-arrays hmm obsseq) (unless (float= fzprob bzprob) (format t "forward probability != backward probability~%")) (multiple-value-bind (gamma xi) (hmm-bw-arrays hmm symT statN obsseq alpha beta fzprob) (dotimes (i statN) (pdist-setf startp (nth i states) (aref gamma 0 i)) (let ((numer 0.0) (denom 0.0)) (dotimes (j statN) (setf numer 0.0) (setf denom 0.0) (dotimes (ts (- symT 1)) (incf numer (aref xi ts i j)) (incf denom (aref gamma ts i))) (pdist-cond-setf transp (nth i states) (nth j states) (/ numer denom))) (dotimes (k (length symbls)) (setf numer 0.0) (setf denom 0.0) (dotimes (ts symT) (incf denom (aref gamma ts i)) (when (equal (nth ts obsseq) (nth k symbls)) (incf numer (aref gamma ts i)))) (pdist-cond-setf emissp (nth i states) (nth k symbls) (/ numer denom))))))))))) (defmethod hmm-learn-bw ((hmm hmm-model) stats symbs incomplete &optional (epochs 10)) (hmm-init-random hmm stats symbs) (dotimes (ep epochs) (hmm-baum-welch hmm incomplete)))
12,176
Common Lisp
.lisp
262
37.721374
97
0.598014
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
42de68d2bed9b6157ba11ed5b2f235bf485e75bec251ed18ff75a0418b2cef11
24,476
[ -1 ]
24,477
crf.lisp
jnjcc_cl-nlp/pgm/crf.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; (First-order, linear-chain) Conditional Random Fields (in-package #:cl-nlp) ;;; using CRFsuite jargons: ;;; - `attrsd': attribute name bidictionary ;;; - `labeld': label name bidictionary (defclass crf-model () ((attrsd :initform nil :documentation "attribute name dictionary: attr-name <-> index") (labeld :initform nil :documentation "label name dictionary: labl-name <-> index") (statef :initform nil :documentation "state feature f(s, x, t) as a 2D array-like [s][aid], like Unigram features in CRF++, which generates |Y| x |U| features") (transf :initform nil :documentation "transition feature f(s', s, x, t) as a 2D array-like [s'][s], NOTICE: should have been a 3D array-like [s'][s][aid], like Bigram features in CRF++, which generates |Y| x |Y| x |B| features") (sweigt :initform nil :documentation "CRF model weights for state features") (tweigt :initform nil :documentation "CRF model weights for transition features"))) (defmethod generate-features ((crf crf-model) crfdata) (with-slots (transf statef tweigt sweigt) crf (setf transf (make-cond-freq)) (setf statef (make-cond-freq)) (let ((plid nil)) (do-crf-instance (inst crfdata) (setf plid nil) (do-crf-item (lid attrs inst) (when plid ;; transition feature: <(s', s), 1> (fdist-cond-incf transf plid lid 1)) (do-crf-attr (aid scale attrs) ;; state feature: <(s, aid), scale> (fdist-cond-incf statef lid aid scale)) (setf plid lid)))) (setf sweigt (copy-mutable-dcond statef :fill-value 0)) (setf tweigt (copy-mutable-dcond transf :fill-value 0)) (do-cond-pairs (lid aid scale statef) (format t "~A -> ~A: ~A~%" (crfdata-get-labl crfdata lid) (crfdata-get-aname crfdata aid) scale)) (do-cond-pairs (plid lid val transf) (format t "~A -> ~A: ~A~%" (crfdata-get-labl crfdata plid) (crfdata-get-labl crfdata lid) val)) )) (defmethod crf-potential-one ((crf crf-model) item) (let ((ptval 0)) ;; (car item) being a list, holding label, and possibly word itself ;; e.g. ("NN" "Confidence") ptval)) (defmethod crf-potential ((crf crf-model) inst) (with-slots (states weight) crf (let* ((inT (length inst)) (ptt-list nil)) ))) (defmethod crf-forward-alpha ((crf crf-model) inst) (with-slots (states weight) crf (let* ((inT (length inst)) (stN (length states)) (alpha (make-array (list (+ inT 2) stN) :initial-element 0))) alpha))) (defmethod crf-backward-beta ((crf crf-model) inst) (with-slots (states weight) crf )) (defmethod crf-learn ((crf crf-model) crfdata &optional (algo :sgd)) (etypecase algo (:sgd (crf-learn-sgd crf crfdata))))
2,868
Common Lisp
.lisp
63
40.047619
102
0.646049
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d721fb8e0fd539b418b0ee0d14f4702fcf697a6cc3986bd491eecd4db35b6614
24,477
[ -1 ]
24,478
foftab.lisp
jnjcc_cl-nlp/lm/foftab.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; frequency of frequency table for ngram (in-package #:cl-nlp) ;;; m-gram list reference with index starting from 0: ;;; - proxy list reference for each m-gram (0 <= m <= n) of n-gram ;;; + list elements: some statistics about a certain m-gram ;;; - proxy list reference for n-gram ;;; + list elements: each element of n-gram (defun mlist-init (n &key (initial-element 0)) "NOTICE: reserve place for a fake 0-gram for convenience" (make-list (+ n 1) :initial-element initial-element)) (defun mlist-copy (mlist) (copy-list mlist)) (defun mlist-ref (mlist m) (nth m mlist)) (defun mlist-setf (mlist m val) (setf (nth m mlist) val)) (defun mlist-incf (mlist m &optional (delta 1)) (incf (nth m mlist) delta)) ;;; m-gram list-of-list, with outer index starting from 1, inner index starting from 0: ;;; - proxy list-of-list reference for each m-gram (1 <= m <= n) of n-gram ;;; + outer: a certain m-gram; inner: each element of m-gram, or a `mlist' as above (defun lol-init (n) "NOTICE: for each m-gram, reserve an extra 0-th m-gram for convenience" (let ((lol (make-list n :initial-element nil))) (dotimes (i n) (setf (nth i lol) (make-list 1 :initial-element 0))) lol)) (defun lol-get (lol m) "get info about a certain m-gram, return a `mlist'" (nth (- m 1) lol)) ;; combined `lol-get' and `lol-mref' (defun lol-ref (lol m idx) "access info (e.g., frequency) for `idx'-th m-gram, where `idx' starts from 0, which is just for convenience" (nth idx (nth (- m 1) lol))) (defun lol-aset (lol m cur-len val) "we are appending (and setting) each m-gram one by one" ;; remember the extra 0-th m-gram, thus total length will be (cur-len + 1) (if (= (length (nth (- m 1) lol)) (+ cur-len 1)) (setf (nth (- m 1) lol) (append (nth (- m 1) lol) (list val))) (error "something bad happens..."))) (defun lol-setf (lol m idx val) (setf (nth idx (nth (- m 1) lol)) val)) ;;; frequency of frequency table for n-gram language model ;;; truncated `list-of-list' (by *fof-disc-range* and *fof-uni-range*) (defvar *fof-disc-range* 7) (defvar *fof-uni-range* 3) (defun fof-init (n &optional (disc-range *fof-disc-range*) (uni-range *fof-uni-range*)) (let ((fof (make-list n :initial-element 0))) (dotimes (i (length fof)) (if (= i 0) (setf (nth 0 fof) (make-list (+ uni-range 2) :initial-element 0)) ;; we also need to remember the frequency of frequency 0 and (+ disc-range 1) ;; for discounting purpose, thus the "+2" operation (setf (nth i fof) (make-list (+ disc-range 2) :initial-element 0)))) fof)) (defun fof-disc (fof m) "return discount range for m-gram" (- (length (nth (- m 1) fof)) 2)) (defun fof-copy-init (fof) "copy frequency of frequency table and initialize discount ratio to 1.0" (let ((copy (make-list (length fof) :initial-element 1.0))) (dotimes (i (length fof)) (setf (nth i copy) (make-list (length (nth i fof)) :initial-element 1.0))) copy)) (defun fof-ref (fof m freq) "frequency of frequency `freq' in `m' gram" (when (< freq (length (nth (- m 1) fof))) (nth freq (nth (- m 1) fof)))) (defun fof-setf (fof m freq val) (when (< freq (length (nth (- m 1) fof))) (setf (nth freq (nth (- m 1) fof)) val))) (defun fof-incf (fof m freq &optional (delta 1)) (when (< freq (length (nth (- m 1) fof))) (incf (nth freq (nth (- m 1) fof)) delta))) (defun fof-from-ngram (ngram n &key (disc *fof-disc-range*) (uni *fof-uni-range*) (bos "-1") (eos "-2")) "Only discount frequencies less than discount-range `disc' for m-grams (m > 1), the belief being that events occurring more than `disc' times are well estimated by MLE Requires: `bos' and `eos' non-NIL" (let* ((fof (fof-init n disc uni)) (sorted (sorted-extend ngram n :eos eos)) ;; it is ok we sort by alphabetical order even if idngram (pre-gram (caar sorted)) (pre-freq (cdar sorted)) (m 1) ;; `running-total' for 1, 2, ..., n-gram (NOTICE: each m-gram's are sorted) (running-total (mlist-init n :initial-element pre-freq)) (cur-gram nil) (cur-freq nil) (diff-pos 0)) (dotimes (i (- (length sorted) 1)) ;; starting from 1-th index (setf cur-gram (car (nth (+ i 1) sorted)) cur-freq (cdr (nth (+ i 1) sorted))) (setf diff-pos n) (dotimes (j n) (when (string/= (nth j cur-gram) (nth j pre-gram)) (setf diff-pos j) (return))) (when (= diff-pos n) (error "same gram [~A] appears" (join-strings cur-gram))) (dotimes (d n) ;; `pre-gram'[0, d], which is (d+1)-gram (setf m (+ d 1)) (unless (%malformed-gram pre-gram m bos eos) ;; [0, m), [0, m+1), ..., [0, n) of `cur-gram' are new m-grams (when (> m diff-pos) (fof-incf fof m (mlist-ref running-total m)) (mlist-setf running-total m 0)) (mlist-incf running-total m cur-freq))) (setf pre-gram cur-gram)) ;; one last gram (dotimes (d n) (setf m (+ d 1)) (unless (%malformed-gram pre-gram m bos eos) (fof-incf fof m (mlist-ref running-total m))) (mlist-setf running-total m 0)) fof))
5,339
Common Lisp
.lisp
119
39.907563
108
0.615769
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b380964287aef056a997618301cf0d6d623cad71b2ab89e3762bb50d5d4baf0c
24,478
[ -1 ]
24,479
backoff.lisp
jnjcc_cl-nlp/lm/backoff.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp) (defun %get-next-pointer (curidxs m idminfo) "given `curidxs[m]' as the current m-gram, what is the latest (m+1)-gram it points to?" (if (= (mlist-ref curidxs m) (idm-get-gnum idminfo m)) ;; points to the last (m+1)-gram (idm-get-gnum idminfo (+ m 1)) (idm-get-ptrs idminfo m (mlist-ref curidxs m)))) (defun %fill-next-pointer (curidxs m idminfo endidxs &key (verbose nil)) "given `curidxs[m-1]' as the current (m-1)-gram, fill `endidxs[m]'" (mlist-setf endidxs m (%get-next-pointer curidxs (- m 1) idminfo)) (when verbose (format t "~A-th ~A-gram points to ~A-th ~A-gram~%" (mlist-ref curidxs (- m 1)) (- m 1) (mlist-ref endidxs m) m))) (defun %sum-cond-probs (curidxs endidxs m idminfo) "current (m-1)-gram `curidxs[m-1]' spans from `curidxs[m]' to `endidxs[m]'-th m-gram, sum of conditional probability might not be 1.0, as frequency might be discounted" (let ((mgfreq nil) ;; current m-gram frequency (might be discounted) (condpr 0.0) ;; conditional probability: P(C|AB) (sumcpr 0.0) ;; sum of conditional probability (katzpr 0.0) (sumkatz 0.0)) (do ((idx (mlist-ref curidxs m) (mlist-ref curidxs m))) ((> idx (mlist-ref endidxs m))) (setf mgfreq (idm-get-freq idminfo m idx)) (setf mgfreq (idm-discount-freq idminfo m mgfreq)) ;; P(C|AB) = freq(ABC) / freq(AB) (setf condpr (/ mgfreq (idm-get-freq idminfo (- m 1) (mlist-ref curidxs (- m 1))))) (incf sumcpr condpr) (let ((idlist nil)) ;; backoff: from (w1, w2, w3) to (w2, w3) (loop for k from 2 to m do (push (idm-get-wdid idminfo k (mlist-ref curidxs k)) idlist)) (setf katzpr (katz-backoff (nreverse idlist) (- m 2) idminfo)) (incf sumkatz katzpr)) (mlist-incf curidxs m)) (values sumcpr sumkatz))) (defmethod idm-backoff-gram ((idminfo idinfo-type) n idmin idmax) "backoff alpha for n-gram (n >= 2)" (with-slots (mgram-alphas) idminfo (let ((cgm 1) ;; current gram m ;; `curidxs'-th m-gram, only unigram needs the fake 0-th gram (curidxs (mlist-init (+ n 1) :initial-element 1)) ;; `curidxs'-th m-gram points to `endidxs'-th (m+1)-gram (endidxs (mlist-init (+ n 1) :initial-element 0))) (loop for id from idmin to idmax do (mlist-setf curidxs 1 id) ;; for each unigram, possibly starting from 0 (cond ((= (idm-get-freq idminfo 1 id) 0) ;; deal with zeroton unigrams (when (= n 2) (idm-setf-alpha idminfo 1 (mlist-ref curidxs 1) 1.0))) ((> (idm-get-freq idminfo 1 id) 0) (progn (setf cgm 2) (%fill-next-pointer curidxs cgm idminfo endidxs) (do ((cgm 2)) ((<= cgm 1)) (cond ((= cgm n) (multiple-value-bind (sumcpr sumkatz) (%sum-cond-probs curidxs endidxs cgm idminfo) (let ((leftmass (- 1.0 sumcpr)) (leftkatz (- 1.0 sumkatz))) (if (<= leftkatz 1e-10) (idm-setf-alpha idminfo (- n 1) (mlist-ref curidxs (- n 1)) 0.0) (idm-setf-alpha idminfo (- n 1) (mlist-ref curidxs (- n 1)) (/ leftmass leftkatz)))) ;; current (m-1)-gram finished, explore next (m-1)-gram (decf cgm) (when (> cgm 1) (mlist-incf curidxs cgm)))) ;; `cgm' < n: (m+1)-gram might be available to explore ((< cgm n) (if (<= (mlist-ref curidxs cgm) (mlist-ref endidxs cgm)) (progn (incf cgm) (%fill-next-pointer curidxs cgm idminfo endidxs)) (progn (decf cgm) (when (> cgm 1) (mlist-incf curidxs cgm))))))))))) )))
4,409
Common Lisp
.lisp
83
37.927711
103
0.502661
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
2a42a2e03b8fa109c64e6a78ddd171917035038dc8216c1e43260a50e707ff84
24,479
[ -1 ]
24,480
katz.lisp
jnjcc_cl-nlp/lm/katz.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Katz Backoff Model (in-package #:cl-nlp) (defun %get-next-index (idx m idminfo) "given `idx' as the current m-gram, what is the latest (m+1)-gram it points to?" (if (= idx (idm-get-gnum idminfo m)) ;; points to the last (m+1)-gram (idm-get-gnum idminfo (+ m 1)) (idm-get-ptrs idminfo m idx))) (defun %binary-search (idminfo m beg end wdid) (do ((mid nil)) ((> beg end)) (setf mid (+ beg (floor (- end beg) 2))) (cond ((< wdid (idm-get-wdid idminfo m mid)) (setf end (- mid 1))) ((> wdid (idm-get-wdid idminfo m mid)) (setf beg (+ mid 1))) ((= wdid (idm-get-wdid idminfo m mid)) (return-from %binary-search mid)))) (return-from %binary-search nil)) (defun %find-sub-gram (idlist h idminfo curidxs) "Given `idlist' (H, w), where H is of length h, find sub-gram and write index into `curidxs' e.g. let `idlist' = (6 5 2), we want to know if (6), (6 5) and (6 5 2) exists in turn, which is of length 1, 2, ..., (h+1)" (let ((glen 0) (exists nil)) (do ((m 1 (+ m 1))) ((> m (+ h 1))) (setf exists nil) (cond ((= m 1) (when (> (idm-get-freq idminfo 1 (car idlist)) 0) (setf exists t) (mlist-setf curidxs 1 (car idlist)))) ((> m 1) (let* ((pm (- m 1)) (idx (mlist-ref curidxs pm)) ;; `idx'-th (m-1)-gram spans from (`beg'+1) to `end'-th m-gram (beg (%get-next-index (- idx 1) pm idminfo)) (end (%get-next-index idx pm idminfo))) (incf beg) (setf exists (%binary-search idminfo m beg end (nth (- m 1) idlist))) (when exists (mlist-setf curidxs m exists))))) (if exists ;; Hooray! current m-gram exists! (incf glen) (return))) glen)) (defun katz-backoff (idlist h idminfo) "pKatz(w|H) for `idlist' (H, w), where H is of length h" (let ((prob nil) (mgfreq 0.0) ;; C(H, w) (hgfreq 0.0) ;; C(H) (alpha 0.0)) (if (= 0 h) ;; no history, fall back to unigram probability (setf prob (idm-get-uprob idminfo (car idlist))) (let ((curidxs (mlist-init (+ h 1) :initial-element 0)) (glen 0)) ;; sub gram length found (setf glen (%find-sub-gram idlist h idminfo curidxs)) (cond ((= glen (+ h 1)) ;; C(H, w) > 0, and thus C(H) > 0 (progn (setf mgfreq (idm-get-freq idminfo glen (mlist-ref curidxs glen))) (setf mgfreq (idm-discount-freq idminfo glen mgfreq)) (setf hgfreq (idm-get-freq idminfo h (mlist-ref curidxs h))) (setf prob (/ mgfreq hgfreq)))) ((>= glen h) ;; C(H) > 0 (progn (setf hgfreq (idm-get-freq idminfo h (mlist-ref curidxs h))) (setf alpha (idm-get-alpha idminfo h (mlist-ref curidxs h))) (setf prob (katz-backoff (cdr idlist) (- h 1) idminfo)) (setf prob (* alpha prob)))) ((< glen h) ;; C(H) < 0 (progn (setf prob (katz-backoff (cdr idlist) (- h 1) idminfo))))) (when (= 100 h) (format t "length: ~A; P(~A | " glen (car (last idlist))) (dolist (elem (butlast idlist)) (format t "~A " elem)) (format t ") = ~,5f~%" prob)) )) (when (= 100 h) (format t "length: ~A; P(~A | ) = ~,5f~%" 1 (car (last idlist)) prob)) prob))
3,580
Common Lisp
.lisp
85
33.011765
94
0.519484
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6e8c258675772f6a0216b33cb76d5054e939e1b2bae27d0c3ba1c7aa5e60386e
24,480
[ -1 ]
24,481
idvocab.lisp
jnjcc_cl-nlp/lm/idvocab.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; vocabulary as hash-table: word -> id (in-package #:cl-nlp) (defun update-word-id (vocab word newid) "exist or not, we update word id" (multiple-value-bind (oldid exist) (gethash word vocab) (when exist (format t "~A already exist with id ~A, overwritting" word oldid)) (setf (gethash word vocab) newid))) (defun wfreq-idvocab (wfreq &key (sortby :key)) "hash-table: word -> id; id=0 being OOV words" (let ((wlst (sorted-words wfreq :compare #'> :filter :key :minfreq 0)) (vocab (make-hash-table :test 'equal)) (id 1)) (when (eq sortby :key) (setf wlst (sort wlst #'string<))) (dolist (word wlst) (update-word-id vocab word id) (incf id)) (values vocab (- id 1)))) (defun read-idvocab (stream) (let ((vocab (make-hash-table :test 'equal)) (id 1)) (do ((word (read-line stream nil :eof) (read-line stream nil :eof))) ((eq word :eof)) (update-word-id vocab word id) (incf id)) (values vocab (- id 1))))
1,087
Common Lisp
.lisp
29
32.689655
72
0.62334
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1f62adf433f32dd5fa9843426952162423db8bf64365f6ec0b78b28f4b962271
24,481
[ -1 ]
24,482
idngram.lisp
jnjcc_cl-nlp/lm/idngram.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; idngram count as hash-table: idngram -> count (in-package #:cl-nlp) (defun %join-idngram (sentence beg end idvocab) (join-strings (mapcar (lambda (word) (gethash word idvocab)) (subseq sentence beg end)))) (defun idngram-count (stream n idvocab &key (eow #\Space) (eol #\Newline) (bos -1) (eos -2)) "hash-table: idngram -> count" (let ((idngram-hash (make-hash-table :test 'equal)) (idngram nil) (slens nil)) (do-sentence (sentence stream :eow eow :eol eol) (setf slens (length sentence)) (when bos (dotimes (i (- n 1)) (when (= i slens) (return)) (setf idngram (format nil "~A~A" (repeat-string (format nil "~A~A" bos " ") (- n 1 i)) (%join-idngram sentence 0 (+ i 1) idvocab))) (incf-frequency idngram-hash idngram))) (dotimes (i (- slens n -1)) (setf idngram (%join-idngram sentence i (+ i n) idvocab)) (incf-frequency idngram-hash idngram)) (when eos (when (>= slens (- n 1)) (setf idngram (format nil "~A ~A" (%join-idngram sentence (- slens n -1) slens idvocab) eos)) (incf-frequency idngram-hash idngram)))) idngram-hash)) (defun wngram-idngram (wngram idvocab &key (wbos "<BOS>") (bos -1) (weos "<EOS>") (eos -2)) "word ngram -> id ngram" (let ((idngram-hash (make-hash-table :test 'equal))) (labels ((translate (ngram freq) (setf ngram (join-strings (mapcar (lambda (word) (cond ((string= word wbos) bos) ((string= word weos) eos) (t (gethash word idvocab)))) (split-string ngram #\Space)))) (incf-frequency idngram-hash ngram freq))) (maphash #'translate wngram)) idngram-hash))
2,177
Common Lisp
.lisp
46
33.043478
92
0.496944
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e124b4e687fdf2208a92e470494633fbf135f64a604bf10961d9e528d10746bf
24,482
[ -1 ]
24,483
ngram.lisp
jnjcc_cl-nlp/lm/ngram.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; word ngram count as hash-table: ngram -> count (in-package #:cl-nlp) (defun wngram-count (stream n &key (eow #\Space) (eol #\Newline) (bos "<BOS>") (eos "<EOS>")) "hash-table: ngram -> count" (let ((ngram-hash (make-hash-table :test 'equal)) (ngram nil) (slens nil)) (do-sentence (sentence stream :eow eow :eol eol) (setf slens (length sentence)) (when bos (dotimes (i (- n 1)) (when (= i slens) (return)) (setf ngram (format nil "~A~A" (repeat-string (format nil "~A~A" bos " ") (- n 1 i)) (join-strings (subseq sentence 0 (+ i 1))))) (incf-frequency ngram-hash ngram))) (dotimes (i (- slens n -1)) (setf ngram (join-strings (subseq sentence i (+ i n)))) (incf-frequency ngram-hash ngram)) (when eos (when (>= slens (- n 1)) (setf ngram (format nil "~A ~A" (join-strings (subseq sentence (- slens n -1) slens)) eos)) (incf-frequency ngram-hash ngram)))) ngram-hash))
1,217
Common Lisp
.lisp
30
30.5
93
0.514768
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
47c8886f7b835a5a96c3ed8fb7aa75eb30ab5e30891023296a92e3122b326c85
24,483
[ -1 ]
24,484
lm.lisp
jnjcc_cl-nlp/lm/lm.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp) (defun ngram-lm (corpus-fp n lm-fp &key (disc-type :good-turing) (disc-range *fof-disc-range*) (uni-range *fof-uni-range*) (bos "-1") (eos "-2") (oov :open) (unk "<UNK>") (lmtype :arpa)) (let* ((old-pos (file-position corpus-fp)) (wfreq (word-frequency corpus-fp)) (idvocab (wfreq-idvocab wfreq)) (idngram nil)) (file-position corpus-fp old-pos) (setf idngram (idngram-count corpus-fp n idvocab :bos bos :eos eos)) (multiple-value-bind (idminfo id2word idmin idmax) (idngram-lm idngram n idvocab :disc-type disc-type :disc-range disc-range :uni-range uni-range :oov oov :unk unk :bos bos :eos eos) (ecase lmtype (:arpa (write-arpa idminfo idmin idmax id2word lm-fp))))))
906
Common Lisp
.lisp
18
41.5
104
0.603837
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
215a794309fb9392ea137f9068a32bb229e27e0fee0d3e55e9d22d6063cac324
24,484
[ -1 ]
24,485
idinfo.lisp
jnjcc_cl-nlp/lm/idinfo.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; data structures for idngram info (in-package #:cl-nlp) ;;; Let m <= n be any gram, `freq' be frequency of some m-gram, `idx' be index of some m-gram ;;; - (idngram-tree) ;;; + `mgram-fof'[m][freq]: freq of freq table for each m-gram, and each `freq' ;;; + `mgram-nums'[m]: # of grams for each m-gram (as for unigram, excluding <UNK>) ;;; + `mgram-freqs'[m][idx]: gram freq for each `idx'-th m-gram (in numeric sorted order) ;;; + `mgram-wdids'[m][idx]: for `idx'-th m-gram, what is the end wordid? ;;; - e.g., for '1 2 3' and '1 3 1', 1-th bigram's end wordid is 2, 2-th bigram's end wordid is 3 ;;; + `mgram-alphas'[m][idx]: for `idx'-th m-gram, what is the backoff alpha? (Katz Backoff) ;;; - default 1.0, will change later ;;; + `mgram-ptrs'[m][idx]: for `idx'-th m-gram, what is the latest (m+1)-gram it points to? ;;; - e.g., for 'A B C' and 'A B D', 1-th bigram 'A B' points to the 2-th trigram 'A B D' ;;; - (discount-ratio) & (discount-unigram) ;;; + `mgram-disc'[m][freq]: discount ratio for `freq' of m-gram ;;; + `ugram-prob'[idx]: discounted probability for each unigram ;;; + `ugram-logp'[idx]: log probability for each unigram (defclass idinfo-type () ((n :initform 3 :initarg :n :reader idm-get-n) (disc-range :initform *fof-disc-range* :initarg :disc-range) (uni-range :initform *fof-uni-range* :initarg :uni-range) (mgram-fof :initform nil :reader mgram-fof) (mgram-nums :initform nil :reader mgram-nums) (mgram-freqs :initform nil :reader mgram-freqs) (mgram-wdids :initform nil :reader mgram-wdids) (mgram-alphas :initform nil :reader mgram-alphas) (mgram-ptrs :initform nil :reader mgram-ptrs) (discount-type :initform :good-turing :reader discount-type) (mgram-disc :initform nil :reader mgram-disc) (ugram-prob :initform nil :reader ugram-prob) (ugram-logp :initform nil :reader ugram-logp))) (defmethod initialize-instance :after ((idm idinfo-type) &rest args) (declare (ignore args)) (with-slots (n disc-range uni-range) idm (with-slots (mgram-fof mgram-nums mgram-freqs mgram-wdids mgram-alphas mgram-ptrs mgram-disc) idm (setf mgram-fof (fof-init n disc-range uni-range)) (setf mgram-nums (mlist-init n :initial-element 0)) (setf mgram-freqs (lol-init n)) (setf mgram-wdids (lol-init n)) (setf mgram-alphas (lol-init n)) (setf mgram-ptrs (lol-init n)) (setf mgram-disc (fof-copy-init mgram-fof))))) (defmethod idm-get-fof ((idm idinfo-type) m freq) (with-slots (mgram-fof) idm (fof-ref mgram-fof m freq))) (defmethod idm-get-gnum ((idm idinfo-type) m) (with-slots (mgram-nums) idm (mlist-ref mgram-nums m))) (defmethod idm-get-freq ((idm idinfo-type) m idx) (with-slots (mgram-freqs) idm (lol-ref mgram-freqs m idx))) (defmethod idm-get-wdid ((idm idinfo-type) m idx) (with-slots (mgram-wdids) idm (lol-ref mgram-wdids m idx))) (defmethod idm-get-alpha ((idm idinfo-type) m idx) (with-slots (mgram-alphas) idm (lol-ref mgram-alphas m idx))) (defmethod idm-get-ptrs ((idm idinfo-type) m idx) (with-slots (mgram-ptrs) idm (lol-ref mgram-ptrs m idx))) (defmethod idm-get-unigram ((idm idinfo-type)) (with-slots (mgram-freqs) idm (lol-get mgram-freqs 1))) (defmethod idm-get-uprob ((idm idinfo-type) idx) (with-slots (ugram-prob) idm (mlist-ref ugram-prob idx))) (defmethod idm-get-logpr ((idm idinfo-type) idx) (with-slots (ugram-logp) idm (mlist-ref ugram-logp idx))) (defmethod idm-incf-fof ((idm idinfo-type) m freq &optional (delta 1)) (with-slots (mgram-fof) idm (fof-incf mgram-fof m freq delta))) (defmethod idm-incf-gnum ((idm idinfo-type) m &optional (delta 1)) "gram number" (with-slots (mgram-nums) idm (mlist-incf mgram-nums m delta))) (defmethod idm-aset-gram ((idm idinfo-type) m freq wdid &optional (alpha 1.0)) "append and set `freq', `wdid' and `alpha' for a brand new m-gram" (with-slots (mgram-nums mgram-freqs mgram-wdids mgram-alphas) idm (let ((idx (mlist-ref mgram-nums m))) (lol-aset mgram-freqs m idx freq) (lol-aset mgram-wdids m idx wdid) (lol-aset mgram-alphas m idx alpha)))) (defmethod idm-aset-ptrs ((idm idinfo-type) m) "remember current m-gram points to current (m+1)-gram" (with-slots (mgram-nums mgram-ptrs) idm (lol-aset mgram-ptrs m (mlist-ref mgram-nums m) (mlist-ref mgram-nums (+ m 1))))) (defmethod idm-setf-alpha ((idm idinfo-type) m idx val) (with-slots (mgram-alphas) idm (lol-setf mgram-alphas m idx val)))
4,628
Common Lisp
.lisp
92
46.967391
104
0.673234
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d6c17974a53d317254e2060fbb53b50581fb7d6605831758b36239635d488577
24,485
[ -1 ]
24,486
idlm.lisp
jnjcc_cl-nlp/lm/idlm.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; idngram language model: ;;;; corpus -> (word-frequency) -> (wfreq-idvocab) \ ;;;; \ / (idngram-lm) ;;;; `---------------------> (idngram-count) / (in-package #:cl-nlp) (defun idngram-lm (idngram n idvocab &key (disc-type :good-turing) (disc-range *fof-disc-range*) (uni-range *fof-uni-range*) (bos "-1") (eos "-2") (oov :open) (unk "<UNK>")) "`disc': discount range for 2-gram, 3-gram, etc; `uni': discount range for 1-gram" (let ((id2word (make-hash-table :test 'equal)) (idmin 0) (idmax -1)) (maphash (lambda (word id) (setf (gethash id id2word) word)) idvocab) (setf idmax (hash-table-count id2word)) (setf (gethash 0 id2word) unk) (when (eq oov :closed) ;; <UNK> not allowed (setf idmin 1)) (let ((idminfo (idngram-tree idngram n idmax :disc disc-range :uni uni-range :bos bos :eos eos))) ;; for unigram, there are frequency zero's: e.g., <UNK>'s frequency will definitely be zero (loop for id from idmin to idmax do (when (= (idm-get-freq idminfo 1 id) 0) (idm-incf-fof idminfo 1 0))) (format nil "fof: ~A~%" (mgram-fof idminfo)) (idm-discount-ratio idminfo disc-type) (format nil "disc-ratio: ~A~%" (mgram-disc idminfo)) (idm-discount-ugram idminfo idmin idmax 1.0) (loop for m from 2 to n do (idm-backoff-gram idminfo m idmin idmax)) (format nil "probs: ~A~%" (ugram-prob idminfo)) (values idminfo id2word idmin idmax))))
1,644
Common Lisp
.lisp
33
43.272727
106
0.579863
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d332da06163dce3a95e79367ec94ad26c7b8251d6b383008019687991eba3461
24,486
[ -1 ]
24,487
reduce.lisp
jnjcc_cl-nlp/lm/reduce.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; reduce n-gram to m-gram (in-package #:cl-nlp) (defun read-ngram (stream &key (eow #\Space)) (let ((ngram-hash (make-hash-table :test 'equal)) (ngram nil)) (do ((line (read-line stream nil :eof) (read-line stream nil :eof))) ((eq line :eof)) (setf ngram (split-string line eow)) (setf (gethash (join-strings (butlast ngram)) ngram-hash) (read-from-string (car (last ngram))))) ngram-hash)) (defun write-ngram (whash &optional (stream t)) (maphash (lambda (key val) (format stream "~A ~A~%" key val)) whash)) (defun ngram-mgram (ngram n m &key (bos "<BOS>") (eos "<EOS>")) "reduce n-gram hash-table `ngram' to m-gram NOTICE: if there are no `eos', the result m-gram will not be precise" (when (<= n m) (error "Requires: n > m")) (let ((mgram-hash (make-hash-table :test 'equal))) (labels ((translate (gramkey freq) (let ((gramlst (split-string gramkey #\Space))) (unless (= (length gramlst) n) (error "gram [~A] not of size ~A" gramkey n)) (cond ((string= (nth 0 gramlst) bos) ;; skip grams full of `bos' (or (every (lambda (word) (string= bos word)) (subseq gramlst 0 m)) (incf-frequency mgram-hash (join-strings (subseq gramlst 0 m)) freq))) ((string= (nth (- n 1) gramlst) eos) ;; if there are no `eos', we will lose those m-gram starting from 1, 2, ... (dotimes (i (- n m)) (unless (= i (- n 1)) (incf-frequency mgram-hash (join-strings (subseq gramlst i (+ i m))) freq)))) (t ;; m-grams starting from 1, 2, etc will be updated in following n-grams (incf-frequency mgram-hash (join-strings (subseq gramlst 0 m)) freq)))))) (maphash #'translate ngram)) mgram-hash)) (defun %malformed-gram (grams m bos eos) "are m-gram `grams'[0:m) malformed?" (or ;; full of `bos' (string= (nth (- m 1) grams) bos) ;; more than one `eos', fake grams from `sorted-extend' (and (>= m 2) (string= (nth (- m 2) grams) eos)))) (defun %sorted-reduce-ngram (ngram n m bos eos &key (idngram-p nil)) "reduce `ngram' of size n to size m, and collect into a list" (let* ((gramlst nil) (sorted (sorted-extend ngram n :eos eos :idngram-p idngram-p)) (pre-gram (caar sorted)) (pre-freq (cdar sorted)) (running-pos 0) (running-total (cdar sorted)) (cur-gram nil) (cur-freq nil) (diff-pos 0)) (dotimes (i (- (length sorted) 1)) (setf cur-gram (car (nth (+ i 1) sorted)) cur-freq (cdr (nth (+ i 1) sorted))) (setf diff-pos n) (dotimes (j n) (when (string/= (nth j cur-gram) (nth j pre-gram)) (setf diff-pos j) (return))) (when (= diff-pos n) (error "same gram [~A] appears" (join-strings cur-gram))) ;; [0, diff-pos], [0, diff-pos+1], ..., [0, n] of `pre-grams' will not appear again (unless (or (>= diff-pos m) (%malformed-gram pre-gram m bos eos)) ;; only collect new grams, and skip grams full of `bos' (if (<= m running-pos) (push (format nil "~A ~A" (join-strings (subseq pre-gram 0 m)) running-total) gramlst) (push (format nil "~A ~A" (join-strings (subseq pre-gram 0 m)) pre-freq) gramlst))) (if (= diff-pos 0) (setf running-total cur-freq) (incf running-total cur-freq)) (setf running-pos diff-pos) (setf pre-gram cur-gram pre-freq cur-freq)) ;; one last gram (unless (or (>= diff-pos m) (%malformed-gram pre-gram m bos eos)) (if (<= m running-pos) (push (format nil "~A ~A" (join-strings (subseq pre-gram 0 m)) running-total) gramlst) (push (format nil "~A ~A" (join-strings (subseq pre-gram 0 m)) pre-freq) gramlst))) (nreverse gramlst))) (defun %collect-ngram-eq (ngram) "collect `ngram' into a list" (let ((gramlst nil)) (labels ((collect (gramkey freq) (push (format nil "~A ~A" gramkey freq) gramlst))) (maphash #'collect ngram)) gramlst)) (defun %sorted-ngram (ngram n m &key (bos "<BOS>") (eos "<EOS>") (idngram-p nil)) "reduce `ngram' of size n to size m, and sort according to alphabetical order" (cond ((< m n) (%sorted-reduce-ngram ngram n m bos eos :idngram-p idngram-p)) ((= m n) (if idngram-p (sort (%collect-ngram-eq ngram) #'%idnstr<) (sort (%collect-ngram-eq ngram) #'string<))) ((> m n) (error "Requires: m <= n")))) (defun sorted-wngram (wngram n m &key (bos "<BOS>") (eos "<EOS>")) (%sorted-ngram wngram n m :bos bos :eos eos :idngram-p nil)) (defun sorted-idngram (idngram n m &key (bos "-1") (eos "-2")) (%sorted-ngram idngram n m :bos bos :eos eos :idngram-p t))
5,051
Common Lisp
.lisp
109
37.908257
101
0.565085
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
5f8a5a11fc7aa845a66e3a60829116bd2aed71c22a981d66bd7b9aae6acfdec9
24,487
[ -1 ]
24,488
arpa.lisp
jnjcc_cl-nlp/lm/arpa.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; ARPA file format: write n-gram Language Model (in-package #:cl-nlp) (defun %write-cond-prob (idminfo m curidxs endidxs id2word stream) (let ((mgfreq nil) (condpr 0.0) (alpha 0.0) (log10prob 0.0) (log10alpha 0.0)) (do ((idx (mlist-ref curidxs m) (mlist-ref curidxs m))) ((> idx (mlist-ref endidxs m))) (setf mgfreq (idm-get-freq idminfo m idx)) (setf mgfreq (idm-discount-freq idminfo m mgfreq)) (setf condpr (/ mgfreq (idm-get-freq idminfo (- m 1) (mlist-ref curidxs (- m 1))))) (if (> condpr 0.0) (setf log10prob (log condpr 10.0)) (setf log10prob *log-infinity*)) (format stream "~,4f" log10prob) (loop for k from 1 to m do (format stream " ~A" (gethash (idm-get-wdid idminfo k (mlist-ref curidxs k)) id2word))) (when (< m (idm-get-n idminfo)) (setf alpha (idm-get-alpha idminfo m (mlist-ref curidxs m))) (if (> alpha 0.0) (setf log10alpha (log alpha 10.0)) (setf log10alpha *log-infinity*)) (format stream " ~,4f" log10alpha)) (format stream "~%") (mlist-incf curidxs m)))) (defun %write-mgram (idminfo m idmin idmax id2word stream) "Refer to `idm-backoff-gram'" (let ((cgm 1) (curidxs (mlist-init (+ m 1) :initial-element 1)) (endidxs (mlist-init (+ m 1) :initial-element 0))) (loop for id from idmin to idmax do (mlist-setf curidxs 1 id) (when (> (idm-get-freq idminfo 1 id) 0) (setf cgm 2) (%fill-next-pointer curidxs cgm idminfo endidxs) (do ((cgm 2)) ((<= cgm 1)) (cond ((= cgm m) (progn (%write-cond-prob idminfo cgm curidxs endidxs id2word stream) (decf cgm) (when (> cgm 1) (mlist-incf curidxs cgm)))) ((< cgm m) (if (<= (mlist-ref curidxs cgm) (mlist-ref endidxs cgm)) (progn (incf cgm) (%fill-next-pointer curidxs cgm idminfo endidxs)) (progn (decf cgm) (when (> cgm 1) (mlist-incf curidxs cgm))))))))))) (defun write-arpa (idminfo idmin idmax id2word &optional (stream t)) (format stream "\\data\\~%") (format stream "ngram 1=~A~%" (+ 1 idmax (- idmin))) (loop for m from 2 to (idm-get-n idminfo) do (format stream "ngram ~A=~A~%" m (idm-get-gnum idminfo m))) (let ((log10prob nil) (log10alpha nil)) (format stream "~%\\1-grams:~%") (loop for id from idmin to idmax do (setf log10prob (/ (idm-get-logpr idminfo id) (log 10.0))) (when (<= (idm-get-uprob idminfo id) 0.0) (setf log10prob *log-infinity*)) (setf log10alpha *log-infinity*) (when (> (idm-get-alpha idminfo 1 id) 0.0) (setf log10alpha (/ (log (idm-get-alpha idminfo 1 id)) (log 10.0)))) (if (> (idm-get-n idminfo) 1) (format stream "~,4f ~A ~,4f~%" log10prob (gethash id id2word) log10alpha) (format stream "~,4f ~A~%" log10prob (gethash id id2word))))) (loop for m from 2 to (idm-get-n idminfo) do (format stream "~%\\~A-grams:~%" m) (%write-mgram idminfo m idmin idmax id2word stream)) (format stream "~%\\end\\~%"))
3,568
Common Lisp
.lisp
77
34.987013
98
0.53186
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
60c60f62db1fa055c238554af4d1f7ff436e872edb0115533f5eeee7653a63f4
24,488
[ -1 ]
24,489
idtree.lisp
jnjcc_cl-nlp/lm/idtree.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; m-gram statistics and trees for n-gram (m <= n) (in-package #:cl-nlp) (defun %collect-grams (pre-gram n cur-gram cur-freq diff bos eos running-total idm) "`cur-gram' and `pre-gram' differs starting from position `diff', which means [0, `diff'], [0, `diff'+1], ..., [0, n] of `cur-gram' are brand new grams, we need to update `running-total', and collect `pre-gram' into `idm'" (let ((pre-idx (parse-integer (car pre-gram) :junk-allowed t)) (cur-idx (parse-integer (car cur-gram) :junk-allowed t)) (m 1)) (dotimes (d n) ;; looping for n, (n-1), ..., 1 grams (setf m (- n d)) (unless (%malformed-gram pre-gram m bos eos) ;; e.g., for trigrams: (NOTICE: what if "5 6 7 30" is the last line?) ;; 1 2 3 10 ;; 1 2 4 20 ;; 5 6 7 30 (when (> m diff) ;; TODO: Good-Turing, etc (idm-incf-fof idm m (mlist-ref running-total m)) ;; say, we are processing "1 2 4", where `diff'=2 ;; now that "1 2 3" being the 1-st trigram, we want to remember its frequency, ;; its last wordid, and its backoff alpha (idm-aset-gram idm m (mlist-ref running-total m) (parse-integer (nth (- m 1) pre-gram) :junk-allowed t) 1.0) (cond ((= m n) (idm-incf-gnum idm m)) ((> m 1) ;; we want to remember the 1-st bigram "1 2" points to the 2-nd trigram "1 2 4" ;; which is the latest trigram it points to (progn (idm-aset-ptrs idm m) (idm-incf-gnum idm m))) ((= m 1) ;; when we are process the 3-rd trigram "3 4 5", we also want to remember that ;; the uni-grams "1", "2", "3", "4" points to the 2-nd bigram "1 2" ;; NOTICE: this only happens if we didn't do `sorted-extend' of <EOS> (do ((idx pre-idx (+ idx 1))) ((>= idx cur-idx)) (idm-aset-ptrs idm 1) (idm-incf-gnum idm 1)))) (mlist-setf running-total m 0)) (mlist-incf running-total m cur-freq))))) (defun idngram-tree (idngram n idmax &key (disc *fof-disc-range*) (uni *fof-uni-range*) (bos "-1") (eos "-2")) (let* ((idm (make-instance 'idinfo-type :disc-range disc :uni-range uni :n n)) (sorted (sorted-extend idngram n :eos eos :idngram-p t)) (pre-gram (caar sorted)) (pre-freq (cdar sorted)) ;; `running-total' for 1, 2, ..., n-gram (NOTICE: each m-gram's are sorted) (running-total (mlist-init n :initial-element pre-freq)) (cur-gram nil) (cur-freq nil) (diff-pos 0)) (dotimes (i (- (length sorted) 1)) ;; starting from 1-th index (setf cur-gram (car (nth (+ i 1) sorted)) cur-freq (cdr (nth (+ i 1) sorted))) (setf diff-pos n) (dotimes (j n) (when (string/= (nth j cur-gram) (nth j pre-gram)) (setf diff-pos j) (return))) (when (= diff-pos n) (error "same gram [~A] appears" (join-strings cur-gram))) (%collect-grams pre-gram n cur-gram cur-freq diff-pos bos eos running-total idm) (setf pre-gram cur-gram)) ;; one last gram (%collect-grams pre-gram n cur-gram cur-freq 0 bos eos running-total idm) ;; NOTICE: for the last gram "5 6 7 30", we have to complete the tree (do ((id (parse-integer (car cur-gram) :junk-allowed t) (+ id 1))) ((> id idmax)) (idm-aset-ptrs idm 1) (idm-incf-gnum idm 1)) idm))
3,642
Common Lisp
.lisp
77
38.207792
110
0.551656
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b22e627b2321a9f6d7f6503f79beb26a3316b2c179d8628297258003a0b37fae
24,489
[ -1 ]
24,490
sorted.lisp
jnjcc_cl-nlp/lm/sorted.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; sort n-gram (possibly reduce to m-gram and sort) (in-package #:cl-nlp) ;;; wngram (as a list) sort (alphabetical order) (defun %wngram< (wng1 wng2) (string< (join-strings wng1) (join-strings wng2))) ;;; idngram (as a list) sort (numeric order) (defun %idngram< (idng1 idng2) ;; idng1 = (n-gram freq) (let ((n (- (length idng1) 1)) (id1 nil) (id2 nil)) (dotimes (i n) (setf id1 (parse-integer (nth i idng1) :junk-allowed t)) (setf id2 (parse-integer (nth i idng2) :junk-allowed t)) (cond ((< id1 id2) (return-from %idngram< t)) ((> id1 id2) (return-from %idngram< nil)))) (return-from %idngram< nil))) ;; idngram (as a string) sort (defun %idnstr< (idnstr1 idnstr2) (let ((idng1 (split-string idnstr1 #\Space)) (idng2 (split-string idnstr2 #\Space))) (%idngram< idng1 idng2))) ;;; now let's sort! (defun %sorted-extend-2 (ngram &key (idngram-p nil)) "for bigram, no need to extend!" (let ((sorted nil)) (labels ((collect (gramkey freq) (push (cons (split-string gramkey #\Space) freq) sorted))) (maphash #'collect ngram)) (if idngram-p (sort sorted #'%idngram< :key #'car) (sort sorted #'%wngram< :key #'car)))) (defun %sorted-extend-n (ngram n &key (eos "<EOS>") (idngram-p nil)) "for each gram (A B C <eos>), extend (B C <eos>) and (C <eos> <eos>) Requires: n > 2" (let ((sorted nil)) (labels ((collect (gramkey freq) (let ((gramlst (split-string gramkey #\Space))) (unless (= (length gramlst) n) (error "gram [~A] not of size ~A" gramkey n)) (push (cons gramlst freq) sorted) (when (string= (nth (- n 1) gramlst) eos) (dotimes (i (- n 2)) (setf gramkey (append (subseq gramlst (+ i 1) n) (make-list (+ i 1) :initial-element eos))) (push (cons gramkey freq) sorted)))))) (maphash #'collect ngram)) (if idngram-p (sort sorted #'%idngram< :key #'car) (sort sorted #'%wngram< :key #'car)))) (defun sorted-extend (ngram n &key (eos "<EOS>") (idngram-p nil)) (if (or (<= n 2) (null eos)) (%sorted-extend-2 ngram :idngram-p idngram-p) (%sorted-extend-n ngram n :eos eos :idngram-p idngram-p)))
2,437
Common Lisp
.lisp
57
35.245614
85
0.567214
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d2f2b641918a61dce4a56611a476a698761889d9932cf38514d33e8b5eb704b3
24,490
[ -1 ]
24,491
discount.lisp
jnjcc_cl-nlp/lm/discount.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Discounting is a kind of smoothing algorithm (in-package #:cl-nlp) (defun %good-turing (mgram-fof m disc-ratios) "Good-Turing discounting ratio in Katz backoff model" (let* ((disc (fof-disc mgram-fof m)) (k disc) ;; common term for Katz's back-off model (common nil) (vanilla nil) (r nil)) (when (and (= m 1) (= disc 1) (> (fof-ref mgram-fof m 0) 0)) ;; special treatment for unigram (fof-setf disc-ratios m 1 (/ (fof-ref mgram-fof m 1) (+ (fof-ref mgram-fof m 1) (fof-ref mgram-fof m 0)))) (return-from %good-turing)) ;; (k+1)*n[k+1] / n[1] (setf common (/ (* (+ k 1) (fof-ref mgram-fof m (+ k 1))) (fof-ref mgram-fof m 1))) (when (or (<= common 0.0) (>= common 1.0)) (return-from %good-turing)) (dotimes (i k) (setf r (+ i 1)) (setf vanilla 1.0) (unless (= (fof-ref mgram-fof m r) 0) ;; vanilla Good-Turing count: rstar = (r+1) * (n[r+1] / n[r]) (setf vanilla (/ (* (+ r 1) (fof-ref mgram-fof m (+ r 1))) (fof-ref mgram-fof m r))) ;; vanilla Good-Turing ratio: (rstar / r) (setf vanilla (/ vanilla r))) ;; NOTICE: the default discount ratio is 1.0 ;; TODO: when 0.0 happens, we might need to decrease `disc-range' (unless (or (<= vanilla 0.0) (>= vanilla 1.0) (<= vanilla common)) (fof-setf disc-ratios m r (/ (- vanilla common) (- 1.0 common))))))) (defun %discount-ratio (mgram-fof n disc-type mgram-disc) (let ((m 1)) (dotimes (i n) (setf m (+ i 1)) (ecase disc-type (:good-turing (%good-turing mgram-fof m mgram-disc)))))) (defun discount-ratio (mgram-fof n disc-type) "discounting m-gram within discount range" (let ((mgram-disc (fof-copy-init mgram-fof))) (%discount-ratio mgram-fof n disc-type mgram-disc) mgram-disc)) (defun discount-freq (mgfreq m disc-ratio disc-type) "Given `disc-ratio', return discounted `mgfreq' of m-gram" (ecase disc-type (:good-turing (when (<= mgfreq (fof-disc disc-ratio m)) (setf mgfreq (* (fof-ref disc-ratio m mgfreq) mgfreq))))) mgfreq) (defun discount-unigram (unigram idmin idmax num-zeros disc-ratio disc-type &optional (zero-frac 1.0)) "discount unigram distribution, give some mass to zerotons: `unigram' being frequency of each unigram, including <UNK>, etc; `num-zeros' being number of zerotons, <UNK> being one of them; `disc-type' being discounting type: :good-turing etc `zero-frac': P(zeroton) is not allowed to exceed `zero-frac' * P(singleton)" (let ((uni (fof-disc disc-ratio 1)) (sumfreq (reduce #'+ unigram :initial-value 0.0)) (probs (mlist-copy unigram)) (logprobs (mlist-copy unigram)) curfreq curprob totprob leftprob zeroprob singprob) (setf totprob 0.0) (loop for id from idmin to idmax do (setf curfreq (mlist-ref unigram id)) (setf curprob (/ curfreq sumfreq)) (ecase disc-type (:good-turing (cond ((<= 1 curfreq uni) (setf curprob (* curprob (fof-ref disc-ratio 1 curfreq)))) ((= 0 curfreq) (setf curprob 1e-99))))) (mlist-setf probs id curprob) (incf totprob curprob)) ;; (1.0 - totprob) probability leftover for zerotons (setf leftprob (- 1.0 totprob)) (setf zeroprob (/ leftprob num-zeros)) ;; probability for singleton (words that occurred exactly once in training data) ;; we might have to make sure probability of zerotons does not exceed this (setf singprob (/ 1.0 sumfreq)) (ecase disc-type (:good-turing (when (>= uni 1) (setf singprob (* singprob (fof-ref disc-ratio 1 1)))))) (when (> zeroprob (* zero-frac singprob)) (setf zeroprob (* zero-frac singprob))) (loop for id from idmin to idmax do (setf curfreq (mlist-ref unigram id)) (when (= curfreq 0) (mlist-setf probs id zeroprob))) ;; probability of zeroton might have changed by `zero-frac' (setf leftprob (- leftprob (* zeroprob num-zeros))) (when (> leftprob 0) (loop for id from idmin to idmax do (let ((old (mlist-ref probs id))) (mlist-setf probs id (/ old (- 1.0 leftprob)))))) (loop for id from idmin to idmax do (let ((pr (mlist-ref probs id))) (mlist-setf logprobs id (log pr)))) (values probs logprobs))) (defmethod idm-discount-ratio ((idm idinfo-type) disc-type) (with-slots (n mgram-fof discount-type mgram-disc) idm (setf discount-type disc-type) (%discount-ratio mgram-fof n disc-type mgram-disc))) (defmethod idm-discount-freq ((idm idinfo-type) m freq) (with-slots (discount-type mgram-disc) idm (discount-freq freq m mgram-disc discount-type))) (defmethod idm-discount-ugram ((idm idinfo-type) idmin idmax &optional (zero-frac 1.0)) "`zero-frac': P(zeroton) is not allowed to exceed `zero-frac' * P(singleton)" (with-slots (discount-type mgram-disc ugram-prob ugram-logp) idm (multiple-value-setq (ugram-prob ugram-logp) (discount-unigram (idm-get-unigram idm) idmin idmax (idm-get-fof idm 1 0) mgram-disc discount-type zero-frac))))
5,302
Common Lisp
.lisp
113
40.274336
102
0.626062
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
57191412d5c49cde3b41523e97c73643fdc8811f804ddb93dff4f43c3645b98f
24,491
[ -1 ]
24,492
wfreq.lisp
jnjcc_cl-nlp/lm/wfreq.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; word frequency as hash-table: word -> frequency (in-package #:cl-nlp) (defun incf-frequency (whash word &optional (delta 1)) (multiple-value-bind (freq exist) (gethash word whash) (unless exist (setf freq 0)) (incf freq delta) (setf (gethash word whash) freq))) (defun word-frequency (stream &key (eow #\Space) (eol #\Newline)) "hash-table: word -> frequency" (let ((whash (make-hash-table :test 'equal))) (do-word (word stream :eow eow :eol eol) (unless (eq word :eol) (incf-frequency whash word))) whash)) (defun sorted-words (whash &key (compare #'>) (filter :key) (minfreq 0)) (let ((vocab-lst nil)) (labels ((collect (word freq) (when (> freq minfreq) (ecase filter ((:full :key) (push (list word freq) vocab-lst)) (:value (push freq vocab-lst)))))) (maphash #'collect whash)) (ecase filter (:full (sort vocab-lst compare :key (lambda (info) (second info)))) (:key (mapcar #'car (sort vocab-lst compare :key (lambda (info) (second info))))) (:value (sort vocab-lst compare)))))
1,271
Common Lisp
.lisp
30
34.333333
74
0.582053
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
45647de38a2da2e969e08990793eb8111a6969c2d9db78c4347e8286eabc20a1
24,492
[ -1 ]
24,493
api.lisp
jnjcc_cl-nlp/probs/api.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Probability Distribution API: ;;;; ;;;; freq-dist-bins ;;;; / ;;;; freq-dist cond-freq-dist -> dcond-prob-dist -> dcond-mutable ;;;; \ / ;;;; freq-dist-hash ;;;; ^ \ ;;;; | dprob-mutable ;;;; | mle-prob-dist ;;;; | / ;;;; (view window) <- dprob-dist ;;;; \ ;;;; lidstone-prob-dist (in-package #:cl-nlp) ;;; make-* functions from frequency distribution (defun derive-prob (fdist bins type &key (gamma 1.0)) "derive probability from `fdist' using `type' estimator" (let ((pdist nil)) (ecase type (:mle (setf pdist (make-instance 'mle-prob-dist :bins bins))) (:lidstone (setf pdist (make-instance 'lidstone-prob-dist :bins bins :gamma gamma)))) (estimate-prob pdist fdist) pdist)) (defun derive-cond-prob (cfdist bins type &key (gamma 0.1)) "derive conditional probability from `cfdist' using `type' estimator" (let ((dcondp (make-instance 'dcond-prob-dist :bins bins))) (with-slots (test) cfdist (with-slots (htable) dcondp (setf htable (make-hash-table :test test)) (labels ((collect (condi fdist) (setf (gethash condi htable) (derive-prob fdist bins type :gamma gamma)) )) (for-each-pair cfdist #'collect)))) dcondp)) ;;; make-* functions from probability literals (defun derive-literal (keylst problst) (let ((pdist (make-instance 'dprob-mutable))) (init-from-literal pdist keylst problst) pdist)) (defun derive-cond-literal (conds keys probmat) "`probmat': list of list, prob from `cond' to `key'" (let ((cpmutable (make-instance 'dcond-mutable)) (condi nil)) (with-slots (htable) cpmutable (setf htable (make-hash-table :test 'equal)) (dotimes (i (length conds)) (setf condi (nth i conds)) (setf (gethash condi htable) (derive-literal keys (nth i probmat))))) cpmutable)) ;;; copy-* from derived probability to mutable probability (defun copy-mutable-dprob (pdist &key (fill-value nil)) (let ((pmutable (make-instance 'dprob-mutable))) (dolist (key (pdist-keys pdist)) (if fill-value (pdist-setf pmutable key fill-value) (pdist-setf pmutable key (pdist-prob pdist key)))) pmutable)) (defun copy-mutable-dcond (cpdist &key (fill-value nil)) (let ((cpmutable (make-instance 'dcond-mutable))) (with-slots (htable) cpmutable (setf htable (make-hash-table :test 'equal)) (dolist (condi (pdist-cond-conds cpdist)) (setf (gethash condi htable) (copy-mutable-dprob (fdist-value cpdist condi) :fill-value fill-value)))) cpmutable)) ;;; log probability (defvar *log-infinity* -99.999) (defun logprob (prob) (if (> prob 0.0) (log prob) *log-infinity*)) (defun logprod (&rest probs) "log(prod1 * prod2 * ...) = log(prod1) + log(prod2) + ..." (reduce #'+ (mapcar #'logprob probs) :initial-value 0.0)) (defun rlogprod (&rest probs) "prob1 + log(prob2) + ..., i.e., prob1 already in log form" (+ (car probs) (apply #'logprod (cdr probs)))) (defun sumexp (&rest logprobs) "meant to calculate probability summation NOTICE: unlike (cl-ml::logsumexp), there will be no overflow problems for exp() with probability as operands" (reduce #'+ (mapcar #'exp logprobs) :initial-value 0.0)) (defun logsumexp (&rest logprobs) "probability summation and then do log again NOTICE: unlike (cl-ml::logsumexp), there will be no overflow problems for exp() with probability operands" (logprob (apply #'sumexp logprobs))) ;;; random probability (defun randprob1d (n &optional (state *random-state*)) (let* ((prob1d (randuni 1.0 n state)) (sum (reduce #'+ prob1d :initial-value 0.0))) (mapcar (lambda (x) (/ x sum)) prob1d))) (defun randprob2d (m n &optional (state *random-state*)) (let ((prob2d (make-list m :initial-element nil))) (dotimes (i m) (setf (nth i prob2d) (randprob1d n state))) prob2d))
4,272
Common Lisp
.lisp
100
38.04
91
0.614052
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
24986a4b589ba1fcf1580c9ac3ac55156eeb41141de6ba25de24eb2d0f8ba19a
24,493
[ -1 ]
24,494
condfreq.lisp
jnjcc_cl-nlp/probs/condfreq.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Conditional Probability Distribution from Conditional Frequency Distribution (in-package #:cl-nlp) (defclass cond-freq-dist (freq-dist-hash) ()) (defmethod fdist-cond-value ((cfdist cond-freq-dist) condi key) (let ((fdist (fdist-value cfdist condi))) (when fdist (fdist-value fdist key)))) (defmethod fdist-cond-freq ((cfdist cond-freq-dist) condi key) "freq(key | condi), will return 0 when `fdist-cond-value' returns nil" (let ((fdist (fdist-value cfdist condi))) (if fdist (fdist-freq fdist key) 0))) (defmethod fdist-cond-incf ((cfdist cond-freq-dist) condi key &optional (delta 1)) (with-slots (test htable) cfdist (let ((fdist (fdist-value cfdist condi))) (unless fdist (setf fdist (make-freq-dist :hash :test test)) (fdist-setf cfdist condi fdist)) (fdist-incf fdist key delta) ))) (defmethod fdist-cond-setf ((cfdist cond-freq-dist) condi key value) (with-slots (test htable) cfdist (let ((fdist (fdist-value cfdist condi))) (unless fdist (setf fdist (make-freq-dist :hash :test test)) (fdist-setf cfdist condi fdist)) (fdist-setf fdist key value)))) ;; how many (`condi', `key') pairs are there? (defmethod fdist-cond-bins ((cfdist cond-freq-dist)) (let ((bins 0) (fdist nil)) (dolist (condi (fdist-keys cfdist)) (setf fdist (fdist-value cfdist condi)) (when fdist (incf bins (fdist-bin fdist)))) bins)) ;;; Derived Probability Distribution, with smoothing (defmethod fdist-cond-sum ((cfdist cond-freq-dist) condi) (let ((fdist (fdist-value cfdist condi))) (fdist-sum fdist))) ;; loop through all (`condi', `key', `value') pairs such that CF(`key'|`condi')=`value' ;; TODO: this macro cannot do (RETURN) right (defmacro do-cond-pairs ((condi key value cfdist) &body body) `(let ((,value nil)) (dolist (,condi (fdist-keys ,cfdist)) (dolist (,key (fdist-keys (fdist-value ,cfdist ,condi))) (setf ,value (fdist-cond-value ,cfdist ,condi ,key)) ,@body)))) ;; Given `condi', loop through all (`key', `value') pairs such that CP(`key'|`condi')=`value' (defmacro do-cond-values ((key value condi cfdist) &body body) `(let ((,value nil)) (dolist (,key (fdist-keys (fdist-value ,cfdist ,condi))) (setf ,value (fdist-cond-value ,cfdist ,condi ,key)) ,@body))) ;;; make-* functions (defun make-cond-freq (&key (test nil)) (make-instance 'cond-freq-dist :test test))
2,563
Common Lisp
.lisp
61
37.377049
93
0.661983
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6a4b1589aa5790a36f52e420b6476c121a547cdb5c812cdf03af50f73a370e26
24,494
[ -1 ]
24,495
freqdist.lisp
jnjcc_cl-nlp/probs/freqdist.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Frequency Distribution (in-package #:cl-nlp) ;;; <key, value> pairs, where value not necessarily being frequency (defclass freq-dist () ((test :initform nil :initarg :test))) (defgeneric fdist-key (fdist key) (:documentation "returns (key . freq) or nil if not exists")) (defmethod fdist-value ((fdist freq-dist) key) "return value associated with `key', not necessarily frequency" (cdr (fdist-key fdist key))) (defmethod fdist-freq ((fdist freq-dist) key) "return freq associated with `key'" (let ((pair (fdist-key fdist key))) (if pair (cdr pair) 0))) (defgeneric for-each-pair (fdist op) (:documentation "do `op' on each (key . value) pair")) (defmethod fdist-keys ((fdist freq-dist)) "return keys into a list" (let ((keylst nil)) (labels ((collect (key value) (declare (ignore value)) (push key keylst))) (for-each-pair fdist #'collect)) keylst)) (defgeneric fdist-incf (fdist key &optional delta) (:documentation "incf value associated with `key' by `delta'")) (defgeneric fdist-setf (fdist key value) ) (defgeneric fdist-decf (fdist key &optional delta) (:documentation "decf value associated with `key' by `delta'")) (defgeneric fdist-count (fdist lst &optional start end) (:documentation "count frequency distribution from `lst'")) (defmethod fdist-count ((fdist freq-dist) lst &optional (start 0) end) (unless end (setf end (length lst))) (do ((i start (1+ i))) ((>= i end)) (fdist-incf fdist (nth i lst)))) ;;; Derived Probability Distribution, with smoothing (defgeneric fdist-sum (fdist) (:documentation "total frequency of all keys, i.e., N NOTICE: only called when we are sure there will be no more `fdist-incf'")) (defgeneric fdist-bin (fdist) (:documentation "number of keys, i.e., B NOTICE: only called when we are sure there will be no more `fdist-incf'")) ;; loop through all (`key', `value') pairs such that F(`key')=`value' (defmacro do-fdist-pairs ((key value fdist) &body body) `(let ((,value nil)) (dolist (,key (fdist-keys ,fdist)) (setf ,value (fdist-value ,fdist ,key)) ,@body))) ;;; make-* functions (defun make-freq-dist (type &key (test nil)) (ecase type (:bin (make-instance 'freq-dist-bins :test test)) (:hash (make-instance 'freq-dist-hash :test test))))
2,424
Common Lisp
.lisp
60
36.75
74
0.681005
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
54444c0ca4bfdd70106ea689c0f22cbbaa5a91e955bdcfe044851149f46d53de
24,495
[ -1 ]
24,496
hashfreq.lisp
jnjcc_cl-nlp/probs/hashfreq.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Frequency Distribution using hash-table (in-package #:cl-nlp) (defclass freq-dist-hash (freq-dist) ((htable :initform nil) (sumfreq :initform nil))) (defmethod initialize-instance :after ((fdist freq-dist-hash) &rest args) (declare (ignore args)) (with-slots (test htable) fdist (unless test (setf test 'eql)) (setf htable (make-hash-table :test test)))) (defmethod fdist-key ((fdist freq-dist-hash) key) (with-slots (htable) fdist (multiple-value-bind (value exist) (gethash key htable) (when exist (cons key value))))) (defmethod for-each-pair ((fdist freq-dist-hash) op) (with-slots (htable) fdist (maphash (lambda (key value) (funcall op key value)) htable))) (defmethod fdist-incf ((fdist freq-dist-hash) key &optional (delta 1)) (with-slots (htable) fdist (multiple-value-bind (value exist) (gethash key htable) (unless exist (setf value 0)) (incf value delta) (setf (gethash key htable) value)))) (defmethod fdist-setf ((fdist freq-dist-hash) key value) (with-slots (htable) fdist (setf (gethash key htable) value))) (defmethod fdist-decf ((fdist freq-dist-hash) key &optional (delta 1)) (with-slots (htable) fdist (multiple-value-bind (value exist) (gethash key htable) (when exist (decf value delta) (if (<= value 0) (remhash key htable) (setf (gethash key htable) value)))))) (defmethod fdist-sum ((fdist freq-dist-hash)) (with-slots (sumfreq htable) fdist (unless sumfreq (let ((freq 0)) (labels ((collect (key value) (declare (ignore key)) (incf freq value))) (maphash #'collect htable)) (setf sumfreq freq))) sumfreq)) (defmethod fdist-bin ((fdist freq-dist-hash)) (with-slots (htable) fdist (hash-table-count htable)))
1,945
Common Lisp
.lisp
52
31.884615
73
0.653744
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
eeef6491cc9dcfc821cecac796fe8d712ae157bdd6334076606eb7385261be46
24,496
[ -1 ]
24,497
mutabledist.lisp
jnjcc_cl-nlp/probs/mutabledist.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Mutable Probability Distribution (in-package #:cl-nlp) (defclass dprob-mutable (freq-dist-hash) ()) (defmethod init-from-literal ((pmutable dprob-mutable) keylst problst) "`keylst': (key1 key2 ...); problst: (prob1 prob2 ...)" (dotimes (i (length keylst)) (fdist-setf pmutable (nth i keylst) (nth i problst)))) (defmethod pdist-prob ((pmutable dprob-mutable) key) (fdist-value pmutable key)) (defmethod pdist-setf ((pmutable dprob-mutable) key value) (fdist-setf pmutable key value)) (defmethod pdist-incf ((pmutable dprob-mutable) key value) (fdist-incf pmutable key value)) (defmethod pdist-normalize ((pmutable dprob-mutable)) (let ((sumprob (fdist-sum pmutable))) (labels ((normalize (key value) (fdist-setf pmutable key (/ value sumprob)))) (for-each-pair pmutable #'normalize)))) (defclass dcond-mutable (dcond-prob-dist) ()) (defmethod pdist-cond-setf ((cpdist dcond-mutable) condi key value) (let ((pmutable (fdist-value cpdist condi))) (unless pmutable (setf pmutable (make-instance 'dprob-mutable))) (pdist-setf pmutable key value))) (defmethod pdist-cond-normalize ((cpdist dcond-mutable)) (labels ((normalize (condi pdist) (fdist-setf cpdist condi (pdist-normalize pdist)))) (for-each-pair cpdist #'normalize)))
1,391
Common Lisp
.lisp
32
39.65625
70
0.706449
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f2984a9ac93e160ab33141b4a2bf4785ab16e88287e210527fe23620d50b7fe1
24,497
[ -1 ]
24,498
derivdist.lisp
jnjcc_cl-nlp/probs/derivdist.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Derived Probability Distribution from Frequency Distribution (in-package #:cl-nlp) ;;; Derive (or, estimate) probability distribution from Frequency Distribution `fdist' ;;; just a view window of `fdist' (defclass dprob-dist () ((fdist :initform nil) ;; how many keys are there in `fdist'? (bins :initform nil :initarg :bins))) (defgeneric estimate-prob (pdist fdist) (:documentation "estimate probability from frequency distribution `fdist'")) (defmethod pdist-keys ((pdist dprob-dist)) (with-slots (fdist) pdist (fdist-keys fdist))) (defgeneric pdist-prob (pdist key) (:documentation "P(key)")) ;;; Derive (or, estimate) conditional probability distribution (defclass dcond-prob-dist (cond-freq-dist) ((bins :initform nil :initarg :bins))) (defmethod pdist-cond-conds ((cpdist dcond-prob-dist)) (fdist-keys cpdist)) (defmethod pdist-cond-prob ((cpdist dcond-prob-dist) condi key) "P(key | condi)" (let ((pdist (fdist-value cpdist condi))) (if pdist (pdist-prob pdist key) 0.0))) ;;; Maximum Likelihood Estimate from Frequency Distribution (defclass mle-prob-dist (dprob-dist) ()) (defmethod estimate-prob ((mle mle-prob-dist) from-fdist) (with-slots (fdist) mle (setf fdist from-fdist))) (defmethod pdist-prob ((mle mle-prob-dist) key) (with-slots (fdist) mle (/ (fdist-freq fdist key) (fdist-sum fdist)))) ;;; Lidstone Estimate from Frequency Distribution ;;; (c + gamma) / (N + B * gamma) (defclass lidstone-prob-dist (dprob-dist) ((gamma :initform 1.0 :initarg :gamma))) (defmethod estimate-prob ((lidstone lidstone-prob-dist) from) (with-slots (fdist) lidstone (setf fdist from))) (defmethod pdist-prob ((lidstone lidstone-prob-dist) key) (with-slots (fdist bins gamma) lidstone (let ((realbins bins)) ;; NOTICE: if `bins' supplied, use it! (some bin with freq=0 might not be in `fdist') ;; otherwise, derive bins from `fdist' (unless realbins (setf realbins (fdist-bin fdist))) (/ (+ (fdist-freq fdist key) gamma) (+ (fdist-sum fdist) (* realbins gamma))))))
2,178
Common Lisp
.lisp
53
37.660377
91
0.698721
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
43f196a2b9a862c6050ac30fd5728c0274cc77fb5250f6fd51834c8b27b86f78
24,498
[ -1 ]
24,499
binfreq.lisp
jnjcc_cl-nlp/probs/binfreq.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; lightweight frequency distribution using bins (in-package #:cl-nlp) (defclass freq-dist-bins (freq-dist) ((bins :initform nil) (sumfreq :initform nil) (binnums :initform nil))) (defmethod fdist-key ((fdist freq-dist-bins) key) (with-slots (test bins) fdist (if test (assoc key bins :test test) (assoc key bins)))) (defmethod for-each-pair ((fdist freq-dist-bins) op) (with-slots (bins) fdist (dolist (pair bins) (funcall op (car pair) (cdr pair))))) (defmethod fdist-incf ((fdist freq-dist-bins) key &optional (delta 1)) (with-slots (test bins) fdist (if (fdist-key fdist key) (if test (incf (cdr (assoc key bins :test test)) delta) (incf (cdr (assoc key bins)) delta)) (push (cons key delta) bins)))) (defmethod fdist-setf ((fdist freq-dist-bins) key value) (with-slots (test bins) fdist (if (fdist-key fdist key) (if test (setf (cdr (assoc key bins :test test)) value) (setf (cdr (assoc key bins)) value))) (when (= value 0) (setf bins (remove-if (lambda (x) (<= x 0)) bins :key #'cdr))))) (defmethod fdist-decf ((fdist freq-dist-bins) key &optional (delta 1)) (when (fdist-key fdist key) (with-slots (test bins) fdist (if test (decf (cdr (assoc key bins :test test)) delta) (decf (cdr (assoc key bins)) delta)) (setf bins (remove-if (lambda (x) (<= x 0)) bins :key #'cdr))))) (defmethod fdist-sum ((fdist freq-dist-bins)) (with-slots (sumfreq bins) fdist (unless sumfreq (setf sumfreq (reduce #'+ (mapcar #'cdr bins) :initial-value 0))) sumfreq)) (defmethod fdist-bin ((fdist freq-dist-bins)) (with-slots (binnums bins) fdist (unless binnums (setf binnums (length bins))) binnums))
1,877
Common Lisp
.lisp
49
32.918367
71
0.631666
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
2c87b38ddb33f1a3281282e58ff4086787ed729718b9f2e6a85a0aee6f93c5dc
24,499
[ -1 ]
24,500
vocab.lisp
jnjcc_cl-nlp/embed/vocab.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Vocabulary for word2vec (in-package #:cl-nlp) (defclass w2v-word-info () ((freq :initform 0 :initarg :freq :reader winfo-freq :documentation "word frequency") (indx :initform -1 :initarg :indx :reader winfo-indx :documentation "word to one-hot") (path :initform nil :reader winfo-path :documentation "huffman tree path from root to parent of leaf") (code :initform nil :reader winfo-code :documentation "huffman code: if left child 0, else 1"))) (defmethod print-object ((info w2v-word-info) stream) (with-slots (freq indx path code) info (format stream "freq: ~A; indx: ~A; code: ~A~%" freq indx code) (format stream "path:~A" path))) (defmethod incf-freq ((info w2v-word-info) &optional (delta 1)) (with-slots (freq) info (incf freq delta))) (defmethod fill-huffman ((info w2v-word-info) plst binary) (with-slots (path code) info (setf path plst) (setf code binary))) (defclass w2v-vocab () ((word-hash :initform (make-hash-table :test 'equal) :reader word-hash) ;; one-hot to word (indx-hash :initform (make-hash-table :test 'equal)) (vocab-size :initform 0 :reader vocab-size))) (defmethod has-word-in-vocab ((vocab w2v-vocab) word) (with-slots (word-hash) vocab (nth-value 1 (gethash word word-hash)))) (defmethod get-word-info ((vocab w2v-vocab) word) (with-slots (word-hash) vocab (gethash word word-hash))) (defmethod get-word-freq ((vocab w2v-vocab) word) (with-slots (word-hash) vocab (slot-value (gethash word word-hash) 'freq))) (defmethod get-word-indx ((vocab w2v-vocab) word) (with-slots (word-hash) vocab (slot-value (gethash word word-hash) 'indx))) (defmethod get-word-path ((vocab w2v-vocab) word) (with-slots (word-hash) vocab (slot-value (gethash word word-hash) 'path))) (defmethod get-word-code ((vocab w2v-vocab) word) (with-slots (word-hash) vocab (slot-value (gethash word word-hash) 'code))) (defmethod get-indx-word ((vocab w2v-vocab) indx) (with-slots (indx-hash) vocab (gethash indx indx-hash))) (defmethod add-word-safe ((vocab w2v-vocab) word freq) (with-slots (word-hash indx-hash vocab-size) vocab (setf (gethash word word-hash) (make-instance 'w2v-word-info :freq freq :indx vocab-size)) (setf (gethash vocab-size indx-hash) word) (incf vocab-size))) (defmethod incf-word-freq ((vocab w2v-vocab) word freq) (with-slots (word-hash) vocab (incf-freq (gethash word word-hash) freq))) (defmethod add-word-to-vocab ((vocab w2v-vocab) word &optional (freq 1)) (if (has-word-in-vocab vocab word) (incf-word-freq vocab word freq) (add-word-safe vocab word freq))) (defmethod sorted-vocab ((vocab w2v-vocab) &key (compare #'>) (filter :value)) (with-slots (word-hash) vocab (let ((vocab-lst nil)) (labels ((collect (word info) (ecase filter (:full (push (list word info) vocab-lst)) (:key (push (list word info) vocab-lst)) (:value (push info vocab-lst))))) (maphash #'collect word-hash)) (ecase filter (:full (sort vocab-lst compare :key (lambda (info) (winfo-freq (second info))))) (:key (mapcar #'car (sort vocab-lst compare :key (lambda (info) (winfo-freq (second info)))))) (:value (sort vocab-lst compare :key (lambda (info) (winfo-freq info)))))))) (defmethod create-huffman ((vocab w2v-vocab)) (let ((winfos (sorted-vocab vocab :compare #'< :filter :value))) (multiple-value-bind (huff coding parents binarys) (huffman-from-list winfos :coded t :keyfn #'identity :freqfn #'winfo-freq :sorted t) (declare (ignore huff coding)) (let ((path nil) (nleaf (length winfos))) (dotimes (i nleaf) (setf path nil) ;; `indx' is index of inner node, which should subtract `nleaf' (do ((indx (nth i parents) (nth indx parents))) ((null indx)) (push (- indx nleaf) path)) (fill-huffman (nth i winfos) path (nth i binarys))))))) (defun learn-vocab-from-memory (fpath &key (eow #\Space)) "small file which fits into memory" (let ((vocab (make-instance 'w2v-vocab))) (do-example-from-file (example indx fpath) (let ((words (split-string example eow))) (dolist (word words) (add-word-to-vocab vocab word)))) vocab)) (defun learn-vocab-from-file (fpath &key (eow #\Space) (eol #\Newline)) (let ((vocab (make-instance 'w2v-vocab)) (fs (open fpath))) (do-word (word fs :eow eow :eol eol) (unless (eq word :eol) (add-word-to-vocab vocab word))) (close fs) vocab)) (defun learn-vocab-from-string (string &key (eow #\Space) (eol #\Newline)) (let ((vocab (make-instance 'w2v-vocab)) (sents (split-string string eol)) (words nil)) (dolist (sent sents) (setf words (split-string sent eow)) (dolist (word words) (add-word-to-vocab vocab word))) vocab)) (defun learn-vocab-from-list (lsts) "`lsts' being list of lists" (let ((vocab (make-instance 'w2v-vocab))) (dolist (sent lsts) (dolist (word sent) (add-word-to-vocab vocab word))) vocab)) (defun get-next-sentence (iterable i &key (max-len 100) (eow #\Space) (eol #\Newline)) "get (i+1)-th sentence from stream, or list Returns: :eof if no more sentence; or list of words (could be empty list)" (etypecase iterable (stream (read-next-sentence iterable :max-len max-len :eow eow :eol eol)) (list (if (>= i (length iterable)) :eof (nth (+ i 1) iterable))) (t (error "get-next-sentence only supports stream or list"))))
5,867
Common Lisp
.lisp
132
38.022727
92
0.63673
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b68477268af27c3a483df77aabe79428ca36ae87091b8a48e6a9b62158022ee9
24,500
[ -1 ]
24,501
word2vec.lisp
jnjcc_cl-nlp/embed/word2vec.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp) (defclass word2vec () ((dimensions :initform 128 :initarg :dimensions :documentation "dimensionality of the word vectors") (vocabulary :initform nil :documentation "word2vec vocabulary") (in-matrix :initform nil :documentation "input vectors of words") (out-matrix :initform nil :documentation "output vectors of words") (window :initform 5 :initarg :window :documentation "maximum distance between center and context word") (min-count :initform 5 :initarg :min-count :documentation "discard words with frequency less than this") (max-sents :initform 100 :initarg :max-sents :documentation "max length of training sentences") (algo :initform :skip-gram :initarg :algo :documentation "training algorithm: :skip-gram or :cbow") (eta0 :initform 0.025 :initarg :eta0 :documentation "the starting learning rate, default is 0.025 for :skip-gram and 0.05 for :cbow") (eta :initform nil :documentation "learn rate schedule") (hsoftmax :initform nil :initarg :hsoftmax :documentation "hierarchical softmax, t or nil") (negsample :initform 5 :initarg :negsample :documentation "number of noise words in negative sampling, common values are [3, 10]") (negtable :initform nil :documentation "sampling table for negative sampling") (epochs :initform 100 :initarg :epochs :documentation "number of epochs over the corpus"))) (defmethod %widx ((w2v word2vec) word) "word string -> matrix index" (with-slots (vocabulary) w2v (get-word-indx vocabulary word))) (defmethod %winv ((w2v word2vec) word) "input vector for word" (with-slots (in-matrix) w2v (mrv in-matrix (%widx w2v word)))) (defmethod %winvi ((w2v word2vec) i) "input vector for i-th word" (with-slots (in-matrix) w2v (mrv in-matrix i))) (defmethod %woutv ((w2v word2vec) word) "output vector for word" (with-slots (out-matrix) w2v (mcv out-matrix (%widx w2v word)))) (defmethod %woutvi ((w2v word2vec) i) "output vector for i-th word" (with-slots (out-matrix) w2v (mcv out-matrix i))) (defmethod %word ((w2v word2vec) indx) "matrix index -> word string" (with-slots (vocabulary) w2v (get-indx-word vocabulary indx))) (defmethod initialize-instance :after ((w2v word2vec) &rest args) (declare (ignore args)) (with-slots (eta0 eta) w2v (setf eta eta0))) (defmethod learn-rate-schedule ((w2v word2vec) nwords) (with-slots (vocabulary eta0 eta) w2v (let ((vocsz (vocab-size vocabulary))) (setf eta (* eta0 (- 1 (/ nwords (+ vocsz 1))))) (when (< eta (* eta0 0.0001)) (setf eta (* eta0 0.0001)))))) (defmethod hierarchal-softmax ((w2v word2vec) sentence center randwin hiddens hidgrad) ":cbow, `hiddens' is average of context words, `center' is target word; :skip-gram, `hiddens' is of context word (which is a little different from papers), while `center' is still target word" (with-slots (vocabulary algo eta) w2v (create-huffman vocabulary) ;; (yhat - label) * vj, where vj is inner node of huffman tree ;; `hpath': huffman path for `center' word, contains inner node index into `out-matrix' (let (yhat label vj hpath) ;; left child: label 1; right child: label 0 (setf label (- 1 (get-word-code vocabulary (nth center sentence)))) (setf hpath (get-word-path vocabulary (nth center sentence))) (dolist (nidx hpath) (setf vj (%woutvi w2v nidx)) (setf yhat (cl-ml::sigmoid (vdot vj hiddens))) ;; eta * (yhat - label) (setf yhat (* eta (- yhat label))) (do-vector (i hidgrad) (incf (vref hidgrad i) (* yhat (vref vj i)))) (do-vector (i vj) (decf (vref vj i) (* yhat (vref hiddens i))))) (ecase algo (:cbow ;; update gradient for each context word (do ((context (- center randwin) (1+ context))) ((> context (+ center randwin))) (when (and (< -1 context (length sentence)) (/= context center)) (setf hiddens (%winv w2v (nth context sentence))) (do-vector (i hiddens) ;; maybe we should multiply 1/cw on gradient (decf (vref hiddens i) (vref hidgrad i)))))) (:skip-gram ;; with :skip-gram, `hiddens' is just alias of `context' word (do-vector (i hiddens) (decf (vref hiddens i) (vref hidgrad i)))))))) (defmethod subsmpling-word ((w2v word2vec)) "The subsampling randomly discards frequent words while keeping the ranking same" ) ;;; TODO: negative sampling (defmethod %init-negative-sampling ((w2v word2vec)) ) (defmethod neg-sampling-word ((w2v word2vec)) (with-slots (in-matrix) w2v (random (nrow in-matrix)))) (defmethod negative-sampling ((w2v word2vec) sentence center randwin hiddens hidgrad) "(`center', context) is a training sample; with `hiddens' being input vector of `context'!!!" (with-slots (algo eta negsample) w2v ;; (yhat - label) * vj, where vj is negative words, or `center' ;; `cidx': index of `center' into `out-matrix' (let (yhat label vj cidx) (setf cidx (%widx w2v (nth center sentence))) (dotimes (neg (+ negsample 1)) (if (= neg 0) (setf vj cidx label 1) ;; (`center', `context'): positive sample (setf vj (neg-sampling-word w2v) label 0)) (when (or (= label 1) (/= vj cidx)) (setf vj (%woutvi w2v vj)) (setf yhat (cl-ml::sigmoid (vdot vj hiddens))) ;; eta * (yhat - label) (setf yhat (* eta (- yhat label))) ;; hgradsum := hgradsum + [eta * (yhat - label)] * vj (do-vector (i hidgrad) (incf (vref hidgrad i) (* yhat (vref vj i)))) ;; vj := vj - [eta * (yhat - label)] * h (do-vector (i vj) (decf (vref vj i) (* yhat (vref hiddens i)))))) (ecase algo (:cbow ;; update gradient for each context word (do ((context (- center randwin) (1+ context))) ((> context (+ center randwin))) (when (and (< -1 context (length sentence)) (/= context center)) (setf hiddens (%winv w2v (nth context sentence))) (do-vector (i hiddens) ;; maybe we should multiply 1/cw on gradient (decf (vref hiddens i) (vref hidgrad i)))))) (:skip-gram (do-vector (i hiddens) (decf (vref hiddens i) (vref hidgrad i)))))))) (defmethod fit-cbow ((w2v word2vec) sentence center randwin hiddens hidgrad) "CBOW using hierarchal softmax or negative sampling" (with-slots (hsoftmax negsample) w2v (let ((cw 0)) (do-vector (i hiddens) (setf (vref hiddens i) 0)) (do ((context (- center randwin) (1+ context))) ((> context (+ center randwin))) (when (and (< -1 context (length sentence)) (/= context center)) (incf cw) (m+= hiddens (%winv w2v (nth context sentence))))) (when (> cw 0) (m/= hiddens cw) ;; NOTICE: `hidgrad' is gradient of `hiddens' ;; for cbow, there is only one target word `center' (do-vector (i hidgrad) (setf (vref hidgrad i) 0)) (cond (hsoftmax (hierarchal-softmax w2v sentence center randwin hiddens hidgrad)) ((> negsample 0) (progn (negative-sampling w2v sentence center randwin hiddens hidgrad))) (t (error "one of :hsoftmax or :negsample needed for CBOW"))))))) (defmethod fit-skip-gram ((w2v word2vec) sentence center randwin hidgrad) "Skip-gram using hierarchal softmax or negative sampling for :skip-gram, `hiddens' = (mrv in-matrix center)" (with-slots (hsoftmax negsample) w2v (let ((hiddens nil) ;; NOTICE: `hiddens' should have been vector of `center' ;; in word2vec, we switch to `context', and `center' became the target word ;; (hiddens (%winv w2v (nth center sentence))) ) (do ((context (- center randwin) (1+ context))) ((> context (+ center randwin))) (when (and (< -1 context (length sentence)) (/= context center)) ;; NOTICE: `hidgrad' should have been gradient of `center' vector: ;; summed across all context words ;; Now it is just gradient of `context': ;; summed across huffman inner vector in hierarchal-softmax ;; summed across `center' and negative sampling words in negative-sampling (setf hiddens (%winv w2v (nth context sentence))) (do-vector (i hidgrad) (setf (vref hidgrad i) 0)) (cond (hsoftmax (hierarchal-softmax w2v sentence center randwin hiddens hidgrad)) ((> negsample 0) (progn (negative-sampling w2v sentence center randwin hiddens hidgrad))) (t (error "one of :hsoftmax or :negsample needed for Skip-gram")))))))) (defmethod %init-network ((w2v word2vec) vocab) (with-slots (dimensions vocabulary in-matrix out-matrix) w2v (setf vocabulary vocab) (with-slots (vocab-size) vocab (setf in-matrix (make-rand-matrix vocab-size dimensions)) (setf out-matrix (make-rand-matrix dimensions vocab-size))))) (defmethod %fit-from ((w2v word2vec) from type) (ecase type (:list (%init-network w2v (learn-vocab-from-list from))) (:file (%init-network w2v (learn-vocab-from-file from))) (:string (%init-network w2v (learn-vocab-from-string from)))) (format t "Vocab size: ~A~%" (vocab-size (slot-value w2v 'vocabulary))) (with-slots (dimensions window max-sents algo negsample epochs) w2v (when (> negsample 0) (%init-negative-sampling w2v)) (let (;; # of sentences, # of words, # of words in current sentence (nsents 0) (nwords 0) (ncwords 0) (corpus nil) ;; hidden layer vector and hidden layer gradient (hiddens (make-row-vector dimensions :initial-element 0)) (hidgrad (make-vector dimensions :initial-element 0))) (dotimes (ep epochs) (ecase type (:file (setf corpus (open from))) (:string (setf corpus (make-string-input-stream from))) (:list (setf corpus from))) (do ((sentence (get-next-sentence corpus nsents :max-len max-sents) (get-next-sentence corpus nsents :max-len max-sents))) ((eq sentence :eof)) (incf nsents) (setf ncwords 0) (dotimes (center (length sentence)) (incf nwords) (incf ncwords) (when (= (nth-value 1 (floor nwords 10000)) 0) ;; learn rate schedule every 1w words (learn-rate-schedule w2v nwords)) (let* ((b (randint window)) ;; [-window, window] -> [-window + b, window - b] (randwin (- window b))) (ecase algo (:cbow (fit-cbow w2v sentence center randwin hiddens hidgrad)) ;; no need to fill `hiddens' for Skip-gram (:skip-gram (fit-skip-gram w2v sentence center randwin hidgrad)))))) (case type ((:file :string) (close corpus))))))) (defmethod fit ((w2v word2vec) X &optional y) "by default, fit from file" (declare (ignore y)) (%fit-from w2v X :file)) (defmethod fit-from-string ((w2v word2vec) X &optional y) (declare (ignore y)) (%fit-from w2v X :string)) (defmethod fit-from-list ((w2v word2vec) X &optional y) (declare (ignore y)) (%fit-from w2v X :list)) (defmethod has-embedding ((w2v word2vec) X) (with-slots (vocabulary) w2v (has-word-in-vocab vocabulary X))) (defmethod transform ((w2v word2vec) X) (with-slots (vocabulary in-matrix) w2v (let ((idx (get-word-indx vocabulary X))) (mrv in-matrix idx)))) (defmethod sim-word ((w2v word2vec) X &optional (n 10)) (with-slots (vocabulary in-matrix) w2v (let ((idx (get-word-indx vocabulary X)) (sims nil)) (do-matrix-row (i in-matrix) (unless (= i idx) (push (cons i (cosine-distance (mrv in-matrix i) (mrv in-matrix idx))) sims))) (setf sims (sort sims #'> :key #'cdr)) (mapcar (lambda (pair) (cons (get-indx-word vocabulary (car pair)) (cdr pair))) (subseq sims 0 n)))))
12,538
Common Lisp
.lisp
272
38.102941
95
0.615391
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
ba231eb06bcdd50c22969ac0d4fe757a3a5ad286d591c3ea453bd0fe19c30b17
24,501
[ -1 ]
24,502
node2vec.lisp
jnjcc_cl-nlp/embed/node2vec.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp) (defclass node2vec () ((embed-size :initform 128 :initarg :embed-size :documentation "embedding size") (w2v-model :initform nil :documentation "word2vec model") (walk-length :initform 80 :initarg :walk-length :documentation "random walk steps") (num-walks :initform 10 :initarg :num-walks :documentation "number of walks per src, thus the total number of walks is `num-walks' * `node-count'") (return-p :initform 1 :initarg :return-p :documentation "parameter p controls the likelihood of immediately revisiting a node in the walk.") (inout-q :initform 1 :initarg :inout-q :documentation "parameter q allows the search to differentiate between 'inward' and 'outward' nodes") (alias-nodes :initform nil :documentation "init alias sampling for nodes") (alias-edges :initform nil :documentation "init alias sampling for edges"))) (defun %alias-from-weights (weights) (multiple-value-bind (ptable atable) (alias-initialize weights) (list ptable atable))) (defmethod alias-of-edge ((n2v node2vec) X src dst weight) "the core transition probability of node2vec" (with-slots (return-p inout-q) n2v (let ((neighbors (sorted-neighbors X dst)) (dst-nbr nil) (dst-wei nil) (weights nil)) (dolist (dst-lst neighbors) (setf dst-nbr (first dst-lst)) (setf dst-wei (second dst-lst)) (cond ;; trying to return to `src': [weight / p] ((same-node X dst-nbr src) (push (/ dst-wei return-p) weights)) ;; trying to go to neighbors of `dst'; edge exists between neighbor and `src' ((has-edge X dst-nbr src) (push dst-wei weights)) ;; trying to go to neighbors of `dst'; no edge exists between neighbor and `src' (t (push (/ dst-wei inout-q) weights)))) (setf weights (nreverse weights)) (%alias-from-weights weights)))) (defmethod alias-of-node ((n2v node2vec) X node value) (declare (ignore value)) (let ((neighbors (sorted-neighbors X node)) (weights nil)) (setf weights (mapcar #'second neighbors)) (%alias-from-weights weights))) (defmethod init-trans-probs ((n2v node2vec) X) "probabilities of node and edge for random walk" (with-slots (alias-nodes alias-edges) n2v (setf alias-nodes (make-hash-table :test (cl-ml/graph::node-eq X))) (setf alias-edges (make-hash-table :test 'equal)) (do-graph-nodes (node value X) (setf (gethash node alias-nodes) (alias-of-node n2v X node value))) (ecase (graph-type X) (:undirected (do-graph-edges (un vn weight X) (setf (gethash (list un vn) alias-edges) (alias-of-edge n2v X un vn weight)) (setf (gethash (list vn un) alias-edges) (alias-of-edge n2v X vn un weight)))) (:directed (do-graph-edges (un vn weight X) (setf (gethash (list un vn) alias-edges) (alias-of-edge n2v X un vn weight))))))) (defmethod simulate-one-walk ((n2v node2vec) X src) "Requires: (init-trans-probs) called!" (with-slots (walk-length alias-nodes alias-edges) n2v (let ((walk-lst (list src)) ;; edge of (`prenode', `curnode') (prenode nil) (curnode nil) ;; alias tables of `curnode', or of the edge (`prenode', `curnode') (ctables nil) ;; neighbors of `curnode' (curnbrs nil)) (dotimes (step (- walk-length 1)) (setf curnode (car walk-lst)) ;; we do not need edge weight now (setf curnbrs (sorted-neighbors X curnode :weighted nil)) (when (null curnbrs) (return)) (if (= (length walk-lst) 1) (setf ctables (gethash curnode alias-nodes)) (progn (setf prenode (second walk-lst)) (setf ctables (gethash (list prenode curnode) alias-edges)))) (push (alias-draw-element curnbrs (first ctables) (second ctables)) walk-lst)) (nreverse walk-lst)))) (defmethod simulate-walks ((n2v node2vec) X) "Repeatedly simulate random walks from each node Requires: (init-trans-probs) called!" (with-slots (num-walks) n2v (let ((walks nil) (nodes (get-nodes X :valued nil))) (dotimes (i num-walks) (shuffle nodes) (dolist (src nodes) (push (simulate-one-walk n2v X src) walks))) walks))) (defmethod fit ((n2v node2vec) X &optional y) "X as a graph" (declare (ignore y)) (init-trans-probs n2v X) (with-slots (embed-size w2v-model) n2v (setf w2v-model (make-instance 'word2vec :dimensions embed-size)) (let ((walks (simulate-walks n2v X))) (fit-from-list w2v-model walks)))) (defmethod transform ((n2v node2vec) node) (with-slots (w2v-model) n2v (transform w2v-model node)))
4,806
Common Lisp
.lisp
104
39.807692
90
0.653666
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9fe9738f58fb6678a1b601d11939d23ac18affc16175a04548bfc00f04ca1b63
24,502
[ -1 ]
24,503
bidict.lisp
jnjcc_cl-nlp/algo/bidict.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Bidirectional dictionary using association list / hash-table ;;;; - forward: string -> int (which is unique, mainly used as indices) ;;;; - backward: int -> string (in-package #:cl-nlp/algo) ;;; Bidirectional dictionary using association list (defun make-badict () (list (make-adict) (make-adict))) (defun badict-len (badict) (adict-len (car badict))) (defmacro badict-add (badict key value) (let ((old-sym (gensym "OVAL-"))) `(let ((,old-sym (adict-ref (car ,badict) ,key))) (adict-add (car ,badict) ,key ,value) (when ,old-sym (setf (cadr ,badict) (remove-if (lambda (x) (eq (car x) ,old-sym)) (cadr ,badict)))) (push (cons ,value ,key) (cadr ,badict))))) (defun zip-badict (keys values) (list (zip-adict keys values) (zip-adict values keys))) (defun badict-ref (badict key) (adict-ref (car badict) key)) (defun badict-bref (badict value) "backward reference" (cdr (assoc value (cadr badict)))) ;;; Bidirectional dictionary using hash-table (defun make-bhdict () (list (make-hdict) (make-hdict))) (defun bhdict-len (bhdict) (hdict-len (car bhdict))) (defun bhdict-add (bhdict key value) (unless value (error "NOTICE: we do not allow nil values in bhdict")) (setf (gethash key (car bhdict)) value (gethash value (cadr bhdict)) key)) (defun zip-bhdict (keys values) (let ((bhdict (make-bhdict))) (dotimes (i (length keys)) (bhdict-add bhdict (nth i keys) (nth i values))) bhdict)) (defun bhdict-ref (bhdict key) (hdict-ref (car bhdict) key)) (defun bhdict-bref (bhdict value) (hdict-ref (cadr bhdict) value))
1,699
Common Lisp
.lisp
45
34.333333
93
0.669104
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1815bd5849156b2cd0e0869201b87a92658a9e220f333fe49f337be851cd435d
24,503
[ -1 ]
24,504
distance.lisp
jnjcc_cl-nlp/algo/distance.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Edit Distance (in-package #:cl-nlp/algo) (defun edit-distance (lst1 lst2 &key (equal #'string=)) (let ((m (length lst1)) (n (length lst2)) (leven nil)) (setf leven (make-array (list (+ m 1) (+ n 1)) :initial-element 0)) ;; leven[i][0] (dotimes (i (+ m 1)) (setf (aref leven i 0) i)) ;; leven[0][j] (dotimes (j (+ n 1)) (setf (aref leven 0 j) j)) (let ((rplce nil) (i nil) (j nil)) (dotimes (l1 m) ;; leven[1:][1:] (setf i (+ l1 1)) (dotimes (l2 n) (setf j (+ l2 1)) (if (funcall equal (nth l1 lst1) (nth l2 lst2)) (setf rplce 0) (setf rplce 1)) (setf (aref leven i j) (min (+ (aref leven (- i 1) j) 1) (+ (aref leven i (- j 1)) 1) (+ (aref leven (- i 1) (- j 1)) rplce)))))) (aref leven m n)))
987
Common Lisp
.lisp
30
24.7
71
0.463874
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
70d3e9a1b0ef2c34b41420fbe822620e30f2ac72391abc69068433c705693842
24,504
[ -1 ]
24,505
dict.lisp
jnjcc_cl-nlp/algo/dict.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Dictionary (for string) using association list / hash-table ;;;; (cl-ml::bins) mainly used for non-string keys (in-package #:cl-nlp/algo) ;;; Dictionary using association list (defun make-adict () nil) (defun adict-len (adict) (length adict)) ;; similar to `binincf' (defmacro adict-add (adict key value) `(if (assoc ,key ,adict :test #'string=) (setf (cdr (assoc ,key ,adict :test #'string=)) ,value) (push (cons ,key ,value) ,adict))) ;; similar to `binpush', append `value' to value list of `key' (defmacro adict-append (adict key value) `(if (assoc ,key ,adict :test #'string=) (setf (cdr (assoc ,key ,adict :test #'string=)) (append (cdr (assoc ,key ,adict :test #'string=)) (list ,value))) (push (cons ,key (list ,value)) ,adict))) (defun zip-adict (keys values) (mapcar #'cons keys values)) (defun adict-ref (adict key) (cdr (assoc key adict :test #'string=))) ;;; Dictionary using hash-table (defun make-hdict () (make-hash-table :test 'equal)) (defun hdict-len (hdict) (hash-table-count hdict)) (defun hdict-add (hdict key value) (unless value (error "NOTICE: we do not allow nil values in hdict")) (setf (gethash key hdict) value)) (defun hdict-append (hdict key value) (multiple-value-bind (val exist) (gethash key hdict) (unless exist (setf val nil)) (setf val (append val (list value))) (setf (gethash key hdict) val))) (defun zip-hdict (keys values) (let ((hdict (make-hdict))) (dotimes (i (length keys)) (hdict-add hdict (nth i keys) (nth i values))) hdict)) (defun hdict-ref (hdict key) ;; nil value not allowed during `hdict-add' (gethash key hdict))
1,786
Common Lisp
.lisp
49
32.612245
66
0.656032
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
2949d58339ea12e8c1105ed9f0e600950887522df3c880b1e4eebecff2f69f00
24,505
[ -1 ]
24,506
packages.lisp
jnjcc_cl-nlp/algo/packages.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; Common data structure and algorithms for NLP (in-package #:cl-user) (defpackage #:cl-nlp/algo (:nicknames #:nlp/algo) (:use #:cl) (:export #:edit-distance #:make-adict #:zip-adict #:adict-len #:adict-add #:adict-append #:adict-ref #:make-hdict #:zip-hdict #:hdict-len #:hdict-add #:hdict-append #:hdict-ref #:make-badict #:zip-badict #:badict-len #:badict-add #:badict-ref #:badict-bref #:make-bhdict #:zip-bhdict #:bhdict-len #:bhdict-add #:bhdict-ref #:bhdict-bref ))
611
Common Lisp
.lisp
13
41.076923
90
0.628571
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
561d571016833806e8ce1790acd010c90914992dee1900526d6e3e542c762a67
24,506
[ -1 ]
24,507
ner.lisp
jnjcc_cl-nlp/ner/ner.lisp
;;;; Copyright (c) 2012-2015 jnjcc, Yste.org. All rights reserved. ;;;; (in-package #:cl-nlp)
95
Common Lisp
.lisp
3
30.333333
66
0.67033
jnjcc/cl-nlp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6cfe5215477f9a7c193dbfaf5d3abfaa98690f4d48a58c27c246d32e5846c49d
24,507
[ -1 ]