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
19,165
similarity.lisp
Eggy115_Lisp/kgn/similarity.lisp
;; tools for ranking similarity of any two things (in-package #:kgn) (defun compare-name-to-uri (name uri) ;; Assume URI is in the form <http://dbpedia.org/resource/United_States_Senate_career_of_Barack_Obama> (let* ((last-slash-index (or (search "/" uri :from-end t) 0)) (uri-suffix (remove #\Space (subseq uri (+ last-slash-index 1)))) (cleaned-uri-suffix (remove #\/ uri)) (squashed-name (string-downcase (remove #\Space name))) (score (float (/ (length (intersection (coerce cleaned-uri-suffix 'list) (coerce squashed-name 'list))) (length uri-suffix))))) (print (list uri-suffix squashed-name score)) score)) (defun ta () (compare-name-to-uri "Barack Obama" "<http://dbpedia.org/resource/United_States_Senate_career_of_Barack_Obama>") (compare-name-to-uri "Barack Obama" "<http://dbpedia.org/resource/Barack_Obama>"))
914
Common Lisp
.lisp
14
57.785714
137
0.673143
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f2cd36b342f097e8a898faab59df5172eb1e8a448a100e76957f45310dcefece
19,165
[ -1 ]
19,166
gen-output.lisp
Eggy115_Lisp/kgn/gen-output.lisp
(in-package #:kgn) (defun write-to-output (sparql-string &key (output-stream t) (output-type :sparql)) nil)
115
Common Lisp
.lisp
3
35
84
0.7
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
97fdd00a96b27c27a7cb627ae42a97f7f840cfac7998ea0ebb4e246858476ac8
19,166
[ -1 ]
19,167
deliver.lisp
Eggy115_Lisp/kgn/deliver.lisp
;; LispWorks, to be run from command line (not multiprocessing): ;; ;; lispworks -build deliver.lisp (in-package "CL-USER") (load-all-patches) (load "~/quicklisp/setup.lisp") (ql:quickload "kgn") #| (deliver 'kgn:kgn #+:cocoa (create-macos-application-bundle "~/KnowledgeGraphNavigator.app" ;; Do not copy file associations... :document-types nil ;; ...or CFBundleIdentifier from the LispWorks bundle :identifier "com.markwatson.kgn" ) #-:cocoa "~/hello" 0 :interface :capi :startup-bitmap-file nil ;;:template-bundle (pathname-location ;; (current-pathname "templates/KnowledgeGraphNavigator.app/")) :KEEP-PRETTY-PRINTER t :split :resources) |# (defvar *target-application-path* "~/KnowledgeGraphNavigator.app") (deliver 'kgn:kgn (create-macos-application-bundle *target-application-path* :template-bundle (pathname-location (current-pathname "templates/KnowledgeGraphNavigator.app/"))) 0 :interface :capi :KEEP-PRETTY-PRINTER t :split :resources :startup-bitmap-file nil )
1,307
Common Lisp
.lisp
38
25.131579
90
0.590072
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3efbf53525759f766a4a373486732ff92c26c0ab9d840bd3a76ebda05db49cc7
19,167
[ -1 ]
19,168
gui.lisp
Eggy115_Lisp/kgn/gui.lisp
;;---------------------------------------------------------------------------- ;; To try it, compile and load this file and then execute: ;; ;; (kgn::kgn) ;; ;;---------------------------------------------------------------------------- ;; Copyright (c) 2020 Mark Watson. All rights reserved. ;;---------------------------------------------------------------------------- (in-package #:kgn) (defvar *width* 1370) (defvar *best-width* 1020) (defvar *show-info-pane* t) (defvar *pane2-message* "In order to process your query a series of SPARQL queries will be formed based on the query. These generated SPARQL queries will be shown here and the reuslts of the queries will be formatted and displayed in the results display pane below.") (defvar *pane3-message* "Enter a query containing entities like people's names, companys, places, etc. following by the RETURN key to start processing your query. You can also directly use a DBPedia URI for an entity, for example: <http://dbpedia.org/resource/Apple_Inc.> When you start this application, a sample query is randomly chosen to get you started.") (defun test-callback-click (selected-node-name) (ignore-errors (format nil "* user clicked on node: ~A~%" selected-node-name))) (defun test-callback-click-shift (selected-node-name) (ignore-errors (if (equal (subseq selected-node-name 0 5) "<http") (trivial-open-browser:open-browser (subseq selected-node-name 1 (- (length selected-node-name) 1)))) (format nil "* user shift-clicked on node: ~A - OPEN WEB BROWSER~%" selected-node-name))) (defun cache-callback (&rest x) (declare (ignore x)) (if *USE-CACHING* (capi:display (make-instance 'options-panel-interface)))) (defun website-callback (&rest x) (declare (ignore x)) (trivial-open-browser:open-browser "http://www.knowledgegraphnavigator.com/")) (defun toggle-grapher-visibility (&rest x) (declare (ignore x)) (setf *show-info-pane* (not *show-info-pane*))) (defvar *examples*) (setf *examples* '("Bill Gates and Melinda Gates at Microsoft in Seattle" "Bill Clinton <http://dbpedia.org/resource/Georgia_(U.S._state)>" "Bill Gates and Steve Jobs visited IBM and Microsoft in Berlin, San Francisco, Toronto, Canada" "Steve Jobs lived near San Francisco and was a founder of <http://dbpedia.org/resource/Apple_Inc.>" "<http://dbpedia.org/resource/Bill_Gates> visited IBM" "<http://dbpedia.org/resource/Bill_Gates> visited <http://dbpedia.org/resource/Apple_Inc.>" "Bill Gates visited <http://dbpedia.org/resource/Apple_Inc.>")) (capi:define-interface kgn-interface () () (:menus (action-menu "Actions" ( ("Copy generated SPARQL to clipboard" :callback #'(lambda (&rest x) (declare (ignore x)) (let ((messages (capi:editor-pane-text text-pane2))) (capi::set-clipboard text-pane2 (format nil "---- Generated SPARQL and comments:~%~%~A~%~%" messages) nil)))) ("Copy results to clipboard" :callback #'(lambda (&rest x) (declare (ignore x)) (let ((results (capi:editor-pane-text text-pane3))) (capi::set-clipboard text-pane2 (format nil "---- Results:~%~%~A~%" results) nil)))) ("Copy generated SPARQL and results to clipboard" :callback #'(lambda (&rest x) (declare (ignore x)) (let ((messages (capi:editor-pane-text text-pane2)) (results (capi:editor-pane-text text-pane3))) (capi::set-clipboard text-pane2 (format nil "---- Generated SPARQL and comments:~%~%~A~%~%---- Results:~%~%~A~%" messages results) nil)))) ("Visit Knowledge Graph Navigator Web Site" :callback 'website-callback) ("Clear query cache" :callback 'cache-callback) ((if *show-info-pane* "Stop showing Grapher window for new results" "Start showing Grapher window for new results") :callback 'toggle-grapher-visibility) ))) (:menu-bar action-menu) (:panes (text-pane1 capi:text-input-pane :text (nth (random (length *examples*)) *examples*) :title "Query" :min-height 80 :max-height 100 :max-width *width* ;;:min-width (- *width* 480) :width *best-width* :callback 'start-progress-bar-test-from-background-thread) (progress-bar capi:progress-bar :start 0 :end 100 ) (text-pane2 capi:collector-pane :font "Courier" :min-height 210 :max-height 250 :title "Generated SPARQL queries to get results" :text "Note: to answer queries, this app makes multipe SPARQL queries to DBPedia. These SPARQL queries will be shown here." :vertical-scroll t :create-callback #'(lambda (&rest x) (declare (ignore x)) (setf (capi:editor-pane-text text-pane2) *pane2-message*)) :max-width *width* :width *best-width* :horizontal-scroll t) (text-pane3 capi:collector-pane ;; capi:display-pane ;; capi:text-input-pane :text *pane3-message* :font "Courier" :line-wrap-marker nil :wrap-style :split-on-space :vertical-scroll :with-bar :title "Results" :horizontal-scroll t :min-height 220 :width *best-width* :create-callback #'(lambda (&rest x) (declare (ignore x)) (setf (capi:editor-pane-text text-pane3) *pane3-message*)) :max-height 240 :max-width *width*) (info capi:title-pane :text "Use natural language queries to generate SPARQL")) (:layouts (main-layout capi:grid-layout '(nil info nil text-pane1 nil text-pane2 nil text-pane3 nil progress-bar) :x-ratios '(1 99) :has-title-column-p t)) (:default-initargs :layout 'main-layout :title "Knowledge Graph Navigator" :best-width *best-width* :max-width *width*)) (defun start-progress-bar-test-from-background-thread (query-text self) (format t "~%** ** entering start-progress-bar-test-from-background-thread:~%~%self=~S~%~%" self) (with-slots (text-pane2 text-pane3 progress-bar) self (print text-pane2) (flet ((update-progress-bar (percent) (capi:execute-with-interface self #'(lambda () (setf (capi:range-slug-start progress-bar) percent))))) (mp:process-run-function "progress-bar-test-from-background-thread" '() 'run-and-monitor-progress-background-thread #'update-progress-bar query-text text-pane2 text-pane3 )))) ;; This function runs in a separate thread. The call to sleep ;; simulates a slow operation being done. (defvar *percent*) (defun run-and-monitor-progress-background-thread (updater text text-pane2 text-pane3) (setf *percent* 0) (unwind-protect (setf (capi:editor-pane-text text-pane2) "") (setf (capi:editor-pane-text text-pane3) "") ;;(capi:display-message "done") (let ((message-stream (collector-pane-stream text-pane2)) (results-stream (collector-pane-stream text-pane3))) (format message-stream "# Starting to process query....~%") (format results-stream *pane3-message*) (let ((user-selections (get-entity-data-helper text :updater updater :message-stream message-stream))) ;; wrapped-results ;; (results ;; (with-output-to-string (results-stream) (setf *percent* (+ *percent* 2)) (funcall updater *percent*) (setf (capi:editor-pane-text text-pane3) "") (dolist (ev user-selections) (if (> (length (cadr ev)) 0) (let () (terpri results-stream) (capi::write-string-with-properties (format nil "- - - ENTITY TYPE: ~A - - -" (car ev)) '(:highlight :compiler-error-highlight) results-stream) (terpri results-stream) (dolist (uri (cadr ev)) (setf uri (car uri)) (case (car ev) (:people (pprint-results (dbpedia-get-person-detail uri :message-stream message-stream) :stream results-stream)) (:companies (pprint-results (dbpedia-get-company-detail uri :message-stream message-stream) :stream results-stream)) (:countries (pprint-results (dbpedia-get-country-detail uri :message-stream message-stream) :stream results-stream)) (:cities (pprint-results (dbpedia-get-city-detail uri :message-stream message-stream) :stream results-stream)) (:products (pprint-results (dbpedia-get-product-detail uri :message-stream message-stream) :stream results-stream)))))) (setf *percent* (+ *percent* 1)) (funcall updater *percent*)) (let (links x) (dolist (ev user-selections) (dolist (uri (second ev)) (setf uri (car uri)) (if (> (length ev) 2) (setf x (caddr ev))) (setf links (cons (list (symbol-name (first ev)) uri x) links)) (setf *percent* (+ *percent* 1)) (funcall updater *percent*))) (setf links (append links (entity-results->relationship-links user-selections :message-stream message-stream :updater updater))) (setf *percent* (+ *percent* 2)) (funcall updater *percent*) (if *show-info-pane* (lw-grapher:make-info-panel-grapher '("PEOPLE" "COMPANIES" "COUNTRIES" "CITIES" "PRODUCTS" "PLACES") links 'test-callback-click 'test-callback-click-shift))))) ;; do not use #' !! (funcall updater 0))) ;; MAIN entry point for application: (defun kgn () (ignore-errors (create-dbpedia)) (capi:display (make-instance 'kgn-interface)))
10,676
Common Lisp
.lisp
232
35.232759
339
0.57283
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b1528c9fc404618945ce877e65bad81047112cb2f227b100cc1c77135d2633ce
19,168
[ -1 ]
19,169
reasoning.lisp
Eggy115_Lisp/reasoning/reasoning.lisp
(require :agraph) (in-package :db.agraph.user) (create-triple-store "/tmp/rdfstore_2") (register-namespace "rdf" "http://www.w3.org/1999/02/22-rdf-syntax-ns#") (register-namespace "kb" "http:://knowledgebooks.com/ontology#") (register-namespace "test_news" "http://news.yahoo.com/s/nm/20080616/ts_nm") (enable-!-reader) ;;(load-ntriples "news2.nt") ;; overwrite *db* with a new RDFS++ inferencing enable ;; triple store (i.e., wrap existing triple store): (apply-rdfs++-reasoner) ;; rdf:type examples: (add-triple !kb:man !rdf:type !kb:person) (add-triple !kb:sam !rdf:type !kb:man) ;; explicit: (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ASK { kb:sam rdf:type kb:man }" :results-format :boolean) ;; implicit: (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ASK { kb:sam rdf:type kb:person }" :results-format :boolean) ;; note: query returns a false value; now use rdfs:subClassOf (add-triple !kb:man !rdfs:subClassOf !kb:person) (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ASK { kb:sam rdf:type kb:person }" :results-format :boolean) ;; now this query returns true. ;; inverse of example: (add-triple !kb:Mark !kb:husband-of !kb:Carol) (add-triple !kb:wife-of !owl:inverseOf !kb:husband-of) (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?y ?x WHERE { ?y kb:wife-of ?x }") (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?y ?x WHERE { ?y kb:wife-of ?x }" :results-format :lists) (setq *r* (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?y ?x WHERE { ?y kb:wife-of ?x }" :results-format :alists)) (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?y ?x WHERE { ?y kb:wife-of ?x }" :results-format :arrays) (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?y ?x WHERE { ?y kb:wife-of ?x }" :results-format :sparql-json) :: Same As: (add-triple !kb:Mark !owl:sameAs !kb:test_news:Mark) (add-triple !kb:Mark !kb:name !"Mark Watson") (register-namespace "test_news" "http://news.yahoo.com/s/nm/20080616/ts_nm") (add-triple !test_news:Mark !kb:height !"6 feet 4 inches") (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?x ?name ?height WHERE { ?x kb:height ?height . ?x kb:name ?name }" :results-format :lists) (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?p ?o WHERE { kb:Mark ?p ?o }" :results-format :lists) ;; owl:TransitiveProperty (add-triple !kb:relativeOf !rdf:type !owl:TransitiveProperty) (add-triple !kb:Mark !kb:relativeOf !kb:Ron) (add-triple !kb:Ron !kb:relativeOf !kb:Julia) (add-triple !kb:Julia !kb:relativeOf !kb:Ken) (defvar *r2* (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?relative WHERE { kb:Mark kb:relativeOf ?relative }" :results-format :sparql-json)) ;; OLD FROM LAST CHAPTER: REMOVE: ;; warning: the following generates an XML response: (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?article_uri ?city_name WHERE { ?article_uri kb:containsCity ?city_name . }") ;; generate a list of hash tables response: (defvar *r1* (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?article_uri ?city_name WHERE { ?article_uri kb:containsCity ?city_name . }" :results-format :hashes)) (dolist (result *r1*) (maphash #'(lambda (key value) (format t " key: ~S value: ~S~%" key value)) result)) ;; try an ASK query: (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> ASK { ?any_article kb:containsCity 'Chicago' }" :results-format :boolean) ;; query that returns a list of arrays for each result: (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?article_uri ?city_name WHERE { ?article_uri kb:containsCity ?city_name . }" :results-format :arrays) ;; query to find all cities and people mentioned in each article: (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?article_uri ?city_name ?person_name WHERE { ?article_uri kb:containsCity ?city_name . ?article_uri kb:containsPerson ?person_name . }" :results-format :arrays) ;; using regular expression filters: (sparql:run-sparql " PREFIX kb: <http:://knowledgebooks.com/ontology#> SELECT ?article_uri WHERE { ?article_uri kb:containsPerson ?person_name . FILTER regex(?person_name, '^*Putin*') }" :results-format :lists)
5,022
Common Lisp
.lisp
131
34.282443
91
0.684463
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
0f415708eccd4d21969f84ad354a8bda6c1c869a9ba3b67198d0211c78485e71
19,169
[ -1 ]
19,170
backend.lisp
Eggy115_Lisp/web_app/backend.lisp
(push "../knowledgebooks_nlp/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :kbnlp) (eval-when (compile load eval) (require :aserve) (require :agraph)) (defpackage :user (:use :net.aserve.client :kbnlp)) (in-package :user) (db.agraph.user::enable-!-reader) ; enable the ! reader macro (db.agraph.user::create-triple-store "/tmp/webportal_rdf") (db.agraph.user::register-namespace "kb" "http://knowledgebooks.com/rdfs#") (db.agraph.user::register-freetext-predicate !kb:docTitle) (db.agraph.user::register-freetext-predicate !kb:docText) (db.agraph.user::load-ntriples #p"init.nt") (defun valid-login? (user-name password) (format t "~%checking login: ~A ~A~%" user-name password) (let ((users-list (db.agraph.user::get-triples-list :p "<http://kbsportal.com#login>" :o (db.agraph.user::literal user-name))) (password-list (db.agraph.user::get-triples-list :p "<http://kbsportal.com#password>" :o (db.agraph.user::literal password)))) (print users-list) (print password-list) (and users-list password-list (db.agraph.user::part= (db.agraph.user::subject (car users-list)) (db.agraph.user::subject (car password-list)))))) ;; <http://kbsportal.com/user/1> <http://kbsportal.com#login> "demo" . ;; <http://kbsportal.com/user/1> <http://kbsportal.com#password> "demo" . (defun add-document (doc-uri doc-title doc-text) (let* ((txt-obj (kbnlp:make-text-object doc-text :title doc-title :url doc-uri)) (resource (db.agraph.user::resource doc-uri))) (db.agraph.user::add-triple resource !rdf:type !kb:document) (db.agraph.user::add-triple resource !kb:docTitle (db.agraph.user::literal doc-title)) (db.agraph.user::add-triple resource !kb:docText (db.agraph.user::literal doc-text)) (dolist (human-name (kbnlp::text-human-names txt-obj)) (pprint human-name) (db.agraph.user::add-triple resource !kb:docPersonEntity (db.agraph.user::literal human-name))) (dolist (place-name (kbnlp::text-place-names txt-obj)) (pprint place-name) (db.agraph.user::add-triple resource !kb:docPlaceEntity (db.agraph.user::literal place-name))) (dolist (tag (kbnlp::text-category-tags txt-obj)) (pprint tag) (db.agraph.user::add-triple resource !kb:docTag (db.agraph.user::literal (format nil "~A/~A" (car tag) (cadr tag))))))) ;; (add-document "file:///test1.txt" "test 1" "John Smith went to Mexico instead of paying his taxes to the IRS") ;; (db.agraph.user::print-triples (db.agraph.user::get-triples)) (defun doc-search (search-term-string) "return a list of matching doc IDs" (db.agraph.user::freetext-get-ids search-term-string)) (defun get-doc-info (doc-id) (let* ((parts (db.agraph.user::get-triple-by-id doc-id)) (subject (db.agraph.user::subject parts)) (predicate (db.agraph.user::predicate parts)) (object (db.agraph.user::object parts))) (mapcar #'(lambda (obj) (list (db.agraph.user::part->concise (db.agraph.user::subject obj)) (db.agraph.user::part->concise (db.agraph.user::predicate obj)) (db.agraph.user::part->terse (db.agraph.user::object obj)))) (db.agraph.user::get-triples-list :s subject)))) ;; (part->string u :format :terse) (defun print-all-docs () (dolist (result (db.agraph.user::get-triples-list :o !kb:document)) (pprint result) (terpri))) (defun delete-all-docs () "This is just for testing, when I want to remove all test docs" (db.agraph.user::delete-triples :o !kb:document) (db.agraph.user::delete-triples :p !kb:docText) (db.agraph.user::delete-triples :p !kb:docTitle) (db.agraph.user::delete-triples :p !kb:docPersonEntity) (db.agraph.user::delete-triples :p !kb:docPlaceEntity) (db.agraph.user::delete-triples :p !kb:docTag) (db.agraph.user::delete-triples :p !kb:doc))
4,129
Common Lisp
.lisp
77
45.688312
114
0.644295
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
98880c470cc7641359cc5a8bb41cd62d196924f5030c0b3cb5d04bb53565a0f2
19,170
[ -1 ]
19,171
webapp.lisp
Eggy115_Lisp/web_app/webapp.lisp
(eval-when (compile load eval) (require :aserve) (require :webactions) (load "backend.lisp") (load "../utils/file-utils.lisp")) (defpackage :user (:use :net.aserve :net.html.generator)) (in-package :user) (defun action-check-login (req ent) (let ((session (websession-from-req req))) (let ((user (websession-variable session "username"))) (if* (and user passwd (valid-login? user passwd)) then ; already logged in ; just go to the real home "browser" else ; must login "login")))) (defun action-got-login (req ent) (let ((session (websession-from-req req))) (let ((user (cdr (assoc "username" (net.aserve:request-query req) :test #'equal))) (passwd (cdr (assoc "password" (net.aserve:request-query req) :test #'equal)))) (format t "~%* * checking login: ~A ~A~%" user passwd) (if* (and user passwd (valid-login? user passwd)) then ; already logged in "browser" ; just go to the real home else ; must login "login")))) (webaction-project "dojotest" :destination "web/" :index "login" :map '(("menu" action-check-login) ("menu" "menu.clp") ("browser" "browser.clp") ("search" "/do-search") ("admin" "/upload.clp") ("about" "/about.clp") ("wiki" "/wiki.clp") ("upload" "/upload.clp") ;;("upload" "/do-upload" "/do-upload" (:redirect t)) ("gotlogin" action-got-login) ("login" "login.clp"))) (defun do-search (req ent) (net.aserve:with-http-response (req ent) (net.aserve:with-http-body (req ent) (let ((test-input (cdr (assoc "input_test_form_text" (net.aserve:request-query req) :test #'equal)))) (princ (format nil "AJAX: ~A <a href=\"/search\" target=\"new\">click here</a>" test-input) net.html.generator:*html-stream*))))) (defparameter *known-form-items* '("description" "tags" "file")) (defparameter *text-output-limit* 1024) (defparameter *attachments* (make-array 10 :fill-pointer 0 :adjustable t)) ;;; create a size length buffer and retrieve multipart body into it from ;;; request. if length is nil, then retrieve the entire sequence. ;;; returns multiple values: buffer containing sequence and bytes read. (defun fetch-multipart-sequence (req &key (length nil) (format :binary)) (if* length then (let ((buffer (make-array length :element-type (if (equal format :text) 'character '(unsigned-byte 8)))) (start 0) (end length)) (do* ((bytes-read start index) (index start (get-multipart-sequence req buffer :start index :end end))) ((or (null index) (= index end)) (values buffer (or index bytes-read))))) else (let ((buffer (get-all-multipart-data req :type format))) (values buffer (length buffer))))) (defun process-upload-form (req ent &aux text-data fname) (with-http-response (req ent) (with-http-body (req ent) (html (:html (:head (:title "file Upload Results")) (:body (do ((header (get-multipart-header req) (get-multipart-header req))) (nil) (multiple-value-bind (type item-name filename content-type) (parse-multipart-header header) (when filename (setf fname filename)) ;;(print (list "filename" filename "type:" type)) (when (equal type :eof) (return t)) ;; no more headers. (when (member item-name *known-form-items* :test #'equal) ;; it's a form item we know about, handle it. (case type ((:data) (push (format nil "~A" (fetch-multipart-sequence req :format :text)) text-data)) ((:file) (let* ((mp-data (fetch-multipart-sequence req)) pos) (setf (websession-variable (websession-from-req req) "upload-status") "Upload complete.") ;; write mp-data to a file: (with-open-file (ostr fname :direction :output :if-exists :supersede) (write-sequence mp-data ostr :end pos))))))))))) ;; TBD: add text describing the semantics of the uploaded document: <div style="padding: 30px"> (princ (format nil "<div style=\"padding: 30px\"><div style=\"border: 2px solid black; padding: 50px; width: 500px \">") net.html.generator:*html-stream*) (princ (format nil "<h2>File ~A uploaded OK</h2>" fname) net.html.generator:*html-stream*) (princ (format nil "TBD: list semantic information from uploaded document here:<br/><br />") net.html.generator:*html-stream*) (princ (format nil "<a href=\"/admin\">Continue working...</a> <br /><br />") net.html.generator:*html-stream*) (princ (format nil "</div></div>") net.html.generator:*html-stream*))) (format t "saved filename: ~A tags: ~A description: ~A~%" fname (car text-data) (cadr text-data)) ;; save data to database: (let ((text (file-string fname))) (add-document (concatenate 'string "file:///" fname) fname text))) (defparameter *response-method-not-allowed* (net.aserve::make-resp 405 "Method Not Allowed")) (push *response-method-not-allowed* net.aserve::*responses*) (net.aserve:publish :path "/search" :content-type "text/html" :function #'do-search) (net.aserve:publish :path "/do-upload" :content-type "text/html" :function #'process-upload-form) ;;;;;;;; CLP macro calls to define custom tags: (def-clp-function search_results (req ent args body) (let ((session (websession-from-req req)) (test-input (cdr (assoc "input_test_form_text" (net.aserve:request-query req) :test #'equal)))) (push test-input (websession-variable session "history")) (net.html.generator:html (:princ (format nil "Search results: ~A" test-input))) (if test-input (dolist (doc-id (doc-search test-input)) (princ (format nil "<pre>~A</pre>~%" (get-doc-info doc-id)) net.html.generator:*html-stream*))))) (net.aserve:start :port 8000) ;; to stop: ;; (net.aserve:shutdown)
6,150
Common Lisp
.lisp
131
39.671756
131
0.621111
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
647f6d6849ac2f4e4e1b03649a94cf778dddffba2da2aabca68e0d96627a9506
19,171
[ -1 ]
19,172
test.lisp
Eggy115_Lisp/web_app/test.lisp
(load "../utils/lisp-unit.lisp") (use-package :lisp-unit) (load "backend.lisp") (lisp-unit:define-test "create-doc-test1" (add-document "file:///test1.doc" "test title" "John Smith went to Mexico") (pprint (db.agraph.user::print-triples (db.agraph.user::get-triples))) (let ((person-list (db.agraph.user::get-triples-list :p !kb:docPersonEntity)) (place-list (db.agraph.user::get-triples-list :p !kb:docPlaceEntity))) (lisp-unit:assert-equal (db.agraph.user::part->string (db.agraph.user::object (car person-list))) "\"John Smith\"") (lisp-unit:assert-equal (db.agraph.user::part->string (db.agraph.user::object (car place-list))) "\"Mexico\""))) (lisp-unit:define-test "print-triples" (print-all-docs) (lisp-unit:assert-equal t t)) (lisp-unit:define-test "good-login" (lisp-unit:assert-equal t (valid-login? "demo" "demo"))) (lisp-unit:define-test "bad-login" (lisp-unit:assert-equal nil (valid-login? "demo" "demo2"))) (run-tests) (db.agraph.user::delete-triples :o !kb:document) (db.agraph.user::delete-triples :p !kb:docText) (db.agraph.user::delete-triples :p !kb:docTitle) (db.agraph.user::delete-triples :p !kb:docPersonEntity) (db.agraph.user::delete-triples :p !kb:docPlaceEntity) (db.agraph.user::delete-triples :p !kb:docTag) (db.agraph.user::delete-triples :p !kb:doc)
1,386
Common Lisp
.lisp
31
40.322581
80
0.683544
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
dd4c48fae65d9f308ca2a5191e2ece8a61e0ec4fc41eea116d5218cfeab8a235
19,172
[ -1 ]
19,173
test.lisp
Eggy115_Lisp/geonames/test.lisp
(push "../utils/cl-json_0.4.0/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :cl-json) (push "../utils/s-xml/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :s-xml) (push "../utils/split-sequence/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :split-sequence) (push "../utils/usocket-0.4.1/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :usocket) (push "../utils/trivial-gray-streams-2008-11-02/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :trivial-gray-streams) (push "../utils/flexi-streams-1.0.7/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :flexi-streams) (push "../utils/chunga-1.1.1/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :chunga) (push "../utils/cl-base64-3.3.3/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :cl-base64) (push "../utils/puri-1.5.5/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :puri) (push "../utils/drakma-1.2.3/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :drakma) (push "../utils/cl-geonames/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :cl-geonames) (cl-geonames:geo-country-info :country '("FR" "GB" "ES"))
1,185
Common Lisp
.lisp
23
48.565217
75
0.695614
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
df5bf4deb027593b470e306c4d6845f6316190466a3a639029eb94e528bc23fd
19,173
[ -1 ]
19,174
package.lisp
Eggy115_Lisp/kgcreator/package.lisp
;;;; kgcreator.lisp (defpackage #:kgcreator (:use #:cl #:entities_dbpedia #:categorize_summarize #:myutils #:cl-who #:hunchentoot #:parenscript) (:export kgcreator))
176
Common Lisp
.lisp
4
40.5
103
0.705882
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8e45d6bb0ccd444c57eeb217d83142b051b0198ec30877eea631e4574910d03d
19,174
[ -1 ]
19,175
kgcreator.lisp
Eggy115_Lisp/kgcreator/kgcreator.lisp
;; KGCreator main program (in-package #:kgcreator) (ensure-directories-exist "temp/") (defun get-files-and-meta (fpath) (let ((data (directory (concatenate 'string fpath "/" "*.txt"))) (meta (directory (concatenate 'string fpath "/" "*.meta")))) (if (not (equal (length data) (length meta))) (let () (princ "Error: must be matching *.meta files for each *.txt file") (terpri) '()) (let ((ret '())) (dotimes (i (length data)) (setq ret (cons (list (nth i data) (nth i meta)) ret))) ret)))) (opts:define-opts (:name :help :description "KGcreator command line app. example: ./KGcreator -i test_data -r out.rdf -c out.cyper" :short #\h :long "help") (:name :rdf :description "RDF output file name" :short #\r :long "rdf" :arg-parser #'identity ;; <- takes an argument :arg-parser #'identity) ;; <- takes an argument (:name :cypher :description "Cypher output file name" :short #\c :long "cypher" :arg-parser #'identity) ;; <- takes an argument (:name :inputdir :description "Cypher output file name" :short #\i :long "inputdir" :arg-parser #'identity)) ;; <- takes an argument (defun kgcreator () ;; don't need: &aux args sb-ext:*posix-argv*) (handler-case (let* ((opts (opts:get-opts)) (input-path (if (find :inputdir opts) (nth (1+ (position :inputdir opts)) opts))) (rdf-output-path (if (find :rdf opts) (nth (1+ (position :rdf opts)) opts))) (cypher-output-path (if (find :cypher opts) (nth (1+ (position :cypher opts)) opts)))) (format t "input-path: ~a rdf-output-path: ~a cypher-output-path:~a~%" input-path rdf-output-path cypher-output-path) (if (not input-path) (format t "You must specify an input path.~%") (locally (declare #+sbcl(sb-ext:muffle-conditions sb-kernel:redefinition-warning)) (handler-bind (#+sbcl(sb-kernel:redefinition-warning #'muffle-warning)) ;; stuff that emits redefinition-warning's (let () (if rdf-output-path (rdf-from-files rdf-output-path (get-files-and-meta input-path))) (if cypher-output-path (cypher-from-files cypher-output-path (get-files-and-meta input-path)))))))) (t (c) (format t "We caught a runtime error: ~a~%" c) (values 0 c))) (format t "~%Shutting down KGcreator - done processing~%~%")) (defun test1 () (get-files-and-meta "~/GITHUB/common-lisp/kgcreator/test_data")) (defun print-hash-entry (key value) (format t "The value associated with the key ~S is ~S~%" key value)) (defun test2 () (let ((h (entities_dbpedia:find-entities-in-text "Bill Clinton and George Bush went to Mexico and England and watched Univision. They enjoyed Dakbayan sa Dabaw and shoped at Best Buy and listened to Al Stewart. They agree on República de Nicaragua and support Sweden Democrats and Leicestershire Miners Association and both sent their kids to Darul Uloom Deoband."))) (entities_dbpedia:entity-iterator #'print-hash-entry h))) (defun test7 () (rdf-from-files "out.rdf" (get-files-and-meta "test_data")))
3,187
Common Lisp
.lisp
76
36.434211
371
0.646716
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1efbcdb555c5a9af814be9eb81d9a1f45e40e708e669cb4cd3f11dea35332c74
19,175
[ -1 ]
19,176
neo4j.lisp
Eggy115_Lisp/kgcreator/neo4j.lisp
(in-package #:kgcreator) (let ((*entity-nodes-hash*)) (defun cypher-from-files (output-file-path text-and-meta-pairs) (setf *entity-nodes-hash* (make-hash-table :test #'equal :size 200)) ;;(print (list "==> cypher-from-files"output-file-path text-and-meta-pairs )) (with-open-file (str output-file-path :direction :output :if-exists :supersede ;; WARNING: after I start testing with more than file, need to change this :if-does-not-exist :create) (defun generateNeo4jCategoryNodes () (let* ((names categorize_summarize::categoryNames)) (dolist (name names) (format str (myutils:replace-all (concatenate 'string "CREATE (" name ":CategoryType {name:\"" name "\"})~%") "/" "_")))) (format str "~%")) (defun cypher-from-files-handle-single-file (text-input-file meta-input-file) (let* ((text (file-to-string text-input-file)) (words (myutils:words-from-string text)) (meta (file-to-string meta-input-file))) ;; TBD parse JSON (defun generate-original-doc-node () (let ((node-name (node-name-from-uri meta))) (if (null (gethash node-name *entity-nodes-hash*)) (let* ((cats (categorize words)) (sum (summarize words cats))) (setf (gethash node-name *entity-nodes-hash*) t) (format str (concatenate 'string "CREATE (" node-name ":News {name:\"" node-name "\", uri: \"" meta "\", summary: \"" sum "\"})~%")) (dolist (cat cats) (let ((hash-check (concatenate 'string node-name (car cat)))) (if (null (gethash hash-check *entity-nodes-hash*)) (let () (setf (gethash hash-check *entity-nodes-hash*) t) (format str (concatenate 'string "CREATE (" node-name ")-[:Category]->(" (car cat) ")~%")))))))))) (defun generate-dbpedia-nodes (key entity-pairs) (dolist (entity-pair entity-pairs) (if (null (gethash (node-name-from-uri (cadr entity-pair)) *entity-nodes-hash*)) (let () (setf (gethash (node-name-from-uri (cadr entity-pair)) *entity-nodes-hash*) t) (format str (concatenate 'string "CREATE (" (node-name-from-uri (cadr entity-pair)) ":" key " {name: \"" (car entity-pair) "\", uri: \"" (cadr entity-pair) "\"})~%")))))) (defun generate-dbpedia-contains-cypher (key value) (generate-original-doc-node) (generate-dbpedia-nodes key value) (let ((relation-name (concatenate 'string key "DbPediaLink"))) (dolist (entity-pair value) (let* ((node-name (node-name-from-uri meta)) (object-node-name (node-name-from-uri (cadr entity-pair))) (hash-check (concatenate 'string node-name object-node-name))) (if (null (gethash hash-check *entity-nodes-hash*)) (let () (setf (gethash hash-check *entity-nodes-hash*) t) (format str (concatenate 'string "CREATE (" node-name ")-[:" relation-name "]->(" object-node-name ")~%")))))))))) ;; start code for cypher-from-files (output-file-path text-and-meta-pairs) (generateNeo4jCategoryNodes) ;; just once, not for every input file (dolist (pair text-and-meta-pairs) (cypher-from-files-handle-single-file (car pair) (cadr pair)) (let ((h (entities_dbpedia:find-entities-in-text (file-to-string (car pair))))) (entities_dbpedia:entity-iterator #'generate-dbpedia-contains-cypher h)))))) (defvar test_files '((#P"~/GITHUB/common-lisp/kgcreator/test_data/test3.txt" #P"~/GITHUB/common-lisp/kgcreator/test_data/test3.meta") (#P"~/GITHUB/common-lisp/kgcreator/test_data/test2.txt" #P"~/GITHUB/common-lisp/kgcreator/test_data/test2.meta") (#P"~/GITHUB/common-lisp/kgcreator/test_data/test1.txt" #P"~/GITHUB/common-lisp/kgcreator/test_data/test1.meta"))) (defun test2a () (cypher-from-files "out.cypher" test_files))
3,953
Common Lisp
.lisp
75
44.826667
106
0.628691
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3eb3221b0612d92c0474b1ac7531a545649c69112aad7a182e1dd6a9e3317b0d
19,176
[ -1 ]
19,177
web.lisp
Eggy115_Lisp/kgcreator/web.lisp
(in-package #:kgcreator) (ql:quickload '(cl-who hunchentoot parenscript)) (setf (html-mode) :html5) (defun write-files-run-code (a-uri raw-text) (if (< (length raw-text) 10) (list "not enough text" "not enough text") ;; generate random file number (let* ((filenum (+ 1000 (random 5000))) (meta-name (concatenate 'string "temp/" (write-to-string filenum) ".meta")) (text-name (concatenate 'string "temp/" (write-to-string filenum) ".txt")) (rdf-name (concatenate 'string "temp/" (write-to-string filenum) ".rdf")) (cypher-name (concatenate 'string "temp/" (write-to-string filenum) ".cypher")) ret) ;; write meta file (with-open-file (str meta-name :direction :output :if-exists :supersede :if-does-not-exist :create) (format str a-uri)) ;; write text file (with-open-file (str text-name :direction :output :if-exists :supersede :if-does-not-exist :create) (format str raw-text)) ;; generate rdf and cypher files (rdf-from-files rdf-name (list (list text-name meta-name))) (cypher-from-files cypher-name (list (list text-name meta-name))) ;; read files and return results (setf ret (list (replace-all (replace-all (uiop:read-file-string rdf-name) ">" "&gt;") "<" "&lt;") (uiop:read-file-string cypher-name))) (print (list "ret:" ret)) ret))) (defvar *h* (make-instance 'easy-acceptor :port 3000)) ;; define a handler with the arbitrary name my-greetings: (define-easy-handler (my-greetings :uri "/") (text) (setf (hunchentoot:content-type*) "text/html") (let ((rdf-and-cypher (write-files-run-code "http://test.com/1" text))) (print (list "*** rdf-and-cypher:" rdf-and-cypher)) (with-html-output-to-string (*standard-output* nil :prologue t) (:html (:head (:title "KGCreator Demo") (:link :rel "stylesheet" :href "styles.css" :type "text/css")) (:body :style "margin: 90px" (:h1 "Enter plain text for the demo to create RDF and Cypher") (:p "For more information on the KGCreator product please visit the web site:" (:a :href "https://markwatson.com/products/" "Mark Watson's commercial products")) (:p "The KGCreator product is a command line tool that processes all text files in a source " "directory and produces both RDF data triples for semantic web applications and " "Cypher input data files for the Neo4J graph database. " "For the purposes of this demo the URI for your input text is hardwired to &lt;http://test.com/1&gt;" "but the KGCreator product offers flexibility for assigning URIs to data sources and further, " "creates links for relationships between input sources.") (:p :style "text-align: left" "To try the demo paste plain text into the following form that contains information on companies, news, politics, famous people, broadcasting networks, political parties, countries and other locations, etc. ") (:p "Do not include and special characters or character sets:") (:form :method :post (:textarea :rows "20" :cols "90" :name "text" :value text) (:br) (:input :type :submit :value "Submit text to process")) (:h3 "RDF:") (:pre (str (car rdf-and-cypher))) (:h3 "Cypher:") (:pre (str (cadr rdf-and-cypher)))))))) (defun kgcweb () (hunchentoot:start *h*))
3,530
Common Lisp
.lisp
79
37.962025
214
0.641212
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
bd2612f3e0ef9e0b795718e2bff97cefc1641d6e1166fd103b67079ae523fa32
19,177
[ -1 ]
19,178
rdf.lisp
Eggy115_Lisp/kgcreator/rdf.lisp
(in-package #:kgcreator) (let ((*rdf-nodes-hash*)) (defun rdf-from-files (output-file-path text-and-meta-pairs) (setf *rdf-nodes-hash* (make-hash-table :test #'equal :size 200)) (print (list "==> rdf-from-files" output-file-path text-and-meta-pairs )) (with-open-file (str output-file-path :direction :output :if-exists :supersede :if-does-not-exist :create) (defun rdf-from-files-handle-single-file (text-input-file meta-input-file) (let* ((text (file-to-string text-input-file)) (words (myutils:words-from-string text)) (meta (file-to-string meta-input-file))) ;; TBD parse JSON (defun generate-original-doc-node-rdf () (let ((node-name (node-name-from-uri meta))) (if (null (gethash node-name *rdf-nodes-hash*)) (let* ((cats (categorize words)) (sum (summarize words cats))) (print (list "$$$$$$ cats:" cats)) (setf (gethash node-name *rdf-nodes-hash*) t) (format str (concatenate 'string "<" meta "> <http:knowledgebooks.com/schema/summary> \"" sum "\" . ~%")) (dolist (cat cats) (let ((hash-check (concatenate 'string node-name (car cat)))) (if (null (gethash hash-check *rdf-nodes-hash*)) (let () (setf (gethash hash-check *rdf-nodes-hash*) t) (format str (concatenate 'string "<" meta "> <http://knowledgebooks.com/schema/topicCategory> " "<http://knowledgebooks.com/schema/" (car cat) "> . ~%")))))))))) (defun generate-dbpedia-contains-rdf (key value) (generate-original-doc-node-rdf) (let ((relation-name (concatenate 'string key "DbPediaLink"))) (dolist (entity-pair value) (let* ((node-name (node-name-from-uri meta)) (object-node-name (node-name-from-uri (cadr entity-pair))) (hash-check (concatenate 'string node-name object-node-name))) (if (null (gethash hash-check *rdf-nodes-hash*)) (let () (setf (gethash hash-check *rdf-nodes-hash*) t) (format str (concatenate 'string "<" meta "> <http://knowledgebooks.com/schema/contains/" key "> " (cadr entity-pair) " .~%")))))))))) ;; start code for rdf-from-files (output-file-path text-and-meta-pairs) (dolist (pair text-and-meta-pairs) (rdf-from-files-handle-single-file (car pair) (cadr pair)) (let ((h (entities_dbpedia:find-entities-in-text (file-to-string (car pair))))) (entities_dbpedia:entity-iterator #'generate-dbpedia-contains-rdf h)))))) (defvar test_files '((#P"~/GITHUB/common-lisp/kgcreator/test_data/test3.txt" #P"~/GITHUB/common-lisp/kgcreator/test_data/test3.meta"))) (defvar test_filesZZZ '((#P"~/GITHUB/common-lisp/kgcreator/test_data/test3.txt" #P"~/GITHUB/common-lisp/kgcreator/test_data/test3.meta") (#P"~/GITHUB/common-lisp/kgcreator/test_data/test2.txt" #P"~/GITHUB/common-lisp/kgcreator/test_data/test2.meta") (#P"~/GITHUB/common-lisp/kgcreator/test_data/test1.txt" #P"~/GITHUB/common-lisp/kgcreator/test_data/test1.meta"))) (defun test3a () (rdf-from-files "out.rdf" test_files))
3,675
Common Lisp
.lisp
62
43.66129
88
0.548441
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
eda60ce0d21bbdb8d372220cbc705dbe4bf834034b48ec532ccdb94a45a28c6a
19,178
[ -1 ]
19,179
rdfext.lisp
Eggy115_Lisp/rdf/rdfext.lisp
;; demonstration of AllegroGraph RDF extensions: (require :agraph) (in-package :db.agraph.user) (create-triple-store "/tmp/rdfstore_1") ;; default data store is kept in *db* *db* (register-namespace "kb" "http://knowledgebooks.com/rdfs#") (resource "http://demo_news/12931") (defvar *demo-article* (resource "http://demo_news/12931")) (add-triple *demo-article* !rdf:type !kb:article :db *db* :g !"news-data") (add-triple *demo-article* !kb:containsPerson !"Barack Obama" :db *db* :g !"news-data") (add-triple *demo-article* !kb:processed !"yes" :db *db* :g !"work-flow") ;; query on optional graph value: (print-triples (get-triples :g !"work-flow")) (get-triple-by-id 3)
708
Common Lisp
.lisp
15
43.866667
88
0.695394
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1d9002283297a4108e4ca7eb9d2319a6ec4810028c9f5f8aed024acc07bd84d6
19,179
[ -1 ]
19,180
web-hunchentoot-example.lisp
Eggy115_Lisp/hunchentoot_examples/web-hunchentoot-example.lisp
(ql:quickload :hunchentoot) (ql:quickload :cl-who) (in-package :cl-user) (defpackage hdemo (:use :cl :cl-who :hunchentoot)) (in-package :hdemo) (defvar *h* (make-instance 'easy-acceptor :port 3000)) ;; define a handler with the arbitrary name my-greetings: (define-easy-handler (my-greetings :uri "/hello") (name) (setf (hunchentoot:content-type*) "text/html") (with-html-output-to-string (*standard-output* nil :prologue t) (:html (:head (:title "hunchentoot test")) (:body (:h1 "hunchentoot form demo") (:form :method :post (:input :type :text :name "name" :value name) (:input :type :submit :value "Submit your name")) (:p "Hello " (str name)))))) (hunchentoot:start *h*)
801
Common Lisp
.lisp
25
26
66
0.613577
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f6b280c1bef718eee434e54d36b2a927fca6f6538c283941a87d9407cce74dc8
19,180
[ -1 ]
19,181
web-hunchentoot-json.lisp
Eggy115_Lisp/hunchentoot_examples/web-hunchentoot-json.lisp
(ql:quickload :hunchentoot) (ql:quickload :cl-json) (defvar *h* (make-instance 'hunchentoot:easy-acceptor :port 3000)) ;; define a handler with the name animal: (hunchentoot:define-easy-handler (animal :uri "/animal") (name) (print name) (setf (hunchentoot:content-type*) "text/plain") (cond ((string-equal name "cat") (json:encode-json-to-string (list (list '(average_weight . 10) '(friendly . nil)) "A cat can live indoors or outdoors."))) ((string-equal name "dog") (json:encode-json-to-string (list (list '(average_weight . 40) '(friendly . t)) "A dog is a loyal creature, much valued by humans."))) (t (json:encode-json-to-string (list () "unknown type of animal"))))) (hunchentoot:start *h*)
869
Common Lisp
.lisp
28
23.928571
67
0.588235
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
2c5a8721846d4e18d61c3d8cf85605f33dd32ba161a90c4f127d1cd6e277c6de
19,181
[ -1 ]
19,182
in-memory.lisp
Eggy115_Lisp/flexi-streams-1.0.7/in-memory.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/in-memory.lisp,v 1.31 2008/05/19 07:57:07 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defclass in-memory-stream (trivial-gray-stream-mixin) ((transformer :initarg :transformer :accessor in-memory-stream-transformer :documentation "A function used to transform the written/read octet to the value stored/retrieved in/from the underlying vector.") #+:cmu (open-p :initform t :accessor in-memory-stream-open-p :documentation "For CMUCL we have to keep track of this manually.")) (:documentation "An IN-MEMORY-STREAM is a binary stream that reads octets from or writes octets to a sequence in RAM.")) (defclass in-memory-input-stream (in-memory-stream fundamental-binary-input-stream) () (:documentation "An IN-MEMORY-INPUT-STREAM is a binary stream that reads octets from a sequence in RAM.")) #+:cmu (defmethod output-stream-p ((stream in-memory-input-stream)) "Explicitly states whether this is an output stream." (declare (optimize speed)) nil) (defclass in-memory-output-stream (in-memory-stream fundamental-binary-output-stream) () (:documentation "An IN-MEMORY-OUTPUT-STREAM is a binary stream that writes octets to a sequence in RAM.")) #+:cmu (defmethod input-stream-p ((stream in-memory-output-stream)) "Explicitly states whether this is an input stream." (declare (optimize speed)) nil) (defclass list-stream () ((list :initarg :list :accessor list-stream-list :documentation "The underlying list of the stream.")) (:documentation "A LIST-STREAM is a mixin for IN-MEMORY streams where the underlying sequence is a list.")) (defclass vector-stream () ((vector :initarg :vector :accessor vector-stream-vector :documentation "The underlying vector of the stream which \(for output) must always be adjustable and have a fill pointer.")) (:documentation "A VECTOR-STREAM is a mixin for IN-MEMORY streams where the underlying sequence is a vector.")) (defclass list-input-stream (list-stream in-memory-input-stream) () (:documentation "A binary input stream that gets its data from an associated list of octets.")) (defclass vector-input-stream (vector-stream in-memory-input-stream) ((index :initarg :index :accessor vector-stream-index :type (integer 0 #.array-dimension-limit) :documentation "An index into the underlying vector denoting the current position.") (end :initarg :end :accessor vector-stream-end :type (integer 0 #.array-dimension-limit) :documentation "An index into the underlying vector denoting the end of the available data.")) (:documentation "A binary input stream that gets its data from an associated vector of octets.")) (defclass vector-output-stream (vector-stream in-memory-output-stream) () (:documentation "A binary output stream that writes its data to an associated vector.")) #+:cmu (defmethod open-stream-p ((stream in-memory-stream)) "Returns a true value if STREAM is open. See ANSI standard." (declare #.*standard-optimize-settings*) (in-memory-stream-open-p stream)) #+:cmu (defmethod close ((stream in-memory-stream) &key abort) "Closes the stream STREAM. See ANSI standard." (declare #.*standard-optimize-settings*) (declare (ignore abort)) (prog1 (in-memory-stream-open-p stream) (setf (in-memory-stream-open-p stream) nil))) (defmethod check-if-open ((stream in-memory-stream)) "Checks if STREAM is open and signals an error otherwise." (declare #.*standard-optimize-settings*) (unless (open-stream-p stream) (error 'in-memory-stream-closed-error :stream stream))) (defmethod stream-element-type ((stream in-memory-stream)) "The element type is always OCTET by definition." (declare #.*standard-optimize-settings*) 'octet) (defmethod transform-octet ((stream in-memory-stream) octet) "Applies the transformer of STREAM to octet and returns the result." (declare #.*standard-optimize-settings*) (funcall (or (in-memory-stream-transformer stream) #'identity) octet)) (defmethod stream-read-byte ((stream list-input-stream)) "Reads one byte by simply popping it off of the top of the list." (declare #.*standard-optimize-settings*) (check-if-open stream) (with-accessors ((list list-stream-list)) stream (transform-octet stream (or (pop list) (return-from stream-read-byte :eof))))) (defmethod stream-listen ((stream list-input-stream)) "Checks whether list is not empty." (declare #.*standard-optimize-settings*) (check-if-open stream) (with-accessors ((list list-stream-list)) stream list)) (defmethod stream-read-sequence ((stream list-input-stream) sequence start end &key) "Repeatedly pops elements from the list until it's empty." (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (with-accessors ((list list-stream-list)) stream (loop for index of-type fixnum from start below end while list do (setf (elt sequence index) (pop list)) finally (return index)))) (defmethod stream-read-byte ((stream vector-input-stream)) "Reads one byte and increments INDEX pointer unless we're beyond END pointer." (declare #.*standard-optimize-settings*) (check-if-open stream) (with-accessors ((index vector-stream-index) (end vector-stream-end) (vector vector-stream-vector)) stream (let ((current-index index)) (declare (fixnum current-index)) (cond ((< current-index (the fixnum end)) (incf (the fixnum index)) (transform-octet stream (aref vector current-index))) (t :eof))))) (defmethod stream-listen ((stream vector-input-stream)) "Checking whether INDEX is beyond END." (declare #.*standard-optimize-settings*) (check-if-open stream) (with-accessors ((index vector-stream-index) (end vector-stream-end)) stream (< (the fixnum index) (the fixnum end)))) (defmethod stream-read-sequence ((stream vector-input-stream) sequence start end &key) "Traverses both sequences in parallel until the end of one of them is reached." (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (loop with vector-end of-type fixnum = (vector-stream-end stream) with vector = (vector-stream-vector stream) for index of-type fixnum from start below end for vector-index of-type fixnum = (vector-stream-index stream) while (< vector-index vector-end) do (setf (elt sequence index) (aref vector vector-index)) (incf (the fixnum (vector-stream-index stream))) finally (return index))) (defmethod stream-write-byte ((stream vector-output-stream) byte) "Writes a byte \(octet) by extending the underlying vector." (declare #.*standard-optimize-settings*) (check-if-open stream) (with-accessors ((vector vector-stream-vector)) stream (vector-push-extend (transform-octet stream byte) vector))) (defmethod stream-write-sequence ((stream vector-output-stream) sequence start end &key) "Just calls VECTOR-PUSH-EXTEND repeatedly." (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (with-accessors ((vector vector-stream-vector)) stream (loop for index of-type fixnum from start below end do (vector-push-extend (elt sequence index) vector)) sequence)) (defmethod stream-file-position ((stream vector-input-stream)) "Simply returns the index into the underlying vector." (declare #.*standard-optimize-settings*) (with-accessors ((index vector-stream-index)) stream index)) (defmethod (setf stream-file-position) (position-spec (stream vector-input-stream)) "Sets the index into the underlying vector if POSITION-SPEC is acceptable." (declare #.*standard-optimize-settings*) (with-accessors ((index vector-stream-index) (end vector-stream-end)) stream (setq index (case position-spec (:start 0) (:end end) (otherwise (unless (integerp position-spec) (error 'in-memory-stream-position-spec-error :format-control "Unknown file position designator: ~S." :format-arguments (list position-spec) :stream stream :position-spec position-spec)) (unless (<= 0 position-spec end) (error 'in-memory-stream-position-spec-error :format-control "File position designator ~S is out of bounds." :format-arguments (list position-spec) :stream stream :position-spec position-spec)) position-spec))) position-spec)) (defmethod stream-file-position ((stream vector-output-stream)) "Simply returns the fill pointer of the underlying vector." (declare #.*standard-optimize-settings*) (with-accessors ((vector vector-stream-vector)) stream (fill-pointer vector))) (defmethod (setf stream-file-position) (position-spec (stream vector-output-stream)) "Sets the fill pointer underlying vector if POSITION-SPEC is acceptable. Adjusts the vector if necessary." (declare #.*standard-optimize-settings*) (with-accessors ((vector vector-stream-vector)) stream (let* ((total-size (array-total-size vector)) (new-fill-pointer (case position-spec (:start 0) (:end (warn "File position designator :END doesn't really make sense for an output stream.") total-size) (otherwise (unless (integerp position-spec) (error 'in-memory-stream-position-spec-error :format-control "Unknown file position designator: ~S." :format-arguments (list position-spec) :stream stream :position-spec position-spec)) (unless (<= 0 position-spec array-total-size-limit) (error 'in-memory-stream-position-spec-error :format-control "File position designator ~S is out of bounds." :format-arguments (list position-spec) :stream stream :position-spec position-spec)) position-spec)))) (declare (fixnum total-size new-fill-pointer)) (when (> new-fill-pointer total-size) (adjust-array vector new-fill-pointer)) (setf (fill-pointer vector) new-fill-pointer) position-spec))) (defmethod make-in-memory-input-stream ((vector vector) &key (start 0) (end (length vector)) transformer) "Returns a binary input stream which will supply, in order, the octets in the subsequence of VECTOR bounded by START and END. Each octet returned will be transformed in turn by the optional TRANSFORMER function." (declare #.*standard-optimize-settings*) (make-instance 'vector-input-stream :vector vector :index start :end end :transformer transformer)) (defmethod make-in-memory-input-stream ((list list) &key (start 0) (end (length list)) transformer) "Returns a binary input stream which will supply, in order, the octets in the subsequence of LIST bounded by START and END. Each octet returned will be transformed in turn by the optional TRANSFORMER function." (declare #.*standard-optimize-settings*) (make-instance 'list-input-stream :list (subseq list start end) :transformer transformer)) (defun make-output-vector (&key (element-type 'octet)) "Creates and returns an array which can be used as the underlying vector for a VECTOR-OUTPUT-STREAM." (declare #.*standard-optimize-settings*) (make-array 0 :adjustable t :fill-pointer 0 :element-type element-type)) (defun make-in-memory-output-stream (&key (element-type 'octet) transformer) "Returns a binary output stream which accepts objects of type ELEMENT-TYPE \(a subtype of OCTET) and makes available a sequence that contains the octes that were actually output. The octets stored will each be transformed by the optional TRANSFORMER function." (declare #.*standard-optimize-settings*) (make-instance 'vector-output-stream :vector (make-output-vector :element-type element-type) :transformer transformer)) (defmethod get-output-stream-sequence ((stream in-memory-output-stream) &key as-list) "Returns a vector containing, in order, all the octets that have been output to the IN-MEMORY stream STREAM. This operation clears any octets on STREAM, so the vector contains only those octets which have been output since the last call to GET-OUTPUT-STREAM-SEQUENCE or since the creation of the stream, whichever occurred most recently. If AS-LIST is true the return value is coerced to a list." (declare #.*standard-optimize-settings*) (with-accessors ((vector vector-stream-vector)) stream (prog1 (if as-list (coerce vector 'list) vector) (setq vector (make-output-vector))))) (defmethod output-stream-sequence-length ((stream in-memory-output-stream)) "Returns the current length of the underlying vector of the IN-MEMORY output stream STREAM." (declare (optimize speed)) (with-accessors ((vector vector-stream-vector)) stream (length (the (simple-array * (*)) vector)))) (defmacro with-input-from-sequence ((var sequence &key start end transformer) &body body) "Creates an IN-MEMORY input stream from SEQUENCE using the parameters START and END, binds VAR to this stream and then executes the code in BODY. A function TRANSFORMER may optionally be specified to transform the returned octets. The stream is automatically closed on exit from WITH-INPUT-FROM-SEQUENCE, no matter whether the exit is normal or abnormal. The return value of this macro is the return value of BODY." (with-rebinding (sequence) `(let (,var) (unwind-protect (progn (setq ,var (make-in-memory-input-stream ,sequence :start (or ,start 0) :end (or ,end (length ,sequence)) :transformer ,transformer)) ,@body) (when ,var (close ,var)))))) (defmacro with-output-to-sequence ((var &key as-list (element-type ''octet) transformer) &body body) "Creates an IN-MEMORY output stream, binds VAR to this stream and then executes the code in BODY. The stream stores data of type ELEMENT-TYPE \(a subtype of OCTET) which is \(optionally) transformed by the function TRANSFORMER prior to storage. The stream is automatically closed on exit from WITH-OUTPUT-TO-SEQUENCE, no matter whether the exit is normal or abnormal. The return value of this macro is a vector \(or a list if AS-LIST is true) containing the octets that were sent to the stream within BODY." `(let (,var) (unwind-protect (progn (setq ,var (make-in-memory-output-stream :element-type ,element-type :transformer ,transformer)) ,@body (get-output-stream-sequence ,var :as-list ,as-list)) (when ,var (close ,var)))))
17,724
Common Lisp
.lisp
365
39.969863
102
0.661997
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f3335bfce978d67783f69eb05aee6a6e06faaf56973de4428ebfefd5ff6bf916
19,182
[ 336633 ]
19,183
length.lisp
Eggy115_Lisp/flexi-streams-1.0.7/length.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/length.lisp,v 1.6 2008/05/29 10:25:14 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defgeneric encoding-factor (format) (:documentation "Given an external format FORMAT, returns a factor which denotes the octets to characters ratio to expect when encoding/decoding. If the returned value is an integer, the factor is assumed to be exact. If it is a \(double) float, the factor is supposed to be based on heuristics and usually not exact. This factor is used in string.lisp.") (declare #.*standard-optimize-settings*)) (defmethod encoding-factor ((format flexi-8-bit-format)) (declare #.*standard-optimize-settings*) ;; 8-bit encodings map octets to characters in an exact one-to-one ;; fashion 1) (defmethod encoding-factor ((format flexi-utf-8-format)) (declare #.*standard-optimize-settings*) ;; UTF-8 characters can be anything from one to six octets, but we ;; assume that the "overhead" is only about 5 percent - this ;; estimate is obviously very much dependant on the content 1.05d0) (defmethod encoding-factor ((format flexi-utf-16-format)) (declare #.*standard-optimize-settings*) ;; usually one character maps to two octets, but characters with ;; code points above #x10000 map to four octets - we assume that we ;; usually don't see these characters but of course have to return a ;; float 2.0d0) (defmethod encoding-factor ((format flexi-utf-32-format)) (declare #.*standard-optimize-settings*) ;; UTF-32 always matches every character to four octets 4) (defmethod encoding-factor ((format flexi-crlf-mixin)) (declare #.*standard-optimize-settings*) ;; if the sequence #\Return #\Linefeed is the line-end marker, this ;; obviously makes encodings potentially longer and definitely makes ;; the estimate unexact (* 1.02d0 (call-next-method))) (defgeneric check-end (format start end i) (declare #.*fixnum-optimize-settings*) (:documentation "Helper function used below to determine if we tried to read past the end of the sequence.") (:method (format start end i) (declare #.*fixnum-optimize-settings*) (declare (ignore start)) (declare (fixnum end i)) (when (> i end) (signal-encoding-error format "This sequence can't be decoded ~ using ~A as it is too short. ~A octet~:P missing at then end." (external-format-name format) (- i end)))) (:method ((format flexi-utf-16-format) start end i) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end i)) (declare (ignore i)) ;; don't warn twice (when (evenp (- end start)) (call-next-method)))) (defgeneric compute-number-of-chars (format sequence start end) (declare #.*standard-optimize-settings*) (:documentation "Computes the exact number of characters required to decode the sequence of octets in SEQUENCE from START to END using the external format FORMAT.")) (defmethod compute-number-of-chars :around (format (list list) start end) (declare #.*standard-optimize-settings*) (call-next-method format (coerce list 'vector) start end)) (defmethod compute-number-of-chars ((format flexi-8-bit-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (- end start)) (defmethod compute-number-of-chars ((format flexi-crlf-mixin) sequence start end) ;; this method only applies to the 8-bit formats as all other ;; formats with CRLF line endings have their own specialized methods ;; below (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (- end start))) (declare (fixnum i length)) (loop (when (>= i end) (return)) (let ((position (search #.(vector +cr+ +lf+) sequence :start2 i :end2 end :test #'=))) (unless position (return)) (setq i (1+ position)) (decf length))) length)) (defmethod compute-number-of-chars ((format flexi-utf-8-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((octet (aref sequence i)) ;; note that there are no validity checks here (length (cond ((not (logbitp 7 octet)) 1) ((= #b11000000 (logand* octet #b11100000)) 2) ((= #b11100000 (logand* octet #b11110000)) 3) (t 4)))) (declare (fixnum length) (type octet octet)) (incf sum) (incf i length))) (check-end format start end i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-8-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (loop (when (>= i end) (return)) (let* ((octet (aref sequence i)) ;; note that there are no validity checks here (length (cond ((not (logbitp 7 octet)) 1) ((= #b11000000 (logand* octet #b11100000)) 2) ((= #b11100000 (logand* octet #b11110000)) 3) (t 4)))) (declare (fixnum length) (type octet octet)) (unless (and (= octet +lf+) (= last-octet +cr+)) (incf sum)) (incf i length) (setq last-octet octet))) (check-end format start end i) sum)) (defmethod compute-number-of-chars :before ((format flexi-utf-16-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (declare (ignore sequence)) (when (oddp (- end start)) (signal-encoding-error format "~A octet~:P cannot be decoded ~ using UTF-16 as ~:*~A is not even." (- end start)))) (defmethod compute-number-of-chars ((format flexi-utf-16-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence (1+ i))) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (incf sum) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-utf-16-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence i)) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (incf sum) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-16-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence (1+ i))) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (unless (and (zerop high-octet) (= (the octet (aref sequence i)) +lf+) (= last-octet +cr+)) (incf sum)) (setq last-octet (if (zerop high-octet) (aref sequence i) 0)) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-16-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((sum 0) (i start) (last-octet 0)) (declare (fixnum i sum) (type octet last-octet)) (decf end 2) (loop (when (> i end) (return)) (let* ((high-octet (aref sequence i)) (length (cond ((<= #xd8 high-octet #xdf) 4) (t 2)))) (declare (fixnum length) (type octet high-octet)) (unless (and (zerop high-octet) (= (the octet (aref sequence (1+ i))) +lf+) (= last-octet +cr+)) (incf sum)) (setq last-octet (if (zerop high-octet) (aref sequence (1+ i)) 0)) (incf i length))) (check-end format start (+ end 2) i) sum)) (defmethod compute-number-of-chars :before ((format flexi-utf-32-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (let ((length (- end start))) (when (plusp (mod length 4)) (signal-encoding-error format "~A octet~:P cannot be decoded ~ using UTF-32 as ~:*~A is not a multiple-value of four." length)))) (defmethod compute-number-of-chars ((format flexi-utf-32-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore sequence)) (ceiling (- end start) 4)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-32-le-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (ceiling (- end start) 4))) (decf end 8) (loop (when (> i end) (return)) (cond ((loop for j of-type fixnum from i for octet across #.(vector +cr+ 0 0 0 +lf+ 0 0 0) always (= octet (aref sequence j))) (decf length) (incf i 8)) (t (incf i 4)))) length)) (defmethod compute-number-of-chars ((format flexi-crlf-utf-32-be-format) sequence start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (vector sequence)) (let ((i start) (length (ceiling (- end start) 4))) (decf end 8) (loop (when (> i end) (return)) (cond ((loop for j of-type fixnum from i for octet across #.(vector 0 0 0 +cr+ 0 0 0 +lf+) always (= octet (aref sequence j))) (decf length) (incf i 8)) (t (incf i 4)))) length)) (defgeneric compute-number-of-octets (format sequence start end) (declare #.*standard-optimize-settings*) (:documentation "Computes the exact number of octets required to encode the sequence of characters in SEQUENCE from START to END using the external format FORMAT.")) (defmethod compute-number-of-octets :around (format (list list) start end) (declare #.*standard-optimize-settings*) (call-next-method format (coerce list 'string*) start end)) (defmethod compute-number-of-octets ((format flexi-8-bit-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore string)) (- end start)) (defmethod compute-number-of-octets ((format flexi-utf-8-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((< char-code #x80) 1) ((< char-code #x800) 2) ((< char-code #x10000) 3) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-8-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 2) ((< char-code #x80) 1) ((< char-code #x800) 2) ((< char-code #x10000) 3) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-utf-16-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-16-le-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 4) ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-crlf-utf-16-be-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (let ((sum 0) (i start)) (declare (fixnum i sum)) (loop (when (>= i end) (return)) (let* ((char-code (char-code (char string i))) (char-length (cond ((= char-code #.(char-code #\Newline)) 4) ((< char-code #x10000) 2) (t 4)))) (declare (fixnum char-length) (type char-code-integer char-code)) (incf sum char-length) (incf i))) sum)) (defmethod compute-number-of-octets ((format flexi-utf-32-format) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end)) (declare (ignore string)) (* 4 (- end start))) (defmethod compute-number-of-octets ((format flexi-crlf-mixin) string start end) (declare #.*fixnum-optimize-settings*) (declare (fixnum start end) (string string)) (+ (call-next-method) (* (case (external-format-name format) (:utf-32 4) (otherwise 1)) (count #\Newline string :start start :end end :test #'char=)))) (defgeneric character-length (format char) (declare #.*fixnum-optimize-settings*) (:documentation "Returns the number of octets needed to encode the single character CHAR.") (:method (format char) (compute-number-of-octets format (string char) 0 1))) (defmethod character-length :around ((format flexi-crlf-mixin) (char (eql #\Newline))) (declare #.*fixnum-optimize-settings*) (+ (call-next-method format +cr+) (call-next-method format +lf+))) (defmethod character-length ((format flexi-8-bit-format) char) (declare #.*fixnum-optimize-settings*) (declare (ignore char)) 1) (defmethod character-length ((format flexi-utf-32-format) char) (declare #.*fixnum-optimize-settings*) (declare (ignore char)) 4)
17,967
Common Lisp
.lisp
425
34.284706
93
0.608536
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
154e3b39b889ed56702b5e41c811bfeae7baf696fde59936092acd0e440b1f60
19,183
[ 123547 ]
19,184
iso-8859.lisp
Eggy115_Lisp/flexi-streams-1.0.7/iso-8859.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/iso-8859.lisp,v 1.7 2008/05/18 21:32:15 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) ;;; the following code was auto-generated from files which can be ;;; found at <ftp://ftp.unicode.org/Public/MAPPINGS/ISO8859/> (defconstant +iso-8859-tables+ `((:iso-8859-1 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255))) (:iso-8859-2 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 260 728 321 164 317 346 167 168 352 350 356 377 173 381 379 176 261 731 322 180 318 347 711 184 353 351 357 378 733 382 380 340 193 194 258 196 313 262 199 268 201 280 203 282 205 206 270 272 323 327 211 212 336 214 215 344 366 218 368 220 221 354 223 341 225 226 259 228 314 263 231 269 233 281 235 283 237 238 271 273 324 328 243 244 337 246 247 345 367 250 369 252 253 355 729))) (:iso-8859-3 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 294 728 163 164 65533 292 167 168 304 350 286 308 173 65533 379 176 295 178 179 180 181 293 183 184 305 351 287 309 189 65533 380 192 193 194 65533 196 266 264 199 200 201 202 203 204 205 206 207 65533 209 210 211 212 288 214 215 284 217 218 219 220 364 348 223 224 225 226 65533 228 267 265 231 232 233 234 235 236 237 238 239 65533 241 242 243 244 289 246 247 285 249 250 251 252 365 349 729))) (:iso-8859-4 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 260 312 342 164 296 315 167 168 352 274 290 358 173 381 175 176 261 731 343 180 297 316 711 184 353 275 291 359 330 382 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206 298 272 325 332 310 212 213 214 215 216 370 218 219 220 360 362 223 257 225 226 227 228 229 230 303 269 233 281 235 279 237 238 299 273 326 333 311 244 245 246 247 248 371 250 251 252 361 363 729))) (:iso-8859-5 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 173 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 8470 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 167 1118 1119))) (:iso-8859-6 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 65533 65533 65533 164 65533 65533 65533 65533 65533 65533 65533 1548 173 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 1563 65533 65533 65533 1567 65533 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 65533 65533 65533 65533 65533 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533))) (:iso-8859-7 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 8216 8217 163 8364 8367 166 167 168 169 890 171 172 173 65533 8213 176 177 178 179 900 901 902 183 904 905 906 187 908 189 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 65533 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 65533))) (:iso-8859-8 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 65533 162 163 164 165 166 167 168 169 215 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 247 187 188 189 190 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 8215 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 65533 65533 8206 8207 65533))) (:iso-8859-9 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 286 209 210 211 212 213 214 215 216 217 218 219 220 304 350 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 287 241 242 243 244 245 246 247 248 249 250 251 252 305 351 255))) (:iso-8859-10 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 260 274 290 298 296 310 167 315 272 352 358 381 173 362 330 176 261 275 291 299 297 311 183 316 273 353 359 382 8213 363 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206 207 208 325 332 211 212 213 214 360 216 370 218 219 220 221 222 223 257 225 226 227 228 229 230 303 269 233 281 235 279 237 238 239 240 326 333 243 244 245 246 361 248 371 250 251 252 253 254 312))) (:iso-8859-11 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 65533 65533 65533 65533 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 65533 65533 65533 65533))) (:iso-8859-13 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 8221 162 163 164 8222 166 167 216 169 342 171 172 173 174 198 176 177 178 179 8220 181 182 183 248 185 343 187 188 189 190 230 260 302 256 262 196 197 280 274 268 201 377 278 290 310 298 315 352 323 325 211 332 213 214 215 370 321 346 362 220 379 381 223 261 303 257 263 228 229 281 275 269 233 378 279 291 311 299 316 353 324 326 243 333 245 246 247 371 322 347 363 252 380 382 8217))) (:iso-8859-14 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 7682 7683 163 266 267 7690 167 7808 169 7810 7691 7922 173 174 376 7710 7711 288 289 7744 7745 182 7766 7809 7767 7811 7776 7923 7812 7813 7777 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 372 209 210 211 212 213 214 7786 216 217 218 219 220 221 374 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 373 241 242 243 244 245 246 7787 248 249 250 251 252 253 375 255))) (:iso-8859-15 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 8364 165 352 167 353 169 170 171 172 173 174 175 176 177 178 179 381 181 182 183 382 185 186 187 338 339 376 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255))) (:iso-8859-16 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 260 261 321 8364 8222 352 167 353 169 536 171 377 173 378 379 176 177 268 322 381 8221 182 183 382 269 537 187 338 339 376 380 192 193 194 258 196 262 198 199 200 201 202 203 204 205 206 207 272 323 210 211 212 336 214 346 368 217 218 219 220 280 538 223 224 225 226 259 228 263 230 231 232 233 234 235 236 237 238 239 273 324 242 243 244 337 246 347 369 249 250 251 252 281 539 255)))) "A list of the ISO-8859 encodings where each element is a cons with the car being a keyword denoting the encoding and the cdr being a vector enumerating the corresponding character codes.")
16,875
Common Lisp
.lisp
45
371
1,099
0.723385
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
85c2117c117dfbaf651d0090cfd160990926a627b05f8e1c93bdd58b5f3a7254
19,184
[ 180185 ]
19,185
encode.lisp
Eggy115_Lisp/flexi-streams-1.0.7/encode.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/encode.lisp,v 1.26 2008/05/26 10:55:08 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defgeneric char-to-octets (format char writer) (declare #.*standard-optimize-settings*) (:documentation "Converts the character CHAR to a sequence of octets using the external format FORMAT. The conversion is performed by calling the unary function \(which must be a functional object) WRITER repeatedly each octet. The return value of this function is unspecified.")) (defgeneric write-sequence* (format stream sequence start end) (declare #.*standard-optimize-settings*) (:documentation "A generic function which dispatches on the external format and does the real work for STREAM-WRITE-SEQUENCE.")) (defgeneric string-to-octets* (format string start end) (declare #.*standard-optimize-settings*) (:documentation "A generic function which dispatches on the external format and does the real work for STRING-TO-OCTETS.")) (defmethod string-to-octets* :around (format (list list) start end) (declare #.*standard-optimize-settings*) (string-to-octets* format (coerce list 'string*) start end)) (defmacro define-sequence-writers ((format-class) &body body) "Non-hygienic utility macro which defines methods for WRITE-SEQUENCE* and STRING-TO-OCTETS* for the class FORMAT-CLASS. For BODY see the docstring of DEFINE-CHAR-ENCODERS." (let ((body `((locally (declare #.*fixnum-optimize-settings*) ,@body)))) `(progn (defmethod string-to-octets* ((format ,format-class) string start end) (declare #.*standard-optimize-settings*) (declare (fixnum start end) (string string)) (let ((octets (make-array (compute-number-of-octets format string start end) :element-type 'octet)) (j 0)) (declare (fixnum j)) (loop for i of-type fixnum from start below end do (macrolet ((octet-writer (form) `(progn (setf (aref (the (array octet *) octets) j) ,form) (incf j)))) (symbol-macrolet ((char-getter (char string i))) (progn ,@body)))) octets)) (defmethod write-sequence* ((format ,format-class) stream sequence start end) (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (with-accessors ((column flexi-stream-column)) stream (let* ((octet-seen-p nil) (buffer-pos 0) ;; estimate should be good enough... (factor (encoding-factor format)) ;; we don't want arbitrarily large buffer, do we? (buffer-size (min +buffer-size+ (ceiling (* factor (- end start))))) (buffer (make-octet-buffer buffer-size))) (declare (fixnum buffer-pos buffer-size) (boolean octet-seen-p) (type (array octet *) buffer)) (macrolet ((octet-writer (form) `(write-octet ,form))) (labels ((flush-buffer () "Sends all octets in BUFFER to the underlying stream." (write-sequence buffer stream :end buffer-pos) (setq buffer-pos 0)) (write-octet (octet) "Adds one octet to the buffer and flushes it if necessary." (declare (type octet octet)) (when (>= buffer-pos buffer-size) (flush-buffer)) (setf (aref buffer buffer-pos) octet) (incf buffer-pos)) (write-object (object) "Dispatches to WRITE-OCTET or WRITE-CHARACTER depending on the type of OBJECT." (etypecase object (octet (setq octet-seen-p t) (write-octet object)) (character (symbol-macrolet ((char-getter object)) ,@body))))) (macrolet ((iterate (&body output-forms) "An unhygienic macro to implement the actual iteration through SEQUENCE. OUTPUT-FORM is the form to retrieve one sequence element and put its octet representation into the buffer." `(loop for index of-type fixnum from start below end do (progn ,@output-forms) finally (when (plusp buffer-pos) (flush-buffer))))) (etypecase sequence (string (iterate (symbol-macrolet ((char-getter (char sequence index))) ,@body))) (array (iterate (symbol-macrolet ((char-getter (aref sequence index))) ,@body))) (list (iterate (write-object (nth index sequence)))))) ;; update the column slot, setting it to NIL if we sent ;; octets (setq column (cond (octet-seen-p nil) (t (let ((last-newline-pos (position #\Newline sequence :test #'char= :start start :end end :from-end t))) (cond (last-newline-pos (- end last-newline-pos 1)) (column (+ column (- end start)))))))))))))))) (defmacro define-char-encoders ((lf-format-class cr-format-class crlf-format-class) &body body) "Non-hygienic utility macro which defines several encoding-related methods for the classes LF-FORMAT-CLASS, CR-FORMAT-CLASS, and CRLF-FORMAT-CLASS where it is assumed that CR-FORMAT-CLASS is the same encoding as LF-FORMAT-CLASS but with CR instead of LF line endings and similar for CRLF-FORMAT-CLASS, i.e. LF-FORMAT-CLASS is the base class. BODY is a code template for the code to convert one character to octets. BODY must contain a symbol CHAR-GETTER representing the form which is used to obtain the character and a forms like \(OCTET-WRITE <thing>) to write the octet <thing>. The CHAR-GETTER form might be called more than once." `(progn (defmethod char-to-octets ((format ,lf-format-class) char writer) (declare #.*fixnum-optimize-settings*) (declare (character char) (function writer)) (symbol-macrolet ((char-getter char)) (macrolet ((octet-writer (form) `(funcall writer ,form))) ,@body))) (define-sequence-writers (,lf-format-class) ,@body) (define-sequence-writers (,cr-format-class) ;; modify the body so that the getter replaces a #\Newline ;; with a #\Return ,@(sublis `((char-getter . ,(with-unique-names (char) `(let ((,char char-getter)) (declare (character ,char)) (if (char= ,char #\Newline) #\Return ,char))))) body)) (define-sequence-writers (,crlf-format-class) ;; modify the body so that we potentially write octets for ;; two characters (#\Return and #\Linefeed) - the original ;; body is wrapped with the WRITE-CHAR local function ,(with-unique-names (char write-char) `(flet ((,write-char (,char) ,@(sublis `((char-getter . ,char)) body))) (let ((,char char-getter)) (declare (character ,char)) (cond ((char= ,char #\Newline) (,write-char #\Return) (,write-char #\Linefeed)) (t (,write-char ,char))))))))) (define-char-encoders (flexi-latin-1-format flexi-cr-latin-1-format flexi-crlf-latin-1-format) (let ((octet (char-code char-getter))) (when (> octet 255) (signal-encoding-error format "~S (code ~A) is not a LATIN-1 character." char-getter octet)) (octet-writer octet))) (define-char-encoders (flexi-ascii-format flexi-cr-ascii-format flexi-crlf-ascii-format) (let ((octet (char-code char-getter))) (when (> octet 127) (signal-encoding-error format "~S (code ~A) is not an ASCII character." char-getter octet)) (octet-writer octet))) (define-char-encoders (flexi-8-bit-format flexi-cr-8-bit-format flexi-crlf-8-bit-format) (with-accessors ((encoding-hash external-format-encoding-hash)) format (let ((octet (gethash (char-code char-getter) encoding-hash))) (unless octet (signal-encoding-error format "~S (code ~A) is not in this encoding." char-getter octet)) (octet-writer octet)))) (define-char-encoders (flexi-utf-8-format flexi-cr-utf-8-format flexi-crlf-utf-8-format) ;; the old version using LDB was more elegant, but some Lisps had ;; trouble optimizing it (let ((char-code (char-code char-getter))) (tagbody (cond ((< char-code #x80) (octet-writer char-code) (go zero)) ((< char-code #x800) (octet-writer (logior* #b11000000 (ash* char-code -6))) (go one)) ((< char-code #x10000) (octet-writer (logior* #b11100000 (ash* char-code -12))) (go two)) (t (octet-writer (logior* #b11110000 (ash* char-code -18))))) (octet-writer (logior* #b10000000 (logand* #b00111111 (ash* char-code -12)))) two (octet-writer (logior* #b10000000 (logand* #b00111111 (ash* char-code -6)))) one (octet-writer (logior* #b10000000 (logand* #b00111111 char-code))) zero))) (define-char-encoders (flexi-utf-16-le-format flexi-cr-utf-16-le-format flexi-crlf-utf-16-le-format) (flet ((write-word (word) (octet-writer (logand* #x00ff word)) (octet-writer (ash* (logand* #xff00 word) -8)))) (declare (inline write-word)) (let ((char-code (char-code char-getter))) (declare (type char-code-integer char-code)) (cond ((< char-code #x10000) (write-word char-code)) (t (decf char-code #x10000) (write-word (logior* #xd800 (ash* char-code -10))) (write-word (logior* #xdc00 (logand* #x03ff char-code)))))))) (define-char-encoders (flexi-utf-16-be-format flexi-cr-utf-16-be-format flexi-crlf-utf-16-be-format) (flet ((write-word (word) (octet-writer (ash* (logand* #xff00 word) -8)) (octet-writer (logand* #x00ff word)))) (declare (inline write-word)) (let ((char-code (char-code char-getter))) (declare (type char-code-integer char-code)) (cond ((< char-code #x10000) (write-word char-code)) (t (decf char-code #x10000) (write-word (logior* #xd800 (ash* char-code -10))) (write-word (logior* #xdc00 (logand* #x03ff char-code)))))))) (define-char-encoders (flexi-utf-32-le-format flexi-cr-utf-32-le-format flexi-crlf-utf-32-le-format) (let ((char-code (char-code char-getter))) (octet-writer (logand* #x00ff char-code)) (octet-writer (logand* #x00ff (ash* char-code -8))) (octet-writer (logand* #x00ff (ash* char-code -16))) (octet-writer (logand* #x00ff (ash* char-code -24))))) (define-char-encoders (flexi-utf-32-be-format flexi-cr-utf-32-be-format flexi-crlf-utf-32-be-format) (let ((char-code (char-code char-getter))) (octet-writer (logand* #x00ff (ash* char-code -24))) (octet-writer (logand* #x00ff (ash* char-code -16))) (octet-writer (logand* #x00ff (ash* char-code -8))) (octet-writer (logand* #x00ff char-code)))) (defmethod char-to-octets ((format flexi-cr-mixin) char writer) (declare #.*fixnum-optimize-settings*) (declare (character char)) (if (char= char #\Newline) (call-next-method format #\Return writer) (call-next-method))) (defmethod char-to-octets ((format flexi-crlf-mixin) char writer) (declare #.*fixnum-optimize-settings*) (declare (character char)) (cond ((char= char #\Newline) (call-next-method format #\Return writer) (call-next-method format #\Linefeed writer)) (t (call-next-method))))
14,448
Common Lisp
.lisp
259
42.355212
101
0.57667
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3ff2c61505296d54201bbdd4f9d365be76622ac26b6af1da99e4aceb6fe8fb8d
19,185
[ 434932 ]
19,186
util.lisp
Eggy115_Lisp/flexi-streams-1.0.7/util.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/util.lisp,v 1.24 2008/05/25 21:26:12 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) #+:lispworks (eval-when (:compile-toplevel :load-toplevel :execute) (import '(lw:with-unique-names lw:when-let))) #-:lispworks (defmacro when-let ((var form) &body body) "Evaluates FORM and binds VAR to the result, then executes BODY if VAR has a true value." `(let ((,var ,form)) (when ,var ,@body))) #-:lispworks (defmacro with-unique-names ((&rest bindings) &body body) "Syntax: WITH-UNIQUE-NAMES ( { var | (var x) }* ) declaration* form* Executes a series of forms with each VAR bound to a fresh, uninterned symbol. The uninterned symbol is as if returned by a call to GENSYM with the string denoted by X - or, if X is not supplied, the string denoted by VAR - as argument. The variable bindings created are lexical unless special declarations are specified. The scopes of the name bindings and declarations do not include the Xs. The forms are evaluated in order, and the values of all but the last are discarded \(that is, the body is an implicit PROGN)." ;; reference implementation posted to comp.lang.lisp as ;; <[email protected]> by Vebjorn Ljosa - see also ;; <http://www.cliki.net/Common%20Lisp%20Utilities> `(let ,(mapcar #'(lambda (binding) (check-type binding (or cons symbol)) (if (consp binding) (destructuring-bind (var x) binding (check-type var symbol) `(,var (gensym ,(etypecase x (symbol (symbol-name x)) (character (string x)) (string x))))) `(,binding (gensym ,(symbol-name binding))))) bindings) ,@body)) #+:lispworks (eval-when (:compile-toplevel :load-toplevel :execute) (setf (macro-function 'with-rebinding) (macro-function 'lw:rebinding))) #-:lispworks (defmacro with-rebinding (bindings &body body) "WITH-REBINDING ( { var | (var prefix) }* ) form* Evaluates a series of forms in the lexical environment that is formed by adding the binding of each VAR to a fresh, uninterned symbol, and the binding of that fresh, uninterned symbol to VAR's original value, i.e., its value in the current lexical environment. The uninterned symbol is created as if by a call to GENSYM with the string denoted by PREFIX - or, if PREFIX is not supplied, the string denoted by VAR - as argument. The forms are evaluated in order, and the values of all but the last are discarded \(that is, the body is an implicit PROGN)." ;; reference implementation posted to comp.lang.lisp as ;; <[email protected]> by Vebjorn Ljosa - see also ;; <http://www.cliki.net/Common%20Lisp%20Utilities> (loop for binding in bindings for var = (if (consp binding) (car binding) binding) for name = (gensym) collect `(,name ,var) into renames collect ``(,,var ,,name) into temps finally (return `(let ,renames (with-unique-names ,bindings `(let (,,@temps) ,,@body)))))) (defun normalize-external-format-name (name) "Converts NAME \(a symbol) to a `canonical' name for an external format, e.g. :LATIN1 will be converted to :ISO-8859-1. Also checks if there is an external format with that name and signals an error otherwise." (let ((real-name (or (cdr (assoc name +name-map+ :test #'eq)) name))) (unless (find real-name +name-map+ :test #'eq :key #'cdr) (error 'external-format-error :format-control "~S is not known to be a name for an external format." :format-arguments (list name))) real-name)) (defun ascii-name-p (name) "Checks whether NAME is the keyword :ASCII." (eq name :us-ascii)) (defun koi8-r-name-p (name) "Checks whether NAME is the keyword :KOI8-R." (eq name :koi8-r)) (defun code-page-name-p (name) "Checks whether NAME is the keyword :CODE-PAGE." (eq name :code-page)) (defun iso-8859-name-p (name) "Checks whether NAME \(a keyword) names one of the known ISO-8859 encodings." (find name +iso-8859-tables+ :key #'car)) (defun known-code-page-id-p (id) "Checks whether ID \(a number) denotes one of the known Windows code pages." (and (find id +code-page-tables+ :key #'car) id)) #+:lispworks (defun sans (plist &rest keys) "Returns PLIST with keyword arguments from KEYS removed." (sys::remove-properties plist keys)) #-:lispworks (defun sans (plist &rest keys) "Returns PLIST with keyword arguments from KEYS removed." ;; stolen from Usenet posting <[email protected]> by Erik ;; Naggum (let ((sans ())) (loop (let ((tail (nth-value 2 (get-properties plist keys)))) ;; this is how it ends (unless tail (return (nreconc sans plist))) ;; copy all the unmatched keys (loop until (eq plist tail) do (push (pop plist) sans) (push (pop plist) sans)) ;; skip the matched key (setq plist (cddr plist)))))) #+:lispworks (defmacro with-accessors (slot-entries instance &body body) "For LispWorks, we prefer SLOT-VALUE over accessors for better performance." ;; note that we assume that the variables have the same names as the ;; slots `(with-slots ,(mapcar #'car slot-entries) ,instance ,@body)) (defun make-octet-buffer (&optional (size +buffer-size+)) "Creates and returns a fresh buffer \(a specialized array) of size +BUFFER-SIZE+ to hold octets." (declare #.*standard-optimize-settings*) (make-array size :element-type 'octet)) (defun type-equal (type1 type2) "Whether TYPE1 and TYPE2 denote the same type." (declare #.*standard-optimize-settings*) (and (subtypep type1 type2) (subtypep type2 type1))) (defun maybe-rewind (stream octets) "Tries to `rewind' the \(binary) stream STREAM by OCTETS octets. Returns a true value if it succeeds." (when-let (position (file-position stream)) (file-position stream (- position octets)))) (defmacro logand* (x y) "Solely for optimization purposes. Some Lisps need it, some don't." `(the fixnum (logand ,x ,y))) (defmacro logior* (x y) "Solely for optimization purposes. Some Lisps need it, some don't." `(the fixnum (logior ,x ,y))) (defmacro ash* (integer count) "Solely for optimization purposes. Some Lisps need it, some don't." `(the fixnum (ash ,integer ,count)))
8,318
Common Lisp
.lisp
175
40.657143
92
0.660602
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
fbe13e9ceebb65eee24cc5ffa559d006ea0d92365ae6790c0c571b4481fe91d5
19,186
[ 458577 ]
19,187
koi8-r.lisp
Eggy115_Lisp/flexi-streams-1.0.7/koi8-r.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/koi8-r.lisp,v 1.2 2008/05/18 21:32:15 edi Exp $ ;;; Copyright (c) 2006, Igor Plekhov. All rights reserved. ;;; Copyright (c) 2006-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) ;; http://unicode.org/Public/MAPPINGS/VENDORS/MISC/KOI8-R.TXT (defconstant +koi8-r-table+ (make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 9472 9474 9484 9488 9492 9496 9500 9508 9516 9524 9532 9600 9604 9608 9612 9616 9617 9618 9619 8992 9632 8729 8730 8776 8804 8805 160 8993 176 178 183 247 9552 9553 9554 1105 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 1025 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 169 1102 1072 1073 1094 1076 1077 1092 1075 1093 1080 1081 1082 1083 1084 1085 1086 1087 1103 1088 1089 1090 1091 1078 1074 1100 1099 1079 1096 1101 1097 1095 1098 1070 1040 1041 1062 1044 1045 1060 1043 1061 1048 1049 1050 1051 1052 1053 1054 1055 1071 1056 1057 1058 1059 1046 1042 1068 1067 1047 1064 1069 1065 1063 1066)) "An array enumerating the character codes for the KOI8-R encoding.")
2,877
Common Lisp
.lisp
29
96.517241
1,063
0.743472
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
0bb2c1600cab30e5d4b8b66c0be76e9d23bd0c2ed8f3d57b9a9c96b19ddf9245
19,187
[ 188031, 252341 ]
19,188
io.lisp
Eggy115_Lisp/flexi-streams-1.0.7/io.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/io.lisp,v 1.2 2008/05/20 23:44:45 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defmethod reset-input-state ((flexi-io-stream flexi-io-stream)) "This method is used to clear any state associated with previous input before output is attempted on the stream. It can fail if the octet stack is not empty and the stream can't be `rewound'." (declare #.*standard-optimize-settings*) (with-accessors ((last-char-code flexi-stream-last-char-code) (last-octet flexi-stream-last-octet) (octet-stack flexi-stream-octet-stack) (stream flexi-stream-stream)) flexi-io-stream (when octet-stack (unless (maybe-rewind stream (length octet-stack)) (error 'flexi-stream-out-of-sync-error :stream flexi-io-stream)) (setq octet-stack nil)) (setq last-octet nil last-char-code nil))) (defmethod stream-write-byte :before ((stream flexi-io-stream) byte) (declare #.*standard-optimize-settings*) (declare (ignore byte)) (reset-input-state stream)) (defmethod stream-write-char :before ((stream flexi-io-stream) char) (declare #.*standard-optimize-settings*) (declare (ignore char)) (reset-input-state stream)) (defmethod stream-write-sequence :before ((stream flexi-io-stream) sequence start end &key) (declare #.*standard-optimize-settings*) (declare (ignore sequence start end)) (reset-input-state stream)) (defmethod stream-clear-output :before ((stream flexi-io-stream)) (declare #.*standard-optimize-settings*) (reset-input-state stream)) (defmethod reset-output-state ((flexi-io-stream flexi-io-stream)) "This method is used to clear any state associated with previous output before the stream is used for input." (declare #.*standard-optimize-settings*) (with-accessors ((column flexi-stream-column)) flexi-io-stream (setq column nil))) (defmethod stream-read-byte :before ((stream flexi-io-stream)) (declare #.*standard-optimize-settings*) (reset-output-state stream)) (defmethod stream-read-char :before ((stream flexi-io-stream)) (declare #.*standard-optimize-settings*) (reset-output-state stream)) (defmethod stream-read-sequence :before ((stream flexi-io-stream) sequence start end &key) (declare #.*standard-optimize-settings*) (declare (ignore sequence start end)) (reset-output-state stream)) (defmethod stream-unread-char :before ((stream flexi-io-stream) char) (declare #.*standard-optimize-settings*) (declare (ignore char)) (reset-output-state stream)) (defmethod unread-byte :before (byte (stream flexi-io-stream)) (declare #.*standard-optimize-settings*) (declare (ignore byte)) (reset-output-state stream)) (defmethod stream-clear-input :before ((stream flexi-io-stream)) (declare #.*standard-optimize-settings*) (reset-output-state stream)) (defmethod write-byte* :after (byte (stream flexi-io-stream)) "Keep POSITION slot up to date even when performing output." (declare #.*standard-optimize-settings*) (declare (ignore byte)) (with-accessors ((position flexi-stream-position)) stream (incf position)))
4,721
Common Lisp
.lisp
91
47.043956
92
0.7209
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d3d09af46f19100207967dfaee201c1fe478de45442eb0880be2b83207fdd5e0
19,188
[ 138420, 494176 ]
19,189
lw-char-stream.lisp
Eggy115_Lisp/flexi-streams-1.0.7/lw-char-stream.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/lw-char-stream.lisp,v 1.1 2008/05/23 14:43:09 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defclass flexi-char-output-stream (flexi-output-stream) () (:documentation "This class is for output streams where the underlying stream is bivalent but not binary. It exists solely for the purpose of optimizing output to binary streams on LispWorks. See WRITE-BYTE*.")) (defclass flexi-char-input-stream (flexi-input-stream) () (:documentation "This class is for input streams where the underlying stream is bivalent but not binary. It exists solely for the purpose of optimizing input to binary streams on LispWorks. See READ-BYTE*.")) (defclass flexi-char-io-stream (flexi-char-input-stream flexi-char-output-stream flexi-io-stream) () (:documentation "This class is for bidirectional streams where the underlying stream is bivalent but not binary. It exists solely for the purpose of optimizing input and output from/to binary streams on LispWorks. See READ-BYTE* and WRITE-BYTE*.")) (defmethod initialize-instance :after ((flexi-stream flexi-output-stream) &rest initargs) "Might change the class of FLEXI-STREAM for optimization purposes. Only needed for LispWorks." (declare #.*standard-optimize-settings*) (declare (ignore initargs)) (with-accessors ((stream flexi-stream-stream)) flexi-stream (unless (subtypep (stream-element-type stream) 'octet) (change-class flexi-stream (typecase flexi-stream (flexi-io-stream 'flexi-char-io-stream) (otherwise 'flexi-char-output-stream)))))) (defmethod initialize-instance :after ((flexi-stream flexi-input-stream) &rest initargs) "Might change the class of FLEXI-STREAM for optimization purposes. Only needed for LispWorks." (declare #.*standard-optimize-settings*) (declare (ignore initargs)) (with-accessors ((stream flexi-stream-stream)) flexi-stream (unless (subtypep (stream-element-type stream) 'octet) (change-class flexi-stream (typecase flexi-stream (flexi-io-stream 'flexi-char-io-stream) (otherwise 'flexi-char-input-stream))))))
3,729
Common Lisp
.lisp
66
51.318182
101
0.723977
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
569b3a1192920e1378fe6ba6f4bdc0c13c15bcf3152398ef4f67f630bb526bf1
19,189
[ 217287, 305295 ]
19,190
output.lisp
Eggy115_Lisp/flexi-streams-1.0.7/output.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/output.lisp,v 1.65 2008/05/24 23:15:25 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defgeneric write-byte* (byte stream) (declare #.*standard-optimize-settings*) (:documentation "Writes one byte \(octet) to the underlying stream STREAM.")) #-:lispworks (defmethod write-byte* (byte (flexi-output-stream flexi-output-stream)) (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) flexi-output-stream (write-byte byte stream))) #+:lispworks (defmethod write-byte* (byte (flexi-output-stream flexi-output-stream)) (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) flexi-output-stream (write-byte byte stream))) #+:lispworks (defmethod write-byte* (byte (flexi-output-stream flexi-char-output-stream)) "This method is only used for LispWorks bivalent streams which aren't binary." (declare #.*standard-optimize-settings*) ;; we use WRITE-SEQUENCE because WRITE-BYTE doesn't work with all ;; bivalent streams in LispWorks (4.4.6) (with-accessors ((stream flexi-stream-stream)) flexi-output-stream (write-sequence (make-array 1 :element-type 'octet :initial-element byte) stream) byte)) (defmethod stream-write-char ((stream flexi-output-stream) char) (declare #.*standard-optimize-settings*) (with-accessors ((external-format flexi-stream-external-format)) stream (flet ((writer (octet) (write-byte* octet stream))) (declare (dynamic-extent (function writer))) (char-to-octets external-format char #'writer)))) (defmethod stream-write-char :after ((stream flexi-output-stream) char) (declare #.*standard-optimize-settings*) ;; update the column unless we're in the middle of the line and ;; the current value is NIL (with-accessors ((column flexi-stream-column)) stream (cond ((char= char #\Newline) (setq column 0)) (column (incf (the integer column)))))) (defmethod stream-clear-output ((flexi-output-stream flexi-output-stream)) "Simply calls the corresponding method for the underlying output stream." (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) flexi-output-stream (clear-output stream))) (defmethod stream-finish-output ((flexi-output-stream flexi-output-stream)) "Simply calls the corresponding method for the underlying output stream." (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) flexi-output-stream (finish-output stream))) (defmethod stream-force-output ((flexi-output-stream flexi-output-stream)) "Simply calls the corresponding method for the underlying output stream." (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) flexi-output-stream (force-output stream))) (defmethod stream-line-column ((flexi-output-stream flexi-output-stream)) "Returns the column stored in the COLUMN slot of the FLEXI-OUTPUT-STREAM object STREAM." (declare #.*standard-optimize-settings*) (with-accessors ((column flexi-stream-column)) flexi-output-stream column)) (defmethod stream-write-byte ((flexi-output-stream flexi-output-stream) byte) "Writes a byte \(octet) to the underlying stream." (declare #.*standard-optimize-settings*) (with-accessors ((column flexi-stream-column)) flexi-output-stream ;; set column to NIL because we don't know how to handle binary ;; output mixed with character output (setq column nil) (write-byte* byte flexi-output-stream))) #+:allegro (defmethod stream-terpri ((stream flexi-output-stream)) "Writes a #\Newline character to the underlying stream." (declare #.*standard-optimize-settings*) ;; needed for AllegroCL - grrr... (stream-write-char stream #\Newline)) (defmethod stream-write-sequence ((flexi-output-stream flexi-output-stream) sequence start end &key) "An optimized version which uses a buffer underneath. The function can accepts characters as well as octets and it decides what to do based on the element type of the sequence \(if possible) or on the individual elements, i.e. you can mix characters and octets in SEQUENCE if you want. Whether that really works might also depend on your Lisp, some of the implementations are more picky than others." (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (with-accessors ((column flexi-stream-column) (external-format flexi-stream-external-format) (stream flexi-stream-stream)) flexi-output-stream (when (>= start end) (return-from stream-write-sequence sequence)) (when (and (vectorp sequence) (subtypep (array-element-type sequence) 'integer)) ;; if this is pure binary output, just send all the stuff to the ;; underlying stream directly and skip the rest (setq column nil) (return-from stream-write-sequence (write-sequence sequence stream :start start :end end))) ;; otherwise hand over to the external format to do the work (write-sequence* external-format flexi-output-stream sequence start end)) sequence) (defmethod stream-write-string ((stream flexi-output-stream) string &optional (start 0) (end (length string))) "Simply hands over to the optimized method for STREAM-WRITE-SEQUENCE." (declare #.*standard-optimize-settings*) (stream-write-sequence stream string start (or end (length string))))
7,196
Common Lisp
.lisp
142
45.309859
101
0.715711
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
322ab3269a431a5d2849f48811a60feb313f6cd3741ae9593ad678e5d34f3a15
19,190
[ 43991, 92952 ]
19,191
strings.lisp
Eggy115_Lisp/flexi-streams-1.0.7/strings.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/strings.lisp,v 1.34 2008/05/26 10:55:08 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defun string-to-octets (string &key (external-format :latin1) (start 0) (end (length string))) "Converts the Lisp string STRING from START to END to an array of octets corresponding to the external format designated by EXTERNAL-FORMAT. In spite of the name, STRING can be any sequence of characters, but the function is optimized for strings." (declare #.*standard-optimize-settings*) (setq external-format (maybe-convert-external-format external-format)) ;; the external format knows how to do it... (string-to-octets* external-format string start end)) (defun octets-to-string (sequence &key (external-format :latin1) (start 0) (end (length sequence))) "Converts the Lisp sequence SEQUENCE of octets from START to END to a string using the external format designated by EXTERNAL-FORMAT. This function is optimized for the case of SEQUENCE being a vector. Don't use lists if you're in a hurry." (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (setq external-format (maybe-convert-external-format external-format)) ;; the external format knows how to do it... (octets-to-string* external-format sequence start end)) (defun octet-length (string &key (external-format :latin1) (start 0) (end (length string))) "Returns the length of the substring of STRING from START to END in octets if encoded using the external format EXTERNAL-FORMAT. In spite of the name, STRING can be any sequence of characters, but the function is optimized for strings." (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (setq external-format (maybe-convert-external-format external-format)) (compute-number-of-octets external-format string start end)) (defun char-length (sequence &key (external-format :latin1) (start 0) (end (length sequence))) "Kind of the inverse of OCTET-LENGTH. Returns the length of the subsequence \(of octets) of SEQUENCE from START to END in characters if decoded using the external format EXTERNAL-FORMAT. Note that this function doesn't check for the validity of the data in SEQUENCE. This function is optimized for the case of SEQUENCE being a vector. Don't use lists if you're in a hurry." (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (setq external-format (maybe-convert-external-format external-format)) (compute-number-of-chars external-format sequence start end))
4,164
Common Lisp
.lisp
68
56.264706
95
0.730334
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8cfab7fe45e37d3bb7543f3bfb3cf8a5561dea49a47fe5682fc74389ad42e96c
19,191
[ 95834, 97745 ]
19,192
specials.lisp
Eggy115_Lisp/flexi-streams-1.0.7/specials.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/specials.lisp,v 1.33 2008/05/25 01:40:54 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defvar *standard-optimize-settings* '(optimize speed (safety 0) (space 0) (debug 1) (compilation-speed 0)) "The standard optimize settings used by most declaration expressions.") (defvar *fixnum-optimize-settings* '(optimize speed (safety 0) (space 0) (debug 1) (compilation-speed 0) #+:lispworks (hcl:fixnum-safety 0)) "Like *STANDARD-OPTIMIZE-SETTINGS*, but \(on LispWorks) with all arithmetic being fixnum arithmetic.") (defconstant +lf+ (char-code #\Linefeed)) (defconstant +cr+ (char-code #\Return)) (defvar *current-unreader* nil "A unary function which might be called to `unread' a character \(i.e. the sequence of octets it represents). Used by the function OCTETS-TO-CHAR-CODE and must always be bound to a suitable functional object when this function is called.") (defvar +name-map+ '((:utf8 . :utf-8) (:utf16 . :utf-16) (:ucs2 . :utf-16) (:ucs-2 . :utf-16) (:unicode . :utf-16) (:utf32 . :utf-32) (:ucs4 . :utf-32) (:ucs-4 . :utf-32) (:ascii . :us-ascii) (:koi8r . :koi8-r) (:latin-1 . :iso-8859-1) (:latin1 . :iso-8859-1) (:latin-2 . :iso-8859-2) (:latin2 . :iso-8859-2) (:latin-3 . :iso-8859-3) (:latin3 . :iso-8859-3) (:latin-4 . :iso-8859-4) (:latin4 . :iso-8859-4) (:cyrillic . :iso-8859-5) (:arabic . :iso-8859-6) (:greek . :iso-8859-7) (:hebrew . :iso-8859-8) (:latin-5 . :iso-8859-9) (:latin5 . :iso-8859-9) (:latin-6 . :iso-8859-10) (:latin6 . :iso-8859-10) (:thai . :iso-8859-11) (:latin-7 . :iso-8859-13) (:latin7 . :iso-8859-13) (:latin-8 . :iso-8859-14) (:latin8 . :iso-8859-14) (:latin-9 . :iso-8859-15) (:latin9 . :iso-8859-15) (:latin-0 . :iso-8859-15) (:latin0 . :iso-8859-15) (:latin-10 . :iso-8859-16) (:latin10 . :iso-8859-16) (:codepage . :code-page) #+(and :lispworks :win32) (win32:code-page . :code-page)) "An alist which mapes alternative names for external formats to their canonical counterparts.") (defvar +shortcut-map+ '((:ucs-2le . (:ucs-2 :little-endian t)) (:ucs-2be . (:ucs-2 :little-endian nil)) (:ucs-4le . (:ucs-4 :little-endian t)) (:ucs-4be . (:ucs-4 :little-endian nil)) (:utf-16le . (:utf-16 :little-endian t)) (:utf-16be . (:utf-16 :little-endian nil)) (:utf-32le . (:utf-32 :little-endian t)) (:utf-32be . (:utf-32 :little-endian nil)) (:ibm437 . (:code-page :id 437)) (:ibm850 . (:code-page :id 850)) (:ibm852 . (:code-page :id 852)) (:ibm855 . (:code-page :id 855)) (:ibm857 . (:code-page :id 857)) (:ibm860 . (:code-page :id 860)) (:ibm861 . (:code-page :id 861)) (:ibm862 . (:code-page :id 862)) (:ibm863 . (:code-page :id 863)) (:ibm864 . (:code-page :id 864)) (:ibm865 . (:code-page :id 865)) (:ibm866 . (:code-page :id 866)) (:ibm869 . (:code-page :id 869)) (:windows-1250 . (:code-page :id 1250)) (:windows-1251 . (:code-page :id 1251)) (:windows-1252 . (:code-page :id 1252)) (:windows-1253 . (:code-page :id 1253)) (:windows-1254 . (:code-page :id 1254)) (:windows-1255 . (:code-page :id 1255)) (:windows-1256 . (:code-page :id 1256)) (:windows-1257 . (:code-page :id 1257)) (:windows-1258 . (:code-page :id 1258))) "An alist which maps shortcuts for external formats to their long forms.") (defvar *default-eol-style* #+:win32 :crlf #-:win32 :lf "The end-of-line style used by external formats if none is explicitly given. Depends on the OS the code is compiled on.") (defvar *default-little-endian* #+:little-endian t #-:little-endian nil "Whether external formats are little-endian by default \(i.e. unless explicitly specified). Depends on the platform the code is compiled on.") (defvar *substitution-char* nil "If this value is not NIL, it should be a character which is used \(as if by a USE-VALUE restart) whenever during reading an error of type FLEXI-STREAM-ENCODING-ERROR would have been signalled otherwise.") (defconstant +iso-8859-hashes+ (loop for (name . table) in +iso-8859-tables+ collect (cons name (invert-table table))) "An alist which maps names for ISO-8859 encodings to hash tables which map character codes to the corresponding octets.") (defconstant +code-page-hashes+ (loop for (id . table) in +code-page-tables+ collect (cons id (invert-table table))) "An alist which maps IDs of Windows code pages to hash tables which map character codes to the corresponding octets.") (defconstant +ascii-hash+ (invert-table +ascii-table+) "A hash table which maps US-ASCII character codes to the corresponding octets.") (defconstant +koi8-r-hash+ (invert-table +koi8-r-table+) "A hash table which maps KOI8-R character codes to the corresponding octets.") (defconstant +buffer-size+ 8192 "Default size for buffers used for internal purposes.") (pushnew :flexi-streams *features*) ;; stuff for Nikodemus Siivola's HYPERDOC ;; see <http://common-lisp.net/project/hyperdoc/> ;; and <http://www.cliki.net/hyperdoc> ;; also used by LW-ADD-ONS (defvar *hyperdoc-base-uri* "http://weitz.de/flexi-streams/") (let ((exported-symbols-alist (loop for symbol being the external-symbols of :flexi-streams collect (cons symbol (concatenate 'string "#" (string-downcase symbol)))))) (defun hyperdoc-lookup (symbol type) (declare (ignore type)) (cdr (assoc symbol exported-symbols-alist :test #'eq))))
7,399
Common Lisp
.lisp
175
36.834286
96
0.647182
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
cd06015e35ae463675dc07e921d7f62a522fe26b15aa30a90cb04695f229b8b3
19,192
[ 206277, 474594 ]
19,193
decode.lisp
Eggy115_Lisp/flexi-streams-1.0.7/decode.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/decode.lisp,v 1.35 2008/08/26 10:59:22 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defun recover-from-encoding-error (external-format format-control &rest format-args) "Helper function used by OCTETS-TO-CHAR-CODE below to deal with encoding errors. Checks if *SUBSTITUTION-CHAR* is not NIL and returns its character code in this case. Otherwise signals an EXTERNAL-FORMAT-ENCODING-ERROR as determined by the arguments to this function and provides a corresponding USE-VALUE restart." (when *substitution-char* (return-from recover-from-encoding-error (char-code *substitution-char*))) (restart-case (apply #'signal-encoding-error external-format format-control format-args) (use-value (char) :report "Specify a character to be used instead." :interactive (lambda () (loop (format *query-io* "Type a character: ") (let ((line (read-line *query-io*))) (when (= 1 (length line)) (return (list (char line 0))))))) (char-code char)))) (defgeneric octets-to-char-code (format reader) (declare #.*standard-optimize-settings*) (:documentation "Converts a sequence of octets to a character code \(which is returned, or NIL in case of EOF) using the external format FORMAT. The sequence is obtained by calling the function \(which must be a functional object) READER with no arguments which should return one octet per call. In the case of EOF, READER should return NIL. The special variable *CURRENT-UNREADER* must be bound correctly whenever this function is called.")) (defgeneric octets-to-string* (format sequence start end) (declare #.*standard-optimize-settings*) (:documentation "A generic function which dispatches on the external format and does the real work for OCTETS-TO-STRING.")) (defmethod octets-to-string* :around (format (list list) start end) (declare #.*standard-optimize-settings*) (octets-to-string* format (coerce list 'vector) start end)) (defmacro define-sequence-readers ((format-class) &body body) "Non-hygienic utility macro which defines methods for READ-SEQUENCE* and OCTETS-TO-STRING* for the class FORMAT-CLASS. BODY is described in the docstring of DEFINE-CHAR-ENCODERS but can additionally contain a form \(UNGET <form>) which has to be replaced by the correct code to `unread' the octets for the character designated by <form>." (let* ((body `((block char-decoder (locally (declare #.*fixnum-optimize-settings*) ,@body))))) `(progn (defmethod read-sequence* ((format ,format-class) flexi-input-stream sequence start end) (with-accessors ((position flexi-stream-position) (bound flexi-stream-bound) (octet-stack flexi-stream-octet-stack) (last-octet flexi-stream-last-octet) (last-char-code flexi-stream-last-char-code) (stream flexi-stream-stream)) flexi-input-stream (let* (buffer (buffer-pos 0) (buffer-end 0) (index start) donep ;; whether we will later be able to rewind the stream if ;; needed (to get rid of unused octets in the buffer) (can-rewind-p (maybe-rewind stream 0)) (factor (encoding-factor format)) (integer-factor (floor factor)) ;; it's an interesting question whether it makes sense ;; performance-wise to make RESERVE significantly bigger ;; (and thus put potentially a lot more octets into ;; OCTET-STACK), especially for UTF-8 (reserve (cond ((or (not (floatp factor)) (not can-rewind-p)) 0) (t (ceiling (* (- factor integer-factor) (- end start))))))) (declare (fixnum buffer-pos buffer-end index integer-factor reserve) (boolean can-rewind-p)) (flet ((compute-fill-amount () "Computes the amount of octets we can savely read into the buffer without violating the stream's bound \(if there is one) and without potentially reading much more than we need \(unless we can rewind afterwards)." (let ((minimum (min (the fixnum (+ (the fixnum (* integer-factor (the fixnum (- end index)))) reserve)) +buffer-size+))) (cond (bound (min minimum (- bound position))) (t minimum)))) (fill-buffer (end) "Tries to fill the buffer from BUFFER-POS to END and returns NIL if the buffer doesn't contain any new data." (when donep (return-from fill-buffer nil)) ;; put data from octet stack into buffer if there is any (loop (when (>= buffer-pos end) (return)) (let ((next-octet (pop octet-stack))) (cond (next-octet (setf (aref (the (array octet *) buffer) buffer-pos) (the octet next-octet)) (incf buffer-pos)) (t (return))))) (setq buffer-end (read-sequence buffer stream :start buffer-pos :end end)) ;; we reached EOF, so we remember this (when (< buffer-end end) (setq donep t)) ;; BUFFER-POS is only greater than zero if the buffer ;; already contains unread data from the octet stack ;; (see below), so we test for ZEROP here and do /not/ ;; compare with BUFFER-POS (unless (zerop buffer-end) (incf position buffer-end)))) (let ((minimum (compute-fill-amount))) (declare (fixnum minimum)) (setq buffer (make-octet-buffer minimum)) ;; fill buffer for the first time or return immediately if ;; we don't succeed (unless (fill-buffer minimum) (return-from read-sequence* start))) (setq buffer-pos 0) (macrolet ((iterate (set-place) "A very unhygienic macro to implement the actual iteration through the sequence including housekeeping for the flexi stream. SET-PLACE is the place \(using the index INDEX) used to access the sequence." `(flet ((leave () "This is the function used to abort the LOOP iteration below." (when (> index start) (setq last-octet nil last-char-code ,(sublis '((index . (1- index))) set-place))) (return-from read-sequence* index))) (loop (when (>= index end) ;; check if there are octets in the ;; buffer we didn't use - see ;; COMPUTE-FILL-AMOUNT above (let ((rest (- buffer-end buffer-pos))) (when (plusp rest) (or (and can-rewind-p (maybe-rewind stream rest)) (loop (when (>= buffer-pos buffer-end) (return)) (decf buffer-end) (push (aref (the (array octet *) buffer) buffer-end) octet-stack))))) (leave)) (let ((next-char-code (progn (symbol-macrolet ((octet-getter ;; this is the code to retrieve the next octet (or ;; NIL) and to fill the buffer if needed (block next-octet (when (>= buffer-pos buffer-end) (setq buffer-pos 0) (unless (fill-buffer (compute-fill-amount)) (return-from next-octet))) (prog1 (aref (the (array octet *) buffer) buffer-pos) (incf buffer-pos))))) (macrolet ((unget (form) `(unread-char% ,form flexi-input-stream))) ,',@body))))) (unless next-char-code (leave)) (setf ,set-place (code-char next-char-code)) (incf index)))))) (etypecase sequence (string (iterate (char sequence index))) (array (iterate (aref sequence index))) (list (iterate (nth index sequence))))))))) (defmethod octets-to-string* ((format ,format-class) sequence start end) (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (let* ((i start) (string-length (compute-number-of-chars format sequence start end)) (string (make-array string-length :element-type 'char*))) (declare (fixnum i string-length)) (loop for j of-type fixnum from 0 below string-length do (setf (schar string j) (code-char (macrolet ((unget (form) `(decf i (character-length format ,form)))) ;; we don't need to test for ;; the end of SEQUENCE as the ;; computation has been done ;; for us already (symbol-macrolet ((octet-getter (prog1 (aref sequence i) (incf i)))) ,@body)))) finally (return string))))))) (defmacro define-char-decoders ((lf-format-class cr-format-class crlf-format-class) &body body) "Non-hygienic utility macro which defines several decoding-related methods for the classes LF-FORMAT-CLASS, CR-FORMAT-CLASS, and CRLF-FORMAT-CLASS where it is assumed that CR-FORMAT-CLASS is the same encoding as LF-FORMAT-CLASS but with CR instead of LF line endings and similar for CRLF-FORMAT-CLASS, i.e. LF-FORMAT-CLASS is the base class. BODY is a code template for the code to read octets and return one character code. BODY must contain a symbol OCTET-GETTER representing the form which is used to obtain the next octet." (let* ((body (with-unique-names (char-code) `((let ((,char-code (progn ,@body))) (when (and ,char-code (or (<= #xd8 (logand* #x00ff (ash* ,char-code -8)) #xdf) (> ,char-code #x10ffff))) (recover-from-encoding-error format "Illegal code point ~A \(#x~:*~X)." ,char-code)) ,char-code))))) `(progn (defmethod octets-to-char-code ((format ,lf-format-class) reader) (declare #.*fixnum-optimize-settings*) (declare (function reader)) (symbol-macrolet ((octet-getter (funcall reader))) ,@(sublis '((char-decoder . octets-to-char-code)) body))) (define-sequence-readers (,lf-format-class) ,@body) (define-sequence-readers (,cr-format-class) ,(with-unique-names (char-code) `(let ((,char-code (progn ,@body))) (case ,char-code (#.+cr+ #.(char-code #\Newline)) (otherwise ,char-code))))) (define-sequence-readers (,crlf-format-class) ,(with-unique-names (char-code next-char-code get-char-code) `(flet ((,get-char-code () ,@body)) (let ((,char-code (,get-char-code))) (case ,char-code (#.+cr+ (let ((,next-char-code (,get-char-code))) (case ,next-char-code (#.+lf+ #.(char-code #\Newline)) ;; we saw a CR but no LF afterwards, but then the data ;; ended, so we just return #\Return ((nil) +cr+) ;; if the character we peeked at wasn't a ;; linefeed character we unread its constituents (otherwise (unget (code-char ,next-char-code)) ,char-code)))) (otherwise ,char-code))))))))) (define-char-decoders (flexi-latin-1-format flexi-cr-latin-1-format flexi-crlf-latin-1-format) octet-getter) (define-char-decoders (flexi-ascii-format flexi-cr-ascii-format flexi-crlf-ascii-format) (when-let (octet octet-getter) (if (> (the octet octet) 127) (recover-from-encoding-error format "No character which corresponds to octet #x~X." octet) octet))) (define-char-decoders (flexi-8-bit-format flexi-cr-8-bit-format flexi-crlf-8-bit-format) (with-accessors ((decoding-table external-format-decoding-table)) format (when-let (octet octet-getter) (let ((char-code (aref (the (simple-array char-code-integer *) decoding-table) (the octet octet)))) (if (or (null char-code) (= (the char-code-integer char-code) 65533)) (recover-from-encoding-error format "No character which corresponds to octet #x~X." octet) char-code))))) (define-char-decoders (flexi-utf-8-format flexi-cr-utf-8-format flexi-crlf-utf-8-format) (let (first-octet-seen) (declare (boolean first-octet-seen)) (macrolet ((read-next-byte () '(prog1 (or octet-getter (cond (first-octet-seen (return-from char-decoder (recover-from-encoding-error format "End of data while in UTF-8 sequence."))) (t (return-from char-decoder nil)))) (setq first-octet-seen t)))) (flet ((recover-from-overlong-sequence (value) (restart-case (recover-from-encoding-error format "`Overlong' UTF-8 sequence for code point #x~X." value) (accept-overlong-sequence () :report "Accept the code point and continue." value)))) (let ((octet (read-next-byte))) (declare (type octet octet)) (block utf-8-sequence (multiple-value-bind (start count) (cond ((not (logbitp 7 octet)) ;; avoid the overlong checks below (return-from utf-8-sequence octet)) ((= #b11000000 (logand* octet #b11100000)) (values (logand* octet #b00011111) 1)) ((= #b11100000 (logand* octet #b11110000)) (values (logand* octet #b00001111) 2)) ((= #b11110000 (logand* octet #b11111000)) (values (logand* octet #b00000111) 3)) (t (return-from char-decoder (recover-from-encoding-error format "Unexpected value #x~X at start of UTF-8 sequence." octet)))) (declare (fixnum count)) (loop for result of-type code-point = start then (+ (ash* result 6) (logand* octet #b111111)) repeat count for octet of-type octet = (read-next-byte) unless (= #b10000000 (logand* octet #b11000000)) do (return-from char-decoder (recover-from-encoding-error format "Unexpected value #x~X in UTF-8 sequence." octet)) finally (return (cond ((< result (ecase count (1 #x00080) (2 #x00800) (3 #x10000))) (recover-from-overlong-sequence result)) (t result))))))))))) (define-char-decoders (flexi-utf-16-le-format flexi-cr-utf-16-le-format flexi-crlf-utf-16-le-format) (let (first-octet-seen) (declare (boolean first-octet-seen)) (macrolet ((read-next-byte () '(prog1 (or octet-getter (cond (first-octet-seen (return-from char-decoder (recover-from-encoding-error format "End of data while in UTF-16 sequence."))) (t (return-from char-decoder nil)))) (setq first-octet-seen t)))) (flet ((read-next-word () (+ (the octet (read-next-byte)) (ash* (the octet (read-next-byte)) 8)))) (declare (inline read-next-word)) (let ((word (read-next-word))) (declare (type (unsigned-byte 16) word)) (cond ((<= #xd800 word #xdfff) (let ((next-word (read-next-word))) (declare (type (unsigned-byte 16) next-word)) (unless (<= #xdc00 next-word #xdfff) (return-from char-decoder (recover-from-encoding-error format "Unexpected UTF-16 word #x~X following #x~X." next-word word))) (+ (ash* (logand* #b1111111111 word) 10) (logand* #b1111111111 next-word) #x10000))) (t word))))))) (define-char-decoders (flexi-utf-16-be-format flexi-cr-utf-16-be-format flexi-crlf-utf-16-be-format) (let (first-octet-seen) (declare (boolean first-octet-seen)) (macrolet ((read-next-byte () '(prog1 (or octet-getter (cond (first-octet-seen (return-from char-decoder (recover-from-encoding-error format "End of data while in UTF-16 sequence."))) (t (return-from char-decoder nil)))) (setq first-octet-seen t)))) (flet ((read-next-word () (+ (ash* (the octet (read-next-byte)) 8) (the octet (read-next-byte))))) (declare (inline read-next-word)) (let ((word (read-next-word))) (declare (type (unsigned-byte 16) word)) (cond ((<= #xd800 word #xdfff) (let ((next-word (read-next-word))) (declare (type (unsigned-byte 16) next-word)) (unless (<= #xdc00 next-word #xdfff) (return-from char-decoder (recover-from-encoding-error format "Unexpected UTF-16 word #x~X following #x~X." next-word word))) (+ (ash* (logand* #b1111111111 word) 10) (logand* #b1111111111 next-word) #x10000))) (t word))))))) (define-char-decoders (flexi-utf-32-le-format flexi-cr-utf-32-le-format flexi-crlf-utf-32-le-format) (let (first-octet-seen) (declare (boolean first-octet-seen)) (macrolet ((read-next-byte () '(prog1 (or octet-getter (cond (first-octet-seen (return-from char-decoder (recover-from-encoding-error format "End of data while in UTF-32 sequence."))) (t (return-from char-decoder nil)))) (setq first-octet-seen t)))) (loop for count of-type fixnum from 0 to 24 by 8 for octet of-type octet = (read-next-byte) sum (ash* octet count))))) (define-char-decoders (flexi-utf-32-be-format flexi-cr-utf-32-be-format flexi-crlf-utf-32-be-format) (let (first-octet-seen) (declare (boolean first-octet-seen)) (macrolet ((read-next-byte () '(prog1 (or octet-getter (cond (first-octet-seen (return-from char-decoder (recover-from-encoding-error format "End of data while in UTF-32 sequence."))) (t (return-from char-decoder nil)))) (setq first-octet-seen t)))) (loop for count of-type fixnum from 24 downto 0 by 8 for octet of-type octet = (read-next-byte) sum (ash* octet count))))) (defmethod octets-to-char-code ((format flexi-cr-mixin) reader) (declare #.*fixnum-optimize-settings*) (declare (ignore reader)) (let ((char-code (call-next-method))) (case char-code (#.+cr+ #.(char-code #\Newline)) (otherwise char-code)))) (defmethod octets-to-char-code ((format flexi-crlf-mixin) reader) (declare #.*fixnum-optimize-settings*) (declare (function *current-unreader*)) (declare (ignore reader)) (let ((char-code (call-next-method))) (case char-code (#.+cr+ (let ((next-char-code (call-next-method))) (case next-char-code (#.+lf+ #.(char-code #\Newline)) ;; we saw a CR but no LF afterwards, but then the data ;; ended, so we just return #\Return ((nil) +cr+) ;; if the character we peeked at wasn't a ;; linefeed character we unread its constituents (otherwise (funcall *current-unreader* (code-char next-char-code)) char-code)))) (otherwise char-code))))
26,075
Common Lisp
.lisp
447
37.250559
109
0.48448
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b3cf965193e0d719c764e3dd988fa0e8b0c6acbca162c3b981b67e6bac63faef
19,193
[ 174407, 228913 ]
19,194
conditions.lisp
Eggy115_Lisp/flexi-streams-1.0.7/conditions.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/conditions.lisp,v 1.9 2008/05/25 22:23:58 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (define-condition flexi-stream-error (stream-error) () (:documentation "Superclass for all errors related to flexi streams.")) (define-condition flexi-stream-simple-error (flexi-stream-error simple-condition) () (:documentation "Like FLEXI-STREAM-ERROR but with formatting capabilities.")) (define-condition flexi-stream-element-type-error (flexi-stream-error) ((element-type :initarg :element-type :reader flexi-stream-element-type-error-element-type)) (:report (lambda (condition stream) (format stream "Element type ~S not allowed." (flexi-stream-element-type-error-element-type condition)))) (:documentation "Errors of this type are signalled if the flexi stream has a wrong element type.")) (define-condition flexi-stream-out-of-sync-error (flexi-stream-error) () (:report (lambda (condition stream) (declare (ignore condition)) (format stream "Stream out of sync from previous lookahead, couldn't rewind."))) (:documentation "This can happen if you're trying to write to an IO stream which had prior to that `looked ahead' while reading and now can't `rewind' to the octet where you /should/ be.")) (define-condition in-memory-stream-error (stream-error) () (:documentation "Superclass for all errors related to IN-MEMORY streams.")) (define-condition in-memory-stream-simple-error (in-memory-stream-error simple-condition) () (:documentation "Like IN-MEMORY-STREAM-ERROR but with formatting capabilities.")) (define-condition in-memory-stream-closed-error (in-memory-stream-error) () (:report (lambda (condition stream) (format stream "~S is closed." (stream-error-stream condition)))) (:documentation "An error that is signalled when someone is trying to read from or write to a closed IN-MEMORY stream.")) (define-condition in-memory-stream-position-spec-error (in-memory-stream-simple-error) ((position-spec :initarg :position-spec :reader in-memory-stream-position-spec-error-position-spec)) (:documentation "Errors of this type are signalled if an erroneous position spec is used in conjunction with FILE-POSITION.")) (define-condition external-format-condition (simple-condition) ((external-format :initarg :external-format :initform nil :reader external-format-condition-external-format)) (:documentation "Superclass for all conditions related to external formats.")) (define-condition external-format-error (external-format-condition error) () (:documentation "Superclass for all errors related to external formats.")) (define-condition external-format-encoding-error (external-format-error) () (:documentation "Errors of this type are signalled if there is an encoding problem.")) (defun signal-encoding-error (external-format format-control &rest format-args) "Convenience function similar to ERROR to signal conditions of type EXTERNAL-FORMAT-ENCODING-ERROR." (error 'external-format-encoding-error :format-control format-control :format-arguments format-args :external-format external-format))
4,843
Common Lisp
.lisp
90
48.611111
97
0.729374
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
fa441c8722bdf1bb81007a4b8e43cbc374d36cec89f336f882c831da86585ae9
19,194
[ 134905, 218061 ]
19,195
stream.lisp
Eggy115_Lisp/flexi-streams-1.0.7/stream.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/stream.lisp,v 1.61 2008/05/19 22:32:56 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defclass flexi-stream (trivial-gray-stream-mixin) ((stream :initarg :stream :reader flexi-stream-stream :documentation "The actual stream that's used for input and/or output. It must be capable of reading/writing octets with READ-SEQUENCE and/or WRITE-SEQUENCE.") (external-format :initform (make-external-format :iso-8859-1) :initarg :flexi-stream-external-format :accessor flexi-stream-external-format :documentation "The encoding currently used by this stream. Can be changed on the fly.") (element-type :initform 'char* :initarg :element-type :accessor flexi-stream-element-type :documentation "The element type of this stream.")) (:documentation "A FLEXI-STREAM object is a stream that's `layered' atop an existing binary/bivalent stream in order to allow for multi-octet external formats. FLEXI-STREAM itself is a mixin and should not be instantiated.")) (defmethod initialize-instance :after ((flexi-stream flexi-stream) &rest initargs) "Makes sure the EXTERNAL-FORMAT and ELEMENT-TYPE slots contain reasonable values." (declare #.*standard-optimize-settings*) (declare (ignore initargs)) (with-accessors ((external-format flexi-stream-external-format) (element-type flexi-stream-element-type)) flexi-stream (unless (or (subtypep element-type 'character) (subtypep element-type 'octet)) (error 'flexi-stream-element-type-error :element-type element-type :stream flexi-stream)) (setq external-format (maybe-convert-external-format external-format)))) (defmethod (setf flexi-stream-external-format) :around (new-value (flexi-stream flexi-stream)) "Converts the new value to an EXTERNAL-FORMAT object if necessary." (declare #.*standard-optimize-settings*) (call-next-method (maybe-convert-external-format new-value) flexi-stream)) (defmethod (setf flexi-stream-element-type) :before (new-value (flexi-stream flexi-stream)) "Checks whether the new value makes sense before it is set." (declare #.*standard-optimize-settings*) (unless (or (subtypep new-value 'character) (type-equal new-value 'octet)) (error 'flexi-stream-element-type-error :element-type new-value :stream flexi-stream))) (defmethod stream-element-type ((stream flexi-stream)) "Returns the element type that was provided by the creator of the stream." (declare #.*standard-optimize-settings*) (with-accessors ((element-type flexi-stream-element-type)) stream element-type)) (defmethod close ((stream flexi-stream) &key abort) "Closes the flexi stream by closing the underlying `real' stream." (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) stream (cond ((open-stream-p stream) (close stream :abort abort)) (t nil)))) (defmethod open-stream-p ((stream flexi-stream)) "A flexi stream is open if its underlying stream is open." (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) stream (open-stream-p stream))) (defmethod stream-file-position ((stream flexi-stream)) "Dispatch to method for underlying stream." (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) stream (stream-file-position stream))) (defmethod (setf stream-file-position) (position-spec (stream flexi-stream)) "Dispatch to method for underlying stream." (declare #.*standard-optimize-settings*) (with-accessors ((stream flexi-stream-stream)) stream (setf (stream-file-position stream) position-spec))) (defclass flexi-output-stream (flexi-stream fundamental-binary-output-stream fundamental-character-output-stream) ((column :initform 0 :accessor flexi-stream-column :documentation "The current output column. A non-negative integer or NIL.")) (:documentation "A FLEXI-OUTPUT-STREAM is a FLEXI-STREAM that can actually be instatiated and used for output. Don't use MAKE-INSTANCE to create a new FLEXI-OUTPUT-STREAM but use MAKE-FLEXI-STREAM instead.")) #+:cmu (defmethod input-stream-p ((stream flexi-output-stream)) "Explicitly states whether this is an input stream." (declare #.*standard-optimize-settings*) nil) (defclass flexi-input-stream (flexi-stream fundamental-binary-input-stream fundamental-character-input-stream) ((last-char-code :initform nil :accessor flexi-stream-last-char-code :documentation "This slot either holds NIL or the last character \(code) read successfully. This is mainly used for UNREAD-CHAR sanity checks.") (last-octet :initform nil :accessor flexi-stream-last-octet :documentation "This slot either holds NIL or the last octet read successfully from the stream using a `binary' operation such as READ-BYTE. This is mainly used for UNREAD-BYTE sanity checks.") (octet-stack :initform nil :accessor flexi-stream-octet-stack :documentation "A small buffer which holds octets that were already read from the underlying stream but not yet used to produce characters. This is mainly used if we have to look ahead for a CR/LF line ending.") (position :initform 0 :initarg :position :type integer :accessor flexi-stream-position :documentation "The position within the stream where each octet read counts as one.") (bound :initform nil :initarg :bound :type (or null integer) :accessor flexi-stream-bound :documentation "When this is not NIL, it must be an integer and the stream will behave as if no more data is available as soon as POSITION is greater or equal than this value.")) (:documentation "A FLEXI-INPUT-STREAM is a FLEXI-STREAM that can actually be instatiated and used for input. Don't use MAKE-INSTANCE to create a new FLEXI-INPUT-STREAM but use MAKE-FLEXI-STREAM instead.")) #+:cmu (defmethod output-stream-p ((stream flexi-input-stream)) "Explicitly states whether this is an output stream." (declare #.*standard-optimize-settings*) nil) (defclass flexi-io-stream (flexi-input-stream flexi-output-stream) () (:documentation "A FLEXI-IO-STREAM is a FLEXI-STREAM that can actually be instatiated and used for input and output. Don't use MAKE-INSTANCE to create a new FLEXI-IO-STREAM but use MAKE-FLEXI-STREAM instead.")) #+:cmu (defmethod input-stream-p ((stream flexi-io-stream)) "Explicitly states whether this is an input stream." (declare #.*standard-optimize-settings*) t) #+:cmu (defmethod output-stream-p ((stream flexi-io-stream)) "Explicitly states whether this is an output stream." (declare #.*standard-optimize-settings*) t) (defun make-flexi-stream (stream &rest args &key (external-format (make-external-format :iso-8859-1)) element-type column position bound) "Creates and returns a new flexi stream. STREAM must be an open binary or `bivalent' stream, i.e. it must be capable of reading/writing octets with READ-SEQUENCE and/or WRITE-SEQUENCE. The resulting flexi stream is an input stream if and only if STREAM is an input stream. Likewise, it's an output stream if and only if STREAM is an output stream. The default for ELEMENT-TYPE is LW:SIMPLE-CHAR on LispWorks and CHARACTER on other Lisps. EXTERNAL-FORMAT must be an EXTERNAL-FORMAT object or a symbol or a list denoting such an object. COLUMN is the initial column of the stream which is either a non-negative integer or NIL. The COLUMN argument must only be used for output streams. POSITION \(only used for input streams) should be an integer and it denotes the position the stream is in - it will be increased by one for each octet read. BOUND \(only used for input streams) should be NIL or an integer. If BOUND is not NIL and POSITION has gone beyond BOUND, then the stream will behave as if no more input is available." (declare #.*standard-optimize-settings*) ;; these arguments are ignored - they are only there to provide a ;; meaningful parameter list for IDEs (declare (ignore element-type column position bound)) (unless (and (streamp stream) (open-stream-p stream)) (error "~S should have been an open stream." stream)) (apply #'make-instance ;; actual type depends on STREAM (cond ((and (input-stream-p stream) (output-stream-p stream)) 'flexi-io-stream) ((input-stream-p stream) 'flexi-input-stream) ((output-stream-p stream) 'flexi-output-stream)) :stream stream :flexi-stream-external-format external-format (sans args :external-format)))
10,833
Common Lisp
.lisp
214
43.817757
95
0.699139
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
652f0b19000364a285504190413cb90ce3d9a91108c788b66ed8fa9808169213
19,195
[ 217543 ]
19,196
mapping.lisp
Eggy115_Lisp/flexi-streams-1.0.7/mapping.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/mapping.lisp,v 1.3 2008/05/25 19:07:53 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (deftype octet () "A shortcut for \(UNSIGNED-BYTE 8)." '(unsigned-byte 8)) (deftype char* () "Convenience shortcut to paper over the difference between LispWorks and the other Lisps." #+:lispworks 'lw:simple-char #-:lispworks 'character) (deftype string* () "Convenience shortcut to paper over the difference between LispWorks and the other Lisps." #+:lispworks 'lw:text-string #-:lispworks 'string) (deftype char-code-integer () "The subtype of integers which can be returned by the function CHAR-CODE." '(integer 0 #.(1- char-code-limit))) (deftype code-point () "The subtype of integers that's just big enough to hold all Unicode codepoints. See for example <http://unicode.org/glossary/#C>." '(mod #x110000)) (defmacro defconstant (name value &optional doc) "Make sure VALUE is evaluated only once \(to appease SBCL)." `(cl:defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value) ,@(when doc (list doc)))) (defun invert-table (table) "`Inverts' an array which maps octets to character codes to a hash table which maps character codes to octets." (let ((hash (make-hash-table))) (loop for octet from 0 for char-code across table unless (= char-code 65533) do (setf (gethash char-code hash) octet)) hash)) (defun make-decoding-table (list) "Creates and returns an array which contains the elements in the list LIST and has an element type that's suitable for character codes." (make-array (length list) :element-type 'char-code-integer :initial-contents list))
3,224
Common Lisp
.lisp
65
45.523077
94
0.716933
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
207979b3d27d8f302265346a0b17c29c2b506ab57229f0b11e77a946c1090c9b
19,196
[ 339939 ]
19,197
ascii.lisp
Eggy115_Lisp/flexi-streams-1.0.7/ascii.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/ascii.lisp,v 1.9 2008/05/18 21:32:15 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defconstant +ascii-table+ ;; currently not used, but we leave it in here just in case... (make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533)) "An array enumerating the character codes for the US-ASCII encoding.")
2,952
Common Lisp
.lisp
29
99.103448
1,197
0.755586
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d4feaac701db5f5f9cd74d9421104f9b6b898c88814a2b47da30628be181eaed
19,197
[ 77159 ]
19,198
external-format.lisp
Eggy115_Lisp/flexi-streams-1.0.7/external-format.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/external-format.lisp,v 1.24 2008/05/26 10:55:08 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) (defclass external-format () ((name :initarg :name :reader external-format-name :documentation "The name of the external format - a keyword.") (id :initarg :id :initform nil :reader external-format-id :documentation "If the external format denotes a Windows code page this ID specifies which one to use. Otherwise the value is ignored \(and usually NIL).") (little-endian :initarg :little-endian :initform *default-little-endian* :reader external-format-little-endian :documentation "Whether multi-octet values are read and written with the least significant octet first. For 8-bit encodings like :ISO-8859-1 this value is ignored.") (eol-style :initarg :eol-style :reader external-format-eol-style :documentation "The character\(s) to or from which a #\Newline will be translated - one of the keywords :CR, :LF, or :CRLF.")) (:documentation "EXTERNAL-FORMAT objects are used to denote encodings for flexi streams or for the string functions defined in strings.lisp.")) (defmethod make-load-form ((thing external-format) &optional environment) "Defines a way to reconstruct external formats. Needed for OpenMCL." (make-load-form-saving-slots thing :environment environment)) (defclass flexi-cr-mixin () () (:documentation "A mixin for external-formats where the end-of-line designator is #\Return.")) (defclass flexi-crlf-mixin () () (:documentation "A mixin for external-formats where the end-of-line designator is the sequence #\Return #\Linefeed.")) (defclass flexi-8-bit-format (external-format) ((encoding-hash :accessor external-format-encoding-hash) (decoding-table :accessor external-format-decoding-table)) (:documentation "The class for all flexi streams which use an 8-bit encoding and thus need additional slots for the encoding/decoding tables.")) (defclass flexi-cr-8-bit-format (flexi-cr-mixin flexi-8-bit-format) () (:documentation "Special class for external formats which use an 8-bit encoding /and/ have #\Return as the line-end character.")) (defclass flexi-crlf-8-bit-format (flexi-crlf-mixin flexi-8-bit-format) () (:documentation "Special class for external formats which use an 8-bit encoding /and/ have the sequence #\Return #\Linefeed as the line-end character.")) (defclass flexi-ascii-format (flexi-8-bit-format) () (:documentation "Special class for external formats which use the US-ASCII encoding.")) (defclass flexi-cr-ascii-format (flexi-cr-mixin flexi-ascii-format) () (:documentation "Special class for external formats which use the US-ASCII encoding /and/ have #\Return as the line-end character.")) (defclass flexi-crlf-ascii-format (flexi-crlf-mixin flexi-ascii-format) () (:documentation "Special class for external formats which use the US-ASCII encoding /and/ have the sequence #\Return #\Linefeed as the line-end character.")) (defclass flexi-latin-1-format (flexi-8-bit-format) () (:documentation "Special class for external formats which use the ISO-8859-1 encoding.")) (defclass flexi-cr-latin-1-format (flexi-cr-mixin flexi-latin-1-format) () (:documentation "Special class for external formats which use the ISO-8859-1 encoding /and/ have #\Return as the line-end character.")) (defclass flexi-crlf-latin-1-format (flexi-crlf-mixin flexi-latin-1-format) () (:documentation "Special class for external formats which use the ISO-8859-1 encoding /and/ have the sequence #\Return #\Linefeed as the line-end character.")) (defclass flexi-utf-32-format (external-format) () (:documentation "Abstract class for external formats which use the UTF-32 encoding.")) (defclass flexi-utf-32-le-format (flexi-utf-32-format) () (:documentation "Special class for external formats which use the UTF-32 encoding with little-endian byte ordering.")) (defclass flexi-cr-utf-32-le-format (flexi-cr-mixin flexi-utf-32-le-format) () (:documentation "Special class for external formats which use the UTF-32 encoding with little-endian byte ordering /and/ have #\Return as the line-end character.")) (defclass flexi-crlf-utf-32-le-format (flexi-crlf-mixin flexi-utf-32-le-format) () (:documentation "Special class for external formats which use the UTF-32 encoding with little-endian byte ordering /and/ have the sequence #\Return #\Linefeed as the line-end character.")) (defclass flexi-utf-32-be-format (flexi-utf-32-format) () (:documentation "Special class for external formats which use the UTF-32 encoding with big-endian byte ordering.")) (defclass flexi-cr-utf-32-be-format (flexi-cr-mixin flexi-utf-32-be-format) () (:documentation "Special class for external formats which use the UTF-32 encoding with big-endian byte ordering /and/ have #\Return as the line-end character.")) (defclass flexi-crlf-utf-32-be-format (flexi-crlf-mixin flexi-utf-32-be-format) () (:documentation "Special class for external formats which use the the UTF-32 encoding with big-endian byte ordering /and/ have the sequence #\Return #\Linefeed as the line-end character.")) (defclass flexi-utf-16-format (external-format) () (:documentation "Abstract class for external formats which use the UTF-16 encoding.")) (defclass flexi-utf-16-le-format (flexi-utf-16-format) () (:documentation "Special class for external formats which use the UTF-16 encoding with little-endian byte ordering.")) (defclass flexi-cr-utf-16-le-format (flexi-cr-mixin flexi-utf-16-le-format) () (:documentation "Special class for external formats which use the UTF-16 encoding with little-endian byte ordering /and/ have #\Return as the line-end character.")) (defclass flexi-crlf-utf-16-le-format (flexi-crlf-mixin flexi-utf-16-le-format) () (:documentation "Special class for external formats which use the UTF-16 encoding with little-endian byte ordering /and/ have the sequence #\Return #\Linefeed as the line-end character.")) (defclass flexi-utf-16-be-format (flexi-utf-16-format) () (:documentation "Special class for external formats which use the UTF-16 encoding with big-endian byte ordering.")) (defclass flexi-cr-utf-16-be-format (flexi-cr-mixin flexi-utf-16-be-format) () (:documentation "Special class for external formats which use the UTF-16 encoding with big-endian byte ordering /and/ have #\Return as the line-end character.")) (defclass flexi-crlf-utf-16-be-format (flexi-crlf-mixin flexi-utf-16-be-format) () (:documentation "Special class for external formats which use the UTF-16 encoding with big-endian byte ordering /and/ have the sequence #\Return #\Linefeed as the line-end character.")) (defclass flexi-utf-8-format (external-format) () (:documentation "Special class for external formats which use the UTF-8 encoding.")) (defclass flexi-cr-utf-8-format (flexi-cr-mixin flexi-utf-8-format) () (:documentation "Special class for external formats which use the UTF-8 encoding /and/ have #\Return as the line-end character.")) (defclass flexi-crlf-utf-8-format (flexi-crlf-mixin flexi-utf-8-format) () (:documentation "Special class for external formats which use the UTF-8 encoding /and/ have the sequence #\Return #\Linefeed as the line-end character.")) (defmethod initialize-instance :after ((external-format flexi-8-bit-format) &rest initargs) "Sets the fixed encoding/decoding tables for this particular external format." (declare #.*standard-optimize-settings*) (declare (ignore initargs)) (with-accessors ((encoding-hash external-format-encoding-hash) (decoding-table external-format-decoding-table) (name external-format-name) (id external-format-id)) external-format (multiple-value-setq (encoding-hash decoding-table) (cond ((ascii-name-p name) (values +ascii-hash+ +ascii-table+)) ((koi8-r-name-p name) (values +koi8-r-hash+ +koi8-r-table+)) ((iso-8859-name-p name) (values (cdr (assoc name +iso-8859-hashes+ :test #'eq)) (cdr (assoc name +iso-8859-tables+ :test #'eq)))) ((code-page-name-p name) (values (cdr (assoc id +code-page-hashes+)) (cdr (assoc id +code-page-tables+)))))))) (defun external-format-class-name (real-name &key eol-style little-endian id) "Given the initargs for a general external format returns the name \(a symbol) of the most specific subclass matching these arguments." (declare #.*standard-optimize-settings*) (declare (ignore id)) (cond ((ascii-name-p real-name) (ecase eol-style (:lf 'flexi-ascii-format) (:cr 'flexi-cr-ascii-format) (:crlf 'flexi-crlf-ascii-format))) ((eq real-name :iso-8859-1) (ecase eol-style (:lf 'flexi-latin-1-format) (:cr 'flexi-cr-latin-1-format) (:crlf 'flexi-crlf-latin-1-format))) ((or (koi8-r-name-p real-name) (iso-8859-name-p real-name) (code-page-name-p real-name)) (ecase eol-style (:lf 'flexi-8-bit-format) (:cr 'flexi-cr-8-bit-format) (:crlf 'flexi-crlf-8-bit-format))) (t (ecase real-name (:utf-8 (ecase eol-style (:lf 'flexi-utf-8-format) (:cr 'flexi-cr-utf-8-format) (:crlf 'flexi-crlf-utf-8-format))) (:utf-16 (ecase eol-style (:lf (if little-endian 'flexi-utf-16-le-format 'flexi-utf-16-be-format)) (:cr (if little-endian 'flexi-cr-utf-16-le-format 'flexi-cr-utf-16-be-format)) (:crlf (if little-endian 'flexi-crlf-utf-16-le-format 'flexi-crlf-utf-16-be-format)))) (:utf-32 (ecase eol-style (:lf (if little-endian 'flexi-utf-32-le-format 'flexi-utf-32-be-format)) (:cr (if little-endian 'flexi-cr-utf-32-le-format 'flexi-cr-utf-32-be-format)) (:crlf (if little-endian 'flexi-crlf-utf-32-le-format 'flexi-crlf-utf-32-be-format)))))))) (defun make-external-format% (name &key (little-endian *default-little-endian*) id eol-style) "Used internally by MAKE-EXTERNAL-FORMAT to default some of the keywords arguments and to determine the right subclass of EXTERNAL-FORMAT." (declare #.*standard-optimize-settings*) (let* ((real-name (normalize-external-format-name name)) (initargs (cond ((or (iso-8859-name-p real-name) (koi8-r-name-p real-name) (ascii-name-p real-name)) (list :eol-style (or eol-style *default-eol-style*))) ((code-page-name-p real-name) (list :id (or (known-code-page-id-p id) (error 'external-format-error :format-control "Unknown code page ID ~S" :format-arguments (list id))) ;; default EOL style for Windows code pages is :CRLF :eol-style (or eol-style :crlf))) (t (list :eol-style (or eol-style *default-eol-style*) :little-endian little-endian))))) (apply #'make-instance (apply #'external-format-class-name real-name initargs) :name real-name initargs))) (defun make-external-format (name &rest args &key (little-endian *default-little-endian*) id eol-style) "Creates and returns an external format object as specified. NAME is a keyword like :LATIN1 or :UTF-8, LITTLE-ENDIAN specifies the `endianess' of the external format and is ignored for 8-bit encodings, EOL-STYLE is one of the keywords :CR, :LF, or :CRLF which denote the end-of-line character \(sequence), ID is the ID of a Windows code page \(and ignored for other encodings)." (declare #.*standard-optimize-settings*) ;; the keyword arguments are only there for arglist display in the IDE (declare (ignore id little-endian)) (let ((shortcut-args (cdr (assoc name +shortcut-map+)))) (cond (shortcut-args (apply #'make-external-format% (append shortcut-args `(:eol-style ,eol-style)))) (t (apply #'make-external-format% name args))))) (defun maybe-convert-external-format (external-format) "Given an external format designator \(a keyword, a list, or an EXTERNAL-FORMAT object) returns the corresponding EXTERNAL-FORMAT object." (declare #.*standard-optimize-settings*) (typecase external-format (symbol (make-external-format external-format)) (list (apply #'make-external-format external-format)) (otherwise external-format))) (defun external-format-equal (ef1 ef2) "Checks whether two EXTERNAL-FORMAT objects denote the same encoding." (declare #.*standard-optimize-settings*) (let* ((name1 (external-format-name ef1)) (code-page-name-p (code-page-name-p name1))) ;; they must habe the same canonical name (and (eq name1 (external-format-name ef2)) ;; if both are code pages the IDs must be the same (or (not code-page-name-p) (eql (external-format-id ef1) (external-format-id ef2))) ;; for non-8-bit encodings the endianess must be the same (or code-page-name-p (ascii-name-p name1) (koi8-r-name-p name1) (iso-8859-name-p name1) (eq name1 :utf-8) (eq (not (external-format-little-endian ef1)) (not (external-format-little-endian ef2)))) ;; the EOL style must also be the same (eq (external-format-eol-style ef1) (external-format-eol-style ef2))))) (defun normalize-external-format (external-format) "Returns a list which is a `normalized' representation of the external format EXTERNAL-FORMAT. Used internally by PRINT-OBJECT, for example. Basically, the result is an argument list that can be fed back to MAKE-EXTERNAL-FORMAT to create an equivalent object." (declare #.*standard-optimize-settings*) (let ((name (external-format-name external-format)) (eol-style (external-format-eol-style external-format))) (cond ((or (ascii-name-p name) (koi8-r-name-p name) (iso-8859-name-p name) (eq name :utf-8)) (list name :eol-style eol-style)) ((code-page-name-p name) (list name :id (external-format-id external-format) :eol-style eol-style)) (t (list name :eol-style eol-style :little-endian (external-format-little-endian external-format)))))) (defmethod print-object ((object external-format) stream) "How an EXTERNAL-FORMAT object is rendered. Uses NORMALIZE-EXTERNAL-FORMAT." (print-unreadable-object (object stream :type t :identity t) (prin1 (normalize-external-format object) stream)))
17,555
Common Lisp
.lisp
345
41.976812
103
0.652705
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d903d78a72dd7c18534a9ac3241d8f0d9678e3d440b00175dd76f5e14b188008
19,198
[ 80993 ]
19,199
input.lisp
Eggy115_Lisp/flexi-streams-1.0.7/input.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/input.lisp,v 1.78 2008/05/25 19:25:44 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) #-:lispworks (defmethod read-byte* ((flexi-input-stream flexi-input-stream)) "Reads one byte \(octet) from the underlying stream of FLEXI-OUTPUT-STREAM \(or from the internal stack if it's not empty)." (declare #.*standard-optimize-settings*) ;; we're using S instead of STREAM here because of an ;; issue with SBCL: ;; <http://article.gmane.org/gmane.lisp.steel-bank.general/1386> (with-accessors ((position flexi-stream-position) (bound flexi-stream-bound) (octet-stack flexi-stream-octet-stack) (s flexi-stream-stream)) flexi-input-stream (declare (integer position) (type (or null integer) bound)) (when (and bound (>= position bound)) (return-from read-byte* nil)) (incf position) (or (pop octet-stack) (read-byte s nil nil) (progn (decf position) nil)))) #+:lispworks (defmethod read-byte* ((flexi-input-stream flexi-input-stream)) "Reads one byte \(octet) from the underlying \(binary) stream of FLEXI-OUTPUT-STREAM \(or from the internal stack if it's not empty)." (declare #.*standard-optimize-settings*) (with-accessors ((position flexi-stream-position) (bound flexi-stream-bound) (octet-stack flexi-stream-octet-stack) (stream flexi-stream-stream)) flexi-input-stream (declare (integer position) (type (or null integer) bound)) (when (and bound (>= position bound)) (return-from read-byte* nil)) (incf position) (or (pop octet-stack) (read-byte stream nil nil) (progn (decf position) nil)))) #+:lispworks (defmethod read-byte* ((flexi-input-stream flexi-char-input-stream)) "Reads one byte \(octet) from the underlying stream of FLEXI-OUTPUT-STREAM \(or from the internal stack if it's not empty). Only used for LispWorks bivalent streams which aren't binary." (declare #.*standard-optimize-settings*) (with-accessors ((position flexi-stream-position) (bound flexi-stream-bound) (octet-stack flexi-stream-octet-stack) (stream flexi-stream-stream)) flexi-input-stream (declare (integer position) (type (or null integer) bound)) (when (and bound (>= position bound)) (return-from read-byte* nil)) (incf position) (or (pop octet-stack) ;; we use READ-SEQUENCE because READ-BYTE doesn't work with all ;; bivalent streams in LispWorks (let* ((buffer (make-array 1 :element-type 'octet)) (new-position (read-sequence buffer stream))) (cond ((zerop new-position) (decf position) nil) (t (aref buffer 0))))))) (defmethod stream-clear-input ((flexi-input-stream flexi-input-stream)) "Calls the corresponding method for the underlying input stream and also clears the value of the OCTET-STACK slot." (declare #.*standard-optimize-settings*) ;; note that we don't reset the POSITION slot (with-accessors ((octet-stack flexi-stream-octet-stack) (stream flexi-stream-stream)) flexi-input-stream (setq octet-stack nil) (clear-input stream))) (defmethod stream-listen ((flexi-input-stream flexi-input-stream)) "Calls the corresponding method for the underlying input stream but first checks if \(old) input is available in the OCTET-STACK slot." (declare #.*standard-optimize-settings*) (with-accessors ((position flexi-stream-position) (bound flexi-stream-bound) (octet-stack flexi-stream-octet-stack) (stream flexi-stream-stream)) flexi-input-stream (declare (integer position) (type (or null integer) bound)) (when (and bound (>= position bound)) (return-from stream-listen nil)) (or octet-stack (listen stream)))) (defmethod stream-read-byte ((stream flexi-input-stream)) "Reads one byte \(octet) from the underlying stream." (declare #.*standard-optimize-settings*) ;; set LAST-CHAR-CODE slot to NIL because we can't UNREAD-CHAR after ;; this operation (with-accessors ((last-char-code flexi-stream-last-char-code) (last-octet flexi-stream-last-octet)) stream (setq last-char-code nil) (let ((octet (read-byte* stream))) (setq last-octet octet) (or octet :eof)))) (defun unread-char% (char flexi-input-stream) "Used internally to put a character CHAR which was already read back on the stream. Uses the OCTET-STACK slot and decrements the POSITION slot accordingly." (declare #.*standard-optimize-settings*) (with-accessors ((position flexi-stream-position) (octet-stack flexi-stream-octet-stack) (external-format flexi-stream-external-format)) flexi-input-stream (let ((counter 0) octets-reversed) (declare (fixnum counter)) (flet ((writer (octet) (incf counter) (push octet octets-reversed))) (declare (dynamic-extent (function writer))) (char-to-octets external-format char #'writer) (decf position counter) (setq octet-stack (nreconc octets-reversed octet-stack)))))) (defmethod stream-read-char ((stream flexi-input-stream)) (declare #.*standard-optimize-settings*) ;; note that we do nothing for the :LF EOL style because we assume ;; that #\Newline is the same as #\Linefeed in all Lisps which will ;; use this library (with-accessors ((external-format flexi-stream-external-format) (last-octet flexi-stream-last-octet) (last-char-code flexi-stream-last-char-code)) stream ;; set LAST-OCTET slot to NIL because we can't UNREAD-BYTE after ;; this operation (setq last-octet nil) (flet ((reader () (read-byte* stream)) (unreader (char) (unread-char% char stream))) (declare (dynamic-extent (function reader) (function unreader))) (let* ((*current-unreader* #'unreader) (char-code (or (octets-to-char-code external-format #'reader) (return-from stream-read-char :eof)))) ;; remember this character and its char code for UNREAD-CHAR (setq last-char-code char-code) (or (code-char char-code) char-code))))) (defmethod stream-read-char-no-hang ((stream flexi-input-stream)) "Reads one character if the underlying stream has at least one octet available." (declare #.*standard-optimize-settings*) ;; note that this may block for non-8-bit encodings - I think ;; there's no easy way to handle this correctly (and (stream-listen stream) (stream-read-char stream))) (defmethod stream-read-sequence ((flexi-input-stream flexi-input-stream) sequence start end &key) "An optimized version which uses a buffer underneath. The function can deliver characters as well as octets and it decides what to do based on the element type of the sequence \(which takes precedence) and the element type of the stream. What you'll really get might also depend on your Lisp. Some of the implementations are more picky than others - see for example FLEXI-STREAMS-TEST::SEQUENCE-TEST." (declare #.*standard-optimize-settings*) (declare (fixnum start end)) (with-accessors ((octet-stack flexi-stream-octet-stack) (external-format flexi-stream-external-format) (last-octet flexi-stream-last-octet) (last-char-code flexi-stream-last-char-code) (element-type flexi-stream-element-type) (stream flexi-stream-stream)) flexi-input-stream (when (>= start end) (return-from stream-read-sequence start)) (when (or (subtypep (etypecase sequence (vector (array-element-type sequence)) (list t)) 'integer) (and (not (stringp sequence)) (type-equal element-type 'octet))) ;; if binary data is requested, just read from the underlying ;; stream directly and skip the rest (but flush octet stack ;; first) (let ((index start)) (declare (fixnum index)) (when octet-stack (replace sequence octet-stack :start1 start :end1 end) (let ((octets-flushed (min (length octet-stack) (- end start)))) (incf index octets-flushed) (setq octet-stack (nthcdr octets-flushed octet-stack)))) (setq index (read-sequence sequence stream :start index :end end)) (when (> index start) (setq last-char-code nil last-octet (elt sequence (1- index)))) (return-from stream-read-sequence index))) ;; otherwise hand over to the external format to do the work (read-sequence* external-format flexi-input-stream sequence start end))) (defmethod stream-unread-char ((stream flexi-input-stream) char) "Implements UNREAD-CHAR for streams of type FLEXI-INPUT-STREAM. Makes sure CHAR will only be unread if it was the last character read and if it was read with the same encoding that's currently being used by the stream." (declare #.*standard-optimize-settings*) (with-accessors ((last-char-code flexi-stream-last-char-code)) stream (unless last-char-code (error 'flexi-stream-error :format-control "No character to unread from this stream \(or external format has changed or last reading operation was binary).")) (unless (= (char-code char) last-char-code) (error 'flexi-stream-error :format-control "Last character read (~S) was different from ~S." :format-arguments (list (code-char last-char-code) char))) (unread-char% char stream) (setq last-char-code nil) nil)) (defmethod unread-byte (byte (flexi-input-stream flexi-input-stream)) "Similar to UNREAD-CHAR in that it `unreads' the last octet from STREAM. Note that you can only call UNREAD-BYTE after a corresponding READ-BYTE." (declare #.*standard-optimize-settings*) (with-accessors ((last-octet flexi-stream-last-octet) (octet-stack flexi-stream-octet-stack) (position flexi-stream-position)) flexi-input-stream (unless last-octet (error 'flexi-stream-error :format-control "No byte to unread from this stream \(or last reading operation read a character).")) (unless (= byte last-octet) (error 'flexi-stream-error :format-control "Last byte read was different from #x~X." :format-arguments (list byte))) (setq last-octet nil) (decf (the integer position)) (push byte octet-stack) nil)) (defmethod peek-byte ((flexi-input-stream flexi-input-stream) &optional peek-type (eof-error-p t) eof-value) "PEEK-BYTE is like PEEK-CHAR, i.e. it returns an octet from FLEXI-INPUT-STREAM without actually removing it. If PEEK-TYPE is NIL the next octet is returned, if PEEK-TYPE is T, the next octet which is not 0 is returned, if PEEK-TYPE is an octet, the next octet which equals PEEK-TYPE is returned. EOF-ERROR-P and EOF-VALUE are interpreted as usual." (declare #.*standard-optimize-settings*) (loop for octet = (read-byte flexi-input-stream eof-error-p eof-value) until (cond ((null peek-type)) ((eql octet eof-value)) ((eq peek-type t) (plusp octet)) (t (= octet peek-type))) finally (unless (eql octet eof-value) (unread-byte octet flexi-input-stream)) (return octet)))
13,585
Common Lisp
.lisp
275
40.861818
145
0.653101
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5e081c26e5dd03a3e18683a5f46cd3d49b8823dc6d1a6bc575b0cd764f7a418a
19,199
[ 357376, 365517 ]
19,200
code-pages.lisp
Eggy115_Lisp/flexi-streams-1.0.7/code-pages.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/code-pages.lisp,v 1.7 2008/05/18 21:32:15 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams) ;;; the following code was auto-generated with LWW (defconstant +code-page-tables+ `((437 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 199 252 233 226 228 224 229 231 234 235 232 239 238 236 196 197 201 230 198 244 246 242 251 249 255 214 220 162 163 165 8359 402 225 237 243 250 241 209 170 186 191 8976 172 189 188 161 171 187 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 945 223 915 960 931 963 181 964 934 920 937 948 8734 966 949 8745 8801 177 8805 8804 8992 8993 247 8776 176 8729 183 8730 8319 178 9632 160))) (720 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 233 226 132 224 134 231 234 235 232 239 238 141 142 143 144 1617 1618 244 164 1600 251 249 1569 1570 1571 1572 163 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 171 187 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 1590 1591 1592 1593 1594 1601 181 1602 1603 1604 1605 1606 1607 1608 1609 1610 8801 1611 1612 1613 1614 1615 1616 8776 176 8729 183 8730 8319 178 9632 160))) (737 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 931 932 933 934 935 936 937 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 963 962 964 965 966 967 968 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 969 940 941 942 970 943 972 973 971 974 902 904 905 906 908 910 911 177 8805 8804 938 939 247 8776 176 8729 183 8730 8319 178 9632 160))) (775 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 262 252 233 257 228 291 229 263 322 275 342 343 299 377 196 197 201 230 198 333 246 290 162 346 347 214 220 248 163 216 215 164 256 298 243 379 380 378 8221 166 169 174 172 189 188 321 171 187 9617 9618 9619 9474 9508 260 268 280 278 9571 9553 9559 9565 302 352 9488 9492 9524 9516 9500 9472 9532 370 362 9562 9556 9577 9574 9568 9552 9580 381 261 269 281 279 303 353 371 363 382 9496 9484 9608 9604 9612 9616 9600 211 223 332 323 245 213 181 324 310 311 315 316 326 274 325 8217 173 177 8220 190 182 167 247 8222 176 8729 183 185 179 178 9632 160))) (850 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 199 252 233 226 228 224 229 231 234 235 232 239 238 236 196 197 201 230 198 244 246 242 251 249 255 214 220 248 163 216 215 402 225 237 243 250 241 209 170 186 191 174 172 189 188 161 171 187 9617 9618 9619 9474 9508 193 194 192 169 9571 9553 9559 9565 162 165 9488 9492 9524 9516 9500 9472 9532 227 195 9562 9556 9577 9574 9568 9552 9580 164 240 208 202 203 200 305 205 206 207 9496 9484 9608 9604 166 204 9600 211 223 212 210 245 213 181 254 222 218 219 217 253 221 175 180 173 177 8215 190 182 167 247 184 176 168 183 185 179 178 9632 160))) (852 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 199 252 233 226 228 367 263 231 322 235 336 337 238 377 196 262 201 313 314 244 246 317 318 346 347 214 220 356 357 321 215 269 225 237 243 250 260 261 381 382 280 281 172 378 268 351 171 187 9617 9618 9619 9474 9508 193 194 282 350 9571 9553 9559 9565 379 380 9488 9492 9524 9516 9500 9472 9532 258 259 9562 9556 9577 9574 9568 9552 9580 164 273 272 270 203 271 327 205 206 283 9496 9484 9608 9604 354 366 9600 211 223 212 323 324 328 352 353 340 218 341 368 253 221 355 180 173 733 731 711 728 167 247 184 176 168 729 369 344 345 9632 160))) (855 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 1106 1026 1107 1027 1105 1025 1108 1028 1109 1029 1110 1030 1111 1031 1112 1032 1113 1033 1114 1034 1115 1035 1116 1036 1118 1038 1119 1039 1102 1070 1098 1066 1072 1040 1073 1041 1094 1062 1076 1044 1077 1045 1092 1060 1075 1043 171 187 9617 9618 9619 9474 9508 1093 1061 1080 1048 9571 9553 9559 9565 1081 1049 9488 9492 9524 9516 9500 9472 9532 1082 1050 9562 9556 9577 9574 9568 9552 9580 164 1083 1051 1084 1052 1085 1053 1086 1054 1087 9496 9484 9608 9604 1055 1103 9600 1071 1088 1056 1089 1057 1090 1058 1091 1059 1078 1046 1074 1042 1100 1068 8470 173 1099 1067 1079 1047 1096 1064 1101 1069 1097 1065 1095 1063 167 9632 160))) (857 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 199 252 233 226 228 224 229 231 234 235 232 239 238 305 196 197 201 230 198 244 246 242 251 249 304 214 220 248 163 216 350 351 225 237 243 250 241 209 286 287 191 174 172 189 188 161 171 187 9617 9618 9619 9474 9508 193 194 192 169 9571 9553 9559 9565 162 165 9488 9492 9524 9516 9500 9472 9532 227 195 9562 9556 9577 9574 9568 9552 9580 164 186 170 202 203 200 65533 205 206 207 9496 9484 9608 9604 166 204 9600 211 223 212 210 245 213 181 65533 215 218 219 217 236 255 175 180 173 177 65533 190 182 167 247 184 176 168 183 185 179 178 9632 160))) (860 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 199 252 233 226 227 224 193 231 234 202 232 205 212 236 195 194 201 192 200 244 245 242 218 249 204 213 220 162 163 217 8359 211 225 237 243 250 241 209 170 186 191 210 172 189 188 161 171 187 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 945 223 915 960 931 963 181 964 934 920 937 948 8734 966 949 8745 8801 177 8805 8804 8992 8993 247 8776 176 8729 183 8730 8319 178 9632 160))) (861 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 199 252 233 226 228 224 229 231 234 235 232 208 240 222 196 197 201 230 198 244 246 254 251 221 253 214 220 248 163 216 8359 402 225 237 243 250 193 205 211 218 191 8976 172 189 188 161 171 187 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 945 223 915 960 931 963 181 964 934 920 937 948 8734 966 949 8745 8801 177 8805 8804 8992 8993 247 8776 176 8729 183 8730 8319 178 9632 160))) (862 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 162 163 165 8359 402 225 237 243 250 241 209 170 186 191 8976 172 189 188 161 171 187 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 945 223 915 960 931 963 181 964 934 920 937 948 8734 966 949 8745 8801 177 8805 8804 8992 8993 247 8776 176 8729 183 8730 8319 178 9632 160))) (863 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 199 252 233 226 194 224 182 231 234 235 232 239 238 8215 192 167 201 200 202 244 203 207 251 249 164 212 220 162 163 217 219 402 166 180 243 250 168 184 179 175 206 8976 172 189 188 190 171 187 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 945 223 915 960 931 963 181 964 934 920 937 948 8734 966 949 8745 8801 177 8805 8804 8992 8993 247 8776 176 8729 183 8730 8319 178 9632 160))) (864 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 176 183 8729 8730 9618 9472 9474 9532 9508 9516 9500 9524 9488 9484 9492 9496 946 8734 966 177 189 188 8776 171 187 65271 65272 155 156 65275 65276 159 160 173 65154 163 164 65156 65533 65533 65166 65167 65173 65177 1548 65181 65185 65189 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 65233 1563 65201 65205 65209 1567 162 65152 65153 65155 65157 65226 65163 65165 65169 65171 65175 65179 65183 65187 65191 65193 65195 65197 65199 65203 65207 65211 65215 65217 65221 65227 65231 166 172 247 215 65225 1600 65235 65239 65243 65247 65251 65255 65259 65261 65263 65267 65213 65228 65230 65229 65249 65149 1617 65253 65257 65260 65264 65266 65232 65237 65269 65270 65245 65241 65265 9632 65533))) (865 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 199 252 233 226 228 224 229 231 234 235 232 239 238 236 196 197 201 230 198 244 246 242 251 249 255 214 220 248 163 216 8359 402 225 237 243 250 241 209 170 186 191 8976 172 189 188 161 171 164 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 945 223 915 960 931 963 181 964 934 920 937 948 8734 966 949 8745 8801 177 8805 8804 8992 8993 247 8776 176 8729 183 8730 8319 178 9632 160))) (866 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 9617 9618 9619 9474 9508 9569 9570 9558 9557 9571 9553 9559 9565 9564 9563 9488 9492 9524 9516 9500 9472 9532 9566 9567 9562 9556 9577 9574 9568 9552 9580 9575 9576 9572 9573 9561 9560 9554 9555 9579 9578 9496 9484 9608 9604 9612 9616 9600 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1025 1105 1028 1108 1031 1111 1038 1118 176 8729 183 8730 8470 164 9632 160))) (869 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 902 135 183 172 166 8216 8217 904 8213 905 906 938 908 147 148 910 939 169 911 178 179 940 163 941 942 943 970 912 972 973 913 914 915 916 917 918 919 189 920 921 171 187 9617 9618 9619 9474 9508 922 923 924 925 9571 9553 9559 9565 926 927 9488 9492 9524 9516 9500 9472 9532 928 929 9562 9556 9577 9574 9568 9552 9580 931 932 933 934 935 936 937 945 946 947 9496 9484 9608 9604 948 949 9600 950 951 952 953 954 955 956 957 958 959 960 961 963 962 964 900 173 177 965 966 967 167 968 901 176 168 969 971 944 974 9632 160))) (1250 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 8364 129 8218 131 8222 8230 8224 8225 136 8240 352 8249 346 356 381 377 144 8216 8217 8220 8221 8226 8211 8212 152 8482 353 8250 347 357 382 378 160 711 728 321 164 260 166 167 168 169 350 171 172 173 174 379 176 177 731 322 180 181 182 183 184 261 351 187 317 733 318 380 340 193 194 258 196 313 262 199 268 201 280 203 282 205 206 270 272 323 327 211 212 336 214 215 344 366 218 368 220 221 354 223 341 225 226 259 228 314 263 231 269 233 281 235 283 237 238 271 273 324 328 243 244 337 246 247 345 367 250 369 252 253 355 729))) (1251 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 1026 1027 8218 1107 8222 8230 8224 8225 8364 8240 1033 8249 1034 1036 1035 1039 1106 8216 8217 8220 8221 8226 8211 8212 152 8482 1113 8250 1114 1116 1115 1119 160 1038 1118 1032 164 1168 166 167 1025 169 1028 171 172 173 174 1031 176 177 1030 1110 1169 181 182 183 1105 8470 1108 187 1112 1029 1109 1111 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103))) (1252 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 8364 129 8218 402 8222 8230 8224 8225 710 8240 352 8249 338 141 381 143 144 8216 8217 8220 8221 8226 8211 8212 732 8482 353 8250 339 157 382 376 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255))) (1253 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 8364 129 8218 402 8222 8230 8224 8225 136 8240 138 8249 140 141 142 143 144 8216 8217 8220 8221 8226 8211 8212 152 8482 154 8250 156 157 158 159 160 901 902 163 164 165 166 167 168 169 65533 171 172 173 174 8213 176 177 178 179 900 181 182 183 904 905 906 187 908 189 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 65533 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 65533))) (1254 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 8364 129 8218 402 8222 8230 8224 8225 710 8240 352 8249 338 141 142 143 144 8216 8217 8220 8221 8226 8211 8212 732 8482 353 8250 339 157 158 376 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 286 209 210 211 212 213 214 215 216 217 218 219 220 304 350 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 287 241 242 243 244 245 246 247 248 249 250 251 252 305 351 255))) (1255 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 8364 129 8218 402 8222 8230 8224 8225 710 8240 138 8249 140 141 142 143 144 8216 8217 8220 8221 8226 8211 8212 732 8482 154 8250 156 157 158 159 160 161 162 163 8362 165 166 167 168 169 215 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 247 187 188 189 190 191 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1520 1521 1522 1523 1524 65533 65533 65533 65533 65533 65533 65533 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 65533 65533 8206 8207 65533))) (1256 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 8364 1662 8218 402 8222 8230 8224 8225 710 8240 1657 8249 338 1670 1688 1672 1711 8216 8217 8220 8221 8226 8211 8212 1705 8482 1681 8250 339 8204 8205 1722 160 1548 162 163 164 165 166 167 168 169 1726 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 1563 187 188 189 190 1567 1729 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 215 1591 1592 1593 1594 1600 1601 1602 1603 224 1604 226 1605 1606 1607 1608 231 232 233 234 235 1609 1610 238 239 1611 1612 1613 1614 244 1615 1616 247 1617 249 1618 251 252 8206 8207 1746))) (1257 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 8364 129 8218 131 8222 8230 8224 8225 136 8240 138 8249 140 168 711 184 144 8216 8217 8220 8221 8226 8211 8212 152 8482 154 8250 156 175 731 159 160 65533 162 163 164 65533 166 167 216 169 342 171 172 173 174 198 176 177 178 179 180 181 182 183 248 185 343 187 188 189 190 230 260 302 256 262 196 197 280 274 268 201 377 278 290 310 298 315 352 323 325 211 332 213 214 215 370 321 346 362 220 379 381 223 261 303 257 263 228 229 281 275 269 233 378 279 291 311 299 316 353 324 326 243 333 245 246 247 371 322 347 363 252 380 382 729))) (1258 . ,(make-decoding-table '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 8364 129 8218 402 8222 8230 8224 8225 710 8240 138 8249 338 141 142 143 144 8216 8217 8220 8221 8226 8211 8212 732 8482 154 8250 339 157 158 376 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 258 196 197 198 199 200 201 202 203 768 205 206 207 272 209 777 211 212 416 214 215 216 217 218 219 220 431 771 223 224 225 226 259 228 229 230 231 232 233 234 235 769 237 238 239 273 241 803 243 244 417 246 247 248 249 250 251 252 432 8363 255)))) "A list of 8-bit Windows code pages where each element is a cons with the car being the ID of the code page and the cdr being a vector enumerating the corresponding character codes.")
27,266
Common Lisp
.lisp
54
500.333333
1,135
0.730218
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
087101a130def815e88f981340ef0e688dbd2bb167b40445059a28b319647892
19,200
[ 243505 ]
19,201
packages.lisp
Eggy115_Lisp/flexi-streams-1.0.7/packages.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/packages.lisp,v 1.39 2008/05/30 07:50:31 edi Exp $ ;;; Copyright (c) 2005-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :cl-user) (unless (find-symbol (symbol-name :stream-file-position) :trivial-gray-streams) (error "You need a newer version of TRIVIAL-GRAY-STREAMS.")) (defpackage :flexi-streams (:use :cl :trivial-gray-streams) (:nicknames :flex) (:shadow #+:lispworks :with-accessors :defconstant) (:export :*default-eol-style* :*default-little-endian* :*substitution-char* :accept-overlong-sequence :char-length :external-format-condition :external-format-condition-external-format :external-format-eol-style :external-format-error :external-format-encoding-error :external-format-equal :external-format-id :external-format-little-endian :external-format-name :flexi-input-stream :flexi-output-stream :flexi-io-stream :flexi-stream :flexi-stream-bound :flexi-stream-column :flexi-stream-external-format :flexi-stream-element-type :flexi-stream-element-type-error :flexi-stream-element-type-error-element-type :flexi-stream-error :flexi-stream-out-of-sync-error :flexi-stream-position :flexi-stream-stream :get-output-stream-sequence :in-memory-stream :in-memory-stream-closed-error :in-memory-stream-error :in-memory-stream-position-spec-error :in-memory-stream-position-spec-error-position-spec :in-memory-input-stream :in-memory-output-stream :list-stream :make-external-format :make-in-memory-input-stream :make-in-memory-output-stream :make-flexi-stream :octet :octet-length :octets-to-string :output-stream-sequence-length :peek-byte :string-to-octets :unread-byte :vector-stream :with-input-from-sequence :with-output-to-sequence))
3,723
Common Lisp
.lisp
82
36.219512
96
0.645793
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1f5b9e1dd721433e78564626d9cb3078ffe2ca8f82dd6d2ddb15d05b3dba3a70
19,201
[ 320892, 496217 ]
19,202
packages.lisp
Eggy115_Lisp/flexi-streams-1.0.7/test/packages.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/test/packages.lisp,v 1.8 2008/08/01 10:12:43 edi Exp $ ;;; Copyright (c) 2006-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :cl-user) (defpackage :flexi-streams-test (:use :cl :flexi-streams) (:import-from :flexi-streams :with-unique-names :with-rebinding :char* :normalize-external-format) (:export :run-all-tests))
1,842
Common Lisp
.lisp
32
52.9375
100
0.711581
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6555298e05b6f4285828b8354b9dc3647653d5d7e1ccc49e641d2dd501579022
19,202
[ 433813 ]
19,203
test.lisp
Eggy115_Lisp/flexi-streams-1.0.7/test/test.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: FLEXI-STREAMS-TEST; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/flexi-streams/test/test.lisp,v 1.40 2008/07/25 09:56:12 edi Exp $ ;;; Copyright (c) 2006-2008, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :flexi-streams-test) (defmacro with-test-suite ((test-description &key show-progress-p) &body body) "Defines a test suite. Three utilities are available inside of the body of the macro: The function FAIL, and the macros CHECK and WITH-EXPECTED-ERROR. FAIL, the lowest level utility, marks the test defined by WITH-TEST-SUITE as failed. CHECK checks whether its argument is true, otherwise it calls FAIL. If during evaluation of the specified expression any condition is signalled, this is also considered a failure. WITH-EXPECTED-ERROR executes its body and considers the test a success if the specified error was signalled, otherwise it calls FAIL. WITH-TEST-SUITE prints a simple progress report if SHOW-PROGRESS-P is true." (with-unique-names (successp testcount) (with-rebinding (show-progress-p) `(let ((,successp t) (,testcount 1)) (when (and ,show-progress-p (not (numberp ,show-progress-p))) (setq ,show-progress-p 1)) (flet ((fail (format-str &rest format-args) (apply #'format t format-str format-args) (setq ,successp nil)) (maybe-show-progress () (when (and ,show-progress-p (zerop (mod ,testcount ,show-progress-p))) (format t ".") (when (zerop (mod ,testcount (* 10 ,show-progress-p))) (terpri)) (force-output)) (incf ,testcount))) (macrolet ((check (expression) `(progn (maybe-show-progress) (handler-case (unless ,expression (fail "~&Test ~S failed.~%" ',expression)) (error (c) (fail "~&Test ~S failed signalling error of type ~A: ~A.~%" ',expression (type-of c) c))))) (with-expected-error ((condition-type) &body body) `(progn (maybe-show-progress) (handler-case (progn ,@body) (,condition-type () t) (:no-error (&rest args) (declare (ignore args)) (fail "~&Expected condition ~S not signalled.~%" ',condition-type)))))) (format t "~&Test suite: ~S~%" ,test-description) ,@body)) ,successp)))) ;; LW can't indent this correctly because it's in a MACROLET #+:lispworks (editor:setup-indent "with-expected-error" 1 2 4) (defconstant +buffer-size+ 8192 "Size of buffers for COPY-STREAM* below.") (defvar *copy-function* nil "Which function to use when copying from one stream to the other - see for example COPY-FILE below.") (defvar *this-file* (load-time-value (or #.*compile-file-pathname* *load-pathname*)) "The pathname of the file \(`test.lisp') where this variable was defined.") #+:lispworks (defun get-env-variable-as-directory (name) (lw:when-let (string (lw:environment-variable name)) (when (plusp (length string)) (cond ((find (char string (1- (length string))) "\\/" :test #'char=) string) (t (lw:string-append string "/")))))) (defvar *tmp-dir* (load-time-value (merge-pathnames "odd-streams-test/" #+:allegro (system:temporary-directory) #+:lispworks (pathname (or (get-env-variable-as-directory "TEMP") (get-env-variable-as-directory "TMP") #+:win32 "C:/" #-:win32 "/tmp/")) #-(or :allegro :lispworks) #p"/tmp/")) "The pathname of a temporary directory used for testing.") (defvar *test-files* '(("kafka" (:utf8 :latin1 :cp1252)) ("tilton" (:utf8 :ascii)) ("hebrew" (:utf8 :latin8)) ("russian" (:utf8 :koi8r)) ("unicode_demo" (:utf8 :ucs2 :ucs4))) "A list of test files where each entry consists of the name prefix and a list of encodings.") (defun create-file-variants (file-name symbol) "For a name suffix FILE-NAME and a symbol SYMBOL denoting an encoding returns a list of pairs where the car is a full file name and the cdr is the corresponding external format. This list contains all possible variants w.r.t. to line-end conversion and endianness." (let ((args (ecase symbol (:ascii '(:ascii)) (:latin1 '(:latin-1)) (:latin8 '(:hebrew)) (:cp1252 '(:code-page :id 1252)) (:koi8r '(:koi8-r)) (:utf8 '(:utf-8)) (:ucs2 '(:utf-16)) (:ucs4 '(:utf-32)))) (endianp (member symbol '(:ucs2 :ucs4)))) (loop for little-endian in (if endianp '(t nil) '(t)) for endian-suffix in (if endianp '("_le" "_be") '("")) nconc (loop for eol-style in '(:lf :cr :crlf) collect (cons (format nil "~A_~(~A~)_~(~A~)~A.txt" file-name symbol eol-style endian-suffix) (apply #'make-external-format (append args `(:eol-style ,eol-style :little-endian ,little-endian)))))))) (defun create-test-combinations (file-name symbols &optional simplep) "For a name suffix FILE-NAME and a list of symbols SYMBOLS denoting different encodings of the corresponding file returns a list of lists which can be used as arglists by COMPARE-FILES. If SIMPLEP is true, a list which can be used for the string and sequence tests below is returned." (let ((file-variants (loop for symbol in symbols nconc (create-file-variants file-name symbol)))) (loop for (name-in . external-format-in) in file-variants when simplep collect (list name-in external-format-in) else nconc (loop for (name-out . external-format-out) in file-variants collect (list name-in external-format-in name-out external-format-out))))) (defun file-equal (file1 file2) "Returns a true value iff FILE1 and FILE2 have the same contents \(viewed as binary files)." (with-open-file (stream1 file1 :element-type 'octet) (with-open-file (stream2 file2 :element-type 'octet) (and (= (file-length stream1) (file-length stream2)) (loop for byte1 = (read-byte stream1 nil nil) for byte2 = (read-byte stream2 nil nil) while (and byte1 byte2) always (= byte1 byte2)))))) (defun copy-stream (stream-in external-format-in stream-out external-format-out) "Copies the contents of the binary stream STREAM-IN to the binary stream STREAM-OUT using flexi streams - STREAM-IN is read with the external format EXTERNAL-FORMAT-IN and STREAM-OUT is written with EXTERNAL-FORMAT-OUT." (let ((in (make-flexi-stream stream-in :external-format external-format-in)) (out (make-flexi-stream stream-out :external-format external-format-out))) (loop for line = (read-line in nil nil) while line do (write-line line out)))) (defun copy-stream* (stream-in external-format-in stream-out external-format-out) "Like COPY-STREAM, but uses READ-SEQUENCE and WRITE-SEQUENCE instead of READ-LINE and WRITE-LINE." (let ((in (make-flexi-stream stream-in :external-format external-format-in)) (out (make-flexi-stream stream-out :external-format external-format-out)) (buffer (make-array +buffer-size+ :element-type 'char*))) (loop (let ((position (read-sequence buffer in))) (when (zerop position) (return)) (write-sequence buffer out :end position))))) (defun copy-file (path-in external-format-in path-out external-format-out direction-out direction-in) "Copies the contents of the file denoted by the pathname PATH-IN to the file denoted by the pathname PATH-OUT using flexi streams - STREAM-IN is read with the external format EXTERNAL-FORMAT-IN and STREAM-OUT is written with EXTERNAL-FORMAT-OUT. The input file is opened with the :DIRECTION keyword argument DIRECTION-IN, the output file is opened with the :DIRECTION keyword argument DIRECTION-OUT." (with-open-file (in path-in :element-type 'octet :direction direction-in :if-does-not-exist :error :if-exists :overwrite) (with-open-file (out path-out :element-type 'octet :direction direction-out :if-does-not-exist :create :if-exists :supersede) (funcall *copy-function* in external-format-in out external-format-out)))) #+:lispworks (defun copy-file-lw (path-in external-format-in path-out external-format-out direction-out direction-in) "Same as COPY-FILE, but uses character streams instead of binary streams. Only used to test LispWorks-specific behaviour." (with-open-file (in path-in :external-format '(:latin-1 :eol-style :lf) :element-type 'base-char :direction direction-in :if-does-not-exist :error :if-exists :overwrite) (with-open-file (out path-out :external-format '(:latin-1 :eol-style :lf) :element-type 'base-char :direction direction-out :direction :output :if-does-not-exist :create :if-exists :supersede) (funcall *copy-function* in external-format-in out external-format-out)))) (defun compare-files (&key verbose) "Each test in this suite copies the contents of one file \(in the `test' directory) to another file \(in a temporary directory) using flexi streams with different external formats. The resulting file is compared with an existing file in the `test' directory to check if the outcome is as expected. Uses various variants of the :DIRECTION keyword when opening the files. Returns a true value iff all tests succeeded. Prints information about each individual comparison if VERBOSE is true." (with-test-suite ("Reading/writing files" :show-progress-p (not verbose)) (flet ((one-comparison (path-in external-format-in path-out external-format-out verbose) (when verbose (format t "~&File ~S, using copy function ~S" (file-namestring path-in) *copy-function*) (format t "~& and external formats ~S --> ~S" (normalize-external-format external-format-in) (normalize-external-format external-format-out))) (let ((full-path-in (merge-pathnames path-in *this-file*)) (full-path-out (ensure-directories-exist (merge-pathnames path-out *tmp-dir*))) (full-path-orig (merge-pathnames path-out *this-file*))) (dolist (direction-out '(:output :io)) (dolist (direction-in '(:input :io)) (when verbose (format t "~&...directions ~S --> ~S" direction-in direction-out)) (copy-file full-path-in external-format-in full-path-out external-format-out direction-out direction-in) (check (file-equal full-path-out full-path-orig)) #+:lispworks (progn (when verbose (format t "~&...directions ~S --> ~S \(LispWorks)" direction-in direction-out)) (copy-file-lw full-path-in external-format-in full-path-out external-format-out direction-out direction-in) (check (file-equal full-path-out full-path-orig)))))))) (loop with compare-files-args-list = (loop for (file-name symbols) in *test-files* nconc (create-test-combinations file-name symbols)) for *copy-function* in '(copy-stream copy-stream*) do (loop for (path-in external-format-in path-out external-format-out) in compare-files-args-list do (one-comparison path-in external-format-in path-out external-format-out verbose)))))) (defun file-as-octet-vector (pathspec) "Returns the contents of the file denoted by PATHSPEC as a vector of octets." (with-open-file (in pathspec :element-type 'octet) (let ((vector (make-array (file-length in) :element-type 'octet))) (read-sequence vector in) vector))) (defun file-as-string (pathspec external-format) "Reads the contents of the file denoted by PATHSPEC using the external format EXTERNAL-FORMAT and returns the result as a string." (with-open-file (in pathspec :element-type 'octet) (let* ((number-of-octets (file-length in)) (in (make-flexi-stream in :external-format external-format)) (string (make-array number-of-octets :element-type #+:lispworks 'lw:simple-char #-:lispworks 'character :fill-pointer t))) (setf (fill-pointer string) (read-sequence string in)) string))) (defun old-string-to-octets (string &key (external-format (make-external-format :latin1)) (start 0) end) "The old version of STRING-TO-OCTETS. We can use it to test in-memory streams." (declare (optimize speed)) (with-output-to-sequence (out) (let ((flexi (make-flexi-stream out :external-format external-format))) (write-string string flexi :start start :end end)))) (defun old-octets-to-string (vector &key (external-format (make-external-format :latin1)) (start 0) (end (length vector))) "The old version of OCTETS-TO-STRING. We can use it to test in-memory streams." (declare (optimize speed)) (with-input-from-sequence (in vector :start start :end end) (let ((flexi (make-flexi-stream in :external-format external-format)) (result (make-array (- end start) :element-type #+:lispworks 'lw:simple-char #-:lispworks 'character :fill-pointer t))) (setf (fill-pointer result) (read-sequence result flexi)) result))) (defun string-tests (&key verbose) "Tests whether conversion from strings to octets and vice versa works as expected. Also tests with the old versions of the conversion functions in order to test in-memory streams." (with-test-suite ("String tests" :show-progress-p (and (not verbose) 10)) (flet ((one-string-test (pathspec external-format verbose) (when verbose (format t "~&With external format ~S:" (normalize-external-format external-format))) (let* ((full-path (merge-pathnames pathspec *this-file*)) (octets-vector (file-as-octet-vector full-path)) (octets-list (coerce octets-vector 'list)) (string (file-as-string full-path external-format))) (when verbose (format t "~&...testing OCTETS-TO-STRING")) (check (string= (octets-to-string octets-vector :external-format external-format) string)) (check (string= (octets-to-string octets-list :external-format external-format) string)) (when verbose (format t "~&...testing STRING-TO-OCTETS")) (check (equalp (string-to-octets string :external-format external-format) octets-vector)) (when verbose (format t "~&...testing in-memory streams")) (check (string= (old-octets-to-string octets-vector :external-format external-format) string)) (check (string= (old-octets-to-string octets-list :external-format external-format) string)) (check (equalp (old-string-to-octets string :external-format external-format) octets-vector))))) (loop with simple-test-args-list = (loop for (file-name symbols) in *test-files* nconc (create-test-combinations file-name symbols t)) for (pathspec external-format) in simple-test-args-list do (one-string-test pathspec external-format verbose))))) (defun sequence-equal (seq1 seq2) "Whether the two sequences have the same elements." (and (= (length seq1) (length seq2)) (loop for i below (length seq1) always (eql (elt seq1 i) (elt seq2 i))))) (defun sequence-tests (&key verbose) "Several tests to confirm that READ-SEQUENCE and WRITE-SEQUENCE behave as expected." (with-test-suite ("Sequence tests" :show-progress-p (and (not verbose) 10)) (flet ((one-sequence-test (pathspec external-format verbose) (when verbose (format t "~&With external format ~S:" (normalize-external-format external-format))) (let* ((full-path (merge-pathnames pathspec *this-file*)) (file-string (file-as-string full-path external-format)) (string-length (length file-string)) (octets (file-as-octet-vector full-path)) (octet-length (length octets))) (when (external-format-equal external-format (make-external-format :utf8)) (when verbose (format t "~&...reading octets")) #-:openmcl ;; FLEXI-STREAMS puts integers into the list, but OpenMCL ;; thinks they are characters... (with-open-file (in full-path :element-type 'octet) (let* ((in (make-flexi-stream in :external-format external-format)) (list (make-list octet-length))) (setf (flexi-stream-element-type in) 'octet) #-:clisp (read-sequence list in) #+:clisp (ext:read-byte-sequence list in) (check (sequence-equal list octets)))) (with-open-file (in full-path :element-type 'octet) (let* ((in (make-flexi-stream in :external-format external-format)) (third (floor octet-length 3)) (half (floor octet-length 2)) (vector (make-array half :element-type 'octet))) (check (sequence-equal (loop repeat third collect (read-byte in)) (subseq octets 0 third))) (read-sequence vector in) (check (sequence-equal vector (subseq octets third (+ third half))))))) (when verbose (format t "~&...reading characters")) (with-open-file (in full-path :element-type 'octet) (let* ((in (make-flexi-stream in :external-format external-format)) (string (make-string (- string-length 10) :element-type 'char*))) (setf (flexi-stream-element-type in) 'octet) (check (sequence-equal (loop repeat 10 collect (read-char in)) (subseq file-string 0 10))) (read-sequence string in) (check (sequence-equal string (subseq file-string 10))))) (with-open-file (in full-path :element-type 'octet) (let* ((in (make-flexi-stream in :external-format external-format)) (list (make-list (- string-length 100)))) (check (sequence-equal (loop repeat 50 collect (read-char in)) (subseq file-string 0 50))) #-:clisp (read-sequence list in) #+:clisp (ext:read-char-sequence list in) (check (sequence-equal list (subseq file-string 50 (- string-length 50)))) (check (sequence-equal (loop repeat 50 collect (read-char in)) (subseq file-string (- string-length 50)))))) (with-open-file (in full-path :element-type 'octet) (let* ((in (make-flexi-stream in :external-format external-format)) (array (make-array (- string-length 50)))) (check (sequence-equal (loop repeat 25 collect (read-char in)) (subseq file-string 0 25))) #-:clisp (read-sequence array in) #+:clisp (ext:read-char-sequence array in) (check (sequence-equal array (subseq file-string 25 (- string-length 25)))) (check (sequence-equal (loop repeat 25 collect (read-char in)) (subseq file-string (- string-length 25)))))) (let ((path-out (ensure-directories-exist (merge-pathnames pathspec *tmp-dir*)))) (when verbose (format t "~&...writing sequences")) (with-open-file (out path-out :direction :output :if-exists :supersede :element-type 'octet) (let ((out (make-flexi-stream out :external-format external-format))) (write-sequence octets out))) (check (file-equal full-path path-out)) (with-open-file (out path-out :direction :output :if-exists :supersede :element-type 'octet) (let ((out (make-flexi-stream out :external-format external-format))) (write-sequence file-string out))) (check (file-equal full-path path-out)) (with-open-file (out path-out :direction :output :if-exists :supersede :element-type 'octet) (let ((out (make-flexi-stream out :external-format external-format))) (write-sequence file-string out :end 100) (write-sequence octets out :start (length (string-to-octets file-string :external-format external-format :end 100))))) (check (file-equal full-path path-out)))))) (loop with simple-test-args-list = (loop for (file-name symbols) in *test-files* nconc (create-test-combinations file-name symbols t)) for (pathspec external-format) in simple-test-args-list do (one-sequence-test pathspec external-format verbose))))) (defmacro using-values ((&rest values) &body body) "Executes BODY and feeds an element from VALUES to the USE-VALUE restart each time a EXTERNAL-FORMAT-ENCODING-ERROR is signalled. Signals an error when there are more or less EXTERNAL-FORMAT-ENCODING-ERRORs than there are elements in VALUES." (with-unique-names (value-stack condition-counter) `(let ((,value-stack ',values) (,condition-counter 0)) (handler-bind ((external-format-encoding-error #'(lambda (c) (declare (ignore c)) (unless ,value-stack (error "Too many encoding errors signalled, expected only ~A." ,(length values))) (incf ,condition-counter) (use-value (pop ,value-stack))))) (prog1 (progn ,@body) (when ,value-stack (error "~A encoding errors signalled, but ~A were expected." ,condition-counter ,(length values)))))))) (defun accept-overlong (octets code-point) "Converts the `overlong' UTF-8 sequence OCTETS to using OCTETS-TO-STRINGS, accepts the expected error with the corresponding restart and checks that the result is CODE-POINT." (handler-bind ((external-format-encoding-error (lambda (c) (declare (ignore c)) (invoke-restart 'accept-overlong-sequence)))) (string= (octets-to-string octets :external-format :utf-8) (string (code-char code-point))))) (defun read-flexi-line (sequence external-format) "Creates and returns a string from the octet sequence SEQUENCE using the external format EXTERNAL-FORMAT." (with-input-from-sequence (in sequence) (setq in (make-flexi-stream in :external-format external-format)) (read-line in))) (defun read-flexi-line* (sequence external-format) "Like READ-FLEXI-LINE but uses OCTETS-TO-STRING internally." (octets-to-string sequence :external-format external-format)) (defun error-handling-tests (&key verbose) "Tests several possible errors and how they are handled." (with-test-suite ("Testing error handling" :show-progress-p (not verbose)) (macrolet ((want-encoding-error (input format) `(with-expected-error (external-format-encoding-error) (read-flexi-line* ,input ,format)))) (when verbose (format t "~&\"Overlong\" UTF-8 sequences")) (want-encoding-error #(#b11000000 #b10000000) :utf-8) (want-encoding-error #(#b11000001 #b10000000) :utf-8) (want-encoding-error #(#b11100000 #b10011111 #b10000000) :utf-8) (want-encoding-error #(#b11110000 #b10001111 #b10000000 #b10000000) :utf-8) (check (accept-overlong #(#b11000000 #b10000000) #b00000000)) (check (accept-overlong #(#b11000001 #b10000000) #b01000000)) (check (accept-overlong #(#b11100000 #b10011111 #b10000000) #b011111000000)) (check (accept-overlong #(#b11110000 #b10001111 #b10000000 #b10000000) #b1111000000000000)) (when verbose (format t "~&Invalid lead octets in UTF-8")) (want-encoding-error #(#b11111000) :utf-8) (want-encoding-error #(#b11111001) :utf-8) (want-encoding-error #(#b11111100) :utf-8) (want-encoding-error #(#b11111101) :utf-8) (want-encoding-error #(#b11111110) :utf-8) (want-encoding-error #(#b11111111) :utf-8) (when verbose (format t "~&Illegal code points")) (want-encoding-error #(#x00 #x00 #x11 #x00) :utf-32le) (want-encoding-error #(#x00 #xd8) :utf-16le) (want-encoding-error #(#xff #xdf) :utf-16le)) (macrolet ((want-encoding-error (input format) `(with-expected-error (external-format-encoding-error) (read-flexi-line* ,input ,format)))) (when verbose (format t "~&UTF-8 sequences which are too short")) (want-encoding-error #(#xe4 #xf6 #xfc) :utf8) (want-encoding-error #(#xc0) :utf8) (want-encoding-error #(#xe0 #xff) :utf8) (want-encoding-error #(#xf0 #xff #xff) :utf8) (when verbose (format t "~&UTF-16 sequences with an odd number of octets")) (want-encoding-error #(#x01) :utf-16le) (want-encoding-error #(#x01 #x01 #x01) :utf-16le) (want-encoding-error #(#x01) :utf-16be) (want-encoding-error #(#x01 #x01 #x01) :utf-16be) (when verbose (format t "~&Missing words in UTF-16")) (want-encoding-error #(#x01 #xd8) :utf-16le) (want-encoding-error #(#xd8 #x01) :utf-16be) (when verbose (format t "~&Missing octets in UTF-32")) (want-encoding-error #(#x01) :utf-32le) (want-encoding-error #(#x01 #x01) :utf-32le) (want-encoding-error #(#x01 #x01 #x01) :utf-32le) (want-encoding-error #(#x01 #x01 #x01 #x01 #x01) :utf-32le) (want-encoding-error #(#x01) :utf-32be) (want-encoding-error #(#x01 #x01) :utf-32be) (want-encoding-error #(#x01 #x01 #x01) :utf-32be) (want-encoding-error #(#x01 #x01 #x01 #x01 #x01) :utf-32be)) (when verbose (format t "~&Handling of EOF in the middle of CRLF")) (check (string= #.(string #\Return) (read-flexi-line `(,(char-code #\Return)) '(:ascii :eol-style :crlf)))) (let ((*substitution-char* #\?)) (when verbose (format t "~&Fixed substitution character #\?") (format t "~&:ASCII doesn't have characters with char codes > 127")) (check (string= "a??" (read-flexi-line `(,(char-code #\a) 128 200) :ascii))) (check (string= "a??" (read-flexi-line* `#(,(char-code #\a) 128 200) :ascii))) (when verbose (format t "~&:WINDOWS-1253 doesn't have a characters with codes 170 and 210")) (check (string= "a??" (read-flexi-line `(,(char-code #\a) 170 210) :windows-1253))) (check (string= "a??" (read-flexi-line* `#(,(char-code #\a) 170 210) :windows-1253))) (when verbose (format t "~&Not a valid UTF-8 sequence")) (check (string= "??" (read-flexi-line '(#xe4 #xf6 #xfc) :utf8)))) (let ((*substitution-char* nil)) (when verbose (format t "~&Variable substitution using USE-VALUE restart") (format t "~&:ASCII doesn't have characters with char codes > 127")) (check (string= "abc" (using-values (#\b #\c) (read-flexi-line `(,(char-code #\a) 128 200) :ascii)))) (check (string= "abc" (using-values (#\b #\c) (read-flexi-line* `#(,(char-code #\a) 128 200) :ascii)))) (when verbose (format t "~&:WINDOWS-1253 doesn't have a characters with codes 170 and 210")) (check (string= "axy" (using-values (#\x #\y) (read-flexi-line `(,(char-code #\a) 170 210) :windows-1253)))) (check (string= "axy" (using-values (#\x #\y) (read-flexi-line* `#(,(char-code #\a) 170 210) :windows-1253)))) (when verbose (format t "~&Not a valid UTF-8 sequence")) (check (string= "QW" (using-values (#\Q #\W) (read-flexi-line '(#xe4 #xf6 #xfc) :utf8)))) (when verbose (format t "~&UTF-8 can't start neither with #b11111110 nor with #b11111111")) (check (string= "QW" (using-values (#\Q #\W) (read-flexi-line '(#b11111110 #b11111111) :utf8)))) (when verbose (format t "~&Only one octet in UTF-16 sequence")) (check (string= "E" (using-values (#\E) (read-flexi-line '(#x01) :utf-16le)))) (when verbose (format t "~&Two octets in UTF-16, but value of resulting word suggests that another word follows")) (check (string= "R" (using-values (#\R) (read-flexi-line '(#x01 #xd8) :utf-16le)))) (when verbose (format t "~&The second word must fit into the [#xdc00; #xdfff] interval, but it is #xdbff")) (check (string= "T" (using-values (#\T) (read-flexi-line '(#x01 #xd8 #xff #xdb) :utf-16le)))) (check (string= "T" (using-values (#\T) (read-flexi-line* #(#x01 #xd8 #xff #xdb) :utf-16le)))) (when verbose (format t "~&The same as for little endian above, but using inverse order of bytes in words")) (check (string= "E" (using-values (#\E) (read-flexi-line '(#x01) :utf-16be)))) (check (string= "R" (using-values (#\R) (read-flexi-line '(#xd8 #x01) :utf-16be)))) (check (string= "T" (using-values (#\T) (read-flexi-line '(#xd8 #x01 #xdb #xff) :utf-16be)))) (check (string= "T" (using-values (#\T) (read-flexi-line* #(#xd8 #x01 #xdb #xff) :utf-16be)))) (when verbose (format t "~&EOF in the middle of a 4-octet sequence in UTF-32")) (check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01) :utf-32le)))) (check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01) :utf-32le)))) (check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01 #x01) :utf-32le)))) (check (string= "aY" (using-values (#\Y) (read-flexi-line `(,(char-code #\a) #x00 #x00 #x00 #x01) :utf-32le)))) (check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01) :utf-32be)))) (check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01) :utf-32be)))) (check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01 #x01) :utf-32be)))) (check (string= "aY" (using-values (#\Y) (read-flexi-line `(#x00 #x00 #x00 ,(char-code #\a) #x01) :utf-32be))))))) (defun unread-char-tests (&key verbose) "Tests whether UNREAD-CHAR behaves as expected." (with-test-suite ("UNREAD-CHAR behaviour." :show-progress-p (and (not verbose) 100)) (flet ((test-one-file (file-name external-format) (when verbose (format t "~& ...and external format ~A" (normalize-external-format external-format))) (with-open-file (in (merge-pathnames file-name *this-file*) :element-type 'flex:octet) (let ((in (make-flexi-stream in :external-format external-format))) (loop repeat 300 for char = (read-char in) do (unread-char char in) (check (char= (read-char in) char))))))) (loop for (file-name symbols) in *test-files* when verbose do (format t "~&With file ~S" file-name) do (loop for symbol in symbols do (loop for (file-name . external-format) in (create-file-variants file-name symbol) do (test-one-file file-name external-format))))))) (defun run-all-tests (&key verbose) "Runs all tests for FLEXI-STREAMS and returns a true value iff all tests succeeded. VERBOSE is interpreted by the individual test suites above." (let ((successp t)) (macrolet ((run-test-suite (&body body) `(unless (progn ,@body) (setq successp nil)))) (run-test-suite (compare-files :verbose verbose)) (run-test-suite (string-tests :verbose verbose)) (run-test-suite (sequence-tests :verbose verbose)) (run-test-suite (error-handling-tests :verbose verbose)) (run-test-suite (unread-char-tests :verbose verbose)) (format t "~2&~:[Some tests failed~;All tests passed~]." successp) successp)))
37,621
Common Lisp
.lisp
635
44.437795
112
0.565511
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
433d565dbb89c9097f066896f55e1fe0a8a06d35f8ce6a5938c9e79e140be2cf
19,203
[ 383033 ]
19,204
HTMLstream.lisp
Eggy115_Lisp/loving_snippets/HTMLstream.lisp
;; Copyright Mark Watson 2001-2013. All Rights Reserved. ;; License: AGPL version 3 (http://www.gnu.org/licenses/agpl-3.0.txt) ;; Alternative license: you may also use this software under the Apache 2 License. ;; This copyright notice should not be removed from this file and in files derived from this file. (defclass HTMLstream () ((out :accessor out)) (:documentation "Provide HTML generation services")) (defmethod set-header ((ho HTMLstream) title) (with-accessors ((out out)) ho (setf out (make-string-output-stream)) (princ "<HTML><head><title>" out) (princ title out) (princ "</title></head><BODY>" out) (terpri out))) (defmethod add-H1 ((ho HTMLstream) some-text) (with-accessors ((out out)) ho (princ "<H1>" out) (princ some-text out) (princ "</H1>" out) (terpri out))) (defmethod add-H2 ((ho HTMLstream) some-text) (with-accessors ((out out)) ho (princ "<H2>" out) (princ some-text out) (princ "</H2>" out) (terpri out))) (defmethod add-H3 ((ho HTMLstream) some-text) (with-accessors ((out out)) ho (princ "<H3>" out) (princ some-text out) (princ "</H3>" out) (terpri out))) (defmethod add-H4 ((ho HTMLstream) some-text) (with-accessors ((out out)) ho (princ "<H4>" out) (princ some-text out) (princ "</H4>" out) (terpri out))) (defmethod add-element ((ho HTMLstream) element) (with-accessors ((out out)) ho (princ element out) (terpri out))) (defmethod add-table ((ho HTMLstream) table-data) (with-accessors ((out out)) ho (princ "<TABLE BORDER=\"1\" WIDTH=\"100%\">" out) (dolist (d table-data) (terpri out) (princ " <TR>" out) (terpri out) (dolist (w d) (princ " <TD>" out) (let ((str (princ-to-string w))) (setq str (string-left-trim '(#\() str)) (setq str (string-right-trim '(#\)) str)) (princ str out)) (princ "</TD>" out) (terpri out)) (princ " </TR>" out) (terpri out)) (princ "</TABLE>" out) (terpri out))) (defmethod get-html-string ((ho HTMLstream)) (with-accessors ((out out)) ho (princ "</BODY></HTML>" out) (terpri out) (get-output-stream-string out))) (defun test (&aux x) (setq x (make-instance 'HTMLstream)) (set-header x "test page") (add-element x "test text - this could be any element") (add-table x '(("<b>Key phrase</b>" "<b>Ranking value</b>") ("this is a test" 3.3))) (get-html-string x)) (princ "There is 1 test function for the HTMLstream CLOS class. Try:") (terpri) (princ "(test)") (terpri)
2,746
Common Lisp
.lisp
95
23.6
99
0.600766
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
907edb37f99b0e0c8e201d184ffbe5bffbd30bf643a203b99f74df2d3baee9ae
19,204
[ -1 ]
19,205
lambda1.lisp
Eggy115_Lisp/loving_snippets/lambda1.lisp
(defun test1 () (let ((my-func (lambda (x) (+ x 1)))) (funcall my-func 1)))
90
Common Lisp
.lisp
4
18
26
0.5
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
58ef1060e80240c4fd2c0023d7e84c889452d8cd7fd49a078e888d83aac24a01
19,205
[ -1 ]
19,206
astar_search.lisp
Eggy115_Lisp/loving_snippets/astar_search.lisp
;; Perform a heuristic A* search between the start and goal nodes: ;; ;; Copyright 1990, 2017 by Mark Watson (defun A*search (nodes paths start goal &aux possible-paths best) (defun Y-coord (x) (truncate (cadr x))) (defun X-coord (x) (truncate (car x))) (defun dist-between-points (point1 point2) (let ((x-dif (- (X-coord point2) (X-coord point1))) (y-dif (- (Y-coord point2) (Y-coord point1)))) (sqrt (+ (* x-dif x-dif) (* y-dif y-dif))))) (setq possible-paths (list (list (dist-between-points (eval start) (eval goal)) 0 (list start)))) (defun init-network () (setq paths (init-lengths paths)) (init-path-list nodes paths)) (defun init-lengths (pathlist) (let (new-path-list pathlength path-with-length) (dolist (path pathlist) (setq pathlength (slow-path-length path)) (setq path-with-length (append path (list pathlength))) (setq new-path-list (cons path-with-length new-path-list))) new-path-list)) (defun init-path-list (nodes paths) (dolist (node nodes) (setf (get node 'path-list) ;; let returns all paths connected to node: (let (path-list) (dolist (path paths) (if (equal node (start-node-name path)) (setq path-list (cons (list (end-node-name path) (path-length path)) path-list)) (if (equal node (end-node-name path)) (setq path-list (cons (list (start-node-name path) (path-length path)) path-list))))) path-list )))) (defun slow-path-length (path) (dist-between-points (start-node path) (end-node path))) (defun path-length (x) (caddr x)) (defun start-node (path) (eval (car path))) (defun end-node (path) (eval (cadr path))) (defun start-node-name (x) (car x)) (defun end-node-name (x) (cadr x)) (defun first-on-path (x) (caddr x)) (defun goal-node (x) (car x)) (defun distance-to-that-node (x) (cadr x)) (defun enumerate-children (node goal) (let* ( (start-to-lead-node-dist (cadr node)) ;; distance already calculated (path (caddr node)) (lead-node (car path))) (if (get-stored-path lead-node goal) (consider-best-path lead-node goal path start-to-lead-node-dist) (consider-all-nodes lead-node goal path start-to-lead-node-dist)))) (defun consider-best-path (lead-node goal path distance-to-here) (let* ( (first-node (get-first-node-in-path lead-node goal)) (dist-to-first (+ distance-to-here (get-stored-dist lead-node first-node))) (total-estimate (+ distance-to-here (get-stored-dist lead-node goal))) (new-path (cons first-node path))) (list (list total-estimate dist-to-first new-path)))) (defun get-stored-path (start goal) (if (equal start goal) (list start 0) (assoc goal (get start 'path-list)))) (defun node-not-in-path (node path) (if (null path) t (if (equal node (car path)) nil (node-not-in-path node (cdr path))))) (defun consider-all-nodes (lead-node goal path start-to-lead-node-dist) (let (dist-to-first total-estimate new-path new-nodes) (dolist (node (collect-linked-nodes lead-node)) (if (node-not-in-path node path) (let () (setq dist-to-first (+ start-to-lead-node-dist (get-stored-dist lead-node node))) (setq total-estimate (+ dist-to-first (dist-between-points (eval node) (eval goal)))) (setq new-path (cons node path)) (setq new-nodes (cons (list total-estimate dist-to-first new-path) new-nodes))))) new-nodes)) (defun collect-linked-nodes (node) (let (links) (dolist (link (get node 'path-list)) (if (null (first-on-path link)) (setq links (cons (goal-node link) links)))) links)) (defun get-stored-dist (node1 node2) (distance-to-that-node (get-stored-path node1 node2))) (defun collect-ascending-search-list-order (a l) (if (null l) (list a) (if (< (car a) (caar l)) (cons a l) (cons (car l) (Collect-ascending-search-list-order a (cdr l)))))) (defun get-first-node-in-path (start goal) (let (first-node) (setq first-node (first-on-path (get-stored-path start goal))) (if first-node first-node goal))) (defun a*-helper () (if possible-paths (let () (setq best (car possible-paths)) (setq possible-paths (cdr possible-paths)) (if (equal (first (caddr best)) goal) best (let () (dolist (child (enumerate-children best goal)) (setq possible-paths (collect-ascending-search-list-order child possible-paths))) (a*-helper)))))) (init-network) (reverse (caddr (a*-helper)))) ;; test code: (defun test () (defvar n1 '(30 201)) (defvar n2 '(25 140)) (defvar n3 '(55 30)) (defvar n4 '(105 190)) (defvar n5 '(95 110)) (defvar n6 '(140 22)) (defvar n7 '(160 150)) (defvar n8 '(170 202)) (defvar n9 '(189 130)) (defvar n10 '(200 55)) (defvar n11 '(205 201)) (print (A*search '(n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11) ;; nodes '((n1 n2) (n2 n3) (n3 n5) (n3 n6) (n6 n10) ;; paths (n9 n10) (n7 n9) (n1 n4) (n4 n2) (n5 n8) (n8 n4) (n7 n11)) 'n1 'n11))) ;; starting and goal nodes
6,244
Common Lisp
.lisp
151
29.635762
80
0.526046
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
25ebca83760dbe1171e4bdc8250cd99244e4fda6b85cdd482e16799faac46063
19,206
[ -1 ]
19,207
macro1.lisp
Eggy115_Lisp/loving_snippets/macro1.lisp
;; first simple macro example: (defmacro double-list (a-list) (let ((ret (gensym))) `(let ((,ret nil)) (dolist (x ,a-list) (setq ,ret (append ,ret (list x x)))) ,ret))) ;; use the macro: (defun test (x) (double-list x))
269
Common Lisp
.lisp
10
21
47
0.541833
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
bcc011edffde8bb1b58f9e32cce7bd744bcaa2df310864dbf59800e07066ae74
19,207
[ -1 ]
19,208
Hopfield_neural_network.lisp
Eggy115_Lisp/loving_snippets/Hopfield_neural_network.lisp
;; Common LISP Hopfield Network for associative memory recall. ;; Copyright 1989, 2017 by Mark Watson ;; Note: for more detailed comments and explanations of the code, please see ;; the book [Loving Common Lisp, or the Savvy Programmer's Secret Weapon](https://leanpub.com/lovinglisp) ;; that can be read free online and is released under a Creative Commons License (ql:quickload "plotlib") (defpackage #:hopfield (:use #:cl #:plotlib)) ;; TBD: define exports (in-package #:hopfield) (proclaim '(special *num-inputs* *num-training-examples* *training-list* *inputCells* *tempStorage* *HopfieldWeights*)) (defun Hopfield-Init (training-data &aux temp *num-inputs* *num-training-examples* *training-list* *inputCells* *tempStorage* *HopfieldWeights*) (setq *num-inputs* (length (car training-data))) (setq *num-training-examples* (length training-data)) (setq *training-list* (make-array (list *num-training-examples* *num-inputs*))) (setq *inputCells* (make-array (list *num-inputs*))) (setq *tempStorage* (make-array (list *num-inputs*))) (setq *HopfieldWeights* (make-array (list *num-inputs* *num-inputs*))) (dotimes (j *num-training-examples*) ;; copy training data (dotimes (i *num-inputs*) (setf (aref *training-list* j i) (nth i (nth j training-data))))) (defun adjustInput (value) ;; this function is lexically scoped (if (< value 0.1) -1.0 +1.0)) (dotimes (i *num-inputs*) ;; adjust training data (dotimes (n *num-training-examples*) (setf (aref *training-list* n i) (adjustInput (aref *training-list* n i))))) (dotimes (i *num-inputs*) ;; zero weights (dotimes (j *num-inputs*) (setf (aref *HopfieldWeights* i j) 0))) (dotimes (j-1 (- *num-inputs* 1)) ;; autocorrelation weight matrix (let ((j (+ j-1 1))) (dotimes (i j) (dotimes (s *num-training-examples*) (setq temp (truncate (+ (* ;; 2 if's truncate values to -1 or 1: (adjustInput (aref *training-list* s i)) (adjustInput (aref *training-list* s j))) (aref *HopfieldWeights* i j)))) (setf (aref *HopfieldWeights* i j) temp) (setf (aref *HopfieldWeights* j i) temp))))) (dotimes (i *num-inputs*) (setf (aref *tempStorage* i) 0) (dotimes (j i) (setf (aref *tempStorage* i) (+ (aref *tempStorage* i) (aref *HopfieldWeights* i j))))) (list ;; return the value of the Hopfield network data object *num-inputs* *num-training-examples* *training-list* *inputCells* *tempStorage* *HopfieldWeights*)) ;; ; Iterate the network to let it settle in a stable pattern ; which will (we hope) be the original training pattern ; most closely resembling the noisy test pattern: ;; (defun HopfieldNetRecall (aHopfieldNetwork numberOfIterations) (let ((*num-inputs* (nth 0 aHopfieldNetwork)) (*num-training-examples* (nth 1 aHopfieldNetwork)) (*training-list* (nth 2 aHopfieldNetwork)) (*inputCells* (nth 3 aHopfieldNetwork)) (*tempStorage* (nth 4 aHopfieldNetwork)) (*HopfieldWeights* (nth 5 aHopfieldNetwork))) (defun deltaEnergy (row-index y &aux (temp 0.0)) ;; this function is lexically scoped (dotimes (j *num-inputs*) (setq temp (+ temp (* (aref *HopfieldWeights* row-index j) (aref y j))))) (- (* 2.0 temp) (aref *tempStorage* row-index))) (dotimes (ii numberOfIterations) ;; main code (dotimes (i *num-inputs*) (setf (aref *inputCells* i) (if (> (deltaEnergy i *inputCells*) 0) 1 0)))))) (defvar plot-size 8) (defvar plot-size+1 (+ plot-size 1)) (defun test (&aux aHopfieldNetwork) (let ((tdata '( ;; sample sine wave data with different periods: (1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 1 1 0 0 0) (0 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 1 0) (0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 1 1 0 1 1))) (width 300) (height 180)) (vecto::with-canvas (:width width :height height) (plotlib:plot-string-bold 10 (- height 14) "Hopfield pattern classifier") ;; Set up network: (print tdata) (setq aHopfieldNetwork (Hopfield-Init tdata)) ;; lexically scoped variables are accesible by inner functions: (let ((*num-inputs* (nth 0 aHopfieldNetwork)) (*num-training-examples* (nth 1 aHopfieldNetwork)) (*training-list* (nth 2 aHopfieldNetwork)) (*inputCells* (nth 3 aHopfieldNetwork)) (*tempStorage* (nth 4 aHopfieldNetwork)) (*HopfieldWeights* (nth 5 aHopfieldNetwork))) (defun plotExemplar (row &aux (dmin 0.0) (dmax 1.0) (x 20) (y 40)) (let ((YSize (array-dimension *training-list* 1))) (plotlib:plot-string (+ x 20) (- height (- y 10)) "Original Training Exemplar") (dotimes (j Ysize) (plotlib:plot-fill-rect (+ x (* j plot-size+1)) (- height y) plot-size plot-size (truncate (* (/ (- (aref *training-list* row j) dmin) (- dmax dmin)) 5))) (plotlib:plot-frame-rect (+ x (* j plot-size+1)) (- height y) plot-size plot-size)))) (defun plot-original-inputCells (&aux (dmin 0.0) (dmax 1.0) (x 20) (y 80)) (let ((Xsize (array-dimension *inputCells* 0))) (plotlib:plot-string (+ x 20) (- height (- y 10)) "Scrambled Inputs") (dotimes (j Xsize) (plotlib:plot-fill-rect (+ x (* j plot-size+1)) (- height y) plot-size plot-size (truncate (* (/ (- (aref *inputCells* j) dmin) (- dmax dmin)) 5))) (plotlib:plot-frame-rect (+ x (* j plot-size+1)) (- height y) plot-size plot-size)))) (defun plot-inputCells (&aux (dmin 0.0) (dmax 1.0) (x 20) (y 120)) (let ((Xsize (array-dimension *inputCells* 0))) (plotlib:plot-string (+ x 20) (- height (- y 10)) "Reconstructed Inputs") (dotimes (j Xsize) (plotlib:plot-fill-rect (+ x (* j plot-size+1)) (- height y) plot-size plot-size (truncate (* (/ (- (aref *inputCells* j) dmin) (- dmax dmin)) 5))) (plotlib:plot-frame-rect (+ x (* j plot-size+1)) (- height y) plot-size plot-size)))) (defun modifyInput (arrSize arr) ;; modify input array for testing (dotimes (i arrSize) (if (< (random 50) 5) (if (> (aref arr i) 0) (setf (aref arr i) -1) (setf (aref arr i) 1))))) ;; Test network on training data that is randomly modified: (dotimes (iter 10) ;; cycle 10 times and make 10 plots (dotimes (s *num-training-examples*) (dotimes (i *num-inputs*) (setf (aref *inputCells* i) (aref *training-list* s i))) (plotExemplar s) (modifyInput *num-inputs* *inputCells*) (plot-original-inputCells) (dotimes (call-net 5) ;; iterate Hopfield net 5 times (HopfieldNetRecall aHopfieldNetwork 1) ;; calling with 1 iteration (plot-inputCells))) (vecto::save-png (concatenate 'string "output_plot_hopfield_nn_" (format nil "~5,'0d" iter) ".png"))))))) (princ "There is 1 test function for the Hopfield neural network model. Try:") (terpri) (princ "(in-package #:hopfield)") (terpri) (princ "(test)") (terpri)
7,976
Common Lisp
.lisp
152
41.059211
106
0.567613
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
50007417e6305c884837522643a78c4f49d84d2063135e0e91bf48fe97d4501a
19,208
[ -1 ]
19,209
backprop_neural_network.lisp
Eggy115_Lisp/loving_snippets/backprop_neural_network.lisp
;; File DeltaRule.Lisp ;; Copyright 1990, 2017 by Mark Watson ;; Note: for more detailed comments and explanations of the code, please see ;; the book [Loving Common Lisp, or the Savvy Programmer's Secret Weapon](https://leanpub.com/lovinglisp) ;; that can be read free online and is released under a Creative Commons License ;;;;;;;;;;;;; Externally (callable) functions in this file: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; (NewDeltaNetwork sizeList) ; Args: sizeList = list of sizes of slabs. This also defines ; the number of slabs in the network. ; (e.g., '(10 5 4) ==> a 3-slab network with 10 ; input neurons, 5 hidden neurons, and 4 output ; neurons). ; ; Returned value = a list describing the network: ; (nLayers sizeList ; (activation-array[1] .. activation-array[nLayers]) ; (weight-array[2] .. weight-array[nLayers]) ; (sum-of-products[2] .. sum-of-products[nLayers[nLayers]) ; (back-prop-error[2] .. back-prop-error[nLayers])) ; (old-delta-weights[2] .. for momentum term ; (DeltaLearn networkList trainingList) ; Args: output-plot-file-name a string to plot, nil to not plot ; networkList = list returned from function NewDeltaNetwork ; trainingList = a list of lists of training exemplars. ; For example, a list might be: ; (((0 1) (1 0)) ; first exemplar ; ((1 0) (0 1))) ; second exemplar ; Note: the inner sub-lists can also be arrays. ; nIterations = number of complete training iterations ; ; Returned value = average error at output neurons for last ; training cycle. ; (DeltaRecall networkList inputList) ; Args: networkList = list returned from function 'NewDeltaNetwork' ; inputList = list OR array of input activation values ; ; Returned value = list of output neuron values ; (DeltaPlot networkList) ==> plots a network. Must call '(init-plot) first. ; (WriteDeltaNetwork fileName networkList) ==> saves a network to disk ; (ReadDeltaNetwork fileName) ==> returns a network list ;;;;;;;;;;;;;;;;;;; End of list of externally callable functions ;;;;;;;;;;;;; (ql:quickload "plotlib") (defpackage #:deltarule (:use #:cl #:plotlib)) ;; TBD: define exports (proclaim '(special eidaList defaultEidaList *delta-default-input-noise-value* *delta-rule-debug-flag* )) ;; Define default learning rates for each layer of neurons: (setq defaultEidaList '(0.5 0.4 0.3 0.2 0.08 0.07)) ;; Define the default noise to add to each input neuron: (setq *delta-default-input-noise-value* 0.08) (setq *delta-rule-debug-flag* nil) ;; ; Utilities to plot a network ;; (defun plotActivations (title x y data dmin dmax height) (let ((size (array-dimension data 0)) (ypos 0) (xpos x)) (plotlib:plot-string x (- height (- y 10)) title) (dotimes (i size) (if (< size 20) (setq ypos y xpos (+ x (* i 9))) (if (< i (/ size 2)) (setq ypos (- y 7) xpos (+ x (* i 9))) (setq ypos (+ y 2) xpos (+ x (* (- i (/ size 2)) 9))))) (plotlib:plot-size-rect (truncate xpos) (- height (truncate ypos)) 8 8 (min 8 (max 0 (truncate (* (/ (- (aref data i) dmin) (- dmax dmin)) 8))))) (plotlib:plot-frame-rect (truncate xpos) (- height (truncate ypos)) 8 8)))) (defun plotWeights (title x y data dmin dmax deltaWeights height) (let ((Xsize (array-dimension data 0)) (YSize (array-dimension data 1))) (if (< (* Xsize Ysize) 3000) ;; don't try to plot very large weight sets (progn (plotlib:plot-string (+ x 20) (- height (- y 10)) title) (dotimes (i Xsize) (dotimes (j Ysize) (plotlib:plot-size-rect (+ x (* i 9)) (- height (+ y (* j 9))) 8 8 (min 8 (max 0 (truncate (* (/ (- (aref data i j) dmin) (- dmax dmin)) 8))))) (plotlib:plot-frame-rect (+ x (* i 9)) (- height (+ y (* j 9))) 8 8) (plotlib:plot-size-rect (+ (* Xsize 8) 30 x (* i 9)) (- height (+ y (* j 9))) 8 8 (min 8 (max 0 (truncate (* (/ (- (aref deltaWeights i j) -.05) (- .05 -.05)) 8))))) (plotlib:plot-frame-rect (+ (* Xsize 8) 30 x (* i 9)) (- height (+ y (* j 9))) 8 8))))))) (defun DeltaPlot (netList plot-output-file-name) (let ((nLayers (car netList)) (activationList (caddr netList)) (weightList (cadr (cdddr netList))) (deltaWeightList (caddr (cdddr netList))) (minScale 0.0) ;; -0.3) (maxScale 0.6) ;; 0.3) (n 0) (y-start 0) (width 600) (height 600)) (vecto::with-canvas (:width width :height height) (plotlib:plot-string-bold 20 (- height 15) "Delta Network") (plotlib:plot-string 20 (- height 30) "Activation slabs:") (plotActivations "slab1" 10 60 (nth 0 ActivationList) 0.0 ;; lower limit of Sigmoid function 1.0 ;; upper limit of Sigmoid function height) (setq y-start 60) (dotimes (n-1 (- nLayers 1)) (setq n (+ n-1 1)) (if (equal n (- nLayers 1)) (setq minScale -0.1 maxScale 0.1)) ; scale up output display (plotActivations (nth n '("slab1" "slab2" "slab3" "slab4" "slab5" "slab6")) ; title 10 ; x location for subplot (+ y-start (* n 35)) ; y location for subplot (nth n ActivationList) ; data to plot as gray scale minScale maxScale height)) (if (< nLayers 6) (progn (setq y-start (+ y-start (* nLayers 35))) (plotlib:plot-string 20 (- height y-start) "Weights and Delta Weights:") (setq y-start (+ y-start 22)) (dotimes (n (- nLayers 1)) (plotWeights (nth n '("slab1 -> slab2" "slab2 -> slab3" "slab3 -> slab4" "slab4 -> slab5" "slab5 -> slab6")) 10 (+ y-start (* n 70)) ; x,y position of subplot (nth n WeightList) -1.0 1.0 (nth n deltaWeightList) height)))) (vecto::save-png plot-output-file-name)))) ;; ; Calculate Sigmoid and derivative of Sigmoid functions: ;; (defun Sigmoid (x) (/ 1.0 (+ 1.0 (exp (- x))))) (defun dSigmoid (x) (let ((temp (Sigmoid x))) (* temp (- 1.0 temp)))) ;; ; Generate floating point random numbers: ;; (defun frandom (low high) (let ((range (- high low))) (+ (* (/ (random 1000) 1000.0) range) low))) ;; ; Create a new delta network: ;; ;; alpha = coefficient for new weight change ;; beta = coefficient for adding in last weight change (defun NewDeltaNetwork (sizeList &optional (alpha 0.2) (beta 0.8)) (let ((numLayers (length sizeList)) (w-list nil) ; weights (dw-list nil) ; delta weights (old-dw-list nil) ; old delta weights for momentum terms (a-list nil) ; activation values (s-list nil) ; sum of products (d-list nil)) ; back propagated deltas (setq eidaList defaultEidaList) ;; ; Initialize storage for activation energy for all slabs: ;; (setq a-list (mapcar (lambda (size) (make-array (list size) :element-type 'float :initial-element 0.0)) sizeList)) ;; ; Initialize storage for sum of products arrays: ;; (setq s-list (mapcar (lambda (size) (make-array (list size) :element-type 'float :initial-element 0.0)) (cdr sizeList))) ;; ; Initialize storage for delta arrays: ;; (setq d-list (mapcar (lambda (size) (make-array (list size) :element-type 'float :initial-element 0.0)) (cdr sizeList))) ;; ; Initialize storage for the weights: ;; (dotimes (i (- numLayers 1)) (setq w-list (cons (list (nth i sizeList) (nth (+ i 1) sizeList)) w-list))) (setq w-list (mapcar (lambda (size) (make-array size :element-type 'float :initial-element 0.0)) (reverse w-list))) ;; ; Initialize the storage for delta weights: ;; (dotimes (i (- numLayers 1)) (setq dw-list (cons (list (nth i sizeList) (nth (+ i 1) sizeList)) dw-list))) (setq dw-list (mapcar (lambda (size) (make-array size :element-type 'float)) (reverse dw-list))) ;; ; Initialize the storage for old delta weights: ;; (dotimes (i (- numLayers 1)) (setq old-dw-list (cons (list (nth i sizeList) (nth (+ i 1) sizeList)) old-dw-list))) (setq old-dw-list (mapcar (lambda (size) (make-array size :element-type 'float :initial-element 0.0)) (reverse old-dw-list))) ;; ; Initialize values for all activations: ;; (mapc (lambda (x) (let ((num (array-dimension x 0))) (dotimes (n num) (setf (aref x n) (frandom 0.01 0.1))))) a-list) ;; ; Initialize values for all weights: ;; (mapc (lambda (x) (let ((numI (array-dimension x 0)) (numJ (array-dimension x 1))) (dotimes (j numJ) (dotimes (i numI) (setf (aref x i j) (frandom -0.5 0.5)))))) w-list) (list numLayers sizeList a-list s-list w-list dw-list d-list old-dw-list alpha beta))) ;; ; Utility function for training a delta rule neural network. ; The first argument is the name of an output PNG plot file ; and a nil value turns off plotting the network during training. ; The second argument is a network definition (as returned from ; NewDeltaNetwork), the third argument is a list of training ; data cases (see the example test functions at the end of this ; file for examples. ;; (defun DeltaLearn (plot-output-file-name netList trainList) (let ((nLayers (car netList)) (sizeList (cadr netList)) (activationList (caddr netList)) (sumOfProductsList (car (cdddr netList))) (weightList (cadr (cdddr netList))) (deltaWeightList (caddr (cdddr netList))) (deltaList (cadddr (cdddr netList))) (oldDeltaWeightList (cadddr (cdddr (cdr netList)))) (alpha (cadddr (cdddr (cddr netList)))) (beta (cadddr (cdddr (cdddr netList)))) (inputs nil) (targetOutputs nil) (iDimension nil) (jDimension nil) (iActivationVector nil) (jActivationVector nil) (n nil) (weightArray nil) (sumOfProductsArray nil) (iDeltaVector nil) (jDeltaVector nil) (deltaWeightArray nil) (oldDeltaWeightArray nil) (sum nil) (iSumOfProductsArray nil) (error nil) (outputError 0) (delta nil) (eida nil) (inputNoise 0)) ;; ; Zero out deltas: ;; (dotimes (n (- nLayers 1)) (let* ((dw (nth n deltaList)) (len1 (array-dimension dw 0))) (dotimes (i len1) (setf (aref dw i) 0.0)))) ;; ; Zero out delta weights: ;; (dotimes (n (- nLayers 1)) (let* ((dw (nth n deltaWeightList)) (len1 (array-dimension dw 0)) (len2 (array-dimension dw 1))) (dotimes (i len1) (dotimes (j len2) (setf (aref dw i j) 0.0))))) (setq inputNoise *delta-default-input-noise-value*) ;; ; Main loop on training examples: ;; (dolist (tl trainList) (setq inputs (car tl)) (setq targetOutputs (cadr tl)) (if *delta-rule-debug-flag* (print (list "Current targets:" targetOutputs))) (setq iDimension (car sizeList)) ; get the size of the input slab (setq iActivationVector (car activationList)) ; get array of input activations (dotimes (i iDimension) ; copy training inputs to input slab (setf (aref iActivationVector i) (+ (nth i inputs) (frandom (- inputNoise) inputNoise)))) ;; ; Propagate activation through all of the slabs: ;; (dotimes (n-1 (- nLayers 1)) ; update layer i to layer flowing to layer j (setq n (+ n-1 1)) (setq jDimension (nth n sizeList)) ; get the size of the j'th layer (setq jActivationVector (nth n activationList)) ; activation array for slab j (setq weightArray (nth n-1 weightList)) (setq sumOfProductsArray (nth n-1 sumOfProductsList)) (dotimes (j jDimension) ; process each neuron in slab j (setq sum 0.0) ; init sum of products to zero (dotimes (i iDimension) ; to get activation from each neuron in previous slab (setq sum (+ sum (* (aref weightArray i j) (aref iActivationVector i))))) (setf (aref sumOfProductsArray j) sum) ; save sum of products (setf (aref jActivationVector j) (Sigmoid sum))) (setq iDimension jDimension) ; reset index for next slab pair (setq iActivationVector jActivationVector)) ;; ; Activation is spread through the network and sum of products calculated. ; Now modify the weights in the network using back error propagation. Start ; by calculating the error signal for each neuron in the output layer: ;; (setq jDimension (nth (- nLayers 1) sizeList)) ; size of last layer (setq jActivationVector (nth (- nLayers 1) activationList)) (setq jDeltaVector (nth (- nLayers 2) deltaList)) (setq sumOfProductsArray (nth (- nLayers 2) sumOfProductsList)) (setq outputError 0) (dotimes (j jDimension) (setq delta (- (nth j targetOutputs) (aref jActivationVector j))) (setq outputError (+ outputError (abs delta))) (setf (aref jDeltaVector j) (+ (aref jDeltaVector j) (* delta (dSigmoid (aref sumOfProductsArray j)))))) ;; ; Now calculate the backpropagated error signal for all hidden slabs: ;; (dotimes (nn (- nLayers 2)) (setq n (- nLayers 3 nn)) (setq iDimension (nth (+ n 1) sizeList)) (setq iSumOfProductsArray (nth n sumOfProductsList)) (setq iDeltaVector (nth n deltaList)) (dotimes (i iDimension) (setf (aref iDeltaVector i) 0.0)) (setq weightArray (nth (+ n 1) weightList)) (dotimes (i iDimension) (setq error 0.0) (dotimes (j jDimension) (setq error (+ error (* (aref jDeltaVector j) (aref weightArray i j))))) (setf (aref iDeltaVector i) (+ (aref iDeltaVector i) (* error (dSigmoid (aref iSumOfProductsArray i)))))) (setq jDimension iDimension) (setq jDeltaVector iDeltaVector)) ;; ; Update all delta weights in the network: ;; (setq iDimension (car sizeList)) (dotimes (n (- nLayers 1)) (setq iActivationVector (nth n activationList)) (setq jDimension (nth (+ n 1) sizeList)) (setq jDeltaVector (nth n deltaList)) (setq deltaWeightArray (nth n deltaWeightList)) (setq weightArray (nth n weightList)) (setq eida (nth n eidaList)) (dotimes (j jDimension) (dotimes (i iDimension) (setq delta (* eida (aref jDeltaVector j) (aref iActivationVector i))) (setf (aref DeltaWeightArray i j) (+ (aref DeltaWeightArray i j) delta)))) ; remember delta weight change (setq iDimension jDimension)) ;; ; Update all weights in the network: ;; (setq iDimension (car sizeList)) (dotimes (n (- nLayers 1)) (setq iActivationVector (nth n activationList)) (setq jDimension (nth (+ n 1) sizeList)) (setq jDeltaVector (nth n deltaList)) (setq deltaWeightArray (nth n deltaWeightList)) (setq oldDeltaWeightArray (nth n oldDeltaWeightList)) (setq weightArray (nth n weightList)) (dotimes (j jDimension) (dotimes (i iDimension) (setf (aref weightArray i j) (+ (aref weightArray i j) (* alpha (aref deltaWeightArray i j)) (* beta (aref oldDeltaWeightArray i j)))) (setf (aref oldDeltaWeightArray i j) ; save current delta weights (aref deltaWeightArray i j)))) ; ...for next momentum term. (setq iDimension jDimension)) (if plot-output-file-name (DeltaPlot netList plot-output-file-name))) (/ outputError jDimension))) ;; ; Utility for using a trained neural network in the recall mode. ; The first argument to this function is a network definition (as ; returned from NewDeltaNetwork) and the second argument is a list ; of input neuron activation values to drive through the network. ;; (defun DeltaRecall (netList inputs) (let ((nLayers (car netList)) (sizeList (cadr netList)) (activationList (caddr netList)) (weightList (cadr (cdddr netList))) (iDimension nil) (jDimension nil) (iActivationVector nil) (jActivationVector nil) (n nil) (weightArray nil) (returnList nil) (sum nil)) (setq iDimension (car sizeList)) ; get the size of the input slab (setq iActivationVector (car activationList)) ; get array of input activations (dotimes (i iDimension) ; copy training inputs to input slab (setf (aref iActivationVector i) (nth i inputs))) (dotimes (n-1 (- nLayers 1)) ; update layer j to layer i (setq n (+ n-1 1)) (setq jDimension (nth n sizeList)) ; get the size of the j'th layer (setq jActivationVector (nth n activationList)) ; activation array for slab j (setq weightArray (nth n-1 weightList)) (dotimes (j jDimension) ; process each neuron in slab j (setq sum 0.0) ; init sum of products to zero (dotimes (i iDimension) ; to get activation from each neuron in previous slab (setq sum (+ sum (* (aref weightArray i j) (aref iActivationVector i))))) (if *delta-rule-debug-flag* (print (list "sum=" sum))) (setf (aref jActivationVector j) (Sigmoid sum))) (setq iDimension jDimension) ; get ready for next slab pair (setq iActivationVector jActivationVector)) (dotimes (j jDimension) (setq returnList (append returnList (list (aref jActivationVector j))))) returnList)) ;; ; Throw away test functions for two, three and four layer networks: ;; (proclaim '(special temp)) ; temp will be used to hold the network data (defun test2 (&aux RMSerror temp) (setq temp (newdeltanetwork '(2 2))) ; specify a two layer network (2x2) (dotimes (ii 1000) (let ((file-name (if (equal (mod ii 150) 0) (concatenate 'string "output_plot_" (format nil "~12,'0d" ii) ".png") nil))) (setq RMSerror (deltalearn file-name temp '(((1 0) (0 1)) ((0 1) (1 0))))) (if (equal (mod ii 50) 0) ;; print out every 50 cycles (progn (princ "....training cycle \#") (princ ii) (princ " RMS error = ") (princ RMSerror) (terpri)))))) (defun test3 (&optional (restart 'yes) &aux RMSerror) ; three layer network (if (equal restart 'yes) (setq temp (newdeltanetwork '(5 4 5)))) (dotimes (ii 3000) (let ((file-name (if (equal (mod ii 400) 0) (concatenate 'string "output_plot_" (format nil "~12,'0d" ii) ".png") nil))) (setq RMSerror (deltalearn file-name temp '(((1 0 0 0 0) (0 1 0 0 0)) ((0 1 0 0 0) (0 0 1 0 0)) ((0 0 1 0 0) (0 0 0 1 0)) ((0 0 0 1 0) (0 0 0 0 1)) ((0 0 0 0 1) (1 0 0 0 0))))) (if (equal (mod ii 50) 0) ;; print out every 50 cycles (progn (princ "....training cycle \#") (princ ii) (princ " RMS error = ") (princ RMSerror) (terpri)))))) (defun test4 (&optional (restart 'yes) &aux RMSerror) ; four layer network (if (equal restart 'yes) (setq temp (newdeltanetwork '(4 5 5 4)))) (dotimes (ii 7000) (let ((file-name (if (equal (mod ii 1800) 0) (concatenate 'string "output_plot_" (format nil "~12,'0d" ii) ".png") nil))) (setq RMSerror (deltalearn file-name temp '(((1 0 0 0) (0 1 0 0)) ((0 1 0 0) (0 0 1 0)) ((0 0 1 0) (0 0 0 1)) ((0 0 0 1) (1 0 0 0))))) (if (equal (mod ii 150) 0) ;; print out every 150 cycles (progn (princ "....training cycle \#") (princ ii) (princ " RMS error = ") (princ RMSerror) (terpri)))))) (princ "There are 3 test functions for 2, 3, and 4 layered backprop models. Try:") (terpri) (princ "(in-package #:deltarule)") (terpri) (princ "(test2)") (terpri) (princ "(test3)") (terpri) (princ "(test4)") (terpri)
21,557
Common Lisp
.lisp
549
31.526412
106
0.57738
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d59226f2a56430f439260066f36c5d7a748b1fb76223f1cd0b8378aa11dbba57
19,209
[ -1 ]
19,210
macro2.lisp
Eggy115_Lisp/loving_snippets/macro2.lisp
;; another macro example that uses ,@: (defmacro double-args (&rest args) `(let ((ret nil)) (dolist (x ,@args) (setq ret (append ret (list x x)))) ret)) ;; use the macro: (defun test (&rest x) (double-args x))
243
Common Lisp
.lisp
9
22.333333
42
0.587719
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6f9a948f46a2d489996554d025b79017726459ae601d8d72da11e67a93b70716
19,210
[ -1 ]
19,211
mongo_news.lisp
Eggy115_Lisp/loving_snippets/mongo_news.lisp
;; Copyright Mark Watson 2001-2013. All Rights Reserved. ;; License: AGPL version 3 (http://www.gnu.org/licenses/agpl-3.0.txt) ;; Alternative license: you may also use this software under the Apache 2 License. ;; This copyright notice should not be removed from this file and in files derived from this file. (ql:quickload "cl-mongo") (cl-mongo:db.use "news") (defun add-article (uri title text) (let ((doc (cl-mongo:make-document))) (cl-mongo:add-element "uri" uri doc) (cl-mongo:add-element "title" title doc) (cl-mongo:add-element "text" text doc) (cl-mongo:db.insert "article" doc))) ;; example: (add-article "http://test.com" "article title 1" "article text 1") (defun print-articles () (cl-mongo:pp (cl-mongo:iter (cl-mongo:db.find "article" :all)))) ;; for each document, use the cl-mongo:get-element on each element we want to save: (defun article-results->lisp-data (mdata) (let ((ret '())) (print (list "size of result=" (length mdata))) (dolist (a mdata) (print a) (push (list (cl-mongo:get-element "uri" a) (cl-mongo:get-element "title" a) (cl-mongo:get-element "text" a)) ret)) ret)) (defun get-articles () (article-results->lisp-data (cadr (cl-mongo:db.find "article" :all)))) ;; try: (cl-mongo:pp (cl-mongo:iter (cl-mongo:db.find "article" (cl-mongo:kv "uri" "http://test.com")))) ;; try: (cl-mongo:pp (cl-mongo:iter (cl-mongo:db.find "article" (cl-mongo:kv "title" (cl-mongo:kv "$regex" "article")) :limit 10))) (defun search-articles-title (str) ;; find documents where substring 'str' is in the title (article-results->lisp-data (cadr (cl-mongo:iter (cl-mongo:db.find "article" (cl-mongo:kv "title" (cl-mongo:kv "$regex" str)) :limit 10))))) (defun search-articles-text (str) ;; find documents where substring 'str' is in the text element (article-results->lisp-data (cadr (cl-mongo:db.find "article" (cl-mongo:kv "text" (cl-mongo:kv "$regex" str)) :limit 10))))
2,033
Common Lisp
.lisp
39
47.230769
132
0.666159
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a18757740a3f8ab6e4bd94c5533122c671cf786fe99681b99fc4b6c638cb0064
19,211
[ -1 ]
19,212
test-xml-struct-dom.lisp
Eggy115_Lisp/s-xml/test/test-xml-struct-dom.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: test-xml-struct-dom.lisp,v 1.2 2005/08/29 15:01:49 scaekenberghe Exp $ ;;;; ;;;; Unit and functional tests for xml-struct-dom.lisp ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) (assert (xml-equal (with-input-from-string (stream " <foo/>") (parse-xml stream :output-type :xml-struct)) (make-xml-element :name :|foo|))) (assert (xml-equal (parse-xml-string "<tag1><tag2 att1='one'/>this is some text</tag1>" :output-type :xml-struct) (make-xml-element :name :|tag1| :children (list (make-xml-element :name :|tag2| :attributes '((:|att1| . "one"))) "this is some text")))) (assert (xml-equal (parse-xml-string "<tag>&lt;foo&gt;</tag>" :output-type :xml-struct) (make-xml-element :name :|tag| :children (list "<foo>")))) (assert (xml-equal (parse-xml-string "<P><INDEX ITEM='one'/> This is some <B>bold</B> text, with a leading &amp; trailing space </P>" :output-type :xml-struct) (make-xml-element :name :p :children (list (make-xml-element :name :index :attributes '((:item . "one"))) " This is some " (make-xml-element :name :b :children (list "bold")) " text, with a leading & trailing space ")))) (assert (xml-element-p (parse-xml-file (merge-pathnames "xhtml-page.xml" *load-pathname*) :output-type :xml-struct))) (assert (xml-element-p (parse-xml-file (merge-pathnames "ant-build-file.xml" *load-pathname*) :output-type :xml-struct))) (assert (xml-element-p (parse-xml-file (merge-pathnames "plist.xml" *load-pathname*) :output-type :xml-struct))) (assert (string-equal (print-xml-string (make-xml-element :name "foo") :input-type :xml-struct) "<foo/>")) (assert (string-equal (print-xml-string (make-xml-element :name "foo" :attributes '((:|bar| . "1"))) :input-type :xml-struct) "<foo bar=\"1\"/>")) (assert (string-equal (print-xml-string (make-xml-element :name "foo" :children (list "some text")) :input-type :xml-struct) "<foo>some text</foo>")) (assert (string-equal (print-xml-string (make-xml-element :name "foo" :children (list (make-xml-element :name "bar"))) :input-type :xml-struct) "<foo><bar/></foo>")) ;;;; eof
2,653
Common Lisp
.lisp
65
34.953846
112
0.616075
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ceff9cd493e3a61eeb23eaed594faff87ba3ae10075bfbd5d79376d3d607bbee
19,212
[ 449670 ]
19,213
echo.lisp
Eggy115_Lisp/s-xml/test/echo.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: echo.lisp,v 1.1 2005/08/17 13:44:30 scaekenberghe Exp $ ;;;; ;;;; A simple example as well as a useful tool: parse, echo and pretty print XML ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) (defun indent (stream count) (loop :repeat (* count 2) :do (write-char #\space stream))) (defclass echo-xml-seed () ((stream :initarg :stream) (level :initarg :level :initform 0))) #+NIL (defmethod print-object ((seed echo-xml-seed) stream) (with-slots (stream level) seed (print-unreadable-object (seed stream :type t) (format stream "level=~d" level)))) (defun echo-xml-new-element-hook (name attributes seed) (with-slots (stream level) seed (indent stream level) (format stream "<~a" name) (dolist (attribute (reverse attributes)) (format stream " ~a=\'" (car attribute)) (print-string-xml (cdr attribute) stream) (write-char #\' stream)) (format stream ">~%") (incf level) seed)) (defun echo-xml-finish-element-hook (name attributes parent-seed seed) (declare (ignore attributes parent-seed)) (with-slots (stream level) seed (decf level) (indent stream level) (format stream "</~a>~%" name) seed)) (defun echo-xml-text-hook (string seed) (with-slots (stream level) seed (indent stream level) (print-string-xml string stream) (terpri stream) seed)) (defun echo-xml (in out) "Parse a toplevel XML element from stream in, echoing and pretty printing the result to stream out" (start-parse-xml in (make-instance 'xml-parser-state :seed (make-instance 'echo-xml-seed :stream out) :new-element-hook #'echo-xml-new-element-hook :finish-element-hook #'echo-xml-finish-element-hook :text-hook #'echo-xml-text-hook))) ;;;; eof
2,127
Common Lisp
.lisp
55
33.836364
102
0.664717
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1dd68ec1234372e25ab83c597b353b1bc7cfe5c8f064d2e3b50a284bed734dc4
19,213
[ 134723, 134909 ]
19,214
remove-markup.lisp
Eggy115_Lisp/s-xml/test/remove-markup.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: remove-markup.lisp,v 1.1 2004/06/11 11:14:43 scaekenberghe Exp $ ;;;; ;;;; Remove markup from an XML document using the SSAX interface ;;;; ;;;; Copyright (C) 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) (defun remove-xml-markup (in) (let* ((state (make-instance 'xml-parser-state :text-hook #'(lambda (string seed) (cons string seed)))) (result (start-parse-xml in state))) (apply #'concatenate 'string (nreverse result)))) ;;;; eof
779
Common Lisp
.lisp
18
38.555556
87
0.642857
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
01112a1dd5a6a9d06837b70b7e89e1733fd6c622165948124cf880ce9c4e89cd
19,214
[ 291499, 473466 ]
19,215
tracer.lisp
Eggy115_Lisp/s-xml/test/tracer.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: tracer.lisp,v 1.2 2004/06/11 11:14:43 scaekenberghe Exp $ ;;;; ;;;; A simple SSAX tracer example that can be used to understand how the hooks are called ;;;; ;;;; Copyright (C) 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) (defun trace-xml-log (level msg &rest args) (indent *standard-output* level) (apply #'format *standard-output* msg args) (terpri *standard-output*)) (defun trace-xml-new-element-hook (name attributes seed) (let ((new-seed (cons (1+ (car seed)) (1+ (cdr seed))))) (trace-xml-log (car seed) "(new-element :name ~s :attributes ~:[()~;~:*~s~] :seed ~s) => ~s" name attributes seed new-seed) new-seed)) (defun trace-xml-finish-element-hook (name attributes parent-seed seed) (let ((new-seed (cons (1- (car seed)) (1+ (cdr seed))))) (trace-xml-log (car parent-seed) "(finish-element :name ~s :attributes ~:[()~;~:*~s~] :parent-seed ~s :seed ~s) => ~s" name attributes parent-seed seed new-seed) new-seed)) (defun trace-xml-text-hook (string seed) (let ((new-seed (cons (car seed) (1+ (cdr seed))))) (trace-xml-log (car seed) "(text :string ~s :seed ~s) => ~s" string seed new-seed) new-seed)) (defun trace-xml (in) "Parse and trace a toplevel XML element from stream in" (start-parse-xml in (make-instance 'xml-parser-state :seed (cons 0 0) ;; seed car is xml element nesting level ;; seed cdr is ever increasing from element to element :new-element-hook #'trace-xml-new-element-hook :finish-element-hook #'trace-xml-finish-element-hook :text-hook #'trace-xml-text-hook))) (defun trace-xml-file (pathname) "Parse and trace XMl from the file at pathname" (with-open-file (in pathname) (trace-xml in))) ;;;; eof
2,262
Common Lisp
.lisp
49
37.857143
106
0.595357
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
4cee79e2b9df7b8c78a842eac621b520c71723b320b3142e6c513e46712f3fd3
19,215
[ 407834, 458873 ]
19,216
test-sxml-dom.lisp
Eggy115_Lisp/s-xml/test/test-sxml-dom.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: test-sxml-dom.lisp,v 1.1.1.1 2004/06/07 18:49:59 scaekenberghe Exp $ ;;;; ;;;; Unit and functional tests for sxml-dom.lisp ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) (assert (equal (with-input-from-string (stream " <foo/>") (parse-xml stream :output-type :sxml)) '(:|foo|))) (assert (equal (parse-xml-string "<tag1><tag2 att1='one'/>this is some text</tag1>" :output-type :sxml) '(:|tag1| (:|tag2| (:@ (:|att1| "one"))) "this is some text"))) (assert (equal (parse-xml-string "<TAG>&lt;foo&gt;</TAG>" :output-type :sxml) '(:TAG "<foo>"))) (assert (equal (parse-xml-string "<P><INDEX ITEM='one'/> This is some <B>bold</B> text, with a leading &amp; trailing space </P>" :output-type :sxml) '(:p (:index (:@ (:item "one"))) " This is some " (:b "bold") " text, with a leading & trailing space "))) (assert (consp (parse-xml-file (merge-pathnames "xhtml-page.xml" *load-pathname*) :output-type :sxml))) (assert (consp (parse-xml-file (merge-pathnames "ant-build-file.xml" *load-pathname*) :output-type :sxml))) (assert (consp (parse-xml-file (merge-pathnames "plist.xml" *load-pathname*) :output-type :sxml))) (assert (string-equal (print-xml-string '(:|foo|) :input-type :sxml) "<foo/>")) (assert (string-equal (print-xml-string '(:|foo| (:@ (:|bar| "1"))) :input-type :sxml) "<foo bar=\"1\"/>")) (assert (string-equal (print-xml-string '(:foo "some text") :input-type :sxml) "<FOO>some text</FOO>")) (assert (string-equal (print-xml-string '(:|foo| (:|bar|)) :input-type :sxml) "<foo><bar/></foo>")) ;;;; eof
1,992
Common Lisp
.lisp
57
30.894737
99
0.611518
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
98d940f16af992e541f541aba6d6ec1e68cd8d125862654482ea2f7abb4a055e
19,216
[ 409008 ]
19,217
test-xml.lisp
Eggy115_Lisp/s-xml/test/test-xml.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: test-xml.lisp,v 1.3 2005/11/06 12:44:48 scaekenberghe Exp $ ;;;; ;;;; Unit and functional tests for xml.lisp ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) (assert (whitespace-char-p (character " "))) (assert (whitespace-char-p (character " "))) (assert (whitespace-char-p (code-char 10))) (assert (whitespace-char-p (code-char 13))) (assert (not (whitespace-char-p #\A))) (assert (char= (with-input-from-string (stream " ABC") (skip-whitespace stream)) #\A)) (assert (char= (with-input-from-string (stream "ABC") (skip-whitespace stream)) #\A)) (assert (string-equal (with-output-to-string (stream) (print-string-xml "<foo>" stream)) "&lt;foo&gt;")) (assert (string-equal (with-output-to-string (stream) (print-string-xml "' '" stream)) "' '")) (assert (let ((string (map 'string #'identity '(#\return #\tab #\newline)))) (string-equal (with-output-to-string (stream) (print-string-xml string stream)) string))) (defun simple-echo-xml (in out) (start-parse-xml in (make-instance 'xml-parser-state :new-element-hook #'(lambda (name attributes seed) (declare (ignore seed)) (format out "<~a~:{ ~a='~a'~}>" name (mapcar #'(lambda (p) (list (car p) (cdr p))) (reverse attributes)))) :finish-element-hook #'(lambda (name attributes parent-seed seed) (declare (ignore attributes parent-seed seed)) (format out "</~a>" name)) :text-hook #'(lambda (string seed) (declare (ignore seed)) (princ string out))))) (defun simple-echo-xml-string (string) (with-input-from-string (in string) (with-output-to-string (out) (simple-echo-xml in out)))) (assert (let ((xml "<FOO ATT1='1' ATT2='2'><B>Text</B><EMPTY></EMPTY>More text!<SUB><SUB></SUB></SUB></FOO>")) (equal (simple-echo-xml-string xml) xml))) (assert (let ((xml "<p> </p>")) (equal (simple-echo-xml-string xml) xml))) ;;;; eof
2,355
Common Lisp
.lisp
69
29.130435
104
0.616851
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b63e0e394780cc79792b6f488a845df645d618e0e39757737c891390b54b23ab
19,217
[ 117400 ]
19,218
counter.lisp
Eggy115_Lisp/s-xml/test/counter.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: counter.lisp,v 1.2 2004/06/11 11:14:43 scaekenberghe Exp $ ;;;; ;;;; A simple SSAX counter example that can be used as a performance test ;;;; ;;;; Copyright (C) 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) (defclass count-xml-seed () ((elements :initform 0) (attributes :initform 0) (characters :initform 0))) (defun count-xml-new-element-hook (name attributes seed) (declare (ignore name)) (incf (slot-value seed 'elements)) (incf (slot-value seed 'attributes) (length attributes)) seed) (defun count-xml-text-hook (string seed) (incf (slot-value seed 'characters) (length string)) seed) (defun count-xml (in) "Parse a toplevel XML element from stream in, counting elements, attributes and characters" (start-parse-xml in (make-instance 'xml-parser-state :seed (make-instance 'count-xml-seed) :new-element-hook #'count-xml-new-element-hook :text-hook #'count-xml-text-hook))) (defun count-xml-file (pathname) "Parse XMl from the file at pathname, counting elements, attributes and characters" (with-open-file (in pathname) (let ((result (count-xml in))) (with-slots (elements attributes characters) result (format t "~a contains ~d XML elements, ~d attributes and ~d characters.~%" pathname elements attributes characters))))) ;;;; eof
1,675
Common Lisp
.lisp
40
36.9
94
0.678814
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
760df4611e48de2988fc9c68181ab976b0e50c9635c6317693165b8c0b841b93
19,218
[ 152951, 384134 ]
19,219
test-lxml-dom.lisp
Eggy115_Lisp/s-xml/test/test-lxml-dom.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: test-lxml-dom.lisp,v 1.2 2005/11/06 12:44:48 scaekenberghe Exp $ ;;;; ;;;; Unit and functional tests for lxml-dom.lisp ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) (assert (equal (with-input-from-string (stream " <foo/>") (parse-xml stream :output-type :lxml)) :|foo|)) (assert (equal (parse-xml-string "<tag1><tag2 att1='one'/>this is some text</tag1>" :output-type :lxml) '(:|tag1| ((:|tag2| :|att1| "one")) "this is some text"))) (assert (equal (parse-xml-string "<TAG>&lt;foo&gt;</TAG>" :output-type :lxml) '(:TAG "<foo>"))) (assert (equal (parse-xml-string "<P><INDEX ITEM='one'/> This is some <B>bold</B> text, with a leading &amp; trailing space </P>" :output-type :lxml) '(:p ((:index :item "one")) " This is some " (:b "bold") " text, with a leading & trailing space "))) (assert (consp (parse-xml-file (merge-pathnames "xhtml-page.xml" *load-pathname*) :output-type :lxml))) (assert (consp (parse-xml-file (merge-pathnames "ant-build-file.xml" *load-pathname*) :output-type :lxml))) (assert (consp (parse-xml-file (merge-pathnames "plist.xml" *load-pathname*) :output-type :lxml))) (assert (string-equal (print-xml-string :|foo| :input-type :lxml) "<foo/>")) (assert (string-equal (print-xml-string '((:|foo| :|bar| "1")) :input-type :lxml) "<foo bar=\"1\"/>")) (assert (string-equal (print-xml-string '(:foo "some text") :input-type :lxml) "<FOO>some text</FOO>")) (assert (string-equal (print-xml-string '(:|foo| :|bar|) :input-type :lxml) "<foo><bar/></foo>")) (assert (string-equal (second (with-input-from-string (stream "<foo><![CDATA[<greeting>Hello, world!</greeting>]]></foo>") (parse-xml stream :output-type :lxml))) "<greeting>Hello, world!</greeting>")) (assert (string-equal (second (with-input-from-string (stream "<foo><![CDATA[<greeting>Hello, < world!</greeting>]]></foo>") (parse-xml stream :output-type :lxml))) "<greeting>Hello, < world!</greeting>")) ;;;; eof
2,529
Common Lisp
.lisp
65
32.830769
118
0.593994
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
692611c834073444fa0aef420af8bb7c219b1c45bdfdc913b087d03dc426aded
19,219
[ 472210 ]
19,220
all-tests.lisp
Eggy115_Lisp/s-xml/test/all-tests.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: all-tests.lisp,v 1.1.1.1 2004/06/07 18:49:58 scaekenberghe Exp $ ;;;; ;;;; Load and execute all unit and functional tests ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (load (merge-pathnames "test-xml" *load-pathname*) :verbose t) (load (merge-pathnames "test-xml-struct-dom" *load-pathname*) :verbose t) (load (merge-pathnames "test-lxml-dom" *load-pathname*) :verbose t) (load (merge-pathnames "test-sxml-dom" *load-pathname*) :verbose t) ;;;; eof
755
Common Lisp
.lisp
16
45.0625
75
0.686141
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
aad400b5da445d996bdff855f7ff9adb3bd87aac0ae0d0055a47e5fc43572c85
19,220
[ 189786 ]
19,223
xml.lisp
Eggy115_Lisp/s-xml/src/xml.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: xml.lisp,v 1.14 2005/11/20 14:24:34 scaekenberghe Exp $ ;;;; ;;;; This is a Common Lisp implementation of a basic but usable XML parser. ;;;; The parser is non-validating and not complete (no CDATA). ;;;; Namespace and entities are handled. ;;;; The API into the parser is a pure functional parser hook model that comes from SSAX, ;;;; see also http://pobox.com/~oleg/ftp/Scheme/xml.html or http://ssax.sourceforge.net ;;;; Different DOM models are provided, an XSML, an LXML and a xml-element struct based one. ;;;; ;;;; Copyright (C) 2002, 2003, 2004, 2005 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) ;;; error reporting (define-condition xml-parser-error (error) ((message :initarg :message :reader xml-parser-error-message) (args :initarg :args :reader xml-parser-error-args) (stream :initarg :stream :reader xml-parser-error-stream :initform nil)) (:report (lambda (condition stream) (format stream "XML parser ~?~@[ near stream position ~d~]." (xml-parser-error-message condition) (xml-parser-error-args condition) (and (xml-parser-error-stream condition) (file-position (xml-parser-error-stream condition)))))) (:documentation "Thrown by the XML parser to indicate errorneous input")) (setf (documentation 'xml-parser-error-message 'function) "Get the message from an XML parser error" (documentation 'xml-parser-error-args 'function) "Get the error arguments from an XML parser error" (documentation 'xml-parser-error-stream 'function) "Get the stream from an XML parser error") (defun parser-error (message &optional args stream) (make-condition 'xml-parser-error :message message :args args :stream stream)) ;;; utilities (defun whitespace-char-p (char) "Is char an XML whitespace character ?" (or (char= char #\space) (char= char #\tab) (char= char #\return) (char= char #\linefeed))) (defun identifier-char-p (char) "Is char an XML identifier character ?" (or (and (char<= #\A char) (char<= char #\Z)) (and (char<= #\a char) (char<= char #\z)) (and (char<= #\0 char) (char<= char #\9)) (char= char #\-) (char= char #\_) (char= char #\.) (char= char #\:))) (defun skip-whitespace (stream) "Skip over XML whitespace in stream, return first non-whitespace character which was peeked but not read, return nil on eof" (loop (let ((char (peek-char nil stream nil nil))) (if (and char (whitespace-char-p char)) (read-char stream) (return char))))) (defun make-extendable-string (&optional (size 10)) "Make an extendable string which is a one-dimensional character array which is adjustable and has a fill pointer" (make-array size :element-type 'character :adjustable t :fill-pointer 0)) (defun print-string-xml (string stream &key (start 0) end) "Write the characters of string to stream using basic XML conventions" (loop for offset upfrom start below (or end (length string)) for char = (char string offset) do (case char (#\& (write-string "&amp;" stream)) (#\< (write-string "&lt;" stream)) (#\> (write-string "&gt;" stream)) (#\" (write-string "&quot;" stream)) ((#\newline #\return #\tab) (write-char char stream)) (t (if (and (<= 32 (char-code char)) (<= (char-code char) 126)) (write-char char stream) (progn (write-string "&#x" stream) (write (char-code char) :stream stream :base 16) (write-char #\; stream))))))) (defun make-standard-entities () "A hashtable mapping XML entity names to their replacement strings, filled with the standard set" (let ((entities (make-hash-table :test #'equal))) (setf (gethash "amp" entities) (string #\&) (gethash "quot" entities) (string #\") (gethash "apos" entities) (string #\') (gethash "lt" entities) (string #\<) (gethash "gt" entities) (string #\>) (gethash "nbsp" entities) (string #\space)) entities)) (defun resolve-entity (stream extendable-string entities &optional (entity (make-extendable-string))) "Read and resolve an XML entity from stream, positioned after the '&' entity marker, accepting &name; &#DEC; and &#xHEX; formats, destructively modifying string, which is also returned, destructively modifying entity, incorrect entity formats result in errors" (loop (let ((char (read-char stream nil nil))) (cond ((null char) (error (parser-error "encountered eof before end of entity"))) ((char= #\; char) (return)) (t (vector-push-extend char entity))))) (if (char= (char entity 0) #\#) (let ((code (if (char= (char entity 1) #\x) (parse-integer entity :start 2 :radix 16 :junk-allowed t) (parse-integer entity :start 1 :radix 10 :junk-allowed t)))) (when (null code) (error (parser-error "encountered incorrect entity &~s;" (list entity) stream))) (vector-push-extend (code-char code) extendable-string)) (let ((value (gethash entity entities))) (if value (loop :for char :across value :do (vector-push-extend char extendable-string)) (error (parser-error "encountered unknown entity &~s;" (list entity) stream))))) extendable-string) ;;; namespace support (defvar *ignore-namespaces* nil "When t, namespaces are ignored like in the old version of S-XML") (defclass xml-namespace () ((uri :documentation "The URI used to identify this namespace" :accessor get-uri :initarg :uri) (prefix :documentation "The preferred prefix assigned to this namespace" :accessor get-prefix :initarg :prefix :initform nil) (package :documentation "The Common Lisp package where this namespace's symbols are interned" :accessor get-package :initarg :package :initform nil)) (:documentation "Describes an XML namespace and how it is handled")) (defmethod print-object ((object xml-namespace) stream) (print-unreadable-object (object stream :type t :identity t) (format stream "~A - ~A" (get-prefix object) (get-uri object)))) (defvar *local-namespace* (make-instance 'xml-namespace :uri "local" :prefix "" :package (find-package :keyword)) "The local (global default) XML namespace") (defvar *xml-namespace* (make-instance 'xml-namespace :uri "http://www.w3.org/XML/1998/namespace" :prefix "xml" :package (or (find-package :xml) (make-package :xml :nicknames '("XML")))) "REC-xml-names-19990114 says the prefix xml is bound to the namespace http://www.w3.org/XML/1998/namespace.") (defvar *known-namespaces* (list *local-namespace* *xml-namespace*) "The list of known/defined namespaces") (defvar *namespaces* `(("xml" . ,*xml-namespace*) ("" . ,*local-namespace*)) "Ordered list of (prefix . XML-namespace) bindings currently in effect - special variable") (defun find-namespace (uri) "Find a registered XML namespace identified by uri" (find uri *known-namespaces* :key #'get-uri :test #'string-equal)) (defun register-namespace (uri prefix package) "Register a new or redefine an existing XML namespace defined by uri with prefix and package" (let ((namespace (find-namespace uri))) (if namespace (setf (get-prefix namespace) prefix (get-package namespace) (find-package package)) (push (setf namespace (make-instance 'xml-namespace :uri uri :prefix prefix :package (find-package package))) *known-namespaces*)) namespace)) (defun find-namespace-binding (prefix namespaces) "Find the XML namespace currently bound to prefix in the namespaces bindings" (cdr (assoc prefix namespaces :test #'string-equal))) (defun split-identifier (identifier) "Split an identifier 'prefix:name' and return (values prefix name)" (when (symbolp identifier) (setf identifier (symbol-name identifier))) (let ((colon-position (position #\: identifier :test #'char=))) (if colon-position (values (subseq identifier 0 colon-position) (subseq identifier (1+ colon-position))) (values nil identifier)))) (defvar *require-existing-symbols* nil "If t, each XML identifier must exist as symbol already") (defvar *auto-export-symbols* t "If t, export newly interned symbols form their packages") (defun resolve-identifier (identifier namespaces &optional as-attribute) "Resolve the string identifier in the list of namespace bindings" (if *ignore-namespaces* (intern identifier :keyword) (flet ((intern-symbol (string package) ; intern string as a symbol in package (if *require-existing-symbols* (let ((symbol (find-symbol string package))) (or symbol (error "Symbol ~s does not exist in ~s" string package))) (let ((symbol (intern string package))) (when (and *auto-export-symbols* (not (eql package (find-package :keyword)))) (export symbol package)) symbol)))) (multiple-value-bind (prefix name) (split-identifier identifier) (if (or (null prefix) (string= prefix "xmlns")) (if as-attribute (intern (if (string= prefix "xmlns") identifier name) (get-package *local-namespace*)) (let ((default-namespace (find-namespace-binding "" namespaces))) (intern-symbol name (get-package default-namespace)))) (let ((namespace (find-namespace-binding prefix namespaces))) (if namespace (intern-symbol name (get-package namespace)) (error "namespace not found for prefix ~s" prefix)))))))) (defvar *auto-create-namespace-packages* t "If t, new packages will be created for namespaces, if needed, named by the prefix") (defun new-namespace (uri &optional prefix) "Register a new namespace for uri and prefix, creating a package if necessary" (if prefix (register-namespace uri prefix (or (find-package prefix) (if *auto-create-namespace-packages* (make-package prefix :nicknames `(,(string-upcase prefix))) (error "Cannot find or create package ~s" prefix)))) (let ((unique-name (loop :for i :upfrom 0 :do (let ((name (format nil "ns-~d" i))) (when (not (find-package name)) (return name)))))) (register-namespace uri unique-name (if *auto-create-namespace-packages* (make-package (string-upcase unique-name) :nicknames `(,unique-name)) (error "Cannot create package ~s" unique-name)))))) (defun extend-namespaces (attributes namespaces) "Given possible 'xmlns[:prefix]' attributes, extend the namespaces bindings" (unless *ignore-namespaces* (let (default-namespace-uri) (loop :for (key . value) :in attributes :do (if (string= key "xmlns") (setf default-namespace-uri value) (multiple-value-bind (prefix name) (split-identifier key) (when (string= prefix "xmlns") (let* ((uri value) (prefix name) (namespace (find-namespace uri))) (unless namespace (setf namespace (new-namespace uri prefix))) (push `(,prefix . ,namespace) namespaces)))))) (when default-namespace-uri (let ((namespace (find-namespace default-namespace-uri))) (unless namespace (setf namespace (new-namespace default-namespace-uri))) (push `("" . ,namespace) namespaces))))) namespaces) (defun print-identifier (identifier stream &optional as-attribute) "Print identifier on stream using namespace conventions" (declare (ignore as-attribute) (special *namespaces*)) (if *ignore-namespaces* (princ identifier stream) (if (symbolp identifier) (let ((package (symbol-package identifier)) (name (symbol-name identifier))) (let* ((namespace (find package *known-namespaces* :key #'get-package)) (prefix (or (car (find namespace *namespaces* :key #'cdr)) (get-prefix namespace)))) (if (string= prefix "") (princ name stream) (format stream "~a:~a" prefix name)))) (princ identifier stream)))) ;;; the parser state (defclass xml-parser-state () ((entities :documentation "A hashtable mapping XML entity names to their replacement stings" :accessor get-entities :initarg :entities :initform (make-standard-entities)) (seed :documentation "The user seed object" :accessor get-seed :initarg :seed :initform nil) (buffer :documentation "The main reusable character buffer" :accessor get-buffer :initform (make-extendable-string)) (mini-buffer :documentation "The secondary, smaller reusable character buffer" :accessor get-mini-buffer :initform (make-extendable-string)) (new-element-hook :documentation "Called when new element starts" ;; Handle the start of a new xml element with name and attributes, ;; receiving seed from previous element (sibling or parent) ;; return seed to be used for first child (content) ;; or directly to finish-element-hook :accessor get-new-element-hook :initarg :new-element-hook :initform #'(lambda (name attributes seed) (declare (ignore name attributes)) seed)) (finish-element-hook :documentation "Called when element ends" ;; Handle the end of an xml element with name and attributes, ;; receiving parent-seed, the seed passed to us when this element started, ;; i.e. passed to our corresponding new-element-hook ;; and receiving seed from last child (content) ;; or directly from new-element-hook ;; return final seed for this element to next element (sibling or parent) :accessor get-finish-element-hook :initarg :finish-element-hook :initform #'(lambda (name attributes parent-seed seed) (declare (ignore name attributes parent-seed)) seed)) (text-hook :documentation "Called when text is found" ;; Handle text in string, found as contents, ;; receiving seed from previous element (sibling or parent), ;; return final seed for this element to next element (sibling or parent) :accessor get-text-hook :initarg :text-hook :initform #'(lambda (string seed) (declare (ignore string)) seed))) (:documentation "The XML parser state passed along all code making up the parser")) (setf (documentation 'get-seed 'function) "Get the initial user seed of an XML parser state" (documentation 'get-entities 'function) "Get the entities hashtable of an XML parser state" (documentation 'get-new-element-hook 'function) "Get the new element hook of an XML parser state" (documentation 'get-finish-element-hook 'function) "Get the finish element hook of an XML parser state" (documentation 'get-text-hook 'function) "Get the text hook of an XML parser state") #-allegro (setf (documentation '(setf get-seed) 'function) "Set the initial user seed of an XML parser state" (documentation '(setf get-entities) 'function) "Set the entities hashtable of an XML parser state" (documentation '(setf get-new-element-hook) 'function) "Set the new element hook of an XML parser state" (documentation '(setf get-finish-element-hook) 'function) "Set the finish element hook of an XML parser state" (documentation '(setf get-text-hook) 'function) "Set the text hook of an XML parser state") (defmethod get-mini-buffer :after ((state xml-parser-state)) "Reset and return the reusable mini buffer" (with-slots (mini-buffer) state (setf (fill-pointer mini-buffer) 0))) (defmethod get-buffer :after ((state xml-parser-state)) "Reset and return the main reusable buffer" (with-slots (buffer) state (setf (fill-pointer buffer) 0))) ;;; parser support (defun parse-whitespace (stream extendable-string) "Read and collect XML whitespace from stream in string which is destructively modified, return first non-whitespace character which was peeked but not read, return nil on eof" (loop (let ((char (peek-char nil stream nil nil))) (if (and char (whitespace-char-p char)) (vector-push-extend (read-char stream) extendable-string) (return char))))) (defun parse-string (stream state &optional (string (make-extendable-string))) "Read and return an XML string from stream, delimited by either single or double quotes, the stream is expected to be on the opening delimiter, at the end the closing delimiter is also read, entities are resolved, eof before end of string is an error" (let ((delimiter (read-char stream nil nil)) (char)) (when (or (null delimiter) (not (or (char= delimiter #\') (char= delimiter #\")))) (error (parser-error "expected string delimiter" nil stream))) (loop (setf char (read-char stream nil nil)) (cond ((null char) (error (parser-error "encountered eof before end of string"))) ((char= char delimiter) (return)) ((char= char #\&) (resolve-entity stream string (get-entities state) (get-mini-buffer state))) (t (vector-push-extend char string)))) string)) (defun parse-text (stream state extendable-string) "Read and collect XML text from stream in string which is destructively modified, the text ends with a '<', which is peeked and returned, entities are resolved, eof is considered an error" (let (char) (loop (setf char (peek-char nil stream nil nil)) (when (null char) (error (parser-error "encountered unexpected eof in text"))) (when (char= char #\<) (return)) (read-char stream) (if (char= char #\&) (resolve-entity stream extendable-string (get-entities state) (get-mini-buffer state)) (vector-push-extend char extendable-string))) char)) (defun parse-identifier (stream &optional (identifier (make-extendable-string))) "Read and returns an XML identifier from stream, positioned at the start of the identifier, ending with the first non-identifier character, which is peeked, the identifier is written destructively into identifier which is also returned" (loop (let ((char (peek-char nil stream nil nil))) (cond ((and char (identifier-char-p char)) (read-char stream) (vector-push-extend char identifier)) (t (return identifier)))))) (defun skip-comment (stream) "Skip an XML comment in stream, positioned after the opening '<!--', consumes the closing '-->' sequence, unexpected eof or a malformed closing sequence result in a error" (let ((dashes-to-read 2)) (loop (if (zerop dashes-to-read) (return)) (let ((char (read-char stream nil nil))) (if (null char) (error (parser-error "encountered unexpected eof for comment"))) (if (char= char #\-) (decf dashes-to-read) (setf dashes-to-read 2))))) (if (char/= (read-char stream nil nil) #\>) (error (parser-error "expected > ending comment" nil stream)))) (defun read-cdata (stream state &optional (string (make-extendable-string))) "Reads in the CDATA and calls the callback for CDATA if it exists" ;; we already read the <![CDATA[ stuff ;; continue to read until we hit ]]> (let ((char #\space) (last-3-characters (list #\[ #\A #\T)) (pattern (list #\> #\] #\]))) (loop (setf char (read-char stream nil nil)) (when (null char) (error (parser-error "encountered unexpected eof in text"))) (push char last-3-characters) (setf (cdddr last-3-characters) nil) (cond ((equal last-3-characters pattern) (setf (fill-pointer string) (- (fill-pointer string) 2)) (setf (get-seed state) (funcall (get-text-hook state) (copy-seq string) (get-seed state))) (return-from read-cdata)) (t (vector-push-extend char string)))))) (defun skip-special-tag (stream state) "Skip an XML special tag (comments and processing instructions) in stream, positioned after the opening '<', unexpected eof is an error" ;; opening < has been read, consume ? or ! (read-char stream) (let ((char (read-char stream nil nil))) ;; see if we are dealing with a comment (when (char= char #\-) (setf char (read-char stream nil nil)) (when (char= char #\-) (skip-comment stream) (return-from skip-special-tag))) ;; maybe we are dealing with CDATA? (when (and (char= char #\[) (loop :for pattern :across "CDATA[" :for char = (read-char stream nil nil) :when (null char) :do (error (parser-error "encountered unexpected eof in cdata")) :always (char= char pattern))) (read-cdata stream state (get-buffer state)) (return-from skip-special-tag)) ;; loop over chars, dealing with strings (skipping their content) ;; and counting opening and closing < and > chars (let ((taglevel 1) (string-delimiter)) (loop (when (zerop taglevel) (return)) (setf char (read-char stream nil nil)) (when (null char) (error (parser-error "encountered unexpected eof for special (! or ?) tag" nil stream))) (if string-delimiter ;; inside a string we only look for a closing string delimiter (when (char= char string-delimiter) (setf string-delimiter nil)) ;; outside a string we count < and > and watch out for strings (cond ((or (char= char #\') (char= char #\")) (setf string-delimiter char)) ((char= char #\<) (incf taglevel)) ((char= char #\>) (decf taglevel)))))))) ;;; the XML parser proper (defun parse-xml-element-attributes (stream state) "Parse XML element attributes from stream positioned after the tag identifier, returning the attributes as an assoc list, ending at either a '>' or a '/' which is peeked and also returned" (declare (special *namespaces*)) (let (char attributes) (loop ;; skip whitespace separating items (setf char (skip-whitespace stream)) ;; start tag attributes ends with > or /> (when (and char (or (char= char #\>) (char= char #\/))) (return)) ;; read the attribute key (let ((key (copy-seq (parse-identifier stream (get-mini-buffer state))))) ;; skip separating whitespace (setf char (skip-whitespace stream)) ;; require = sign (and consume it if present) (if (and char (char= char #\=)) (read-char stream) (error (parser-error "expected =" nil stream))) ;; skip separating whitespace (skip-whitespace stream) ;; read the attribute value as a string (push (cons key (copy-seq (parse-string stream state (get-buffer state)))) attributes))) ;; return attributes peek char ending loop (values attributes char))) (defun parse-xml-element (stream state) "Parse and return an XML element from stream, positioned after the opening '<'" (declare (special *namespaces*)) ;; opening < has been read (when (char= (peek-char nil stream nil nil) #\!) (skip-special-tag stream state) (return-from parse-xml-element)) (let (char buffer open-tag parent-seed has-children) (setf parent-seed (get-seed state)) ;; read tag name (no whitespace between < and name ?) (setf open-tag (copy-seq (parse-identifier stream (get-mini-buffer state)))) ;; tag has been read, read attributes if any (multiple-value-bind (attributes peeked-char) (parse-xml-element-attributes stream state) (let ((*namespaces* (extend-namespaces attributes *namespaces*))) (setf open-tag (resolve-identifier open-tag *namespaces*) attributes (loop :for (key . value) :in attributes :collect (cons (resolve-identifier key *namespaces* t) value))) (setf (get-seed state) (funcall (get-new-element-hook state) open-tag attributes (get-seed state))) (setf char peeked-char) (when (char= char #\/) ;; handle solitary tag of the form <tag .. /> (read-char stream) (setf char (read-char stream nil nil)) (if (char= #\> char) (progn (setf (get-seed state) (funcall (get-finish-element-hook state) open-tag attributes parent-seed (get-seed state))) (return-from parse-xml-element)) (error (parser-error "expected >" nil stream)))) ;; consume > (read-char stream) (loop (setf buffer (get-buffer state)) ;; read whitespace into buffer (setf char (parse-whitespace stream buffer)) ;; see what ended the whitespace scan (cond ((null char) (error (parser-error "encountered unexpected eof handling ~a" (list open-tag)))) ((char= char #\<) ;; consume the < (read-char stream) (if (char= (peek-char nil stream nil nil) #\/) (progn ;; handle the matching closing tag </tag> and done ;; if we read whitespace as this (leaf) element's contents, it is significant (when (and (not has-children) (plusp (length buffer))) (setf (get-seed state) (funcall (get-text-hook state) (copy-seq buffer) (get-seed state)))) (read-char stream) (let ((close-tag (resolve-identifier (parse-identifier stream (get-mini-buffer state)) *namespaces*))) (unless (eq open-tag close-tag) (error (parser-error "found <~a> not matched by </~a> but by <~a>" (list open-tag open-tag close-tag) stream))) (unless (char= (read-char stream nil nil) #\>) (error (parser-error "expected >" nil stream))) (setf (get-seed state) (funcall (get-finish-element-hook state) open-tag attributes parent-seed (get-seed state)))) (return)) ;; handle child tag and loop, no hooks to call here ;; whitespace between child elements is skipped (progn (setf has-children t) (parse-xml-element stream state)))) (t ;; no child tag, concatenate text to whitespace in buffer ;; handle text content and loop (setf char (parse-text stream state buffer)) (setf (get-seed state) (funcall (get-text-hook state) (copy-seq buffer) (get-seed state)))))))))) (defun start-parse-xml (stream &optional (state (make-instance 'xml-parser-state))) "Parse and return a toplevel XML element from stream, using parser state" (loop (let ((char (skip-whitespace stream))) (when (null char) (return-from start-parse-xml)) ;; skip whitespace until start tag (unless (char= char #\<) (error (parser-error "expected <" nil stream))) (read-char stream) ; consume peeked char (setf char (peek-char nil stream nil nil)) (if (or (char= char #\!) (char= char #\?)) ;; deal with special tags (skip-special-tag stream state) (progn ;; read the main element (parse-xml-element stream state) (return-from start-parse-xml (get-seed state))))))) ;;;; eof
29,560
Common Lisp
.lisp
592
40.059122
112
0.616432
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8cbbdafff4de044fda61a19990507b7e1535c6eff8196936f2cf0325b3c96334
19,223
[ 59130 ]
19,224
sxml-dom.lisp
Eggy115_Lisp/s-xml/src/sxml-dom.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: sxml-dom.lisp,v 1.5 2005/11/20 14:34:15 scaekenberghe Exp $ ;;;; ;;;; LXML implementation of the generic DOM parser and printer. ;;;; ;;;; Copyright (C) 2003, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) ;;; the sxml hooks to generate sxml (defun sxml-new-element-hook (name attributes seed) (declare (ignore name attributes seed)) '()) (defun sxml-finish-element-hook (name attributes parent-seed seed) (let ((xml-element (append (list name) (when attributes (list (let (list) (dolist (attribute attributes (cons :@ list)) (push (list (car attribute) (cdr attribute)) list))))) (nreverse seed)))) (cons xml-element parent-seed))) (defun sxml-text-hook (string seed) (cons string seed)) ;;; the standard DOM interfaces (defmethod parse-xml-dom (stream (output-type (eql :sxml))) (car (start-parse-xml stream (make-instance 'xml-parser-state :new-element-hook #'sxml-new-element-hook :finish-element-hook #'sxml-finish-element-hook :text-hook #'sxml-text-hook)))) (defmethod print-xml-dom (dom (input-type (eql :sxml)) stream pretty level) (declare (special *namespaces*)) (cond ((stringp dom) (print-string-xml dom stream)) ((consp dom) (let ((tag (first dom)) attributes children) (if (and (consp (second dom)) (eq (first (second dom)) :@)) (setf attributes (rest (second dom)) children (rest (rest dom))) (setf children (rest dom))) (let ((*namespaces* (extend-namespaces (loop :for (name value) :in attributes :collect (cons name value)) *namespaces*))) (write-char #\< stream) (print-identifier tag stream) (loop :for (name value) :in attributes :do (print-attribute name value stream)) (if children (progn (write-char #\> stream) (if (and (= (length children) 1) (stringp (first children))) (print-string-xml (first children) stream) (progn (dolist (child children) (when pretty (print-spaces (* 2 level) stream)) (if (stringp child) (print-string-xml child stream) (print-xml-dom child input-type stream pretty (1+ level)))) (when pretty (print-spaces (* 2 (1- level)) stream)))) (print-closing-tag tag stream)) (write-string "/>" stream))))) (t (error "Input not recognized as SXML ~s" dom)))) ;;;; eof
3,089
Common Lisp
.lisp
67
34.641791
90
0.557923
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c41dbef98403147731456fb82a223c1bb9c4b1e8fe53ef5c3e9bb5b7f2198adb
19,224
[ 83459 ]
19,226
xml-struct-dom.lisp
Eggy115_Lisp/s-xml/src/xml-struct-dom.lisp
;;;; -*- mode: lisp -*- ;;;; ;;;; $Id: xml-struct-dom.lisp,v 1.3 2005/09/20 09:57:48 scaekenberghe Exp $ ;;;; ;;;; XML-STRUCT implementation of the generic DOM parser and printer. ;;;; ;;;; Copyright (C) 2002, 2004 Sven Van Caekenberghe, Beta Nine BVBA. ;;;; ;;;; You are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser General Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. (in-package :s-xml) ;;; xml-element struct datastructure and API (defstruct xml-element name ; :tag-name attributes ; a assoc list of (:attribute-name . "attribute-value") children ; a list of children/content either text strings or xml-elements ) (setf (documentation 'xml-element-p 'function) "Return T when the argument is an xml-element struct" (documentation 'xml-element-attributes 'function) "Return the alist of attribute names and values dotted pairs from an xml-element struct" (documentation 'xml-element-children 'function) "Return the list of children from an xml-element struct" (documentation 'xml-element-name 'function) "Return the name from an xml-element struct" (documentation 'make-xml-element 'function) "Make and return a new xml-element struct") (defun xml-element-attribute (xml-element key) "Return the string value of the attribute with name the keyword :key of xml-element if any, return null if not found" (let ((pair (assoc key (xml-element-attributes xml-element) :test #'eq))) (when pair (cdr pair)))) (defun (setf xml-element-attribute) (value xml-element key) "Set the string value of the attribute with name the keyword :key of xml-element, creating a new attribute if necessary or overwriting an existing one, returning the value" (let ((attributes (xml-element-attributes xml-element))) (if (null attributes) (push (cons key value) (xml-element-attributes xml-element)) (let ((pair (assoc key attributes :test #'eq))) (if pair (setf (cdr pair) value) (push (cons key value) (xml-element-attributes xml-element))))) value)) (defun new-xml-element (name &rest children) "Make a new xml-element with name and children" (make-xml-element :name name :children children)) (defun first-xml-element-child (xml-element) "Get the first child of an xml-element" (first (xml-element-children xml-element))) (defun xml-equal (xml-1 xml-2) (and (xml-element-p xml-1) (xml-element-p xml-2) (eq (xml-element-name xml-1) (xml-element-name xml-2)) (equal (xml-element-attributes xml-1) (xml-element-attributes xml-2)) (reduce #'(lambda (&optional (x t) (y t)) (and x y)) (mapcar #'(lambda (x y) (or (and (stringp x) (stringp y) (string= x y)) (xml-equal x y))) (xml-element-children xml-1) (xml-element-children xml-2))))) ;;; printing xml structures (defmethod print-xml-dom (xml-element (input-type (eql :xml-struct)) stream pretty level) (declare (special *namespaces*)) (let ((*namespaces* (extend-namespaces (xml-element-attributes xml-element) *namespaces*))) (write-char #\< stream) (print-identifier (xml-element-name xml-element) stream) (loop :for (name . value) :in (xml-element-attributes xml-element) :do (print-attribute name value stream)) (let ((children (xml-element-children xml-element))) (if children (progn (write-char #\> stream) (if (and (= (length children) 1) (stringp (first children))) (print-string-xml (first children) stream) (progn (dolist (child children) (when pretty (print-spaces (* 2 level) stream)) (if (stringp child) (print-string-xml child stream) (print-xml-dom child input-type stream pretty (1+ level)))) (when pretty (print-spaces (* 2 (1- level)) stream)))) (print-closing-tag (xml-element-name xml-element) stream)) (write-string "/>" stream))))) ;;; the standard hooks to generate xml-element structs (defun standard-new-element-hook (name attributes seed) (declare (ignore name attributes seed)) '()) (defun standard-finish-element-hook (name attributes parent-seed seed) (let ((xml-element (make-xml-element :name name :attributes attributes :children (nreverse seed)))) (cons xml-element parent-seed))) (defun standard-text-hook (string seed) (cons string seed)) ;;; top level standard parser interfaces (defmethod parse-xml-dom (stream (output-type (eql :xml-struct))) (car (start-parse-xml stream (make-instance 'xml-parser-state :new-element-hook #'standard-new-element-hook :finish-element-hook #'standard-finish-element-hook :text-hook #'standard-text-hook)))) ;;;; eof
5,111
Common Lisp
.lisp
107
40.392523
95
0.652375
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9cffaded928f8a64568b5cd2c84760b52b791db67abc057c583da0a600777142
19,226
[ 246329 ]
19,227
util.lisp
Eggy115_Lisp/drakma-1.2.3/util.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/util.lisp,v 1.36 2008/05/30 11:30:45 edi Exp $ ;;; Copyright (c) 2006-2010, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) #+:lispworks (require "comm") #+:lispworks (eval-when (:compile-toplevel :load-toplevel :execute) (import 'lw:when-let)) #-:lispworks (defmacro when-let ((var expr) &body body) "Evaluates EXPR, binds it to VAR, and executes BODY if VAR has a true value." `(let ((,var ,expr)) (when ,var ,@body))) #+:lispworks (eval-when (:compile-toplevel :load-toplevel :execute) (import 'lw:with-unique-names)) #-:lispworks (defmacro with-unique-names ((&rest bindings) &body body) "Syntax: WITH-UNIQUE-NAMES ( { var | (var x) }* ) declaration* form* Executes a series of forms with each VAR bound to a fresh, uninterned symbol. The uninterned symbol is as if returned by a call to GENSYM with the string denoted by X - or, if X is not supplied, the string denoted by VAR - as argument. The variable bindings created are lexical unless special declarations are specified. The scopes of the name bindings and declarations do not include the Xs. The forms are evaluated in order, and the values of all but the last are discarded \(that is, the body is an implicit PROGN)." ;; reference implementation posted to comp.lang.lisp as ;; <[email protected]> by Vebjorn Ljosa - see also ;; <http://www.cliki.net/Common%20Lisp%20Utilities> `(let ,(mapcar #'(lambda (binding) (check-type binding (or cons symbol)) (if (consp binding) (destructuring-bind (var x) binding (check-type var symbol) `(,var (gensym ,(etypecase x (symbol (symbol-name x)) (character (string x)) (string x))))) `(,binding (gensym ,(symbol-name binding))))) bindings) ,@body)) (defun ends-with-p (seq suffix &key (test #'char-equal)) "Returns true if the sequence SEQ ends with the sequence SUFFIX. Individual elements are compared with TEST." (let ((mismatch (mismatch seq suffix :from-end t :test test))) (or (null mismatch) (= mismatch (- (length seq) (length suffix)))))) (defun starts-with-p (seq prefix &key (test #'char-equal)) "Returns true if the sequence SEQ starts with the sequence PREFIX whereby the elements are compared using TEST." (let ((mismatch (mismatch seq prefix :test test))) (or (null mismatch) (= mismatch (length prefix))))) (defun url-encode (string external-format) "Returns a URL-encoded version of the string STRING using the LispWorks external format EXTERNAL-FORMAT." (with-output-to-string (out) (loop for octet across (string-to-octets (or string "") :external-format external-format) for char = (code-char octet) do (cond ((or (char<= #\0 char #\9) (char<= #\a char #\z) (char<= #\A char #\Z) (find char "$-_.!*'()," :test #'char=)) (write-char char out)) ((char= char #\Space) (write-char #\+ out)) (t (format out "%~2,'0x" (char-code char))))))) (defun alist-to-url-encoded-string (alist external-format) "ALIST is supposed to be an alist of name/value pairs where both names and values are strings \(or, for values, NIL). This function returns a string where this list is represented as for the content type `application/x-www-form-urlencoded', i.e. the values are URL-encoded using the external format EXTERNAL-FORMAT, the pairs are joined with a #\\& character, and each name is separated from its value with a #\\= character. If the value is NIL, no #\\= is used." (with-output-to-string (out) (loop for first = t then nil for (name . value) in alist unless first do (write-char #\& out) do (format out "~A~:[~;=~A~]" (url-encode name external-format) value (url-encode value external-format))))) (defun default-port (uri) "Returns the default port number for the \(PURI) URI URI. Works only with the http and https schemes." (ecase (uri-scheme uri) (:http 80) (:https 443))) (defun non-default-port (uri) "If the \(PURI) URI specifies an explicit port number which is different from the default port its scheme, this port number is returned, otherwise NIL." (when-let (port (uri-port uri)) (when (/= port (default-port uri)) port))) (defun user-agent-string (token) "Returns a corresponding user agent string if TOKEN is one of the keywords :DRAKMA, :FIREFOX, :EXPLORER, :OPERA, or :SAFARI. Returns TOKEN itself otherwise." (case token (:drakma (format nil "Drakma/~A (~A~@[ ~A~]; ~A;~@[ ~A;~] http://weitz.de/drakma/)" *drakma-version-string* (or (lisp-implementation-type) "Common Lisp") (or (lisp-implementation-version) "") (or #-:clisp (software-type) #+(or :win32 :mswindows) "Windows" #-(or :win32 :mswindows) "Unix") (or #-:clisp (software-version)))) (:firefox "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6") (:explorer "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)") (:opera "Opera/9.01 (Windows NT 5.1; U; en)") (:safari "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/418.8 (KHTML, like Gecko) Safari/419.3") (otherwise token))) (defun header-value (name headers) "If HEADERS is an alist of headers as returned by HTTP-REQUEST and NAME is a keyword naming a header, this function returns the corresponding value of this header \(or NIL if it's not in HEADERS)." (cdr (assoc name headers :test #'eq))) (defun parameter-present-p (name parameters) "If PARAMETERS is an alist of parameters as returned by, for example, READ-TOKENS-AND-PARAMETERS and NAME is a string naming a parameter, this function returns the full parameter \(name and value) - or NIL if it's not in PARAMETERS." (assoc name parameters :test #'string-equal)) (defun parameter-value (name parameters) "If PARAMETERS is an alist of parameters as returned by, for example, READ-TOKENS-AND-PARAMETERS and NAME is a string naming a parameter, this function returns the value of this parameter - or NIL if it's not in PARAMETERS." (cdr (parameter-present-p name parameters))) (defun make-random-string (&optional (length 50)) "Generates and returns a random string length LENGTH. The string will consist solely of decimal digits and ASCII letters." (with-output-to-string (s) (dotimes (i length) (write-char (ecase (random 5) ((0 1) (code-char (+ #.(char-code #\a) (random 26)))) ((2 3) (code-char (+ #.(char-code #\A) (random 26)))) ((4) (code-char (+ #.(char-code #\0) (random 10))))) s)))) (defun split-string (string &optional (separators " ,-")) "Splits STRING into a list of substrings \(which is returned) separated by the characters in the sequence SEPARATORS. Empty substrings aren't collected." (flet ((make-collector () (make-array 0 :adjustable t :fill-pointer t :element-type #+:lispworks 'lw:simple-char #-:lispworks 'character))) (loop with collector = (make-collector) for char across string for counter downfrom (1- (length string)) when (find char separators :test #'char=) when (plusp (length collector)) collect collector and do (setq collector (make-collector)) end else do (vector-push-extend char collector) and when (zerop counter) collect collector))) (defun safe-parse-integer (string) "Like PARSE-INTEGER, but returns NIL instead of signalling an error." (ignore-errors (parse-integer string))) (defun interpret-as-month (string) "Tries to interpret STRING as a string denoting a month and returns the corresponding number of the month. Accepts three-letter abbreviations like \"Feb\" and full month names likes \"February\". Finally, the function also accepts strings representing integers from one to twelve." (or (when-let (pos (position (subseq string 0 (min 3 (length string))) '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec") :test #'string=)) (1+ pos)) (when-let (num (safe-parse-integer string)) (when (<= 1 num 12) num)))) (defun interpret-as-time-zone (string) "Tries to interpret STRING as a time zone abbreviation which can either be something like \"PST\" or \"GMT\" with an offset like \"GMT-02:00\"." (when-let (zone (cdr (assoc string *time-zone-map* :test #'string=))) (return-from interpret-as-time-zone zone)) (unless (and (= (length string) 9) (starts-with-p string "GMT") (find (char string 3) "+-" :test #'char=) (char= (char string 6) #\:) (every (lambda (pos) (digit-char-p (char string pos))) '(4 5 7 8))) (cookie-date-parse-error "Can't interpret ~S as a time zone." string)) (let ((hours (parse-integer string :start 4 :end 6)) (minutes (parse-integer string :start 7 :end 9))) (* (if (char= (char string 3) #\+) -1 1) (+ hours (/ minutes 60))))) (defun set-referer (referer-uri &optional alist) "Returns a fresh copy of the HTTP header list ALIST with the `Referer' header set to REFERER-URI. If REFERER-URI is NIL, the result will be a list of headers without a `Referer' header." (let ((alist-sans-referer (remove "Referer" alist :key #'car :test #'string=))) (cond (referer-uri (acons "Referer" referer-uri alist-sans-referer)) (t alist-sans-referer)))) (defun text-content-type-p (type subtype) "Returns a true value iff the combination of TYPE and SUBTYPE matches an entry of *TEXT-CONTENT-TYPES*. See docstring of *TEXT-CONTENT-TYPES* for more info." (loop for (candidate-type . candidate-subtype) in *text-content-types* thereis (and (or (null candidate-type) (string-equal type candidate-type)) (or (null candidate-subtype) (string-equal subtype candidate-subtype))))) (defmacro with-sequence-from-string ((stream string) &body body) "Kludge to make Chunga tokenizing functionality usable. Works like WITH-INPUT-FROM-STRING, but creates a sequence of octets that works with CHUNGA::PEEK-CHAR* and friends." `(flex:with-input-from-sequence (,stream (map 'list #'char-code ,string)) ,@body)) (defun split-set-cookie-string (string) "Splits the string STRING which is assumed to be the value of a `Set-Cookie' into parts corresponding to individual cookies and returns a list of these parts \(substrings). The string /should/ be split at commas, but heuristical approach is used instead which doesn't split at commas which are followed by what cannot be recognized as the start of the next cookie. This is necessary because servers send headers containing unquoted commas which are not meant as separators." ;; this would of course be a lot easier with CL-PPCRE's SPLIT (let ((cookie-start 0) (string-length (length string)) search-start result) (tagbody ;; at this point we know that COOKIE-START is the start of a new ;; cookie (at the start of the string or behind a comma) next-cookie (setq search-start cookie-start) ;; we reach this point if the last comma didn't separate two ;; cookies or if there was no previous comma skip-comma (unless (< search-start string-length) (return-from split-set-cookie-string (nreverse result))) ;; look is there's a comma (let* ((comma-pos (position #\, string :start search-start)) ;; and if so, look for a #\= behind the comma (equals-pos (and comma-pos (position #\= string :start comma-pos))) ;; check that (except for whitespace) there's only a token ;; (the name of the next cookie) between #\, and #\= (new-cookie-start-p (and equals-pos (every 'token-char-p (trim-whitespace string :start (1+ comma-pos) :end equals-pos))))) (when (and comma-pos (not new-cookie-start-p)) (setq search-start (1+ comma-pos)) (go skip-comma)) (let ((end-pos (or comma-pos string-length))) (push (trim-whitespace (subseq string cookie-start end-pos)) result) (setq cookie-start (1+ end-pos)) (go next-cookie)))))) #-:lispworks (defun make-ssl-stream (http-stream) "Attaches SSL to the stream HTTP-STREAM and returns the SSL stream \(which will not be equal to HTTP-STREAM)." #+:allegro (socket:make-ssl-client-stream http-stream) #-:allegro (let ((s http-stream)) (cl+ssl:make-ssl-client-stream (cl+ssl:stream-fd s) :close-callback (lambda () (close s)))))
15,445
Common Lisp
.lisp
304
41.720395
106
0.624602
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ce3fa50c04756b3fbafda7d8743fe8a182ef660e05051ca95b058ad151e260e6
19,227
[ -1 ]
19,228
specials.lisp
Eggy115_Lisp/drakma-1.2.3/specials.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/specials.lisp,v 1.19 2008/01/14 01:57:02 edi Exp $ ;;; Copyright (c) 2006-2010, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (defmacro define-constant (name value &optional doc) "A version of DEFCONSTANT for, cough, /strict/ CL implementations." ;; See <http://www.sbcl.org/manual/Defining-Constants.html> `(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value) ,@(when doc (list doc)))) (define-constant +latin-1+ (make-external-format :latin-1 :eol-style :lf) "Default external format when reading headers.") (define-constant +redirect-codes+ '(301 302 303 307) "A list of all HTTP return codes that redirect us to another URI.") (define-constant +known-methods+ '(:copy :delete :delete :get :head :lock :mkcol :move :options :options* :patch :post :propfind :proppatch :put :trace :unlock) "The HTTP methods \(including WebDAV methods) Drakma knows.") (defconstant +buffer-size+ 8192) (defvar *drakma-default-external-format* ':latin-1 "The default value for the external format keyword arguments of HTTP-REQUEST.") (defvar *header-stream* nil "If this variable is not NIL, it should be bound to a stream to which incoming and outgoing headers will be written for debugging purposes.") (defvar *allow-dotless-cookie-domains-p* nil "When this variable is not NIL, cookie domains containing no dots are considered valid. The default is NIL, meaning to disallow such domains except for \"localhost\".") (defvar *ignore-unparseable-cookie-dates-p* nil "Whether Drakma is allowed to treat `Expires' dates in cookie headers as non-existent if it can't parse them. If the value of this variable is NIL \(which is the default), an error will be signalled instead.") (defvar *remove-duplicate-cookies-p* t "Determines how duplicate cookies are handled. Valid values are NIL \(duplicates will not be removed), :KEEP-LAST or T \(for duplicates, only the last cookie value will be kept based on the order of the response header), or :KEEP-FIRST (only the first value will be kept).") (defvar *text-content-types* '(("text" . nil)) "A list of conses which are used by DETERMINE-BODY-FORMAT to decide whether a `Content-Type' header denotes text content. The car and cdr of each cons should each be a string or NIL. A content type matches one of these entries \(and thus denotes text) if the type part is STRING-EQUAL to the car or if the car is NIL and if the subtype part is STRING-EQUAL to the cdr or if the cdr is NIL.") (defvar *body-format-function* 'determine-body-format "A function which determines whether the content body returned by the server is text and should be treated as such or not. The function is called after the request headers have been read and it must accept two arguments, HEADERS and EXTERNAL-FORMAT-IN where HEADERS is like the third return value of HTTP-REQUEST while EXTERNAL-FORMAT-IN is the HTTP-REQUEST argument of the same name. It should return NIL if the body should be regarded as binary content, or a FLEXI-STREAMS external format \(which will be used to read the body) otherwise. This function will only be called if the FORCE-BINARY argument to HTTP-REQUEST was NIL.") (defvar *time-zone-map* ;; list taken from ;; <http://www.timeanddate.com/library/abbreviations/timezones/> '(("A" . -1) ("ACDT" . -10.5) ("ACST" . -9.5) ("ADT" . 3) ("AEDT" . -11) ("AEST" . -10) ("AKDT" . 8) ("AKST" . 9) ("AST" . 4) ("AWDT" . -9) ("AWST" . -8) ("B" . -2) ("BST" . -1) ("C" . -3) ("CDT" . 5) ("CEDT" . -2) ("CEST" . -2) ("CET" . -1) ("CST" . -10.5) ("CST" . -9.5) ("CST" . 6) ("CXT" . -7) ("D" . -4) ("E" . -5) ("EDT" . 4) ("EEDT" . -3) ("EEST" . -3) ("EET" . -2) ("EST" . -11) ("EST" . -10) ("EST" . 5) ("F" . -6) ("G" . -7) ("GMT" . 0) ("H" . -8) ("HAA" . 3) ("HAC" . 5) ("HADT" . 9) ("HAE" . 4) ("HAP" . 7) ("HAR" . 6) ("HAST" . 10) ("HAT" . 2.5) ("HAY" . 8) ("HNA" . 4) ("HNC" . 6) ("HNE" . 5) ("HNP" . 8) ("HNR" . 7) ("HNT" . 3.5) ("HNY" . 9) ("I" . -9) ("IST" . -1) ("K" . -10) ("L" . -11) ("M" . -12) ("MDT" . 6) ("MESZ" . -2) ("MEZ" . -1) ("MST" . 7) ("N" . 1) ("NDT" . 2.5) ("NFT" . -11.5) ("NST" . 3.5) ("O" . 2) ("P" . 3) ("PDT" . 7) ("PST" . 8) ("Q" . 4) ("R" . 5) ("S" . 6) ("T" . 7) ("U" . 8) ("UTC" . 0) ("V" . 9) ("W" . 10) ("WEDT" . -1) ("WEST" . -1) ("WET" . 0) ("WST" . -9) ("WST" . -8) ("X" . 11) ("Y" . 12) ("Z" . 0)) "An alist which maps time zone abbreviations to Common Lisp timezones.") ;; stuff for Nikodemus Siivola's HYPERDOC ;; see <http://common-lisp.net/project/hyperdoc/> ;; and <http://www.cliki.net/hyperdoc> ;; also used by LW-ADD-ONS (defvar *hyperdoc-base-uri* "http://weitz.de/drakma/") (let ((exported-symbols-alist (loop for symbol being the external-symbols of :drakma collect (cons symbol (concatenate 'string "#" (string-downcase symbol)))))) (defun hyperdoc-lookup (symbol type) (declare (ignore type)) (cdr (assoc symbol exported-symbols-alist :test #'eq))))
7,606
Common Lisp
.lisp
197
30.705584
89
0.577866
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f7440660b49413752e4f3651004b1fc27ce55985e342b82c909f43f63c28e8fe
19,228
[ -1 ]
19,229
read.lisp
Eggy115_Lisp/drakma-1.2.3/read.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/read.lisp,v 1.17 2008/05/25 11:35:20 edi Exp $ ;;; Copyright (c) 2006-2010, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (defun read-status-line (stream &optional log-stream) "Reads one line from STREAM \(using Chunga's READ-LINE*) and interprets it as a HTTP status line. Returns a list of two or three values - the protocol \(HTTP version) as a keyword, the status code as an integer, and optionally the reason phrase." (let* ((*current-error-message* "While reading status line:") (line (or (read-line* stream log-stream) (error 'drakma-simple-error :format-control "No status line - probably network error."))) (first-space-pos (or (position #\Space line :test #'char=) (syntax-error "No space in status line ~S." line))) (second-space-pos (position #\Space line :test #'char= :start (1+ first-space-pos)))) (list (cond ((string-equal line "HTTP/1.0" :end1 first-space-pos) :http/1.0) ((string-equal line "HTTP/1.1" :end1 first-space-pos) :http/1.1) (t (syntax-error "Unknown protocol in ~S." line))) (or (ignore-errors (parse-integer line :start (1+ first-space-pos) :end second-space-pos)) (syntax-error "Status code in ~S is not an integer." line)) (and second-space-pos (subseq line (1+ second-space-pos)))))) (defun get-content-type (headers) "Reads and parses a `Content-Type' header and returns it as three values - the type, the subtype, and an alist \(possibly empty) of name/value pairs for the optional parameters. HEADERS is supposed to be an alist of headers as returned by HTTP-REQUEST. Returns NIL if there is no such header amongst HEADERS." (when-let (content-type (header-value :content-type headers)) (with-sequence-from-string (stream content-type) (let* ((*current-error-message* "Corrupted Content-Type header:") (type (read-token stream)) (subtype (and (assert-char stream #\/) (read-token stream))) (parameters (read-name-value-pairs stream))) (values type subtype parameters))))) (defun read-token-and-parameters (stream) "Reads and returns \(as a two-element list) from STREAM a token and an optional list of parameters \(attribute/value pairs) following the token." (skip-whitespace stream) (list (read-token stream) (read-name-value-pairs stream))) (defun skip-more-commas (stream) "Reads and consumes from STREAM any number of commas and whitespace. Returns the following character or NIL in case of END-OF-FILE." (loop while (eql (peek-char* stream nil) #\,) do (read-char* stream) (skip-whitespace stream)) (skip-whitespace stream)) (defun read-tokens-and-parameters (string &key (value-required-p t)) "Reads a comma-separated list of tokens from the string STRING. Each token can be followed by an optional, semicolon-separated list of attribute/value pairs where the attributes are tokens followed by a #\\= character and a token or a quoted string. Returned is a list where each element is either a string \(for a simple token) or a cons of a string \(the token) and an alist \(the attribute/value pairs). If VALUE-REQUIRED-P is NIL, the value part \(including the #\\= character) of each attribute/value pair is optional." (with-sequence-from-string (stream string) (loop with *current-error-message* = (format nil "While parsing ~S:" string) for first = t then nil for next = (and (skip-whitespace stream) (or first (assert-char stream #\,)) (skip-whitespace stream) (skip-more-commas stream)) for token = (and next (read-token stream)) for parameters = (and token (read-name-value-pairs stream :value-required-p value-required-p)) while token collect (if parameters (cons token parameters) token)))) (defun split-tokens (string) "Splits the string STRING into a list of substrings separated by commas and optional whitespace. Empty substrings are ignored." (loop for old-position = -1 then position for position = (and old-position (position #\, string :test #'char= :start (1+ old-position))) for substring = (and old-position (trim-whitespace (subseq string (1+ old-position) position))) while old-position when (plusp (length substring)) collect substring))
6,335
Common Lisp
.lisp
110
48.209091
92
0.648121
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7d75719f344617ffa1e298941b81c06727f14e721e515d5e78e4d6070f2882ca
19,229
[ -1 ]
19,230
conditions.lisp
Eggy115_Lisp/drakma-1.2.3/conditions.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: ODD-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/odd-streams/conditions.lisp,v 1.5 2007/12/31 01:08:45 edi Exp $ ;;; Copyright (c) 2008-2010, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (define-condition drakma-condition (condition) () (:documentation "Superclass for all conditions related to Drakma.")) (define-condition drakma-error (drakma-condition error) () (:documentation "Superclass for all errors related to Drakma.")) (define-condition drakma-simple-error (drakma-error simple-condition) () (:documentation "Like DRAKMA-ERROR but with formatting capabilities.")) (define-condition drakma-warning (drakma-condition warning) () (:documentation "Superclass for all warnings related to Drakma.")) (define-condition drakma-simple-warning (drakma-warning simple-condition) () (:documentation "Like DRAKMA-WARNING but with formatting capabilities.")) (defun drakma-warn (format-control &rest format-arguments) "Signals a warning of type DRAKMA-SIMPLE-WARNING with the provided format control and arguments." (warn 'drakma-simple-warning :format-control format-control :format-arguments format-arguments)) (define-condition parameter-error (drakma-simple-error) () (:documentation "Signalled if a function was called with inconsistent or illegal parameters.")) (defun parameter-error (format-control &rest format-arguments) "Signals an error of type PARAMETER-ERROR with the provided format control and arguments." (error 'parameter-error :format-control format-control :format-arguments format-arguments)) (define-condition syntax-error (drakma-simple-error) () (:documentation "Signalled if Drakma encounters wrong or unknown syntax when reading the reply from the server.")) (defun syntax-error (format-control &rest format-arguments) "Signals an error of type SYNTAX-ERROR with the provided format control and arguments." (error 'syntax-error :format-control format-control :format-arguments format-arguments)) (define-condition cookie-error (drakma-simple-error) ((cookie :initarg :cookie :initform nil :reader cookie-error-cookie :documentation "The COOKIE object that provoked this error. Can be NIL in case such an object couldn't be initialized.")) (:documentation "Signalled if someone tries to create a COOKIE object that's not valid.")) (defun cookie-error (cookie format-control &rest format-arguments) "Signals an error of type COOKIE-ERROR with the provided cookie \(can be NIL), format control and arguments." (error 'cookie-error :cookie cookie :format-control format-control :format-arguments format-arguments)) (define-condition cookie-date-parse-error (cookie-error) () (:documentation "Signalled if Drakma tries to parse the date of an incoming cookie header and can't interpret it.")) (defun cookie-date-parse-error (format-control &rest format-arguments) "Signals an error of type COOKIE-DATE-PARSE-ERROR with the provided format control and arguments." (error 'cookie-date-parse-error :format-control format-control :format-arguments format-arguments))
4,650
Common Lisp
.lisp
89
47.707865
95
0.743641
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3baa273ea05f9b9ba40fe6f73bd8e354b78b17a4bfb799da9f65de93f0d16526
19,230
[ -1 ]
19,231
cookies.lisp
Eggy115_Lisp/drakma-1.2.3/cookies.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/cookies.lisp,v 1.15 2008/01/14 01:57:01 edi Exp $ ;;; Copyright (c) 2006-2010, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (defclass cookie () ((name :initarg :name :initform (cookie-error nil "A cookie must have a name.") :accessor cookie-name :documentation "The name of the cookie.") (value :initarg :value :initform "" :accessor cookie-value :documentation "The cookie's value.") (domain :initarg :domain :initform (cookie-error nil "A cookie must have a domain.") :accessor cookie-domain :documentation "The domain the cookie is valid for.") (path :initarg :path :initform "/" :accessor cookie-path :documentation "The path prefix the cookie is valid for.") (expires :initarg :expires :initform nil :accessor cookie-expires :documentation "When the cookie expires. A Lisp universal time or NIL.") (securep :initarg :securep :initform nil :accessor cookie-securep :documentation "Whether the cookie must only be transmitted over secure connections.") (http-only-p :initarg :http-only-p :initform nil :accessor cookie-http-only-p :documentation "Whether the cookie should not be accessible from Javascript. This is a Microsoft extension that has been implemented in Firefox as well. See <http://msdn2.microsoft.com/en-us/library/ms533046.aspx>.")) (:documentation "Elements of this class represent HTTP cookies.")) (defun render-cookie-date (time) "Returns a string representation of the universal time TIME which can be used for cookie headers." (multiple-value-bind (second minute hour date month year weekday) (decode-universal-time time 0) (format nil "~A, ~2,'0d-~2,'0d-~4,'0d ~2,'0d:~2,'0d:~2,'0d GMT" (aref #("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun") weekday) date month year hour minute second))) (defmethod print-object ((cookie cookie) stream) "Prints a representation of COOKIE similar to a `Set-Cookie' header." (print-unreadable-object (cookie stream :type t) (with-slots (name value expires path domain securep http-only-p) cookie (format stream "~A~@[=~A~]~@[; expires=~A~]~@[; path=~A~]~@[; domain=~A~]~@[; secure~]~@[; HttpOnly~]" name (and (plusp (length value)) value) (and expires (render-cookie-date expires)) path domain securep http-only-p)))) (defun normalize-cookie-domain (domain) "Adds a dot at the beginning of the string DOMAIN unless there is already one." (cond ((starts-with-p domain ".") domain) (t (format nil ".~A" domain)))) (defun valid-cookie-domain-p (domain) "Checks if the string DOMAIN contains enough dots to be acceptable. If *ALLOW-DOTLESS-COOKIE-DOMAINS-P* is non-NIL, every domain name is considered acceptable." (or *allow-dotless-cookie-domains-p* (string-equal domain "localhost") (> (count #\. (normalize-cookie-domain domain) :test #'char=) 1))) (defun cookie-domain-matches (domain uri) "Checks if the domain DOMAIN \(a string) matches the \(PURI) URI URI." (ends-with-p (normalize-cookie-domain (uri-host uri)) (normalize-cookie-domain domain))) (defun send-cookie-p (cookie uri force-ssl) "Checks if the cookie COOKIE should be sent to the server depending on the \(PURI) URI URI and the value of FORCE-SSL \(as in HTTP-REQUEST)." (and ;; check domain (cookie-domain-matches (cookie-domain cookie) uri) ;; check path (starts-with-p (or (uri-path uri) "/") (cookie-path cookie)) ;; check expiry date (let ((expires (cookie-expires cookie))) (or (null expires) (> expires (get-universal-time)))) ;; check if connection must be secure (or (null (cookie-securep cookie)) force-ssl (eq (uri-scheme uri) :https)))) (defun check-cookie (cookie) "Checks if the slots of the COOKIE object COOKIE have valid values and raises a corresponding error of type COOKIE-ERROR otherwise." (with-slots (name value domain path expires) cookie (unless (and (stringp name) (plusp (length name))) (cookie-error cookie "Cookie name ~S must be a non-empty string." name)) (unless (stringp value) (cookie-error cookie "Cookie value ~S must be a non-empty string." value)) (unless (valid-cookie-domain-p domain) (cookie-error cookie "Invalid cookie domain ~S." domain)) (unless (and (stringp path) (plusp (length path))) (cookie-error cookie "Cookie path ~S must be a non-empty string." path)) (unless (or (null expires) (and (integerp expires) (plusp expires))) (cookie-error cookie "Cookie expiry ~S should have been NIL or a universal time." expires)))) (defmethod initialize-instance :after ((cookie cookie) &rest initargs) "Check cookie validity after creation." (declare (ignore initargs)) (check-cookie cookie)) (defmethod (setf cookie-name) :after (new-value (cookie cookie)) "Check cookie validity after name change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-value) :after (new-value (cookie cookie)) "Check cookie validity after value change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-domain) :after (new-value (cookie cookie)) "Check cookie validity after domain change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-path) :after (new-value (cookie cookie)) "Check cookie validity after path change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-expires) :after (new-value (cookie cookie)) "Check cookie validity after expiry change." (declare (ignore new-value)) (check-cookie cookie)) (defun cookie= (cookie1 cookie2) "Returns true if the cookies COOKIE1 and COOKIE2 are equal. Two cookies are considered to be equal if name and path are equal." (and (string= (cookie-name cookie1) (cookie-name cookie2)) (string= (cookie-path cookie1) (cookie-path cookie2)))) (defclass cookie-jar () ((cookies :initarg :cookies :initform nil :accessor cookie-jar-cookies :documentation "A list of the cookies in this cookie jar.")) (:documentation "A COOKIE-JAR object is a collection of cookies.")) (defmethod print-object ((cookie-jar cookie-jar) stream) "Print a cookie jar, showing the number of cookies it contains." (print-unreadable-object (cookie-jar stream :type t :identity t) (format stream "(with ~A cookie~:P)" (length (cookie-jar-cookies cookie-jar))))) (defun parse-cookie-date (string) "Parses a cookie expiry date and returns it as a Lisp universal time. Currently understands the following formats: \"Wed, 06-Feb-2008 21:01:38 GMT\" \"Wed, 06-Feb-08 21:01:38 GMT\" \"Tue Feb 13 08:00:00 2007 GMT\" \"Wednesday, 07-February-2027 08:55:23 GMT\" \"Wed, 07-02-2017 10:34:45 GMT\" Instead of \"GMT\" time zone abbreviations like \"CEST\" and UTC offsets like \"GMT-01:30\" are also allowed." ;; it seems like everybody and their sister invents their own format ;; for this, so (as there's no real standard for it) we'll have to ;; make this function more flexible once we come across something ;; new; as an alternative we could use net-telent-date, but it also ;; fails to parse some of the stuff you encounter in the wild; or we ;; could try to employ CL-PPCRE, but that'd add a new dependency ;; without making this code much cleaner (handler-case (let* ((last-space-pos (or (position #\Space string :test #'char= :from-end t) (cookie-date-parse-error "Can't parse cookie date ~S, no space found." string))) (time-zone-string (subseq string (1+ last-space-pos))) (time-zone (interpret-as-time-zone time-zone-string)) second minute hour day month year) (dolist (part (rest (split-string (subseq string 0 last-space-pos)))) (when (and day month) (cond ((every #'digit-char-p part) (when year (cookie-date-parse-error "Can't parse cookie date ~S, confused by ~S part." string part)) (setq year (parse-integer part))) ((= (count #\: part :test #'char=) 2) (let ((h-m-s (mapcar #'safe-parse-integer (split-string part ":")))) (setq hour (first h-m-s) minute (second h-m-s) second (third h-m-s)))) (t (cookie-date-parse-error "Can't parse cookie date ~S, confused by ~S part." string part)))) (cond ((null day) (unless (setq day (safe-parse-integer part)) (setq month (interpret-as-month part)))) ((null month) (setq month (interpret-as-month part))))) (unless (and second minute hour day month year) (cookie-date-parse-error "Can't parse cookie date ~S, component missing." string)) (when (< year 100) (setq year (+ year 2000))) (encode-universal-time second minute hour day month year time-zone)) (cookie-date-parse-error (condition) (cond (*ignore-unparseable-cookie-dates-p* (drakma-warn "~A" condition) nil) (t (error condition)))))) (defun parse-set-cookie (string) "Parses the `Set-Cookie' header line STRING and returns a list of three-element lists where each one contains the name of the cookie, the value of the cookie, and an attribute/value list for the optional cookie parameters." (let ((*current-error-message* (format nil "While parsing cookie header ~S:" string)) result) (dolist (substring (split-set-cookie-string string)) (with-sequence-from-string (stream substring) (let* ((name/value (read-name-value-pair stream :cookie-syntax t)) (parameters (read-name-value-pairs stream :value-required-p nil :cookie-syntax t))) (push (list (car name/value) (cdr name/value) parameters) result)))) (nreverse result))) (defun get-cookies (headers uri) "Returns a list of COOKIE objects corresponding to the `Set-Cookie' header as found in HEADERS \(an alist as returned by HTTP-REQUEST). Collects only cookies which match the domain of the \(PURI) URI URI." (loop with set-cookie-header = (header-value :set-cookie headers) with parsed-cookies = (and set-cookie-header (parse-set-cookie set-cookie-header)) for (name value parameters) in parsed-cookies for expires = (parameter-value "expires" parameters) for domain = (or (parameter-value "domain" parameters) (uri-host uri)) when (and (valid-cookie-domain-p domain) (cookie-domain-matches domain uri)) collect (make-instance 'cookie :name name :value value :path (or (parameter-value "path" parameters) (uri-path uri) "/") :expires (and expires (plusp (length expires)) (parse-cookie-date expires)) :domain domain :securep (not (not (parameter-present-p "secure" parameters))) :http-only-p (not (not (parameter-present-p "HttpOnly" parameters)))) into new-cookies finally (return (ccase *remove-duplicate-cookies-p* ((nil) new-cookies) ((:keep-last t) (delete-duplicates new-cookies :test #'cookie=)) (:keep-first (delete-duplicates new-cookies :test #'cookie= :from-end T)))))) (defun update-cookies (new-cookies cookie-jar) "Updates the cookies in COOKIE-JAR by replacing those which are equal to a cookie in \(the list) NEW-COOKIES with the corresponding `new' cookie and adding those which are really new." (setf (cookie-jar-cookies cookie-jar) (let ((updated-cookies (loop for old-cookie in (cookie-jar-cookies cookie-jar) collect (or (find old-cookie new-cookies :test #'cookie=) old-cookie)))) (union updated-cookies (set-difference new-cookies updated-cookies :test #'cookie=) :test #'cookie=))) cookie-jar) (defun delete-old-cookies (cookie-jar) "Removes all cookies from COOKIE-JAR which have either expired or which don't have an expiry date." (setf (cookie-jar-cookies cookie-jar) (loop with now = (get-universal-time) for cookie in (cookie-jar-cookies cookie-jar) for expires = (cookie-expires cookie) unless (or (null expires) (< expires now)) collect cookie)) cookie-jar)
14,948
Common Lisp
.lisp
284
43.123239
109
0.634357
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a1f93684a6ca4f128c6ebb3dfadf74c56d69a0a4c7a2890d4cda7f264be784d7
19,231
[ -1 ]
19,232
packages.lisp
Eggy115_Lisp/drakma-1.2.3/packages.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/packages.lisp,v 1.22 2008/01/14 01:57:01 edi Exp $ ;;; Copyright (c) 2006-2010, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :cl-user) (defpackage :drakma (:use :cl :puri :flexi-streams :chunga) ;; the variable defined in the ASDF system definition (:import-from :drakma-asd :*drakma-version-string*) (:shadow :syntax-error :parameter-error) (:export :*allow-dotless-cookie-domains-p* :*body-format-function* :*remove-duplicate-cookies-p* :*drakma-default-external-format* :*header-stream* :*ignore-unparseable-cookie-dates-p* :*text-content-types* :cookie :cookie-error :cookie-error-cookie :cookie-date-parse-error :cookie-domain :cookie-expires :cookie-http-only-p :cookie-jar :cookie-jar-cookies :cookie-name :cookie-path :cookie-securep :cookie-value :cookie= :delete-old-cookies :drakma-condition :drakma-error :drakma-warning :get-content-type :header-value :http-request :parameter-error :parameter-present-p :parameter-value :parse-cookie-date :read-tokens-and-parameters :split-tokens :syntax-error))
2,870
Common Lisp
.lisp
64
36.625
89
0.647923
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
424000c4ec8b55e932fbd5a4972fd73f8a621b80425c262cc63875b1da2826f1
19,232
[ -1 ]
19,233
api.lisp
Eggy115_Lisp/cl-geonames/test/api.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: api.lisp ;;;; Purpose: Unit Tests for the Common Lisp Geonames API. ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2008 by Nicolas Lamirault ;;;; ;;;; cl-geonames are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (in-package :cl-geonames-test) (lift:addtest (cl-geonames-test) unable-host-test (:documentation "Test condition when the Geonames server is unable.") (lift:ensure-condition 'usocket:unknown-error (let ((cl-geonames::*geonames-server* (format nil "http://www.~A.org" (gensym)))) (cl-geonames:geo-country-code "44.8391224692125" "-0.585060840409772")))) (lift:addtest (cl-geonames-test) country-info-test (:documentation "Test retrieve countries informations.") (let ((data (cl-geonames:geo-country-info :country '("FR" "GB")))) (lift:ensure (= 2 (length (cdr data)))) (destructuring-bind (fr-country gb-country) (cdr data) (loop for keyword in '(:|countryCode| :|countryName| :|isoNumeric| :|isoAlpha3| :|fipsCode| :|continent| :|capital| :|areaInSqKm| :|population| :|currencyCode| :|languages| :|geonameId| :|bBoxWest| :|bBoxNorth| :|bBoxEast| :|bBoxSouth|) do (lift:ensure (find keyword (cdr fr-country) :test #'equal :key #'car)) (lift:ensure (find keyword (cdr gb-country) :test #'equal :key #'car))) (lift:ensure (string-equal "FR" (cadr (second fr-country)))) (lift:ensure (string-equal "GB" (cadr (second gb-country)))) (lift:ensure (string-equal "France" (cadr (third fr-country)))) (lift:ensure (string-equal "United Kingdom" (cadr (third gb-country)))) (lift:ensure (string-equal "250" (cadr (fourth fr-country)))) (lift:ensure (string-equal "826" (cadr (fourth gb-country)))) (lift:ensure (string-equal "FRA" (cadr (fifth fr-country)))) (lift:ensure (string-equal "GBR" (cadr (fifth gb-country))))))) (lift:addtest (cl-geonames-test) country-code-test (:documentation "Test retrieve the iso country code for the given LATITUDE/LONGITUDE.") (let ((data (cl-geonames:geo-country-code "44.8391224692125" "-0.585060840409772"))) (let ((infos (find :|countryCode| (cdadr data) :test #'equal :key #'car))) (lift:ensure (string-equal "FR" (cadr infos)))) (let ((infos (find :|countryName| (cdadr data) :test #'equal :key #'car))) (lift:ensure (string-equal "France" (cadr infos)))))) (lift:addtest (cl-geonames-test) country-subdivision-test (:documentation "Test retrieve the country and the administrative subdivison (state, province,...) for the given LATITUDE/LONGITUDE") (let ((data (cl-geonames:geo-country-subdivision "44.8391224692125" "-0.585060840409772"))) (let ((infos (find :|countryCode| (cdadr data) :test #'equal :key #'car))) (lift:ensure (string-equal "FR" (cadr infos)))) (let ((infos (find :|countryName| (cdadr data) :test #'equal :key #'car))) (lift:ensure (string-equal "France" (cadr infos)))) (let ((infos (find :|adminName1| (cdadr data) :test #'equal :key #'car))) (lift:ensure (string-equal "Aquitaine" (cadr infos)))))) (lift:addtest (cl-geonames-test) srtm3-test (:documentation "Test getting the elevation in meters according to srtm3 for the given LATITUDE/LONGITUDE.") (let ((data (cl-geonames:geo-elevation-srtm3 "44.8391224692125" "-0.585060840409772"))) (lift:ensure (not (null data))))) (lift:addtest (cl-geonames-test) gtopo30-test (:documentation "Get the elevation in meters according to gtopo30 for the given LATITUDE/LONGITUDE.") (let ((data (cl-geonames:geo-elevation-gtopo30 "44.8391224692125" "-0.585060840409772"))) (lift:ensure (not (null data))))) (lift:addtest (cl-geonames-test) find-nearby-lat-lng-test (:documentation "Retrieve a list of place for the LATITUDE / LONGITUDE query.") (let ((data (cl-geonames:geo-find-nearby-place-name "44.8391224692125" "-0.585060840409772" :radius 10))) (lift:ensure (= 10 (length (cdr data)))))) (lift:addtest (cl-geonames-test) find-nearby-postal-code-test (:documentation "Retrieve a list of place for the postal code query.") (let ((data (cl-geonames:geo-find-nearby-postal-code "33560" :max-rows 2 :country '("fr")))) (lift:ensure (= 2 (length (cdr data)))) (destructuring-bind (cb ste) (cdr data) (let ((infos (find :|name| (cdr cb) :test #'equal :key #'car))) (lift:ensure (string-equal "Carbon Blanc" (cadr infos)))) (let ((infos (find :|name| (cdr ste) :test #'equal :key #'car))) (lift:ensure (string-equal "Ste Eulalie" (cadr infos)))) (let ((infos (find :|adminName1| (cdr ste) :test #'equal :key #'car))) (lift:ensure (string-equal "Aquitaine" (cadr infos)))) (let ((infos (find :|adminName2| (cdr ste) :test #'equal :key #'car))) (lift:ensure (string-equal "Gironde" (cadr infos))))))) (lift:addtest (cl-geonames-test) find-nearby-postal-code-geocoding-test (:documentation "Retrieve a list of places near latitude and longitude.") (let ((data (cl-geonames:geo-find-nearby-postal-code-geocoding "44.8833333" "-0.5" :max-rows 10))) (lift:ensure (= 10 (length (cdr data)))) (loop for place in (cdr data) as x = (find :|adminName1| (cdr place) :test #'equal :key #'car) as y = (find :|adminName2| (cdr place) :test #'equal :key #'car) do (lift:ensure (string-equal (cadr x) "Aquitaine")) (lift:ensure (string-equal (cadr y) "Gironde"))))) (lift:addtest (cl-geonames-test) lookup-places-test (:documentation "Test research of places using postal code.") (let ((data (cl-geonames:geo-placename-lookup "33560" :country '("FR")))) (lift:ensure (= 2 (length (cdar data)))) (destructuring-bind (cb ste) (cdar data) (let ((infos (find :POSTALCODE cb :test #'equal :key #'car))) (lift:ensure (string-equal (cdr infos) "33560"))) (let ((infos (find :PLACE-NAME cb :test #'equal :key #'car))) (lift:ensure (string-equal (cdr infos) "Carbon Blanc"))) (let ((infos (find :PLACE-NAME ste :test #'equal :key #'car))) (lift:ensure (string-equal (cdr infos) "Ste Eulalie"))) (let ((infos (find :POSTALCODE ste :test #'equal :key #'car))) (lift:ensure (string-equal (cdr infos) "33560"))) (let ((infos (find :COUNTRY-CODE cb :test #'equal :key #'car))) (lift:ensure (string-equal (cdr infos) "FR"))) (let ((infos (find :COUNTRY-CODE ste :test #'equal :key #'car))) (lift:ensure (string-equal (cdr infos) "FR"))) (let ((infos (find :LNG cb :test #'equal :key #'car))) (lift:ensure (= (cdr infos) -0.5))) (let ((infos (find :LNG ste :test #'equal :key #'car))) (lift:ensure (= (cdr infos) -0.5))) (let ((infos (find :LAT cb :test #'equal :key #'car))) (lift:ensure (= (cdr infos) 44.883335))) (let ((infos (find :LAT ste :test #'equal :key #'car))) (lift:ensure (= (cdr infos) 44.883335)))))) (lift:addtest (cl-geonames-test) postal-code-country-info-test (:documentation "Test to retrieve countries list for which postal codes are available.") (let ((data (cl-geonames:geo-postal-code-country-info))) (lift:ensure (< 0 (length (cdr data)))))) (lift:addtest (cl-geonames-test) timezone-test (:documentation "Test to retrieve timezone for at latitude/longitude place.") (let ((data (cl-geonames:geo-timezone "44.8391224692125" "-0.585060840409772"))) (lift:ensure (= 1 (length (cdr data)))) (let ((infos (find :|timezoneId| (cdadr data) :test #'equal :key #'car))) (lift:ensure (string-equal "Europe/Paris" (cadr infos)))))) (lift:addtest (cl-geonames-test) geo-search-test (:documentation "Test for the geo-searching query.") (let ((data (cl-geonames:geo-search "Bordeaux" "Bordeaux" "Bordeaux" :country '("FR") :max-rows 5))) (lift:ensure (= 5 (length (cddr data)))))) (lift:addtest (cl-geonames-test) postal-code-search-test (:documentation "Test for the postal code searching feature.") (let ((data (cl-geonames:geo-postal-code-search "33560" "" :country '("FR")))) (lift:ensure (= 2 (length (cddr data)))) (destructuring-bind (cb ste) (cddr data) (let ((infos (find :|name| (cdr cb) :test #'equal :key #'car))) (lift:ensure (string-equal "Carbon Blanc" (cadr infos)))) (let ((infos (find :|name| (cdr ste) :test #'equal :key #'car))) (lift:ensure (string-equal "Ste Eulalie" (cadr infos))))))) (lift:addtest (cl-geonames-test) output-formats-test (:documentation "check available output formats.") (lift:ensure-condition 'cl-geonames::geonames-output-error (cl-geonames:geo-postal-code-search "33560" "" :country '("FR") :type :foo)))
9,782
Common Lisp
.lisp
168
49.880952
104
0.60855
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7cb81fef25bf4f6f894ad729cb16b2a15b3340b0b805c0fc5252dd2c3b2b6652
19,233
[ 2954 ]
19,234
package.lisp
Eggy115_Lisp/cl-geonames/test/package.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: package.lisp ;;;; Purpose: Package definition file for cl-geonames-test ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2008 by Nicolas Lamirault ;;;; ;;;; clitter users are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (defpackage :cl-geonames-test (:use :cl) (:documentation "Unit Tests for cl-geonames package.") (:export #:run-cl-geonames-tests))
892
Common Lisp
.lisp
19
44.315789
80
0.553633
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ad94b6f903babaf2477d66768b3a230e5c79108d84318851e0c9b54696b85d09
19,234
[ 137913 ]
19,235
specials.lisp
Eggy115_Lisp/cl-geonames/test/specials.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: specials.lisp ;;;; Purpose: Some variables used by the Common Lisp Geonames API Unit Tests. ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2008 by Nicolas Lamirault ;;;; ;;;; cl-geonames are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (in-package :cl-geonames-test) (defparameter *cl-geonames-path* (namestring (asdf:component-relative-pathname (asdf:find-system :cl-geonames))) "Directory with contains cl-geonames source files.")
986
Common Lisp
.lisp
20
46.25
84
0.579832
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
953f466bd716f282f6a4ebf7136933ad570390634fc3ff791382d01fb32a4382
19,235
[ 256535 ]
19,236
definition.lisp
Eggy115_Lisp/cl-geonames/test/definition.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: definition.lisp ;;;; Purpose: Definition of the Common Lisp Geonames API Unit Tests. ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2008 by Nicolas Lamirault ;;;; ;;;; cl-geonames are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (in-package :cl-geonames-test) (lift:deftestsuite cl-geonames-test () ())
844
Common Lisp
.lisp
17
46.941176
80
0.547239
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e99c844f8ab58430b3603c85dce6ebc84b9e8fe0f711cd2266b6aaf3a1e247a8
19,236
[ 399674 ]
19,237
unit-tests.lisp
Eggy115_Lisp/cl-geonames/test/unit-tests.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: unit-tests.lisp ;;;; Purpose: Common Lisp Geonames API Unit Tests. ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2008 by Nicolas Lamirault ;;;; ;;;; cl-geonames are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (in-package :cl-geonames-test) (defun run-cl-geonames-tests () "Run the cl-geonames unit tests." (let ((config-file (concatenate 'string *cl-geonames-path* "etc/lift-standard.config"))) (lift:run-tests :config config-file)))
1,056
Common Lisp
.lisp
22
42.090909
80
0.52832
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9fea2d57f6c20a19bcf1c82964845bcd850330df7ba3ceeb6c2018885eaa4b76
19,237
[ 201108 ]
19,238
package.lisp
Eggy115_Lisp/cl-geonames/src/package.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: package.lisp ;;;; Purpose: Package definition file for cl-geonames ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2006 by Nicolas Lamirault ;;;; ;;;; cl-geonames users are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (defpackage :cl-geonames (:use :cl) (:documentation "Geonames Common Lisp package") (:export #:geo-search #:geo-postal-code-search #:geo-placename-lookup #:geo-find-nearby-postal-code #:geo-find-nearby-postal-code-geocoding #:geo-postal-code-country-info #:geo-find-nearby-place-name #:geo-country-info #:geo-country-code #:geo-country-subdivision #:geo-elevation-srtm3 #:geo-elevation-gtopo30 #:geo-timezone ;; Conditions #:geonames-error #:geonames-request-error #:geonames-output-error ;; Dev #:*debug* ))
1,504
Common Lisp
.lisp
38
31.578947
82
0.529737
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
002ead1866a05c0de84f577c404eed5a0b783342014d68d44732844203984e4e
19,238
[ 453738 ]
19,239
specials.lisp
Eggy115_Lisp/cl-geonames/src/specials.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: specials.lisp ;;;; Purpose: cl-geonames specials informations. ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2006 by Nicolas Lamirault ;;;; ;;;; cl-geonames users are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (in-package :cl-geonames) (defparameter *geonames-server* "http://ws.geonames.org") (defparameter *geonames-search* "/search~A?" "Web service for the geonames full text search") (defparameter *geonames-postal-code-search* "/postalCodeSearch~A?" "Web service to retreive postal codes and places.") (defparameter *geonames-placename-lookup* "/postalCodeLookup~A?" "Web service to retrieve placename lookup with postal code.") (defparameter *geonames-find-near-postal-code* "/findNearbyPostalCodes~A?" "Web service to find nearby postal codes / reverse geocoding") (defparameter *geonames-postal-code-country* "/postalCodeCountryInfo~A?" "Web service to retrieve countries for which postal code geocoding is available.") (defparameter *geonames-find-near-place-name* "/findNearbyPlaceName~A?" "Web service to find nearby place name / reverse geocoding") (defparameter *geonames-country-info* "/countryInfo~A?" "Web service to retrieve informations about countries") (defparameter *geonames-country-code* "/countrycode~A?" "Web service to retreive country code from latitude/longitude.") (defparameter *geonames-country-subdivision* "/countrySubdivision~A?" "Web service to retreive the administrative subdivison (state, province,...).") (defparameter *geonames-elevation-srtm3* "/srtm3~A?" "Web service to retreive the elevation in meters according to srtm3.") (defparameter *geonames-elevation-gtopo30* "/gtopo30~A?" "Web service to retreive the elevation in meters according to gtopo30.") (defparameter *geonames-timezone* "/timezone~A?" "Web service to retreive the timezone at the lat/lng.") (defparameter *debug* nil "If T, active some logs.")
2,499
Common Lisp
.lisp
42
55.452381
85
0.694236
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
74674b12a682080d0f42de7a5298c715d9289f2bd953a4e609efefb759488b42
19,239
[ -1 ]
19,240
conditions.lisp
Eggy115_Lisp/cl-geonames/src/conditions.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: conditions.lisp ;;;; Purpose: cl-geonames conditions. ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2007 by Nicolas Lamirault ;;;; ;;;; cl-geonames users are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (in-package :cl-geonames) (define-condition geonames-error (simple-error) () (:documentation "Main Geonames error.")) (define-condition geonames-query-error (geonames-error) ((message :reader message :initarg :message :documentation "Explanation message.")) (:documentation "Geonames query error.") (:report (lambda (condition stream) (format stream "Geonames error ~A." (message condition))))) (define-condition geonames-request-error (geonames-error) ((code :reader code :initarg :code :documentation "The error code.") (message :reader message :initarg :message :documentation "Explanation message.")) (:documentation "Geonames request error.") (:report (lambda (condition stream) (format stream "Geonames error ~A : ~A." (code condition) (message condition))))) (define-condition geonames-output-error (geonames-error) ((output :reader output :initarg :output :documentation "The output format.")) (:documentation "Geonames output error.") (:report (lambda (condition stream) (format stream "Geonames unknown output ~A." (output condition)))))
2,007
Common Lisp
.lisp
44
39.090909
82
0.601446
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d5d15f439852bf94ce75217425664419fe7f4b7985527908c9212b137a6d981e
19,240
[ -1 ]
19,241
ut-cover.lisp
Eggy115_Lisp/cl-geonames/misc/ut-cover.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: ut-cover.lisp ;;;; Purpose: Unit tests coverage. ;;;; Programmer: Nicolas Lamirault <[email protected]> ;;;; ;;;; This file, part of cl-geonames, is Copyright (c) 2008 by Nicolas Lamirault ;;;; ;;;; cl-geonames users are granted the rights to distribute and use this software ;;;; as governed by the terms of the Lisp Lesser GNU Public License ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL. ;;;; ;;;; ************************************************************************* (require :sb-cover) (declaim (optimize sb-cover:store-coverage-data)) (asdf:oos 'asdf:load-op :cl-geonames-test) (cl-geonames-test:run-cl-geonames-tests) (sb-cover:report "/tmp/cl-geonames-coverage/") (declaim (optimize (sb-cover:store-coverage-data 0)))
997
Common Lisp
.lisp
21
45
82
0.576605
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e516f9c8b6fdb0a9cc444537b02a8f5be9765dc16c4ba99ccb94032f1c81826f
19,241
[ -1 ]
19,242
package.lisp
Eggy115_Lisp/openai/package.lisp
;;;; package.lisp (defpackage #:openai (:use #:cl #:uiop #:cl-json) (:export #:completions #:summarize #:answer-question))
133
Common Lisp
.lisp
4
29.75
57
0.645669
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
0182de727122de1e75deb4856fdf27422a80b2522a02f091c218890f4cbd28d0
19,242
[ -1 ]
19,243
openai.lisp
Eggy115_Lisp/openai/openai.lisp
(in-package #:openai) ;; define the environment variable "OPENAI_KEY" with the value of your OpenAI API key (defvar openai-davinci-model-host "https://api.openai.com/v1/engines/davinci/completions") (defun openai-helper (curl-command) (let ((response (uiop:run-program curl-command :output :string))) ;;(princ curl-command) (with-input-from-string (s response) (let* ((json-as-list (json:decode-json s))) ;; extract text (this might change if OpenAI changes JSON return format): (cdar (cadr (nth 4 json-as-list))))))) (defun completions (starter-text max-tokens) (let* ((curl-command (concatenate 'string "curl " openai-davinci-model-host " -H \"Content-Type: application/json\"" " -H \"Authorization: Bearer " (uiop:getenv "OPENAI_KEY") "\" " " -d '{\"prompt\": \"" starter-text "\", \"max_tokens\": " (write-to-string max-tokens) "}'"))) (openai-helper curl-command))) (defun summarize (some-text max-tokens) (let* ((curl-command (concatenate 'string "curl " openai-davinci-model-host " -H \"Content-Type: application/json\"" " -H \"Authorization: Bearer " (uiop:getenv "OPENAI_KEY") "\" " " -d '{\"prompt\": \"" some-text "\", \"max_tokens\": " (write-to-string max-tokens) ", \"presence_penalty\": 0.0" ", \"temperature\": 0.3, \"top_p\": 1.0, \"frequency_penalty\": 0.0 }'"))) (openai-helper curl-command))) (defun answer-question (question-text max-tokens) (let* ((q-text (concatenate 'string "\nQ: " question-text "\nA:")) (curl-command (concatenate 'string "curl " openai-davinci-model-host " -H \"Content-Type: application/json\"" " -H \"Authorization: Bearer " (uiop:getenv "OPENAI_KEY") "\" " " -d '{\"prompt\": \"" q-text "\", \"max_tokens\": " (write-to-string max-tokens) ", \"presence_penalty\": 0.0, \"stop\": [\"\\n\"]" ", \"temperature\": 0.0, \"top_p\": 1.0, \"frequency_penalty\": 0.0 }'")) (answer (openai-helper curl-command)) (index (search "nQ:" answer))) (if index (string-trim " " (subseq answer 0 index)) (string-trim " " answer)))) #| (print (openai:completions "The President went to Congress" 20)) (print (openai:summarize "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[20] and is on average the third-brightest natural object in the night sky after the Moon and Venus." 30)) (print (openai:answer-question "Where were the 1992 Olympics held?" 60)) (print (openai:answer-question "Where is the Valley of Kings?" 60)) |#
3,335
Common Lisp
.lisp
60
46.25
662
0.605287
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
bd631866d26c58fa127aa7c5fd7264a1ee231aa6334e07ada6c16c7ca51ed337
19,243
[ -1 ]
19,244
opencalais-lib.lisp
Eggy115_Lisp/opencalais/opencalais-lib.lisp
;; Copyright Mark Watson 2008-2010. All Rights Reserved. ;; License: LGPL version 3 (http://www.gnu.org/licenses/lgpl-3.0.txt) ;;(eval-when (compile load eval) ;; (require :aserve)) ;; to pick up client library ;;(require :agraph)) (require :aserve) (push "../utils/split-sequence/" asdf:*central-registry*) (asdf:operate 'asdf:load-op :split-sequence) (defvar *my-opencalais-key* (sys::getenv "OPEN_CALAIS_KEY")) (defvar *PARAMS* (concatenate 'string "&paramsXML=" (cl-user::MAKE-ESCAPED-STRING "<c:params xmlns:c=\"http://s.opencalais.com/1/pred/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><c:processingDirectives c:contentType=\"text/txt\" c:outputFormat=\"xml/rdf\"></c:processingDirectives><c:userDirectives c:allowDistribution=\"true\" c:allowSearch=\"true\" c:externalID=\"17cabs901\" c:submitter=\"ABC\"></c:userDirectives><c:externalMetadata></c:externalMetadata></c:params>"))) (defun entities-from-opencalais-query (query &aux url results index1 index2 lines tokens hash) (setf hash (make-hash-table :test #'equal)) (setf url (concatenate 'string "http://api.opencalais.com/enlighten/calais.asmx/Enlighten?" "licenseID=" *my-opencalais-key* "&content=" (cl-user::MAKE-ESCAPED-STRING query) *PARAMS*)) (setf results (net.aserve.client:do-http-request url)) (setq index1 (search "terms of service.--&gt;" results)) (setq index1 (search "&lt;!--" results :start2 index1)) (setq index2 (search "--&gt;" results :start2 index1)) (setq results (subseq results (+ index1 7) index2)) (setq lines (split-sequence:split-sequence #\Newline results)) (dolist (line lines) (setq index1 (search ": " line)) (if index1 (let ((key (subseq line 0 index1)) (values (split-sequence:split-sequence ", " (subseq line (+ index1 2))))) (if (not (string-equal "Relations" key)) (setf (gethash key hash) values))))) (maphash #'(lambda (key val) (format t "key: ~S val: ~S~%" key val)) hash) hash) ;; (setf x (entities-from-opencalais-query "Senator Hiliary Clinton spoke with the president of France. Clinton and John Smith talked on the airplane going to California. IBM and Pepsi contributed to Clinton's campaign.")) (defun replace-all (string part replacement &key (test #'char=)) "Returns a new string in which all the occurrences of the part is replaced with replacement." (with-output-to-string (out) (loop with part-length = (length part) for old-pos = 0 then (+ pos part-length) for pos = (search part string :start2 old-pos :test test) do (write-string string out :start old-pos :end (or pos (length string))) when pos do (write-string replacement out) while pos)))
2,995
Common Lisp
.lisp
56
45.142857
446
0.639013
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c98b9627f4f4aa2b23f95957d717627205e657919edb56ff019feac027438947
19,244
[ -1 ]
19,245
opencalais-data-store.lisp
Eggy115_Lisp/opencalais/opencalais-data-store.lisp
;; Use the opencalais-lib.lisp utilities to create ;; an RDF data store. Assume that a AG RDF repository is open. ;; Copyright Mark Watson 2008-2010. All Rights Reserved. ;; License: LGPL version 3 (http://www.gnu.org/licenses/lgpl-3.0.txt) (require :agraph) (in-package :db.agraph.user ) (enable-!-reader) (register-namespace "kb" "http:/knowledgebooks.com/rdfs#") (let ((hash (make-hash-table :test #'equal))) (setf (gethash "Country" hash) !kb:containsCountry) (setf (gethash "Person" hash) !kb:containsPerson) (setf (gethash "Company" hash) !kb:containsCompany) (setf (gethash "ProvinceOrState" hash) !kb:containsState) (setf (gethash "Product" hash) !kb:containsProduct) (setf (gethash "Position" hash) !kb:containsProduct) (defun get-rdf-predicate-from-entity-type (entity-type) (let ((et (gethash entity-type hash))) (if (not et) (progn (setf et entity-type) ;; just use a string literal (format t "Warning: entity-type ~S not defined in opencalais-data-store.lisp~%" entity-type))) et))) (defun add-entities-to-rdf-store (subject-uri text) "subject-uri if the subject for triples that this function defines" (maphash #'(lambda (key val) (dolist (entity-val val) (add-triple subject-uri (get-rdf-predicate-from-entity-type key) (literal entity-val)))) (cl-user::entities-from-opencalais-query text)))
1,513
Common Lisp
.lisp
33
38.636364
105
0.65847
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d2aee1dbecad981d26fd4e1cf5a67475df5bb57e16d02dbdb16f99b28704194c
19,245
[ -1 ]
19,246
load.lisp
Eggy115_Lisp/opencalais/load.lisp
;; load and run Open Calais example (load "opencalais-lib") ;;(setf x (cl-user::entities-from-opencalais-query "Senator Hiliary Clinton spoke with the president of France. Clinton and John Smith talked on the airplane going to California. IBM and Pepsi contributed to Clinton's campaign.")) (load "opencalais-data-store") (load "test-opencalais")
360
Common Lisp
.lisp
5
68.4
231
0.772334
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e202e152edde84f1efcd83b0d12581ea2af2229fd8e7edb469164a0dc473aed5
19,246
[ -1 ]
19,247
test-opencalais.lisp
Eggy115_Lisp/opencalais/test-opencalais.lisp
(require :agraph) (in-package :db.agraph.user) (create-triple-store "/tmp/rdfstore_1") ;;(cl-user::add-entities-to-rdf-store !<http://newsdemo.com/1234> "Senator Hiliary Clinton spoke with the president of France. Clinton and John Smith talked on the airplane going to California. IBM and Pepsi contributed to Clinton's campaign.") (print-triples (get-triples-list) :format :concise) (print-triples (get-triples-list :p (get-rdf-predicate-from-entity-type "Company") :o (literal "Pepsi")) :format :concise)
533
Common Lisp
.lisp
10
49.9
247
0.741748
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
26635fb05f3d4ea004cbaa10feb79c7920b27bd5204230310bf57e61b5b8b896
19,247
[ -1 ]
19,248
parse.lisp
Eggy115_Lisp/yason/parse.lisp
;; This file is part of yason, a Common Lisp JSON parser/encoder ;; ;; Copyright (c) 2008 Hans Hübner ;; All rights reserved. ;; ;; Please see the file LICENSE in the distribution. (in-package :yason) (defconstant +default-string-length+ 20 "Default length of strings that are created while reading json input.") (defvar *parse-object-key-fn* #'identity "Function to call to convert a key string in a JSON array to a key in the CL hash produced.") (defvar *parse-json-arrays-as-vectors* nil "If set to a true value, JSON arrays will be parsed as vectors, not as lists.") (defvar *parse-json-booleans-as-symbols* nil "If set to a true value, JSON booleans will be read as the symbols TRUE and FALSE, not as T and NIL, respectively.") (defvar *parse-object-as-alist* nil "If set to a true value, JSON objects will be parsed as association lists and not hash tables.") (defun make-adjustable-string () "Return an adjustable empty string, usable as a buffer for parsing strings and numbers." (make-array +default-string-length+ :adjustable t :fill-pointer 0 :element-type 'character)) (defun parse-number (input) ;; would be ;; (cl-ppcre:scan-to-strings "^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+|)(?:[eE][-+]?[0-9]+|)" buffer) ;; but we want to operate on streams (let ((buffer (make-adjustable-string))) (loop while (position (peek-char nil input nil) ".0123456789+-Ee") do (vector-push-extend (read-char input) buffer)) (values (read-from-string buffer)))) (defun parse-string (input) (let ((output (make-adjustable-string))) (labels ((outc (c) (vector-push-extend c output)) (next () (read-char input)) (peek () (peek-char nil input))) (let* ( (starting-symbol (next)) (string-quoted (equal starting-symbol #\")) ) (unless string-quoted (outc starting-symbol)) (loop (cond ((eql (peek) #\") (next) (return-from parse-string output)) ((eql (peek) #\\) (next) (ecase (next) (#\" (outc #\")) (#\\ (outc #\\)) (#\/ (outc #\/)) (#\b (outc #\Backspace)) (#\f (outc #\Page)) (#\n (outc #\Newline)) (#\r (outc #\Return)) (#\t (outc #\Tab)) (#\u (outc (code-char (let ((buffer (make-string 4))) (read-sequence buffer input) (parse-integer buffer :radix 16))))))) ((and (or (whitespace-p (peek)) (eql (peek) #\:)) (not string-quoted)) (return-from parse-string output)) (t (outc (next))))))))) (defun whitespace-p (char) (member char '(#\Space #\Newline #\Tab #\Linefeed))) (defun skip-whitespace (input) (loop while (and (listen input) (whitespace-p (peek-char nil input))) do (read-char input))) (defun peek-char-skipping-whitespace (input &optional (eof-error-p t)) (skip-whitespace input) (peek-char nil input eof-error-p)) (defun parse-constant (input) (destructuring-bind (expected-string return-value) (find (peek-char nil input nil) `(("true" ,(if *parse-json-booleans-as-symbols* 'true t)) ("false" ,(if *parse-json-booleans-as-symbols* 'false nil)) ("null" nil)) :key (lambda (entry) (aref (car entry) 0)) :test #'eql) (loop for char across expected-string unless (eql (read-char input nil) char) do (error "invalid constant")) return-value)) (define-condition cannot-convert-key (error) ((key-string :initarg :key-string :reader key-string)) (:report (lambda (c stream) (format stream "cannot convert key ~S used in JSON object to hash table key" (key-string c))))) (defun create-container () (if *parse-object-as-alist* '() (make-hash-table :test #'equal))) (defgeneric add-attribute (to key value) (:method ((to hash-table) key value) (setf (gethash key to) value) to) (:method ((to list) key value) (acons key value to))) (defun parse-object (input) (let ((return-value (create-container))) (read-char input) (loop (when (eql (peek-char-skipping-whitespace input) #\}) (return)) (skip-whitespace input) (setf return-value (add-attribute return-value (prog1 (let ((key-string (parse-string input))) (or (funcall *parse-object-key-fn* key-string) (error 'cannot-convert-key :key-string key-string))) (skip-whitespace input) (unless (eql #\: (read-char input)) (error 'expected-colon)) (skip-whitespace input)) (parse input))) (ecase (peek-char-skipping-whitespace input) (#\, (read-char input)) (#\} nil))) (read-char input) return-value)) (defconstant +initial-array-size+ 20 "Initial size of JSON arrays read, they will grow as needed.") (defun %parse-array (input add-element-function) "Parse JSON array from input, calling ADD-ELEMENT-FUNCTION for each array element parsed." (read-char input) (loop (when (eql (peek-char-skipping-whitespace input) #\]) (return)) (funcall add-element-function (parse input)) (ecase (peek-char-skipping-whitespace input) (#\, (read-char input)) (#\] nil))) (read-char input)) (defun parse-array (input) (if *parse-json-arrays-as-vectors* (let ((return-value (make-array +initial-array-size+ :adjustable t :fill-pointer 0))) (%parse-array input (lambda (element) (vector-push-extend element return-value))) return-value) (let (return-value) (%parse-array input (lambda (element) (push element return-value))) (nreverse return-value)))) (defgeneric parse (input) (:documentation "Parse INPUT, which needs to be a string or a stream, as JSON. Returns the lisp representation of the JSON structure parsed.") (:method ((input stream)) (ecase (peek-char-skipping-whitespace input) (#\" (parse-string input)) ((#\- #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (parse-number input)) (#\{ (parse-object input)) (#\[ (parse-array input)) ((#\t #\f #\n) (parse-constant input)))) (:method ((input pathname)) (with-open-file (stream input) (parse stream))) (:method ((input string)) (parse (make-string-input-stream input))))
7,186
Common Lisp
.lisp
182
29.450549
99
0.554167
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
281a4430534e97dc74ac4fb048b2a2ef598c31d3c1b9e794a3472719cc068851
19,248
[ -1 ]
19,249
encode.lisp
Eggy115_Lisp/yason/encode.lisp
;; This file is part of yason, a Common Lisp JSON parser/encoder ;; ;; Copyright (c) 2008 Hans Hübner ;; All rights reserved. ;; ;; Please see the file LICENSE in the distribution. (in-package :yason) (defvar *json-output*) (defgeneric encode (object &optional stream) (:documentation "Encode OBJECT to STREAM in JSON format. May be specialized by applications to perform specific rendering. STREAM defaults to *STANDARD-OUTPUT*.")) ;; from alexandria (defun plist-hash-table (plist &rest hash-table-initargs) "Returns a hash table containing the keys and values of the property list PLIST. Hash table is initialized using the HASH-TABLE-INITARGS." (let ((table (apply #'make-hash-table hash-table-initargs))) (do ((tail plist (cddr tail))) ((not tail)) (setf (gethash (car tail) table) (cadr tail))) table)) (defparameter *char-replacements* (plist-hash-table '(#\\ "\\\\" #\" "\\\"" #\/ "\\/" #\Backspace "\\b" #\Page "\\f" #\Newline "\\n" #\Return "\\r" #\Tab "\\t"))) (defmethod encode ((string string) &optional (stream *standard-output*)) (write-char #\" stream) (dotimes (i (length string)) (let* ((char (aref string i)) (replacement (gethash char *char-replacements*))) (if replacement (write-string replacement stream) (write-char char stream)))) (write-char #\" stream) string) (defmethod encode ((object rational) &optional (stream *standard-output*)) (encode (float object) stream) object) (defmethod encode ((object double-float) &optional (stream *standard-output*)) (encode (coerce object 'single-float) stream) object) (defmethod encode ((object float) &optional (stream *standard-output*)) (princ object stream) object) (defmethod encode ((object integer) &optional (stream *standard-output*)) (princ object stream)) (defun encode-key/value (key value stream) (encode key stream) (write-char #\: stream) (encode value stream)) (defmethod encode ((object hash-table) &optional (stream *standard-output*)) (write-char #\{ stream) (let (printed) (maphash (lambda (key value) (if printed (write-char #\, stream) (setf printed t)) (encode-key/value key value stream)) object)) (write-char #\} stream) object) (defmethod encode ((object vector) &optional (stream *standard-output*)) (write-char #\[ stream) (let (printed) (loop for value across object do (when printed (write-char #\, stream)) (setf printed t) (encode value stream))) (write-char #\] stream) object) (defmethod encode ((object list) &optional (stream *standard-output*)) (write-char #\[ stream) (let (printed) (dolist (value object) (if printed (write-char #\, stream) (setf printed t)) (encode value stream))) (write-char #\] stream) object) (defun encode-symbol/value (symbol value stream) (let ((string (symbol-name symbol))) (encode-key/value string value stream))) (defun encode-alist (object &optional (stream *standard-output*)) (loop initially (write-char #\{ stream) with printed = nil for (key . value) in object do (if printed (write-char #\, stream) (setf printed t)) (encode-symbol/value key value stream) finally (write-char #\} stream) (return object))) (defun encode-plist (object &optional (stream *standard-output*)) (loop initially (write-char #\{ stream) with printed = nil for (key value . rest) on object by #'cddr do (if printed (write-char #\, stream) (setf printed t)) (encode-symbol/value key value stream) finally (write-char #\} stream) (return object))) (defmethod encode ((object (eql 'true)) &optional (stream *standard-output*)) (write-string "true" stream) object) (defmethod encode ((object (eql 'false)) &optional (stream *standard-output*)) (write-string "false" stream) object) (defmethod encode ((object (eql 'null)) &optional (stream *standard-output*)) (write-string "null" stream) object) (defmethod encode ((object (eql t)) &optional (stream *standard-output*)) (write-string "true" stream) object) (defmethod encode ((object (eql nil)) &optional (stream *standard-output*)) (write-string "null" stream) object) (defclass json-output-stream () ((output-stream :reader output-stream :initarg :output-stream) (stack :accessor stack :initform nil)) (:documentation "Objects of this class capture the state of a JSON stream encoder.")) (defun next-aggregate-element () (if (car (stack *json-output*)) (write-char (car (stack *json-output*)) (output-stream *json-output*)) (setf (car (stack *json-output*)) #\,))) (defmacro with-output ((stream) &body body) "Set up a JSON streaming encoder context on STREAM, then evaluate BODY." `(let ((*json-output* (make-instance 'json-output-stream :output-stream ,stream))) ,@body)) (defmacro with-output-to-string* (() &body body) "Set up a JSON streaming encoder context, then evaluate BODY. Return a string with the generated JSON output." `(with-output-to-string (s) (with-output (s) ,@body))) (define-condition no-json-output-context (error) () (:report "No JSON output context is active") (:documentation "This condition is signalled when one of the stream encoding function is used outside the dynamic context of a WITH-OUTPUT or WITH-OUTPUT-TO-STRING* body.")) (defmacro with-aggregate ((begin-char end-char) &body body) `(progn (unless (boundp '*json-output*) (error 'no-json-output-context)) (when (stack *json-output*) (next-aggregate-element)) (write-char ,begin-char (output-stream *json-output*)) (push nil (stack *json-output*)) (prog1 (progn ,@body) (pop (stack *json-output*)) (write-char ,end-char (output-stream *json-output*))))) (defmacro with-array (() &body body) "Open a JSON array, then run BODY. Inside the body, ENCODE-ARRAY-ELEMENT must be called to encode elements to the opened array. Must be called within an existing JSON encoder context, see WITH-OUTPUT and WITH-OUTPUT-TO-STRING*." `(with-aggregate (#\[ #\]) ,@body)) (defmacro with-object (() &body body) "Open a JSON object, then run BODY. Inside the body, ENCODE-OBJECT-ELEMENT or WITH-OBJECT-ELEMENT must be called to encode elements to the object. Must be called within an existing JSON encoder context, see WITH-OUTPUT and WITH-OUTPUT-TO-STRING*." `(with-aggregate (#\{ #\}) ,@body)) (defun encode-array-element (object) "Encode OBJECT as next array element to the last JSON array opened with WITH-ARRAY in the dynamic context. OBJECT is encoded using the ENCODE generic function, so it must be of a type for which an ENCODE method is defined." (next-aggregate-element) (encode object (output-stream *json-output*))) (defun encode-array-elements (&rest objects) "Encode OBJECTS, a list of JSON encodeable object, as array elements." (dolist (object objects) (encode-array-element object))) (defun encode-object-element (key value) "Encode KEY and VALUE as object element to the last JSON object opened with WITH-OBJECT in the dynamic context. KEY and VALUE are encoded using the ENCODE generic function, so they both must be of a type for which an ENCODE method is defined." (next-aggregate-element) (encode-key/value key value (output-stream *json-output*)) value) (defun encode-object-elements (&rest elements) "Encode plist ELEMENTS as object elements." (loop for (key value) on elements by #'cddr do (encode-object-element key value))) (defmacro with-object-element ((key) &body body) "Open a new encoding context to encode a JSON object element. KEY is the key of the element. The value will be whatever BODY serializes to the current JSON output context using one of the stream encoding functions. This can be used to stream out nested object structures." `(progn (next-aggregate-element) (encode ,key (output-stream *json-output*)) (setf (car (stack *json-output*)) #\:) (unwind-protect (progn ,@body) (setf (car (stack *json-output*)) #\,)))) (defgeneric encode-slots (object) (:method-combination progn) (:documentation "Generic function to encode objects. Every class in a hierarchy implements a method for ENCODE-OBJECT that serializes its slots. It is a PROGN generic function so that for a given instance, all slots are serialized by invoking the ENCODE-OBJECT method for all classes that it inherits from.")) (defgeneric encode-object (object) (:documentation "Encode OBJECT, presumably a CLOS object as a JSON object, invoking the ENCODE-SLOTS method as appropriate.") (:method (object) (with-object () (json:encode-slots object))))
9,265
Common Lisp
.lisp
228
34.991228
88
0.67113
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3cb3ccd5d2475fdd1a21990ca4c136b589e5cbb99f9dd8d0652396ba42b4961a
19,249
[ -1 ]
19,250
package.lisp
Eggy115_Lisp/yason/package.lisp
;; This file is part of yason, a Common Lisp JSON parser/encoder ;; ;; Copyright (c) 2008 Hans Hübner ;; All rights reserved. ;; ;; Please see the file LICENSE in the distribution. (defpackage :yason (:use :cl) (:nicknames :json) (:export ;; Parser #:parse #:*parse-object-key-fn* #:*parse-object-as-alist* #:*parse-json-arrays-as-vectors* #:*parse-json-booleans-as-symbols* #:true #:false ;; Basic encoder interface #:encode #:encode-slots #:encode-object #:encode-plist #:encode-alist ;; Streaming encoder interface #:with-output #:with-output-to-string* #:no-json-output-context #:with-array #:encode-array-element #:encode-array-elements #:with-object #:encode-object-element #:encode-object-elements #:with-object-element #:with-response))
880
Common Lisp
.lisp
36
19.722222
65
0.653012
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
539d0d79185401c1daa14111b7d122235462c8957b20da79299d5a5dfd13da85
19,250
[ -1 ]
19,251
coref.lisp
Eggy115_Lisp/coref_web_client/coref.lisp
;;;; coref.lisp (in-package #:coref) ;; (ql:quickload :do-urlencode) (defvar base-url "http://127.0.0.1:8000?text=") (defun coref-client (query) (let ((the-bytes (drakma:http-request (concatenate 'string base-url (do-urlencode:urlencode query) "&no_detail=1") :content-type "application/text"))) (flexi-streams:octets-to-string the-bytes :external-format :utf-8))) ;; secret sauce: get the file path of this file: ;; (useful in NLP, etc. when we want to find data files at runtime) ;; (defvar *base-pathname* #.(or *compile-file-truename* *load-truename*))
633
Common Lisp
.lisp
17
31.823529
73
0.659432
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
eb4376dc4de5722b2c3d54bd6d73f60f3c4b02815c95b59f67bf0558e7f7ae59
19,251
[ -1 ]
19,252
clml_test.lisp
Eggy115_Lisp/clml_examples/clml_test.lisp
;; note; run SBCL using: sbcl --dynamic-space-size 2560 (ql:quickload '(:clml :clml.utility ; Need clml.utility.data to get data from the net :clml.hjs ; Need clml.hjs.read-data to poke around the raw dataset :clml.pca :clml.clustering ;;:iolib )) (in-package #:clmltest) (defun similar-word-test (word1 word2) (let ((word-similarity (clml.text.utilities:calculate-levenshtein-similarity word1 word2))) (format t "similarity of word ~s and word ~s is ~a ~%" word1 word2 word-similarity))) (similar-word-test "density" "dancing") (similar-word-test "fun" "funny") (similar-word-test "xyz" "abc") ;; code from CLML unit test: test-classifier.lisp: (defun classify-k-nn (test train objective-param-name manhattan) (let (original-data-column-length) (setq original-data-column-length (length (aref (clml.hjs.read-data:dataset-points train) 0))) (let* ((k 5) (k-nn-estimator (clml.nearest-search.k-nn:k-nn-analyze train k objective-param-name :all :distance manhattan :normalize t))) (loop for data across (dataset-points (clml.nearest-search.k-nn:k-nn-estimate k-nn-estimator test)) with true = 0 with false = 0 if (equal (aref data 0) (aref data original-data-column-length)) do (incf true) else do (incf false) finally (return (values true false (/ true (+ true false)))))) )) ;; code from CLML unit test: (defun cancer-data-classifier-example () (let ((train1 (clml.hjs.read-data:read-data-from-file "../machine_learning_data/labeled_cancer_training_data.csv" :type :csv :csv-type-spec (append (make-list 9 :initial-element 'double-float) '(symbol)))) (test1 (clml.hjs.read-data:read-data-from-file "../machine_learning_data/labeled_cancer_test_data.csv" :type :csv :csv-type-spec (append (make-list 9 :initial-element 'double-float) '(symbol))))) (print test1) (print (classify-k-nn test1 train1 "Class" :double-manhattan)))) ;;(cancer-data-classifier-example) ;; code from CLML unit test: test-classifier.lisp: (defun classify-k-nn2 (test train objective-param-name manhattan) (print "My tests 2: train data:") (print train) (print "My tests: test data:") (print test) (let (original-data-column-length) (setq original-data-column-length (length (aref (clml.hjs.read-data:dataset-points train) 0))) (let* ((k 5) (k-nn-estimator (clml.nearest-search.k-nn:k-nn-analyze train k objective-param-name :all :distance manhattan :normalize t))) (print "results for test data:") (print (dataset-points (clml.nearest-search.k-nn:k-nn-estimate k-nn-estimator test)))))) ;;(cancer-data-classifier-example2) ;; code from CLML unit test: (defun cancer-data-classifier-example3 () (let ((train1 (clml.hjs.read-data:read-data-from-file "../machine_learning_data/labeled_cancer_training_data.csv" :type :csv :csv-type-spec (append (make-list 9 :initial-element 'double-float) '(symbol))))) (read-and-print-data train1))) ;; code from CLML unit test: test-classifier.lisp: (defun read-and-print-data (clml-data-set) (print "My tests for reading nd printing a CLML data set:") (let ((testdata (clml.hjs.read-data:dataset-points clml-data-set))) (loop for td across testdata do (print td)))) (defun clml-tests-example() (cancer-data-classifier-example3))
3,783
Common Lisp
.lisp
81
37.740741
121
0.626496
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5d9faf2e91d87b0b06d4e78cf9e4d071b29d757a4dd10c4f28c9c8b9f290eda6
19,252
[ -1 ]
19,253
package.lisp
Eggy115_Lisp/clml_examples/package.lisp
;;;; package.lisp (defpackage #:clmltest (:use #:cl #:clml.hjs.read-data) (:export similar-word-test classify-k-nn clml-cancer-data-svm-example clml-read-data-example clml-kmeans-example clml-tests-example)) (print "!!!!! defpackage clmltest package.lisp loaded.")
285
Common Lisp
.lisp
6
43.166667
72
0.721612
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
cb6f7f75d38c4128d9b985b123dc582b387b7a7c6f4d9a2af4a617004d716b41
19,253
[ -1 ]
19,254
clml_kmeans_clustering.lisp
Eggy115_Lisp/clml_examples/clml_kmeans_clustering.lisp
;; note; run SBCL using: sbcl --dynamic-space-size 2560 (ql:quickload '(:clml :clml.hjs ; utilities :clml.clustering)) (in-package #:clmltest) ;; folowing is derived from test code in CLML: (defun cluster-using-k-nn (test train objective-param-name manhattan) (let (original-data-column-length) (setq original-data-column-length (length (aref (clml.hjs.read-data:dataset-points train) 0))) (let* ((k 5) (k-nn-estimator (clml.nearest-search.k-nn:k-nn-analyze train k objective-param-name :all :distance manhattan :normalize t))) (loop for data across (dataset-points (clml.nearest-search.k-nn:k-nn-estimate k-nn-estimator test)) if (equal (aref data 0) (aref data original-data-column-length)) do (format t "Correct: ~a~%" data) else do (format t "Wrong: ~a~%" data))))) ;; folowing is derived from test code in CLML: (defun cancer-data-cluster-example-read-data () (let ((train1 (clml.hjs.read-data:read-data-from-file "../machine_learning_data/labeled_cancer_training_data.csv" :type :csv :csv-type-spec (append (make-list 9 :initial-element 'double-float) '(symbol)))) (test1 (clml.hjs.read-data:read-data-from-file "../machine_learning_data/labeled_cancer_test_data.csv" :type :csv :csv-type-spec (append (make-list 9 :initial-element 'double-float) '(symbol))))) ;;(print test1) (print (cluster-using-k-nn test1 train1 "Class" :double-manhattan)))) (defun clml-kmeans-example () (cancer-data-cluster-example-read-data))
1,768
Common Lisp
.lisp
37
37.567568
121
0.606043
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e77708f82c058b2bb43e1ed2b698f2c580ef38a85f43146660e3ba24ac53b144
19,254
[ -1 ]
19,255
clml_data_apis.lisp
Eggy115_Lisp/clml_examples/clml_data_apis.lisp
;; note; run SBCL using: sbcl --dynamic-space-size 2560 (ql:quickload '(:clml :clml.hjs)) ; read data sets (in-package #:clmltest) (defun read-data () (let ((train1 (clml.hjs.read-data:read-data-from-file "../machine_learning_data/labeled_cancer_training_data.csv" :type :csv :csv-type-spec (append (make-list 9 :initial-element 'double-float) '(symbol))))) (loop-over-and-print-data train1))) (defun loop-over-and-print-data (clml-data-set) (print "Loop over and print a CLML data set:") (let ((testdata (clml.hjs.read-data:dataset-points clml-data-set))) (loop for td across testdata do (print td)))) (defun clml-read-data-example() (read-data))
798
Common Lisp
.lisp
20
31.4
78
0.604167
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1c4c775bfd465c6855140aec9944553c55f449e418fb4ab50af0b6d629d57d9a
19,255
[ -1 ]
19,256
info.lisp
Eggy115_Lisp/clml_examples/info.lisp
(terpri) (terpri) (princ "*************CLML Examples packacke loaded *****") (terpri) (princ "Try running:") (terpri) (princ "(in-package #:clmltest)") (terpri) (princ "(clml-cancer-data-svm-example)") (terpri) (princ "(clml-read-data-example)") (terpri) (princ "(clml-kmeans-example)") (terpri) (princ "(clml-tests-example)") (terpri) (terpri)
364
Common Lisp
.lisp
17
19.294118
59
0.649275
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
11d402c6e9710ed6e1e01462ac930d138abbf1b0d6cad812aa9fc56b9ab454d9
19,256
[ -1 ]
19,257
clml_svm_classifier.lisp
Eggy115_Lisp/clml_examples/clml_svm_classifier.lisp
;; note; run SBCL using: sbcl --dynamic-space-size 2560 (ql:quickload '(:clml :clml.hjs ; utilities :clml.svm)) ;;(defpackage #:clml-svm-classifier-example1 ;; (:use #:cl #:clml.hjs.read-data)) (in-package #:clmltest) (defun svm-classifier-test (kernel train test) "train and test are lists of lists, with first elements being negative samples and the second elements being positive samples" (let ((decision-function (clml.svm.mu:svm kernel (cadr train) (car train))) (correct-positives 0) (wrong-positives 0) (correct-negatives 0) (wrong-negatives 0)) ;; type: #<CLOSURE (LAMBDA (CLML.SVM.MU::Z) :IN CLML.SVM.MU::DECISION)> (print decision-function) (princ "***** NEGATIVE TESTS: calling decision function:") (terpri) (dolist (neg (car test)) ;; negative test examples (let ((prediction (funcall decision-function neg))) (print prediction) (if prediction (incf wrong-negatives) (incf correct-negatives)))) (princ "***** POSITIVE TESTS: calling decision function:") (terpri) (dolist (pos (cadr test)) ;; positive test examples (let ((prediction (funcall decision-function pos))) (print prediction) (if prediction (incf correct-positives) (incf wrong-positives)))) (format t "Number of correct negatives ~a~%" correct-negatives) (format t "Number of wrong negatives ~a~%" wrong-negatives) (format t "Number of correct positives ~a~%" correct-positives) (format t "Number of wrong positives ~a~%" wrong-positives))) (defun cancer-data-svm-example-read-data () (defun split-positive-negative-cases (data) (let ((negative-cases '()) (positive-cases '())) (dolist (d data) ;;(print (list "* d=" d)) (if (equal (symbol-name (first (last d))) "benign") (setf negative-cases (cons (reverse (cdr (reverse d))) negative-cases)) (setf positive-cases (cons (reverse (cdr (reverse d))) positive-cases)))) (list negative-cases positive-cases))) (let* ((train1 (clml.hjs.read-data:read-data-from-file "../machine_learning_data/labeled_cancer_training_data.csv" :type :csv :csv-type-spec (append (make-list 9 :initial-element 'double-float) '(symbol)))) (train-as-list (split-positive-negative-cases (coerce (map 'list #'(lambda (x) (coerce x 'list)) (coerce (clml.hjs.read-data:dataset-points train1) 'list)) 'list))) (test1 (clml.hjs.read-data:read-data-from-file "../machine_learning_data/labeled_cancer_test_data.csv" :type :csv :csv-type-spec (append (make-list 9 :initial-element 'double-float) '(symbol)))) (test-as-list (split-positive-negative-cases (coerce (map 'list #'(lambda (x) (coerce x 'list)) (coerce (clml.hjs.read-data:dataset-points test1) 'list)) 'list)))) ;; we will use a gaussian kernel for numeric data. ;; note: for text classification, use a clml.svm.mu:+linear-kernel+ (svm-classifier-test (clml.svm.mu:gaussian-kernel 2.0d0) train-as-list test-as-list))) (defun clml-cancer-data-svm-example() (cancer-data-svm-example-read-data))
3,546
Common Lisp
.lisp
76
36.447368
86
0.595652
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c991af4396c0472882b52cee7e2aab7e90156d5ecbf8b7828c160a25fd91243d
19,257
[ -1 ]
19,258
package.lisp
Eggy115_Lisp/trivial-gray-streams-2008-11-02/package.lisp
(in-package :trivial-gray-streams-system) #+cmu (eval-when (:compile-toplevel :load-toplevel :execute) (require :gray-streams)) #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'stream:stream-write-string) (require "streamc.fasl"))) #+ecl (eval-when (:compile-toplevel :load-toplevel :execute) (gray::redefine-cl-functions)) (macrolet ((frob () (let ((common-symbols '(#:fundamental-stream #:fundamental-input-stream #:fundamental-output-stream #:fundamental-character-stream #:fundamental-binary-stream #:fundamental-character-input-stream #:fundamental-character-output-stream #:fundamental-binary-input-stream #:fundamental-binary-output-stream #:stream-read-char #:stream-unread-char #:stream-read-char-no-hang #:stream-peek-char #:stream-listen #:stream-read-line #:stream-clear-input #:stream-write-char #:stream-line-column #:stream-start-line-p #:stream-write-string #:stream-terpri #:stream-fresh-line #:stream-finish-output #:stream-force-output #:stream-clear-output #:stream-advance-to-column #:stream-read-byte #:stream-write-byte))) `(defpackage :trivial-gray-streams (:use :cl) (:import-from #+sbcl :sb-gray #+allegro :excl #+cmu :ext #+clisp :gray #+openmcl :ccl #+lispworks :stream #+ecl :gray #-(or sbcl allegro cmu clisp openmcl lispworks ecl) ... ,@common-symbols) (:export #:trivial-gray-stream-mixin #:stream-read-sequence #:stream-write-sequence #:stream-file-position ,@common-symbols))))) (frob))
1,722
Common Lisp
.lisp
45
31.333333
73
0.652487
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
07ddd754cfb6ddc019f86acb73dd4d953629a38404991fac9c569b05e3704ad2
19,258
[ 147173 ]
19,259
mixin.lisp
Eggy115_Lisp/trivial-gray-streams-2008-11-02/mixin.lisp
(in-package :trivial-gray-streams) (defclass trivial-gray-stream-mixin () ()) (defgeneric stream-read-sequence (stream sequence start end &key &allow-other-keys)) (defgeneric stream-write-sequence (stream sequence start end &key &allow-other-keys)) (defgeneric stream-file-position (stream)) (defgeneric (setf stream-file-position) (newval stream)) (defmethod stream-write-string ((stream trivial-gray-stream-mixin) seq &optional start end) (stream-write-sequence stream seq (or start 0) (or end (length seq)))) ;; Implementations should provide this default method, I believe, but ;; at least sbcl and allegro don't. (defmethod stream-terpri ((stream trivial-gray-stream-mixin)) (write-char #\newline stream)) (defmethod stream-file-position ((stream trivial-gray-stream-mixin)) nil) (defmethod (setf stream-file-position) (newval (stream trivial-gray-stream-mixin)) (declare (ignore newval)) nil) #+allegro (progn (defmethod excl:stream-read-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-read-sequence s seq (or start 0) (or end (length seq)))) (defmethod stream:stream-write-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-write-sequence s seq (or start 0) (or end (length seq))))) #+cmu (progn (defmethod ext:stream-read-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-read-sequence s seq (or start 0) (or end (length seq)))) (defmethod ext:stream-write-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-write-sequence s seq (or start 0) (or end (length seq))))) #+lispworks (progn (defmethod stream:stream-read-sequence ((s trivial-gray-stream-mixin) seq start end) (stream-read-sequence s seq start end)) (defmethod stream:stream-write-sequence ((s trivial-gray-stream-mixin) seq start end) (stream-write-sequence s seq start end)) (defmethod stream:stream-file-position ((stream trivial-gray-stream-mixin)) (stream-file-position stream)) (defmethod (setf stream:stream-file-position) (newval (stream trivial-gray-stream-mixin)) (setf (stream-file-position stream) newval))) #+openmcl (progn (defmethod ccl:stream-read-vector ((s trivial-gray-stream-mixin) seq start end) (stream-read-sequence s seq start end)) (defmethod ccl:stream-write-vector ((s trivial-gray-stream-mixin) seq start end) (stream-write-sequence s seq start end))) ;; up to version 2.43 there were no ;; stream-read-sequence, stream-write-sequence ;; functions in CLISP #+clisp (eval-when (:compile-toplevel :load-toplevel :execute) (when (find-symbol "STREAM-READ-SEQUENCE" "GRAY") (pushnew :clisp-has-stream-read/write-sequence *features*))) #+clisp (progn #+clisp-has-stream-read/write-sequence (defmethod gray:stream-read-sequence (seq (s trivial-gray-stream-mixin) &key start end) (stream-read-sequence s seq (or start 0) (or end (length seq)))) #+clisp-has-stream-read/write-sequence (defmethod gray:stream-write-sequence (seq (s trivial-gray-stream-mixin) &key start end) (stream-write-sequence s seq (or start 0) (or end (length seq)))) ;; Even despite the stream-read/write-sequence are present in newer ;; CLISP, it's better to provide stream-(read/write)-(byte/char)-sequence ;; methods too. ;; Example: if fundamental-binary-input-stream comes in the ;; class precedence list of your user-defined stream before ;; the trivial-gray-steam-mixin, the default CLISP's implementation ;; of the gray:stream-read-sequence will be used; and this default ;; implementation calls the gray:stream-read-byte-sequence. ;; Therefore we override gray:stream-read-byte-sequence and call ;; our stream-read-sequence. (defmethod gray:stream-read-byte-sequence ((s trivial-gray-stream-mixin) seq &optional start end no-hang interactive) (when no-hang (error "this stream does not support the NO-HANG argument")) (when interactive (error "this stream does not support the INTERACTIVE argument")) (stream-read-sequence s seq start end)) (defmethod gray:stream-write-byte-sequence ((s trivial-gray-stream-mixin) seq &optional start end no-hang interactive) (when no-hang (error "this stream does not support the NO-HANG argument")) (when interactive (error "this stream does not support the INTERACTIVE argument")) (stream-write-sequence s seq start end)) (defmethod gray:stream-read-char-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-read-sequence s seq start end)) (defmethod gray:stream-write-char-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-write-sequence s seq start end)) (defmethod gray:stream-position ((stream trivial-gray-stream-mixin) position) (if position (setf (stream-file-position stream) position) (stream-file-position stream)))) #+sbcl (progn (defmethod sb-gray:stream-read-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-read-sequence s seq (or start 0) (or end (length seq)))) (defmethod sb-gray:stream-write-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-write-sequence s seq (or start 0) (or end (length seq)))) ;; SBCL extension: (defmethod sb-gray:stream-line-length ((stream trivial-gray-stream-mixin)) 80)) #+ecl (progn (defmethod gray:stream-read-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-read-sequence s seq (or start 0) (or end (length seq)))) (defmethod gray:stream-write-sequence ((s trivial-gray-stream-mixin) seq &optional start end) (stream-write-sequence s seq (or start 0) (or end (length seq)))))
6,000
Common Lisp
.lisp
132
40.204545
80
0.710553
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5d227d92fc054ed092d9ea76d999f1d3a3fd0db05819469e7a5c3a2f5c77f038
19,259
[ 298331 ]
19,260
package.lisp
Eggy115_Lisp/lw-grapher/package.lisp
;;;; package.lisp (defpackage :lw-grapher (:use #:cl #:CAPI) (:export #:grapher #:info-pane-grapher #:make-text-node #:make-info-panel-grapher))
157
Common Lisp
.lisp
4
35.25
86
0.66443
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7bb91802cae9bb3fc5d05e3bfa098a2d46f9d6a1a185bad9029c7d7193bd5ab5
19,260
[ -1 ]
19,261
lw-grapher.lisp
Eggy115_Lisp/lw-grapher/lw-grapher.lisp
(in-package :lw-grapher) ;; A simple Grapher using the layout algorithm from the ISI-Grapher user guide ;; Some code derived from LispWorks CAPI examples drag-and-drop.lisp and circled-graph-nodes.lisp (defclass text-node (capi:pinboard-object) ((text :initarg :text :reader text-node-text) (string-x-offset :accessor text-node-string-x-offset) (string-y-offset :accessor text-node-string-y-offset))) (defmethod capi:draw-pinboard-object (pinboard (self text-node) &key &allow-other-keys) (multiple-value-bind (X Y width height) (capi:static-layout-child-geometry self) (let* ((half-width (floor (1- width) 2)) (half-height (floor (1- height) 2)) (circle-x (+ X half-width)) (circle-y (+ Y half-height)) (background :white) (foreground (if background :black (capi:simple-pane-foreground pinboard))) (text (text-node-text self))) (when background (gp:draw-ellipse pinboard circle-x circle-y half-width half-height :filled t :foreground background)) (gp:draw-ellipse pinboard circle-x circle-y half-width half-height :foreground foreground) (gp:draw-string pinboard text (+ X (text-node-string-x-offset self)) (+ Y (text-node-string-y-offset self)) :foreground foreground)))) (defun make-node (graph-pane node) (declare (ignorable graph-pane)) (make-instance 'text-node :text (format nil "~A" node))) (defmethod capi:calculate-constraints ((self text-node)) (let* ((pl (capi:pinboard-object-pinboard self)) (font (capi:simple-pane-font pl))) (multiple-value-bind (left top right bottom) (gp:get-string-extent (capi:pinboard-object-pinboard self) (text-node-text self) font) (let* ((width (+ 12 (- right left))) (height (+ 12 (- bottom top)))) (setf (text-node-string-x-offset self) (floor (- width (- right left)) 2) (text-node-string-y-offset self ) (+ (floor (- height (- bottom top)) 2) (gp:get-font-ascent pl font))) (capi:with-geometry self (setf capi:%width% width capi:%min-width% width capi:%height% height capi:%min-height% height)))))) (defvar *last-selected-node* nil) (defun handle-mouse-click-on-pane (pane x y) (format t "++ handle-mouse-click-on-pane x=~a y=~a~%" x y) (let ((object (capi:pinboard-object-at-position pane x y))) (format t "---- object=~A~%" object) (if object (let () (if *last-selected-node* (capi:unhighlight-pinboard-object pane *last-selected-node*)) (setf *last-selected-node* object) (capi:highlight-pinboard-object pane object))))) (defun graph-layout (self &key force) (declare (ignore force)) (let* ((nodes (capi:graph-pane-nodes self)) (last-y 0) ;;(height 30) ;;(width 80) ) (format t "~%++++ nodes: ~A~%~%" nodes) (dolist (node nodes) (pprint node) (setf (capi:graph-node-x node) 0 (capi:graph-node-y node) 0)) (labels ((get-unlaid-out-child-nodes (a-node) (let (ret) (dolist (x (capi:graph-node-children a-node)) (if (equal (capi:graph-node-children x) 0) (setf ret (cons x ret)))) (reverse ret))) (get-average-Y-of-node-list (a-node-list) (let ((average 0)) (dolist (another-node a-node-list) (setf average (+ average (capi:graph-node-y another-node)))) (if (equal (length a-node-list) 0) 0 (floor (/ average (length a-node-list)))))) (get-average-X-of-node-list (a-node-list) (let ((average 0)) (dolist (a-node a-node-list) (setf average (+ average (capi:graph-node-x a-node)))) (if (equal (length a-node-list) 0) 0 (floor (/ average (length a-node-list)))))) (layout-Y (a-node) (let ((children (capi:graph-node-children a-node)) (children-needing-layout (get-unlaid-out-child-nodes a-node))) (if (equal (capi:graph-node-y a-node) 0) ;; check in node n has any unlayed-out child nodes (if (> (length children-needing-layout) 0) (let () (dolist (child-node children-needing-layout) (layout-Y child-node)) (setf (capi:graph-node-y a-node) (get-average-Y-of-node-list children))) ;; layout a leaf node: (let () (setf (capi:graph-node-y a-node) (+ last-y (capi:graph-node-height a-node) 5)) (setf last-y (capi:graph-node-y a-node))))))) (get-parents (a-node) (let (ret) (dolist (possible-parent nodes) (dolist (child-to-check (capi:graph-node-children possible-parent)) (if (equal child-to-check a-node) (setf ret (cons possible-parent ret))))) (reverse ret))) (get-all-leaf-nodes () (let (ret) (dolist (node nodes) (if (equal (length (capi:graph-node-children node)) 0) (setf ret (cons node ret)))) (reverse ret))) (layout-X (a-node) (if (equal (capi:graph-node-x a-node) 0) (let ((parents (get-parents a-node))) (if (> (length parents) 0) (let ((max-val 0)) (dolist (parent parents) (layout-X parent)) (dolist (parent parents) (let ((w (+ (capi:graph-node-x parent) (capi:graph-node-width a-node) 9))) (if (> w max-val) (setf max-val w)))) (setf (capi:graph-node-x a-node) max-val))))))) ;; process in Y direction (dolist (root nodes) ;; (capi:graph-pane-roots self)) (layout-Y root)) ;; process in X direction (dolist (a-leaf (get-all-leaf-nodes)) (layout-x a-leaf))))) #| (defun node-children (node) (format t "node: ~S~%" node) (cadr (assoc node '((1 (2 41)) (2 (33 "text node")) (100 '(2 33)) (555 '(100)) (888 (41 999999000111)) ("base-node-0" (1 "text node"))) :test #'equal))) (capi:contain (make-instance 'capi:graph-pane :roots '(1 100 "base-node-0" 555 888) :layout-function 'graph-layout :children-function 'node-children :node-pinboard-class 'text-node :input-model `(((:button-1 :release) ;; :press) ,#'(lambda (pane x y) (handle-mouse-click-on-pane pane x y)))) :node-pane-function 'make-text-node)) |#
7,655
Common Lisp
.lisp
172
30.197674
100
0.49819
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
937061b05d27415220a58f5965bea7ddc77b3775b68e5f2e026cde6b8c479be0
19,261
[ -1 ]
19,262
info-pane-grapher.lisp
Eggy115_Lisp/lw-grapher/info-pane-grapher.lisp
(in-package :lw-grapher) ;; A Grapher (using the layout algorithm from the ISI-Grapher user guide) with an info panel (defun make-info-panel-grapher (h-root-name-list h-edge-list h-callback-function-click h-callback-function-shift-click) (format t "++ make-info-panel-grapher: h-root-name-list: ~S h-edge-list: ~S~%" h-root-name-list h-edge-list) (let (edges roots last-selected-node node-callback-click node-callback-click-shift output-pane) (labels ((handle-mouse-click-on-pane (pane x y) (ignore-errors (let ((object (capi:pinboard-object-at-position pane x y))) (if object (let () (if last-selected-node (capi:unhighlight-pinboard-object pane last-selected-node)) (setf last-selected-node object) (capi:highlight-pinboard-object pane object) (let ((c-stream (collector-pane-stream output-pane))) (format c-stream (funcall node-callback-click (text-node-full-text object))) (terpri c-stream))))))) (handle-mouse-click-shift-on-pane (pane x y) (ignore-errors (let ((object (capi:pinboard-object-at-position pane x y))) (if object (let () (if last-selected-node (capi:unhighlight-pinboard-object pane last-selected-node)) (setf last-selected-node object) (capi:highlight-pinboard-object pane object) (let ((c-stream (collector-pane-stream output-pane))) (format c-stream (funcall node-callback-click-shift (text-node-full-text object))) (terpri c-stream))))))) (info-panel-node-children-helper (node-text) (format t "-- info-panel-node-children-helper node-text: ~S~%" node-text) (let (ret) (dolist (e edges) (if (equal (first e) node-text) (setf ret (cons (second e) ret)))) (format t "- return from info-panel-node-children-helper: ~A~%" (reverse ret)) (reverse ret))) (make-info-panel-grapher-helper (root-name-list edge-list callback-function-click callback-function-click-shift) ;; example: root-name-list: '("n1") edge-list: '(("n1" "n2") ("n1" "n3")) (setf edges edge-list roots root-name-list node-callback-click callback-function-click node-callback-click-shift callback-function-click-shift) (capi:contain (make-instance 'column-layout :title "Entity Browser" :description (list (make-instance 'capi:graph-pane :min-height 330 :max-height 420 :roots roots :layout-function 'graph-layout :children-function #'info-panel-node-children-helper :edge-pane-function #'(lambda(self from to) (declare (ignore self)) (let ((prop-name "")) (dolist (edge edge-list) (if (and (equal from (first edge)) (equal to (second edge))) (if (and (> (length edge) 2) (third edge)) (let ((last-index (search "/" (third edge) :from-end t))) (if last-index (setf prop-name (subseq (third edge) (1+ last-index))) (setf prop-name (third edge))))))) (make-instance 'capi:labelled-arrow-pinboard-object :data (format nil "~A" prop-name)))) :node-pinboard-class 'text-node :input-model `(((:button-1 :release) ,#'(lambda (pane x y) (handle-mouse-click-on-pane pane x y))) ((:button-1 :release :shift) ;; :press) ,#'(lambda (pane x y) (handle-mouse-click-shift-on-pane pane x y)))) :node-pane-function 'make-text-node) (setf output-pane (make-instance 'capi:collector-pane :min-height 130 :max-height 220 :title "Message collection pane" :text "..." :vertical-scroll t :horizontal-scroll t)))) :title "Info Pane Browser: mouse click for info, mouse click + shift for web browser" :best-width 550 :best-height 450))) (make-info-panel-grapher-helper h-root-name-list h-edge-list h-callback-function-click h-callback-function-shift-click))))
5,641
Common Lisp
.lisp
92
36.184783
130
0.454016
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ed288ac0bde7c0b90e4b03c3ea9b8367fd22f4c5152f1ebb1cb6dff89ccf3009
19,262
[ -1 ]
19,263
grapher.lisp
Eggy115_Lisp/lw-grapher/grapher.lisp
(in-package :lw-grapher) ;; A simple Grapher using the layout algorithm from the ISI-Grapher user guide (defun graph-layout (self &key force) (declare (ignore force)) (let* ((nodes (capi:graph-pane-nodes self)) (last-y 0) (horizontal-spacing 35) (vertical-spacing 24) ;;(height 30) ;;(width 80) ) (format t "~%++++ nodes: ~A~%~%" nodes) (dolist (node nodes) (pprint node) (setf (capi:graph-node-x node) 0 (capi:graph-node-y node) 0)) (labels ((get-unlaid-out-child-nodes (a-node) (let (ret) (dolist (x (capi:graph-node-children a-node)) (if (equal (capi:graph-node-children x) 0) (setf ret (cons x ret)))) (reverse ret))) (get-average-Y-of-node-list (a-node-list) (let ((average 0)) (dolist (another-node a-node-list) (setf average (+ average (capi:graph-node-y another-node)))) (if (equal (length a-node-list) 0) 0 (floor (/ average (length a-node-list)))))) (get-average-X-of-node-list (a-node-list) (let ((average 0)) (dolist (a-node a-node-list) (setf average (+ average (capi:graph-node-x a-node)))) (if (equal (length a-node-list) 0) 0 (floor (/ average (length a-node-list)))))) (layout-Y (a-node) (let ((children (capi:graph-node-children a-node)) (children-needing-layout (get-unlaid-out-child-nodes a-node))) (if (equal (capi:graph-node-y a-node) 0) ;; check in node n has any unlayed-out child nodes (if (> (length children-needing-layout) 0) (let () (dolist (child-node children-needing-layout) (layout-Y child-node)) (setf (capi:graph-node-y a-node) (get-average-Y-of-node-list children))) ;; layout a leaf node: (let () (setf (capi:graph-node-y a-node) (+ last-y (capi:graph-node-height a-node) vertical-spacing)) (setf last-y (capi:graph-node-y a-node))))))) (get-parents (a-node) (let (ret) (dolist (possible-parent nodes) (dolist (child-to-check (capi:graph-node-children possible-parent)) (if (equal child-to-check a-node) (setf ret (cons possible-parent ret))))) (reverse ret))) (get-all-leaf-nodes () (let (ret) (dolist (node nodes) (if (equal (length (capi:graph-node-children node)) 0) (setf ret (cons node ret)))) (reverse ret))) (layout-X (a-node) (if (equal (capi:graph-node-x a-node) 0) (let ((parents (get-parents a-node))) (if (> (length parents) 0) (let ((max-val 0)) (dolist (parent parents) (layout-X parent)) (dolist (parent parents) (let ((w (+ (capi:graph-node-x parent) (capi:graph-node-width a-node) horizontal-spacing))) (if (> w max-val) (setf max-val w)))) (setf (capi:graph-node-x a-node) max-val))))))) ;; process in Y direction (dolist (root nodes) ;; (capi:graph-pane-roots self)) (layout-Y root)) ;; process in X direction (dolist (a-leaf (get-all-leaf-nodes)) (layout-x a-leaf))))) (let (edges roots) (defun node-children-helper (node-text) (format t "-- node-children-helper node-text: ~S~%" node-text) (let (ret) (dolist (e edges) (if (equal (first e) node-text) (setf ret (cons (second e) ret)))) (format t "- return from node-children-helper: ~A~%" (reverse ret)) (reverse ret))) (defun make-grapher (root-name-list edge-list) ;; example: root-name-list: '("n1") edge-list: '(("n1" "n2") ("n1" "n3")) (setf edges edge-list roots root-name-list) (capi:contain (make-instance 'capi:graph-pane :roots roots :layout-function 'graph-layout :children-function 'node-children-helper :node-pinboard-class 'text-node :node-pane-function 'make-text-node) :best-width 300 :best-height 400)))
4,718
Common Lisp
.lisp
104
31.038462
117
0.496303
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f2dcef071bf3c467bfe2e35072373ff4ef5b7af3f4d600529c3ddbba5328c3a1
19,263
[ -1 ]
19,264
text-node.lisp
Eggy115_Lisp/lw-grapher/text-node.lisp
(in-package :lw-grapher) ;; A text node class for use with simple Grapher and info panel Grapher (defclass text-node (capi:pinboard-object) ((text :initarg :text :reader text-node-text) (full-text :initarg :full-text :reader text-node-full-text) (string-x-offset :accessor text-node-string-x-offset) (string-y-offset :accessor text-node-string-y-offset))) (defmethod capi:draw-pinboard-object (pinboard (self text-node) ;; code derived from LispWorks CAPI examples &key &allow-other-keys) (multiple-value-bind (X Y width height) (capi:static-layout-child-geometry self) (let* ((half-width (floor (1- width) 2)) (half-height (floor (1- height) 2)) (circle-x (+ X half-width)) (circle-y (+ Y half-height)) (background :white) (foreground (if background :black (capi:simple-pane-foreground pinboard))) (text (text-node-text self))) (when background (gp:draw-ellipse pinboard circle-x circle-y half-width half-height :filled t :foreground background)) (gp:draw-ellipse pinboard circle-x circle-y half-width half-height :foreground foreground) (gp:draw-string pinboard text (+ X (text-node-string-x-offset self)) (+ Y (text-node-string-y-offset self)) :foreground foreground)))) (defun make-text-node (graph-pane node) (declare (ignorable graph-pane)) (let* ((node-name (format nil "~A" node)) (last-index (search "/" node :from-end t))) (if last-index (make-instance 'text-node :text (myutils:replace-all (myutils:replace-all (subseq node-name (1+ last-index)) "_" " ") ">" "") :full-text node-name) (make-instance 'text-node :text node-name :full-text node-name)))) (defmethod capi:calculate-constraints ((self text-node)) ;; code derived from LispWorks CAPI examples (let* ((pl (capi:pinboard-object-pinboard self)) (font (capi:simple-pane-font pl))) (multiple-value-bind (left top right bottom) (gp:get-string-extent (capi:pinboard-object-pinboard self) (text-node-text self) font) (let* ((width (+ 12 (- right left))) (height (+ 12 (- bottom top)))) (setf (text-node-string-x-offset self) (floor (- width (- right left)) 2) (text-node-string-y-offset self ) (+ (floor (- height (- bottom top)) 2) (gp:get-font-ascent pl font))) (capi:with-geometry self (setf capi:%width% width capi:%min-width% width capi:%height% height capi:%min-height% height))))))
3,109
Common Lisp
.lisp
62
35.419355
156
0.535397
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3d71eb43130a230c19d74f5b0af2969c8b67f5573272a2adbbe3961736351cc1
19,264
[ -1 ]
19,265
package.lisp
Eggy115_Lisp/wolfram/package.lisp
(defpackage #:wolfram (:use #:cl #:uiop) (:export #:wolfram #:cleanup-lists #:find-answer-in-text #:entities))
120
Common Lisp
.lisp
3
36
72
0.652174
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3afa8d983180d6dfd2cb7e9ab500d22858e691da2966abe51459a334a4e2ba1c
19,265
[ -1 ]
19,266
wolfram.lisp
Eggy115_Lisp/wolfram/wolfram.lisp
(in-package #:wolfram) (defun wolfram (statement) (uiop:run-program (concatenate 'string "wolframscript -code 'Export[\"test44.txt\"," statement ",\"ExpressionJSON\"]'")) (let* ((ret (uiop:read-file-string "test44.txt"))) (delete-file "test44.txt") (with-input-from-string (s (myutils:replace-all (myutils:replace-all ret "\"'" "\"") "'\"" "\"")) (json:decode-json s)))) (defun cleanup-lists (r) (cdr (recursive-remove "Rule" (recursive-remove "List" r)))) (defun recursive-remove (item tree) (if (atom tree) tree (mapcar (lambda (nested-list) (recursive-remove item nested-list)) (remove item tree :test #'equal)))) #| (defvar example "TextCases['NYC, Los Angeles, and Chicago are the largest cities in the USA in 2018 according to Pete Wilson.', {'City', 'Country', 'Date', 'Person'} -> {'String', 'Interpretation', 'Probability'}]") (defvar example-str (myutils:replace-all example "'" "\"")) (defvar results (wolfram:wolfram example-str)) (pprint results) (defvar results-cleaned (wolfram:cleanup-lists results)) (pprint results-cleaned) |#
1,141
Common Lisp
.lisp
24
42.583333
216
0.661831
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
476be313542d1fecb0e908d2f5d3f97f3e733e8ec9ddc691c612368626957ca4
19,266
[ -1 ]
19,267
test.lisp
Eggy115_Lisp/db_sqlite/test.lisp
(dbi:with-connection (conn :sqlite3 :database-name "test.db") (let* ((query (dbi:prepare conn "SELECT sql FROM sqlite_master WHERE type='table' and name='test'")) (result (dbi:execute query))) (loop for row = (dbi:fetch result) while row do (format t "meta data: ~A~%" row)))) (defvar *z* nil) (dbi:with-connection (conn :sqlite3 :database-name "test.db") (let* ((query (dbi:prepare conn "SELECT * FROM test")) (result (dbi:execute query))) (loop for row = (dbi:fetch result) while row do (setf *z* row) (format t "select all: ~A~%" row)))) ;; * *z* ;; printed value: (:|id| 1 :|str| "cat stand")
697
Common Lisp
.lisp
17
34.176471
103
0.58457
Eggy115/Lisp
2
2
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7205a12ed2213a60e1e40a5dda062f7d37fc83581886d6910c2b58213f4024f5
19,267
[ -1 ]