_id
stringlengths
64
64
repository
stringlengths
6
84
name
stringlengths
4
110
content
stringlengths
0
248k
license
null
download_url
stringlengths
89
454
language
stringclasses
7 values
comments
stringlengths
0
74.6k
code
stringlengths
0
248k
d006401b079da6bde803bf9ad10af31e7cf6eca00a96335c277ee983a7af57c7
sharplispers/ironclad
secp384r1.lisp
;;;; -*- mode: lisp; indent-tabs-mode: nil -*- ;;;; secp384r1.lisp -- secp384r1 (a.k.a. NIST P-384) elliptic curve (in-package :crypto) ;;; class definitions (defclass secp384r1-public-key () ((y :initarg :y :reader secp384r1-key-y :type (simple-array (unsigned-byte 8) (*))))) (defclass secp384r1-private-key () ((x :initarg :x :reader secp384r1-key-x :type (simple-array (unsigned-byte 8) (*))) (y :initarg :y :reader secp384r1-key-y :type (simple-array (unsigned-byte 8) (*))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defclass secp384r1-point () Internally , a point ( x , y ) is represented using the Jacobian projective ;; coordinates (X, Y, Z), with x = X / Z^2 and y = Y / Z^3. ((x :initarg :x :type integer) (y :initarg :y :type integer) (z :initarg :z :type integer))) (defmethod make-load-form ((p secp384r1-point) &optional env) (declare (ignore env)) (make-load-form-saving-slots p))) ;;; constant and function definitions (defconstant +secp384r1-bits+ 384) (defconstant +secp384r1-p+ 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319) (defconstant +secp384r1-b+ 27580193559959705877849011840389048093056905856361568521428707301988689241309860865136260764883745107765439761230575) (defconstant +secp384r1-l+ 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643) (defconstant +secp384r1-i+ 29551504647295859409209280075107710353809804452849085000961220053184291328622652746785449566194203501396205229834239) (defconst +secp384r1-g+ (make-instance 'secp384r1-point :x 26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087 :y 8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871 :z 1)) (defconst +secp384r1-point-at-infinity+ (make-instance 'secp384r1-point :x 1 :y 1 :z 0)) (defmethod ec-scalar-inv ((kind (eql :secp384r1)) n) (expt-mod n (- +secp384r1-p+ 2) +secp384r1-p+)) (defmethod ec-point-equal ((p secp384r1-point) (q secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots ((x1 x) (y1 y) (z1 z)) p (declare (type integer x1 y1 z1)) (with-slots ((x2 x) (y2 y) (z2 z)) q (declare (type integer x2 y2 z2)) (let ((z1z1 (mod (* z1 z1) +secp384r1-p+)) (z2z2 (mod (* z2 z2) +secp384r1-p+))) (and (zerop (mod (- (* x1 z2z2) (* x2 z1z1)) +secp384r1-p+)) (zerop (mod (- (* y1 z2z2 z2) (* y2 z1z1 z1)) +secp384r1-p+))))))) (defmethod ec-double ((p secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots ((x1 x) (y1 y) (z1 z)) p (declare (type integer x1 y1 z1)) (if (zerop z1) +secp384r1-point-at-infinity+ (let* ((xx (mod (* x1 x1) +secp384r1-p+)) (yy (mod (* y1 y1) +secp384r1-p+)) (yyyy (mod (* yy yy) +secp384r1-p+)) (zz (mod (* z1 z1) +secp384r1-p+)) (x1+yy (mod (+ x1 yy) +secp384r1-p+)) (y1+z1 (mod (+ y1 z1) +secp384r1-p+)) (s (mod (* 2 (- (* x1+yy x1+yy) xx yyyy)) +secp384r1-p+)) (m (mod (* 3 (- xx (* zz zz))) +secp384r1-p+)) (u (mod (- (* m m) (* 2 s)) +secp384r1-p+)) (x2 u) (y2 (mod (- (* m (- s u)) (* 8 yyyy)) +secp384r1-p+)) (z2 (mod (- (* y1+z1 y1+z1) yy zz) +secp384r1-p+))) (make-instance 'secp384r1-point :x x2 :y y2 :z z2))))) (defmethod ec-add ((p secp384r1-point) (q secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots ((x1 x) (y1 y) (z1 z)) p (declare (type integer x1 y1 z1)) (with-slots ((x2 x) (y2 y) (z2 z)) q (declare (type integer x2 y2 z2)) (cond ((zerop z1) q) ((zerop z2) p) (t (let* ((z1z1 (mod (* z1 z1) +secp384r1-p+)) (z2z2 (mod (* z2 z2) +secp384r1-p+)) (u1 (mod (* x1 z2z2) +secp384r1-p+)) (u2 (mod (* x2 z1z1) +secp384r1-p+)) (s1 (mod (* y1 z2 z2z2) +secp384r1-p+)) (s2 (mod (* y2 z1 z1z1) +secp384r1-p+))) (if (= u1 u2) (if (= s1 s2) (ec-double p) +secp384r1-point-at-infinity+) (let* ((h (mod (- u2 u1) +secp384r1-p+)) (i (mod (* 4 h h) +secp384r1-p+)) (j (mod (* h i) +secp384r1-p+)) (r (mod (* 2 (- s2 s1)) +secp384r1-p+)) (v (mod (* u1 i) +secp384r1-p+)) (x3 (mod (- (* r r) j (* 2 v)) +secp384r1-p+)) (y3 (mod (- (* r (- v x3)) (* 2 s1 j)) +secp384r1-p+)) (z1+z2 (mod (+ z1 z2) +secp384r1-p+)) (z3 (mod (* (- (* z1+z2 z1+z2) z1z1 z2z2) h) +secp384r1-p+))) (make-instance 'secp384r1-point :x x3 :y y3 :z z3))))))))) (defmethod ec-scalar-mult ((p secp384r1-point) e) Point multiplication on NIST P-384 curve using the Montgomery ladder . (declare (optimize (speed 3) (safety 0) (space 0) (debug 0)) (type integer e)) (do ((r0 +secp384r1-point-at-infinity+) (r1 p) (i (1- +secp384r1-bits+) (1- i))) ((minusp i) r0) (declare (type secp384r1-point r0 r1) (type fixnum i)) (if (logbitp i e) (setf r0 (ec-add r0 r1) r1 (ec-double r1)) (setf r1 (ec-add r0 r1) r0 (ec-double r0))))) (defmethod ec-point-on-curve-p ((p secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots (x y z) p (declare (type integer x y z)) (let* ((y2 (mod (* y y) +secp384r1-p+)) (x3 (mod (* x x x) +secp384r1-p+)) (z2 (mod (* z z) +secp384r1-p+)) (z4 (mod (* z2 z2) +secp384r1-p+)) (z6 (mod (* z4 z2) +secp384r1-p+)) (a (mod (+ x3 (* -3 x z4) (* +secp384r1-b+ z6)) +secp384r1-p+))) (declare (type integer y2 x3 z2 z4 z6 a)) (zerop (mod (- y2 a) +secp384r1-p+))))) (defmethod ec-encode-scalar ((kind (eql :secp384r1)) n) (integer-to-octets n :n-bits +secp384r1-bits+ :big-endian t)) (defmethod ec-decode-scalar ((kind (eql :secp384r1)) octets) (octets-to-integer octets :big-endian t)) (defmethod ec-encode-point ((p secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots (x y z) p (declare (type integer x y z)) (when (zerop z) (error 'ironclad-error :format-control "The point at infinity can't be encoded.")) (let* ((invz (ec-scalar-inv :secp384r1 z)) (invz2 (mod (* invz invz) +secp384r1-p+)) (invz3 (mod (* invz2 invz) +secp384r1-p+)) (x (mod (* x invz2) +secp384r1-p+)) (y (mod (* y invz3) +secp384r1-p+))) (concatenate '(simple-array (unsigned-byte 8) (*)) (vector 4) (ec-encode-scalar :secp384r1 x) (ec-encode-scalar :secp384r1 y))))) (defmethod ec-decode-point ((kind (eql :secp384r1)) octets) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (case (aref octets 0) ((2 3) ;; Compressed point (if (= (length octets) (1+ (/ +secp384r1-bits+ 8))) (let* ((x-bytes (subseq octets 1 (1+ (/ +secp384r1-bits+ 8)))) (x (ec-decode-scalar :secp384r1 x-bytes)) (y-sign (- (aref octets 0) 2)) (y2 (mod (+ (* x x x) (* -3 x) +secp384r1-b+) +secp384r1-p+)) (y (expt-mod y2 +secp384r1-i+ +secp384r1-p+)) (y (if (= (logand y 1) y-sign) y (- +secp384r1-p+ y))) (p (make-instance 'secp384r1-point :x x :y y :z 1))) (if (ec-point-on-curve-p p) p (error 'invalid-curve-point :kind 'secp384r1))) (error 'invalid-curve-point :kind 'secp384r1))) ((4) ;; Uncompressed point (if (= (length octets) (1+ (/ +secp384r1-bits+ 4))) (let* ((x-bytes (subseq octets 1 (1+ (/ +secp384r1-bits+ 8)))) (x (ec-decode-scalar :secp384r1 x-bytes)) (y-bytes (subseq octets (1+ (/ +secp384r1-bits+ 8)))) (y (ec-decode-scalar :secp384r1 y-bytes)) (p (make-instance 'secp384r1-point :x x :y y :z 1))) (if (ec-point-on-curve-p p) p (error 'invalid-curve-point :kind 'secp384r1))) (error 'invalid-curve-point :kind 'secp384r1))) (t (error 'invalid-curve-point :kind 'secp384r1)))) (defun secp384r1-public-key (sk) (let ((a (ec-decode-scalar :secp384r1 sk))) (ec-encode-point (ec-scalar-mult +secp384r1-g+ a)))) (defmethod make-signature ((kind (eql :secp384r1)) &key r s &allow-other-keys) (unless r (error 'missing-signature-parameter :kind 'secp384r1 :parameter 'r :description "first signature element")) (unless s (error 'missing-signature-parameter :kind 'secp384r1 :parameter 's :description "second signature element")) (concatenate '(simple-array (unsigned-byte 8) (*)) r s)) (defmethod destructure-signature ((kind (eql :secp384r1)) signature) (let ((length (length signature))) (if (/= length (/ +secp384r1-bits+ 4)) (error 'invalid-signature-length :kind 'secp384r1) (let* ((middle (/ length 2)) (r (subseq signature 0 middle)) (s (subseq signature middle))) (list :r r :s s))))) (defmethod generate-signature-nonce ((key secp384r1-private-key) message &optional parameters) (declare (ignore key message parameters)) (or *signature-nonce-for-test* (1+ (strong-random (1- +secp384r1-l+))))) ;;; Note that hashing is not performed here. (defmethod sign-message ((key secp384r1-private-key) message &key (start 0) end &allow-other-keys) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (let* ((end (min (or end (length message)) (/ +secp384r1-bits+ 8))) (sk (ec-decode-scalar :secp384r1 (secp384r1-key-x key))) (k (generate-signature-nonce key message)) (invk (modular-inverse-with-blinding k +secp384r1-l+)) (r (ec-scalar-mult +secp384r1-g+ k)) (x (subseq (ec-encode-point r) 1 (1+ (/ +secp384r1-bits+ 8)))) (r (ec-decode-scalar :secp384r1 x)) (r (mod r +secp384r1-l+)) (h (subseq message start end)) (e (ec-decode-scalar :secp384r1 h)) (s (mod (* invk (+ e (* sk r))) +secp384r1-l+))) (if (not (or (zerop r) (zerop s))) (make-signature :secp384r1 :r (ec-encode-scalar :secp384r1 r) :s (ec-encode-scalar :secp384r1 s)) (sign-message key message :start start :end end)))) (defmethod verify-signature ((key secp384r1-public-key) message signature &key (start 0) end &allow-other-keys) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (unless (= (length signature) (/ +secp384r1-bits+ 4)) (error 'invalid-signature-length :kind 'secp384r1)) (let* ((end (min (or end (length message)) (/ +secp384r1-bits+ 8))) (pk (ec-decode-point :secp384r1 (secp384r1-key-y key))) (signature-elements (destructure-signature :secp384r1 signature)) (r (ec-decode-scalar :secp384r1 (getf signature-elements :r))) (s (ec-decode-scalar :secp384r1 (getf signature-elements :s))) (h (subseq message start end)) (e (ec-decode-scalar :secp384r1 h)) (w (modular-inverse-with-blinding s +secp384r1-l+)) (u1 (mod (* e w) +secp384r1-l+)) (u2 (mod (* r w) +secp384r1-l+)) (rp (ec-add (ec-scalar-mult +secp384r1-g+ u1) (ec-scalar-mult pk u2))) (x (subseq (ec-encode-point rp) 1 (1+ (/ +secp384r1-bits+ 8)))) (v (ec-decode-scalar :secp384r1 x)) (v (mod v +secp384r1-l+))) (and (< r +secp384r1-l+) (< s +secp384r1-l+) (= v r)))) (defmethod make-public-key ((kind (eql :secp384r1)) &key y &allow-other-keys) (unless y (error 'missing-key-parameter :kind 'secp384r1 :parameter 'y :description "public key")) (make-instance 'secp384r1-public-key :y y)) (defmethod destructure-public-key ((public-key secp384r1-public-key)) (list :y (secp384r1-key-y public-key))) (defmethod make-private-key ((kind (eql :secp384r1)) &key x y &allow-other-keys) (unless x (error 'missing-key-parameter :kind 'secp384r1 :parameter 'x :description "private key")) (make-instance 'secp384r1-private-key :x x :y (or y (secp384r1-public-key x)))) (defmethod destructure-private-key ((private-key secp384r1-private-key)) (list :x (secp384r1-key-x private-key) :y (secp384r1-key-y private-key))) (defmethod generate-key-pair ((kind (eql :secp384r1)) &key &allow-other-keys) (let* ((sk (ec-encode-scalar :secp384r1 (1+ (strong-random (1- +secp384r1-l+))))) (pk (secp384r1-public-key sk))) (values (make-private-key :secp384r1 :x sk :y pk) (make-public-key :secp384r1 :y pk)))) (defmethod diffie-hellman ((private-key secp384r1-private-key) (public-key secp384r1-public-key)) (let ((s (ec-decode-scalar :secp384r1 (secp384r1-key-x private-key))) (p (ec-decode-point :secp384r1 (secp384r1-key-y public-key)))) (ec-encode-point (ec-scalar-mult p s))))
null
https://raw.githubusercontent.com/sharplispers/ironclad/6cc4da8554558ee2e89ea38802bbf6d83100d4ea/src/public-key/secp384r1.lisp
lisp
-*- mode: lisp; indent-tabs-mode: nil -*- secp384r1.lisp -- secp384r1 (a.k.a. NIST P-384) elliptic curve class definitions coordinates (X, Y, Z), with x = X / Z^2 and y = Y / Z^3. constant and function definitions Compressed point Uncompressed point Note that hashing is not performed here.
(in-package :crypto) (defclass secp384r1-public-key () ((y :initarg :y :reader secp384r1-key-y :type (simple-array (unsigned-byte 8) (*))))) (defclass secp384r1-private-key () ((x :initarg :x :reader secp384r1-key-x :type (simple-array (unsigned-byte 8) (*))) (y :initarg :y :reader secp384r1-key-y :type (simple-array (unsigned-byte 8) (*))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defclass secp384r1-point () Internally , a point ( x , y ) is represented using the Jacobian projective ((x :initarg :x :type integer) (y :initarg :y :type integer) (z :initarg :z :type integer))) (defmethod make-load-form ((p secp384r1-point) &optional env) (declare (ignore env)) (make-load-form-saving-slots p))) (defconstant +secp384r1-bits+ 384) (defconstant +secp384r1-p+ 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319) (defconstant +secp384r1-b+ 27580193559959705877849011840389048093056905856361568521428707301988689241309860865136260764883745107765439761230575) (defconstant +secp384r1-l+ 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643) (defconstant +secp384r1-i+ 29551504647295859409209280075107710353809804452849085000961220053184291328622652746785449566194203501396205229834239) (defconst +secp384r1-g+ (make-instance 'secp384r1-point :x 26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087 :y 8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871 :z 1)) (defconst +secp384r1-point-at-infinity+ (make-instance 'secp384r1-point :x 1 :y 1 :z 0)) (defmethod ec-scalar-inv ((kind (eql :secp384r1)) n) (expt-mod n (- +secp384r1-p+ 2) +secp384r1-p+)) (defmethod ec-point-equal ((p secp384r1-point) (q secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots ((x1 x) (y1 y) (z1 z)) p (declare (type integer x1 y1 z1)) (with-slots ((x2 x) (y2 y) (z2 z)) q (declare (type integer x2 y2 z2)) (let ((z1z1 (mod (* z1 z1) +secp384r1-p+)) (z2z2 (mod (* z2 z2) +secp384r1-p+))) (and (zerop (mod (- (* x1 z2z2) (* x2 z1z1)) +secp384r1-p+)) (zerop (mod (- (* y1 z2z2 z2) (* y2 z1z1 z1)) +secp384r1-p+))))))) (defmethod ec-double ((p secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots ((x1 x) (y1 y) (z1 z)) p (declare (type integer x1 y1 z1)) (if (zerop z1) +secp384r1-point-at-infinity+ (let* ((xx (mod (* x1 x1) +secp384r1-p+)) (yy (mod (* y1 y1) +secp384r1-p+)) (yyyy (mod (* yy yy) +secp384r1-p+)) (zz (mod (* z1 z1) +secp384r1-p+)) (x1+yy (mod (+ x1 yy) +secp384r1-p+)) (y1+z1 (mod (+ y1 z1) +secp384r1-p+)) (s (mod (* 2 (- (* x1+yy x1+yy) xx yyyy)) +secp384r1-p+)) (m (mod (* 3 (- xx (* zz zz))) +secp384r1-p+)) (u (mod (- (* m m) (* 2 s)) +secp384r1-p+)) (x2 u) (y2 (mod (- (* m (- s u)) (* 8 yyyy)) +secp384r1-p+)) (z2 (mod (- (* y1+z1 y1+z1) yy zz) +secp384r1-p+))) (make-instance 'secp384r1-point :x x2 :y y2 :z z2))))) (defmethod ec-add ((p secp384r1-point) (q secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots ((x1 x) (y1 y) (z1 z)) p (declare (type integer x1 y1 z1)) (with-slots ((x2 x) (y2 y) (z2 z)) q (declare (type integer x2 y2 z2)) (cond ((zerop z1) q) ((zerop z2) p) (t (let* ((z1z1 (mod (* z1 z1) +secp384r1-p+)) (z2z2 (mod (* z2 z2) +secp384r1-p+)) (u1 (mod (* x1 z2z2) +secp384r1-p+)) (u2 (mod (* x2 z1z1) +secp384r1-p+)) (s1 (mod (* y1 z2 z2z2) +secp384r1-p+)) (s2 (mod (* y2 z1 z1z1) +secp384r1-p+))) (if (= u1 u2) (if (= s1 s2) (ec-double p) +secp384r1-point-at-infinity+) (let* ((h (mod (- u2 u1) +secp384r1-p+)) (i (mod (* 4 h h) +secp384r1-p+)) (j (mod (* h i) +secp384r1-p+)) (r (mod (* 2 (- s2 s1)) +secp384r1-p+)) (v (mod (* u1 i) +secp384r1-p+)) (x3 (mod (- (* r r) j (* 2 v)) +secp384r1-p+)) (y3 (mod (- (* r (- v x3)) (* 2 s1 j)) +secp384r1-p+)) (z1+z2 (mod (+ z1 z2) +secp384r1-p+)) (z3 (mod (* (- (* z1+z2 z1+z2) z1z1 z2z2) h) +secp384r1-p+))) (make-instance 'secp384r1-point :x x3 :y y3 :z z3))))))))) (defmethod ec-scalar-mult ((p secp384r1-point) e) Point multiplication on NIST P-384 curve using the Montgomery ladder . (declare (optimize (speed 3) (safety 0) (space 0) (debug 0)) (type integer e)) (do ((r0 +secp384r1-point-at-infinity+) (r1 p) (i (1- +secp384r1-bits+) (1- i))) ((minusp i) r0) (declare (type secp384r1-point r0 r1) (type fixnum i)) (if (logbitp i e) (setf r0 (ec-add r0 r1) r1 (ec-double r1)) (setf r1 (ec-add r0 r1) r0 (ec-double r0))))) (defmethod ec-point-on-curve-p ((p secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots (x y z) p (declare (type integer x y z)) (let* ((y2 (mod (* y y) +secp384r1-p+)) (x3 (mod (* x x x) +secp384r1-p+)) (z2 (mod (* z z) +secp384r1-p+)) (z4 (mod (* z2 z2) +secp384r1-p+)) (z6 (mod (* z4 z2) +secp384r1-p+)) (a (mod (+ x3 (* -3 x z4) (* +secp384r1-b+ z6)) +secp384r1-p+))) (declare (type integer y2 x3 z2 z4 z6 a)) (zerop (mod (- y2 a) +secp384r1-p+))))) (defmethod ec-encode-scalar ((kind (eql :secp384r1)) n) (integer-to-octets n :n-bits +secp384r1-bits+ :big-endian t)) (defmethod ec-decode-scalar ((kind (eql :secp384r1)) octets) (octets-to-integer octets :big-endian t)) (defmethod ec-encode-point ((p secp384r1-point)) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (with-slots (x y z) p (declare (type integer x y z)) (when (zerop z) (error 'ironclad-error :format-control "The point at infinity can't be encoded.")) (let* ((invz (ec-scalar-inv :secp384r1 z)) (invz2 (mod (* invz invz) +secp384r1-p+)) (invz3 (mod (* invz2 invz) +secp384r1-p+)) (x (mod (* x invz2) +secp384r1-p+)) (y (mod (* y invz3) +secp384r1-p+))) (concatenate '(simple-array (unsigned-byte 8) (*)) (vector 4) (ec-encode-scalar :secp384r1 x) (ec-encode-scalar :secp384r1 y))))) (defmethod ec-decode-point ((kind (eql :secp384r1)) octets) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (case (aref octets 0) ((2 3) (if (= (length octets) (1+ (/ +secp384r1-bits+ 8))) (let* ((x-bytes (subseq octets 1 (1+ (/ +secp384r1-bits+ 8)))) (x (ec-decode-scalar :secp384r1 x-bytes)) (y-sign (- (aref octets 0) 2)) (y2 (mod (+ (* x x x) (* -3 x) +secp384r1-b+) +secp384r1-p+)) (y (expt-mod y2 +secp384r1-i+ +secp384r1-p+)) (y (if (= (logand y 1) y-sign) y (- +secp384r1-p+ y))) (p (make-instance 'secp384r1-point :x x :y y :z 1))) (if (ec-point-on-curve-p p) p (error 'invalid-curve-point :kind 'secp384r1))) (error 'invalid-curve-point :kind 'secp384r1))) ((4) (if (= (length octets) (1+ (/ +secp384r1-bits+ 4))) (let* ((x-bytes (subseq octets 1 (1+ (/ +secp384r1-bits+ 8)))) (x (ec-decode-scalar :secp384r1 x-bytes)) (y-bytes (subseq octets (1+ (/ +secp384r1-bits+ 8)))) (y (ec-decode-scalar :secp384r1 y-bytes)) (p (make-instance 'secp384r1-point :x x :y y :z 1))) (if (ec-point-on-curve-p p) p (error 'invalid-curve-point :kind 'secp384r1))) (error 'invalid-curve-point :kind 'secp384r1))) (t (error 'invalid-curve-point :kind 'secp384r1)))) (defun secp384r1-public-key (sk) (let ((a (ec-decode-scalar :secp384r1 sk))) (ec-encode-point (ec-scalar-mult +secp384r1-g+ a)))) (defmethod make-signature ((kind (eql :secp384r1)) &key r s &allow-other-keys) (unless r (error 'missing-signature-parameter :kind 'secp384r1 :parameter 'r :description "first signature element")) (unless s (error 'missing-signature-parameter :kind 'secp384r1 :parameter 's :description "second signature element")) (concatenate '(simple-array (unsigned-byte 8) (*)) r s)) (defmethod destructure-signature ((kind (eql :secp384r1)) signature) (let ((length (length signature))) (if (/= length (/ +secp384r1-bits+ 4)) (error 'invalid-signature-length :kind 'secp384r1) (let* ((middle (/ length 2)) (r (subseq signature 0 middle)) (s (subseq signature middle))) (list :r r :s s))))) (defmethod generate-signature-nonce ((key secp384r1-private-key) message &optional parameters) (declare (ignore key message parameters)) (or *signature-nonce-for-test* (1+ (strong-random (1- +secp384r1-l+))))) (defmethod sign-message ((key secp384r1-private-key) message &key (start 0) end &allow-other-keys) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (let* ((end (min (or end (length message)) (/ +secp384r1-bits+ 8))) (sk (ec-decode-scalar :secp384r1 (secp384r1-key-x key))) (k (generate-signature-nonce key message)) (invk (modular-inverse-with-blinding k +secp384r1-l+)) (r (ec-scalar-mult +secp384r1-g+ k)) (x (subseq (ec-encode-point r) 1 (1+ (/ +secp384r1-bits+ 8)))) (r (ec-decode-scalar :secp384r1 x)) (r (mod r +secp384r1-l+)) (h (subseq message start end)) (e (ec-decode-scalar :secp384r1 h)) (s (mod (* invk (+ e (* sk r))) +secp384r1-l+))) (if (not (or (zerop r) (zerop s))) (make-signature :secp384r1 :r (ec-encode-scalar :secp384r1 r) :s (ec-encode-scalar :secp384r1 s)) (sign-message key message :start start :end end)))) (defmethod verify-signature ((key secp384r1-public-key) message signature &key (start 0) end &allow-other-keys) (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))) (unless (= (length signature) (/ +secp384r1-bits+ 4)) (error 'invalid-signature-length :kind 'secp384r1)) (let* ((end (min (or end (length message)) (/ +secp384r1-bits+ 8))) (pk (ec-decode-point :secp384r1 (secp384r1-key-y key))) (signature-elements (destructure-signature :secp384r1 signature)) (r (ec-decode-scalar :secp384r1 (getf signature-elements :r))) (s (ec-decode-scalar :secp384r1 (getf signature-elements :s))) (h (subseq message start end)) (e (ec-decode-scalar :secp384r1 h)) (w (modular-inverse-with-blinding s +secp384r1-l+)) (u1 (mod (* e w) +secp384r1-l+)) (u2 (mod (* r w) +secp384r1-l+)) (rp (ec-add (ec-scalar-mult +secp384r1-g+ u1) (ec-scalar-mult pk u2))) (x (subseq (ec-encode-point rp) 1 (1+ (/ +secp384r1-bits+ 8)))) (v (ec-decode-scalar :secp384r1 x)) (v (mod v +secp384r1-l+))) (and (< r +secp384r1-l+) (< s +secp384r1-l+) (= v r)))) (defmethod make-public-key ((kind (eql :secp384r1)) &key y &allow-other-keys) (unless y (error 'missing-key-parameter :kind 'secp384r1 :parameter 'y :description "public key")) (make-instance 'secp384r1-public-key :y y)) (defmethod destructure-public-key ((public-key secp384r1-public-key)) (list :y (secp384r1-key-y public-key))) (defmethod make-private-key ((kind (eql :secp384r1)) &key x y &allow-other-keys) (unless x (error 'missing-key-parameter :kind 'secp384r1 :parameter 'x :description "private key")) (make-instance 'secp384r1-private-key :x x :y (or y (secp384r1-public-key x)))) (defmethod destructure-private-key ((private-key secp384r1-private-key)) (list :x (secp384r1-key-x private-key) :y (secp384r1-key-y private-key))) (defmethod generate-key-pair ((kind (eql :secp384r1)) &key &allow-other-keys) (let* ((sk (ec-encode-scalar :secp384r1 (1+ (strong-random (1- +secp384r1-l+))))) (pk (secp384r1-public-key sk))) (values (make-private-key :secp384r1 :x sk :y pk) (make-public-key :secp384r1 :y pk)))) (defmethod diffie-hellman ((private-key secp384r1-private-key) (public-key secp384r1-public-key)) (let ((s (ec-decode-scalar :secp384r1 (secp384r1-key-x private-key))) (p (ec-decode-point :secp384r1 (secp384r1-key-y public-key)))) (ec-encode-point (ec-scalar-mult p s))))
1babe154afa6299c03eb1238a34406b7d8342826c3a9fc57514d5b5acbce3961
alesaccoia/festival_flinger
cmu_us_aup_duration.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Carnegie Mellon University ; ; ; and and ; ; ; Copyright ( c ) 1998 - 2000 ; ; ; All Rights Reserved . ; ; ; ;;; ;;; ;;; Permission is hereby granted, free of charge, to use and distribute ;;; ;;; this software and its documentation without restriction, including ;;; ;;; without limitation the rights to use, copy, modify, merge, publish, ;;; ;;; distribute, sublicense, and/or sell copies of this work, and to ;;; ;;; permit persons to whom this work is furnished to do so, subject to ;;; ;;; the following conditions: ;;; 1 . The code must retain the above copyright notice , this list of ; ; ; ;;; conditions and the following disclaimer. ;;; 2 . Any modifications must be clearly marked as such . ; ; ; 3 . Original authors ' names are not deleted . ; ; ; 4 . The authors ' names are not used to endorse or promote products ; ; ; ;;; derived from this software without specific prior written ;;; ;;; permission. ;;; ;;; ;;; CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ; ;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;; ;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;; SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ; ;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;; WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ; ;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;; ;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;; ;;; THIS SOFTWARE. ;;; ;;; ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Duration for English ;;; ;;; Load any necessary files here (require 'cmu_us_aup_durdata) (define (cmu_us_aup::select_duration) "(cmu_us_aup::select_duration) Set up duration for English." (set! duration_cart_tree cmu_us_aup::zdur_tree) (set! duration_ph_info cmu_us_aup::phone_durs) (Parameter.set 'Duration_Method 'Tree_ZScores) (Parameter.set 'Duration_Stretch 1.0) ) (define (cmu_us_aup::reset_duration) "(cmu_us_aup::reset_duration) Reset duration information." t ) (provide 'cmu_us_aup_duration)
null
https://raw.githubusercontent.com/alesaccoia/festival_flinger/87345aad3a3230751a8ff479f74ba1676217accd/lib/voices/us/cmu_us_aup_cg/festvox/cmu_us_aup_duration.scm
scheme
;;; ; ; ; ; ; ; ; ; ;;; Permission is hereby granted, free of charge, to use and distribute ;;; this software and its documentation without restriction, including ;;; without limitation the rights to use, copy, modify, merge, publish, ;;; distribute, sublicense, and/or sell copies of this work, and to ;;; permit persons to whom this work is furnished to do so, subject to ;;; the following conditions: ;;; ; ; conditions and the following disclaimer. ;;; ; ; ; ; ; ; derived from this software without specific prior written ;;; permission. ;;; ;;; ; ; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;; ; ; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;; ; ; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;; THIS SOFTWARE. ;;; ;;; Load any necessary files here
Duration for English (require 'cmu_us_aup_durdata) (define (cmu_us_aup::select_duration) "(cmu_us_aup::select_duration) Set up duration for English." (set! duration_cart_tree cmu_us_aup::zdur_tree) (set! duration_ph_info cmu_us_aup::phone_durs) (Parameter.set 'Duration_Method 'Tree_ZScores) (Parameter.set 'Duration_Stretch 1.0) ) (define (cmu_us_aup::reset_duration) "(cmu_us_aup::reset_duration) Reset duration information." t ) (provide 'cmu_us_aup_duration)
2440f1c1a44dfe3be1002a6c7adff1b9326e1df37edb20b7c65c3eeaec83eb89
facebook/infer
PulseArithmetic.mli
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd open PulseBasicInterface module AbductiveDomain = PulseAbductiveDomain module AccessResult = PulseAccessResult (** Wrapper around {!PulseFormula} that operates on {!AbductiveDomain.t}. *) val and_nonnegative : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_positive : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_eq_int : AbstractValue.t -> IntLit.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_eq_const : AbstractValue.t -> Const.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t type operand = Formula.operand = | AbstractValueOperand of AbstractValue.t | ConstOperand of Const.t | FunctionApplicationOperand of {f: PulseFormula.function_symbol; actuals: AbstractValue.t list} val and_equal : operand -> operand -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_not_equal : operand -> operand -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val eval_binop : AbstractValue.t -> Binop.t -> operand -> operand -> AbductiveDomain.t -> (AbductiveDomain.t * AbstractValue.t) AccessResult.t SatUnsat.t val eval_binop_absval : AbstractValue.t -> Binop.t -> AbstractValue.t -> AbstractValue.t -> AbductiveDomain.t -> (AbductiveDomain.t * AbstractValue.t) AccessResult.t SatUnsat.t * [ eval_binop_absval ret binop lhs rhs astate ] is [ eval_binop ( AbstractValueOperand lhs ) ( AbstractValueOperand rhs ) astate ] [eval_binop ret binop (AbstractValueOperand lhs) (AbstractValueOperand rhs) astate] *) val eval_unop : AbstractValue.t -> Unop.t -> AbstractValue.t -> AbductiveDomain.t -> (AbductiveDomain.t * AbstractValue.t) AccessResult.t SatUnsat.t val prune_binop : negated:bool -> Binop.t -> operand -> operand -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val prune_eq_zero : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t (** helper function wrapping [prune_binop] *) val prune_ne_zero : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t (** helper function wrapping [prune_binop] *) val prune_positive : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t (** helper function wrapping [prune_binop] *) val prune_gt_one : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t (** helper function wrapping [prune_binop] *) val prune_eq_one : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t (** helper function wrapping [prune_binop] *) val is_known_zero : AbductiveDomain.t -> AbstractValue.t -> bool val is_manifest : AbductiveDomain.Summary.t -> bool val and_is_int : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_equal_instanceof : AbstractValue.t -> AbstractValue.t -> Typ.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t
null
https://raw.githubusercontent.com/facebook/infer/8386f9fcbd46061208664264cba61ac80c61e3f0/infer/src/pulse/PulseArithmetic.mli
ocaml
* Wrapper around {!PulseFormula} that operates on {!AbductiveDomain.t}. * helper function wrapping [prune_binop] * helper function wrapping [prune_binop] * helper function wrapping [prune_binop] * helper function wrapping [prune_binop] * helper function wrapping [prune_binop]
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd open PulseBasicInterface module AbductiveDomain = PulseAbductiveDomain module AccessResult = PulseAccessResult val and_nonnegative : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_positive : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_eq_int : AbstractValue.t -> IntLit.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_eq_const : AbstractValue.t -> Const.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t type operand = Formula.operand = | AbstractValueOperand of AbstractValue.t | ConstOperand of Const.t | FunctionApplicationOperand of {f: PulseFormula.function_symbol; actuals: AbstractValue.t list} val and_equal : operand -> operand -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_not_equal : operand -> operand -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val eval_binop : AbstractValue.t -> Binop.t -> operand -> operand -> AbductiveDomain.t -> (AbductiveDomain.t * AbstractValue.t) AccessResult.t SatUnsat.t val eval_binop_absval : AbstractValue.t -> Binop.t -> AbstractValue.t -> AbstractValue.t -> AbductiveDomain.t -> (AbductiveDomain.t * AbstractValue.t) AccessResult.t SatUnsat.t * [ eval_binop_absval ret binop lhs rhs astate ] is [ eval_binop ( AbstractValueOperand lhs ) ( AbstractValueOperand rhs ) astate ] [eval_binop ret binop (AbstractValueOperand lhs) (AbstractValueOperand rhs) astate] *) val eval_unop : AbstractValue.t -> Unop.t -> AbstractValue.t -> AbductiveDomain.t -> (AbductiveDomain.t * AbstractValue.t) AccessResult.t SatUnsat.t val prune_binop : negated:bool -> Binop.t -> operand -> operand -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val prune_eq_zero : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val prune_ne_zero : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val prune_positive : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val prune_gt_one : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val prune_eq_one : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val is_known_zero : AbductiveDomain.t -> AbstractValue.t -> bool val is_manifest : AbductiveDomain.Summary.t -> bool val and_is_int : AbstractValue.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t val and_equal_instanceof : AbstractValue.t -> AbstractValue.t -> Typ.t -> AbductiveDomain.t -> AbductiveDomain.t AccessResult.t SatUnsat.t
659c4fee30bd81cc9481b3177417e87e68097823268441bf1d6a00dc928992dc
jrm-code-project/LISP-Machine
share-disk.lisp
-*- Mode : LISP ; Package : NF ; Base:8 ; : ZL -*- routines to support shared disk -pace (defun multibus-address-to-8086-ptr (adr) (dpb (ldb (byte 16. 4) adr) (byte 16. 16.) (ldb (byte 4. 0) adr))) (defun 8086-ptr-to-multibus-address (ptr) (+ (ash (ldb (byte 16. 16.) ptr) 4) (ldb (byte 16. 0) ptr) #xff000000)) ; first there is the share-iopb-chain, located at a well known place in multibus memory . The head of the chain is a structure that looks like : ; ptr - to - first - share - iopb - 4 byte 8086 address lock - byte - 1 byte - set to 0 if free , 1 if someone is looking at the chain ; debug-byte - 1 byte set to the debug level given to the share starter 8086 program (defconst sharestruct-ptr #xff000080) (defconst sharestruct-lock #xff000084) (defconst sharestruct-debug-level #xff000085) (defconst sharestruct-share-lock 0) (defconst sharestruct-max-iopbs-offset 4) (defconst sharestruct-current-iopb-offset 8) (defconst sharestruct-valid-table-offset 12.) (defconst share-iopb-runme-offset 0) (defconst share-iopb-slot-offset 4) (defconst share-iopb-type-offset 8) (defconst share-iopb-iopb-offset 12.) (defconst share-iopb-interrupt-offset 16.) (defun %nubus-read-unalinged (nubus-adr) (let ((quad-slot (ldb (byte 8 24.) nubus-adr)) (offset (ldb (byte 24. 0) nubus-adr))) (let ((b0 (si:%nubus-read-8 quad-slot offset)) (b1 (si:%nubus-read-8 quad-slot (+ offset 1))) (b2 (si:%nubus-read-8 quad-slot (+ offset 2))) (b3 (si:%nubus-read-8 quad-slot (+ offset 3)))) (dpb b3 (byte 8 24.) (dpb b2 (byte 8 16.) (dpb b1 (byte 8 8) b0)))))) (defun %read-nubus-adr-8 (nubus-adr) (si:%nubus-read-8 (ldb (byte 8 24.) nubus-adr) (ldb (byte 24. 0) nubus-adr))) (defun %write-nubus-adr-8 (nubus-adr data) (si:%nubus-write-8 (ldb (byte 8 24.) nubus-adr) (ldb (byte 24. 0) nubus-adr) data)) (defun %read-nubus-adr (nubus-adr) (si:%nubus-read (ldb (byte 8 24.) nubus-adr) (ldb (byte 24. 0) nubus-adr))) (defun read-8086-multibus-address (nubus-adr) (let ((multibus-address (8086-ptr-to-multibus-address (%nubus-read-unalinged nubus-adr)))) (values (map-multibus-address multibus-address) multibus-address))) (defun map-multibus-address (nubus-address) "return nubus-address, unless it points to the multibus, and is mapped to the nubus. in that case, follow the mapping, and return that address" (cond ((not (= (ldb (byte 8 24.) nubus-address) #xff)) nubus-address) (t (let ((map-to (si:read-multibus-mapping-register (ldb (byte 10. 10.) nubus-address)))) (cond ((ldb-test (byte 1 23.) map-to) ; check valid bit (dpb (ldb (byte 22. 0) map-to) (byte 22. 10.) (ldb (byte 10. 0) nubus-address))) (t nubus-address)))))) (defun print-share-iopbs (&optional print-iopbs) (let ((sharestruct (read-8086-multibus-address sharestruct-ptr))) (format t "~&sharestruct = ~16r" sharestruct) (let ((maxiopbs (%read-nubus-adr-8 (+ sharestruct sharestruct-max-iopbs-offset))) (currentiopb (%read-nubus-adr-8 (+ sharestruct sharestruct-current-iopb-offset)))) (format t "~&maxiopbs = ~d" maxiopbs) (format t "~&currentiopb = ~d" currentiopb) (dotimes (n maxiopbs) (let ((valid (%read-nubus-adr-8 (+ sharestruct sharestruct-valid-table-offset (* 4 n)))) (siopb (read-8086-multibus-address (+ sharestruct sharestruct-valid-table-offset (* 4 maxiopbs) (* n 4))))) (format t "~&slot ~d: (~16r) valid = #x~16r siopb = #x~16r" n (+ sharestruct sharestruct-valid-table-offset (* 4 n)) valid siopb) (when (not (zerop valid)) (print-share-iopb siopb print-iopbs))))))) (defun print-share-iopb (adr &optional print-iopbs) (format t "~&~4tshare-iopb at ~o (#x~16r)" adr adr) (format t "~&~8trunme = ~o" (%read-nubus-adr-8 (+ adr share-iopb-runme-offset))) (format t "~&~8tslot = ~o (#x~:*~16r)" (%read-nubus-adr-8 (+ adr share-iopb-slot-offset))) (format t "~&~8ttype = ~o" (%read-nubus-adr-8 (+ adr share-iopb-type-offset))) (let ((iopb-address (read-8086-multibus-address (+ adr share-iopb-iopb-offset)))) (format t "~&~8tiopb = ~o ~:* ~16r" iopb-address) ; (if print-iopbs ( print - iopb - at - nubus - address iopb - address ) ) ) (let ((inter-multi-loc (read-8086-multibus-address (+ adr share-iopb-interrupt-offset)))) (format t "~&~8tinterrupt = ~o (= nubus ~16r)" inter-multi-loc (map-multibus-address inter-multi-loc)))) (defun remove-share-iopb (slot type) (let ((sharestruct (read-8086-multibus-address sharestruct-ptr))) (let ((maxiopbs (%read-nubus-adr-8 (+ sharestruct sharestruct-max-iopbs-offset)))) (dotimes (n maxiopbs) (let ((valid (%read-nubus-adr-8 (+ sharestruct sharestruct-valid-table-offset (* 4 n)))) (siopb (read-8086-multibus-address (+ sharestruct sharestruct-valid-table-offset (* maxiopbs 4) (* n 4))))) (cond ((not (zerop valid)) (let ((this-slot (%read-nubus-adr-8 (+ siopb share-iopb-slot-offset))) (this-type (%read-nubus-adr-8 (+ siopb share-iopb-type-offset)))) (cond ((and (or (= this-slot slot) (= this-slot (logxor #xf0 slot))) (= this-type type)) (%write-nubus-adr-8 (+ sharestruct sharestruct-valid-table-offset (* n 4)) 0))))))))))) (defstruct (share-iopb (:type :named-array) (:constructor nil) (:print "#<~S Slot #x~x Type #x~x ~S>" (type-of share-iopb) (share-iopb-slot share-iopb) (share-iopb-type share-iopb) (%pointer share-iopb))) share-iopb-runme share-iopb-slot share-iopb-type share-iopb-iopb share-iopb-interrupt) (defun get-share-iopb () (let ((share-iopb (allocate-resource 'si:dma-buffer 1))) (array-initialize share-iopb 0) (setf (array-leader share-iopb 1) 'share-iopb) share-iopb)) (defstruct (interphase-iopb (:type :named-array) (:constructor nil) (:print "#<~S ~S>" (type-of interphase-iopb) (%pointer interphase-iopb))) interphase-iopb-command interphase-iopb-options interphase-iopb-status interphase-iopb-errors interphase-iopb-unit interphase-iopb-head interphase-iopb-cylinder-hi interphase-iopb-cylinder-lo interphase-iopb-sector-hi interphase-iopb-sector-lo interphase-iopb-count-hi interphase-iopb-count-lo interphase-iopb-dma-count interphase-iopb-buffer-hi interphase-iopb-buffer-med interphase-iopb-buffer-lo interphase-iopb-base-reg-hi interphase-iopb-base-reg-lo interphase-iopb-rel-adr-hi interphase-iopb-rel-adr-lo interphase-iopb-reserved interphase-iopb-linked-iopb-hi interphase-iopb-linked-iopb-med interphase-iopb-linked-iopb-lo ) (defun get-interphase-iopb () (let* ((dma-buffer (allocate-resource 'si:dma-buffer 1)) (iopb (si:dma-buffer-8b dma-buffer))) (array-initialize iopb 0) (setf (array-leader iopb 1) 'interphase-iopb) iopb)) (defun insert-share-iopb (slot type) (remove-share-iopb slot type) (let* ((share-iopb (get-share-iopb)) (phys-adr (si:vadr-to-nubus-phys (%pointer-plus share-iopb (si:array-data-offset share-iopb))))) (array-initialize share-iopb 0) (setf (share-iopb-slot share-iopb) slot) (setf (share-iopb-type share-iopb) type) set up pointer from share - iopb to real iopb like the old code , use 650 in virtual address space for iopb , and point ;; to it with our multibus mapping reg (write-multibus-mapping-register lam-multibus-mapping-register-base (+ 1_23. (cadr-page-to-nubus-page 1))) (send *proc* :bus-write (+ prime-memory-adr share-iopb-iopb-offset) (multibus-address-to-8086-ptr (+ (ash lam-multibus-mapping-register-base 10.) (* 250 4)))) ;;no interrupts (send *proc* :bus-write (+ prime-memory-adr share-iopb-interrupt-offset) 0) (share-lock) (unwind-protect (let ((sharestruct (read-8086-multibus-address sharestruct-ptr))) (cond ((zerop (ldb (byte 20. 0) sharestruct)) (ferror nil "~&sharestruct pointer not set up yet"))) (let ((maxiopbs (send *proc* :bus-read-byte (+ sharestruct sharestruct-max-iopbs-offset)))) (dotimes (n maxiopbs (ferror nil "out of iopb slots")) (cond ((zerop (send *proc* :bus-read-byte (+ sharestruct sharestruct-valid-table-offset (* 4 n)))) (send *proc* :bus-write (+ sharestruct sharestruct-valid-table-offset (* 4 maxiopbs) (* 4 n)) (multibus-address-to-8086-ptr (+ (ash lam-multibus-mapping-register-base 10.) (* 140 4)))) (send *proc* :bus-write-byte (+ sharestruct sharestruct-valid-table-offset (* 4 n)) 1) (return nil)))))) (share-unlock)))) (defconst multibus-interrupt-7 #xff01c1fc) (defun share-go () (let ((prime-memory-adr (+ (ash (cadr (car (send *proc* :memory-configuration-list))) 10.) ( dpb ( SEND * PROC * : MEM - SLOT ) ( byte 4 24 . ) # xf0000000 ) (* debug-program-share-iopb-structure 4)))) (send *proc* :bus-write-byte (+ prime-memory-adr share-iopb-runme-offset) 1) (send *proc* :bus-write-byte multibus-interrupt-7 1)))
null
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/pace/nf/share-disk.lisp
lisp
Package : NF ; Base:8 ; : ZL -*- first there is the share-iopb-chain, located at a well known place debug-byte - 1 byte set to the debug level given to the share starter 8086 program check valid bit (if print-iopbs to it with our multibus mapping reg no interrupts
routines to support shared disk -pace (defun multibus-address-to-8086-ptr (adr) (dpb (ldb (byte 16. 4) adr) (byte 16. 16.) (ldb (byte 4. 0) adr))) (defun 8086-ptr-to-multibus-address (ptr) (+ (ash (ldb (byte 16. 16.) ptr) 4) (ldb (byte 16. 0) ptr) #xff000000)) in multibus memory . The head of the chain is a structure that looks like : ptr - to - first - share - iopb - 4 byte 8086 address lock - byte - 1 byte - set to 0 if free , 1 if someone is looking at the chain (defconst sharestruct-ptr #xff000080) (defconst sharestruct-lock #xff000084) (defconst sharestruct-debug-level #xff000085) (defconst sharestruct-share-lock 0) (defconst sharestruct-max-iopbs-offset 4) (defconst sharestruct-current-iopb-offset 8) (defconst sharestruct-valid-table-offset 12.) (defconst share-iopb-runme-offset 0) (defconst share-iopb-slot-offset 4) (defconst share-iopb-type-offset 8) (defconst share-iopb-iopb-offset 12.) (defconst share-iopb-interrupt-offset 16.) (defun %nubus-read-unalinged (nubus-adr) (let ((quad-slot (ldb (byte 8 24.) nubus-adr)) (offset (ldb (byte 24. 0) nubus-adr))) (let ((b0 (si:%nubus-read-8 quad-slot offset)) (b1 (si:%nubus-read-8 quad-slot (+ offset 1))) (b2 (si:%nubus-read-8 quad-slot (+ offset 2))) (b3 (si:%nubus-read-8 quad-slot (+ offset 3)))) (dpb b3 (byte 8 24.) (dpb b2 (byte 8 16.) (dpb b1 (byte 8 8) b0)))))) (defun %read-nubus-adr-8 (nubus-adr) (si:%nubus-read-8 (ldb (byte 8 24.) nubus-adr) (ldb (byte 24. 0) nubus-adr))) (defun %write-nubus-adr-8 (nubus-adr data) (si:%nubus-write-8 (ldb (byte 8 24.) nubus-adr) (ldb (byte 24. 0) nubus-adr) data)) (defun %read-nubus-adr (nubus-adr) (si:%nubus-read (ldb (byte 8 24.) nubus-adr) (ldb (byte 24. 0) nubus-adr))) (defun read-8086-multibus-address (nubus-adr) (let ((multibus-address (8086-ptr-to-multibus-address (%nubus-read-unalinged nubus-adr)))) (values (map-multibus-address multibus-address) multibus-address))) (defun map-multibus-address (nubus-address) "return nubus-address, unless it points to the multibus, and is mapped to the nubus. in that case, follow the mapping, and return that address" (cond ((not (= (ldb (byte 8 24.) nubus-address) #xff)) nubus-address) (t (let ((map-to (si:read-multibus-mapping-register (ldb (byte 10. 10.) nubus-address)))) (dpb (ldb (byte 22. 0) map-to) (byte 22. 10.) (ldb (byte 10. 0) nubus-address))) (t nubus-address)))))) (defun print-share-iopbs (&optional print-iopbs) (let ((sharestruct (read-8086-multibus-address sharestruct-ptr))) (format t "~&sharestruct = ~16r" sharestruct) (let ((maxiopbs (%read-nubus-adr-8 (+ sharestruct sharestruct-max-iopbs-offset))) (currentiopb (%read-nubus-adr-8 (+ sharestruct sharestruct-current-iopb-offset)))) (format t "~&maxiopbs = ~d" maxiopbs) (format t "~&currentiopb = ~d" currentiopb) (dotimes (n maxiopbs) (let ((valid (%read-nubus-adr-8 (+ sharestruct sharestruct-valid-table-offset (* 4 n)))) (siopb (read-8086-multibus-address (+ sharestruct sharestruct-valid-table-offset (* 4 maxiopbs) (* n 4))))) (format t "~&slot ~d: (~16r) valid = #x~16r siopb = #x~16r" n (+ sharestruct sharestruct-valid-table-offset (* 4 n)) valid siopb) (when (not (zerop valid)) (print-share-iopb siopb print-iopbs))))))) (defun print-share-iopb (adr &optional print-iopbs) (format t "~&~4tshare-iopb at ~o (#x~16r)" adr adr) (format t "~&~8trunme = ~o" (%read-nubus-adr-8 (+ adr share-iopb-runme-offset))) (format t "~&~8tslot = ~o (#x~:*~16r)" (%read-nubus-adr-8 (+ adr share-iopb-slot-offset))) (format t "~&~8ttype = ~o" (%read-nubus-adr-8 (+ adr share-iopb-type-offset))) (let ((iopb-address (read-8086-multibus-address (+ adr share-iopb-iopb-offset)))) (format t "~&~8tiopb = ~o ~:* ~16r" iopb-address) ( print - iopb - at - nubus - address iopb - address ) ) ) (let ((inter-multi-loc (read-8086-multibus-address (+ adr share-iopb-interrupt-offset)))) (format t "~&~8tinterrupt = ~o (= nubus ~16r)" inter-multi-loc (map-multibus-address inter-multi-loc)))) (defun remove-share-iopb (slot type) (let ((sharestruct (read-8086-multibus-address sharestruct-ptr))) (let ((maxiopbs (%read-nubus-adr-8 (+ sharestruct sharestruct-max-iopbs-offset)))) (dotimes (n maxiopbs) (let ((valid (%read-nubus-adr-8 (+ sharestruct sharestruct-valid-table-offset (* 4 n)))) (siopb (read-8086-multibus-address (+ sharestruct sharestruct-valid-table-offset (* maxiopbs 4) (* n 4))))) (cond ((not (zerop valid)) (let ((this-slot (%read-nubus-adr-8 (+ siopb share-iopb-slot-offset))) (this-type (%read-nubus-adr-8 (+ siopb share-iopb-type-offset)))) (cond ((and (or (= this-slot slot) (= this-slot (logxor #xf0 slot))) (= this-type type)) (%write-nubus-adr-8 (+ sharestruct sharestruct-valid-table-offset (* n 4)) 0))))))))))) (defstruct (share-iopb (:type :named-array) (:constructor nil) (:print "#<~S Slot #x~x Type #x~x ~S>" (type-of share-iopb) (share-iopb-slot share-iopb) (share-iopb-type share-iopb) (%pointer share-iopb))) share-iopb-runme share-iopb-slot share-iopb-type share-iopb-iopb share-iopb-interrupt) (defun get-share-iopb () (let ((share-iopb (allocate-resource 'si:dma-buffer 1))) (array-initialize share-iopb 0) (setf (array-leader share-iopb 1) 'share-iopb) share-iopb)) (defstruct (interphase-iopb (:type :named-array) (:constructor nil) (:print "#<~S ~S>" (type-of interphase-iopb) (%pointer interphase-iopb))) interphase-iopb-command interphase-iopb-options interphase-iopb-status interphase-iopb-errors interphase-iopb-unit interphase-iopb-head interphase-iopb-cylinder-hi interphase-iopb-cylinder-lo interphase-iopb-sector-hi interphase-iopb-sector-lo interphase-iopb-count-hi interphase-iopb-count-lo interphase-iopb-dma-count interphase-iopb-buffer-hi interphase-iopb-buffer-med interphase-iopb-buffer-lo interphase-iopb-base-reg-hi interphase-iopb-base-reg-lo interphase-iopb-rel-adr-hi interphase-iopb-rel-adr-lo interphase-iopb-reserved interphase-iopb-linked-iopb-hi interphase-iopb-linked-iopb-med interphase-iopb-linked-iopb-lo ) (defun get-interphase-iopb () (let* ((dma-buffer (allocate-resource 'si:dma-buffer 1)) (iopb (si:dma-buffer-8b dma-buffer))) (array-initialize iopb 0) (setf (array-leader iopb 1) 'interphase-iopb) iopb)) (defun insert-share-iopb (slot type) (remove-share-iopb slot type) (let* ((share-iopb (get-share-iopb)) (phys-adr (si:vadr-to-nubus-phys (%pointer-plus share-iopb (si:array-data-offset share-iopb))))) (array-initialize share-iopb 0) (setf (share-iopb-slot share-iopb) slot) (setf (share-iopb-type share-iopb) type) set up pointer from share - iopb to real iopb like the old code , use 650 in virtual address space for iopb , and point (write-multibus-mapping-register lam-multibus-mapping-register-base (+ 1_23. (cadr-page-to-nubus-page 1))) (send *proc* :bus-write (+ prime-memory-adr share-iopb-iopb-offset) (multibus-address-to-8086-ptr (+ (ash lam-multibus-mapping-register-base 10.) (* 250 4)))) (send *proc* :bus-write (+ prime-memory-adr share-iopb-interrupt-offset) 0) (share-lock) (unwind-protect (let ((sharestruct (read-8086-multibus-address sharestruct-ptr))) (cond ((zerop (ldb (byte 20. 0) sharestruct)) (ferror nil "~&sharestruct pointer not set up yet"))) (let ((maxiopbs (send *proc* :bus-read-byte (+ sharestruct sharestruct-max-iopbs-offset)))) (dotimes (n maxiopbs (ferror nil "out of iopb slots")) (cond ((zerop (send *proc* :bus-read-byte (+ sharestruct sharestruct-valid-table-offset (* 4 n)))) (send *proc* :bus-write (+ sharestruct sharestruct-valid-table-offset (* 4 maxiopbs) (* 4 n)) (multibus-address-to-8086-ptr (+ (ash lam-multibus-mapping-register-base 10.) (* 140 4)))) (send *proc* :bus-write-byte (+ sharestruct sharestruct-valid-table-offset (* 4 n)) 1) (return nil)))))) (share-unlock)))) (defconst multibus-interrupt-7 #xff01c1fc) (defun share-go () (let ((prime-memory-adr (+ (ash (cadr (car (send *proc* :memory-configuration-list))) 10.) ( dpb ( SEND * PROC * : MEM - SLOT ) ( byte 4 24 . ) # xf0000000 ) (* debug-program-share-iopb-structure 4)))) (send *proc* :bus-write-byte (+ prime-memory-adr share-iopb-runme-offset) 1) (send *proc* :bus-write-byte multibus-interrupt-7 1)))
b2602d90436733b74a9c2a1d10f55a8c17037ac0592e7857f04c11beaca4f61e
clojurewerkz/money
hiccup.clj
This source code is dual - licensed under the Apache License , version 2.0 , and the Eclipse Public License , version 1.0 . ;; ;; The APL v2.0: ;; ;; ---------------------------------------------------------------------------------- Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ---------------------------------------------------------------------------------- ;; The EPL v1.0 : ;; ;; ---------------------------------------------------------------------------------- Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team . ;; All rights reserved. ;; ;; This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0 , ;; which accompanies this distribution and is available at -v10.html . ;; ---------------------------------------------------------------------------------- (ns clojurewerkz.money.hiccup "Provides Hiccup integration: HTML rendering of monetary amounts" (:require [clojurewerkz.money.format :as fmt] [hiccup.compiler :as hup]) (:import [org.joda.money Money CurrencyUnit])) (extend-protocol hup/HtmlRenderer Money (render-html [^Money money] (fmt/format money)) CurrencyUnit (render-html [^CurrencyUnit cu] (.getCode cu)))
null
https://raw.githubusercontent.com/clojurewerkz/money/734b99e2c8d4617e69b20a68d1a1760262d7786f/src/clojure/clojurewerkz/money/hiccup.clj
clojure
The APL v2.0: ---------------------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ---------------------------------------------------------------------------------- ---------------------------------------------------------------------------------- All rights reserved. This program and the accompanying materials are made available under the terms of which accompanies this distribution and is available at ----------------------------------------------------------------------------------
This source code is dual - licensed under the Apache License , version 2.0 , and the Eclipse Public License , version 1.0 . Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team distributed under the License is distributed on an " AS IS " BASIS , The EPL v1.0 : Copyright ( c ) 2012 - 2014 , , and the ClojureWerkz Team . the Eclipse Public License Version 1.0 , -v10.html . (ns clojurewerkz.money.hiccup "Provides Hiccup integration: HTML rendering of monetary amounts" (:require [clojurewerkz.money.format :as fmt] [hiccup.compiler :as hup]) (:import [org.joda.money Money CurrencyUnit])) (extend-protocol hup/HtmlRenderer Money (render-html [^Money money] (fmt/format money)) CurrencyUnit (render-html [^CurrencyUnit cu] (.getCode cu)))
d4f5de0da269a9318f9baa224ab8c041461263bdc144b1dbafec67c5a904d572
pokepay/aws-sdk-lisp
dax.lisp
;; DO NOT EDIT: File is generated by AWS-SDK/GENERATOR. (uiop:define-package #:aws-sdk/services/dax (:use) (:use-reexport #:aws-sdk/services/dax/api))
null
https://raw.githubusercontent.com/pokepay/aws-sdk-lisp/836b87df520391478a19462443342dc56f4b3f2c/services/dax.lisp
lisp
DO NOT EDIT: File is generated by AWS-SDK/GENERATOR.
(uiop:define-package #:aws-sdk/services/dax (:use) (:use-reexport #:aws-sdk/services/dax/api))
1081f48e5b74f8c04311cff01f79c65a23d063658ec19dfb3b12e45e9e4f601a
ssardina/ergo
arrays.scm
#lang racket ;;; This provides a cheap multi-dimensional array facility. For example ( define x ( build - array ( list 3 5 ) ( lambda ( x y ) 13 ) ) ) ( array - ref x ( list 0 2 ) ) = = > 13 ( array - set ! x ( list 0 3 ) 4 ) then ( array - ref x ( list 0 3 ) ) = = > 4 (provide build-array array-ref array-set array-set* make-array array-set!) ;; calculate a vector index given the multi-dimensional array indices ;; << this is not the most efficient way, but # of dims should be small >> (define (dope-vector dims inds) (if (null? (cdr inds)) (car inds) (+ (* (car inds) (apply * (cdr dims))) (dope-vector (cdr dims) (cdr inds))))) ;; the internal data structure: a list of dimensions and a single vector (define-struct :array (dims vec) #:prefab) ;; make an array with given dims, whose initial values are val (define (make-array dims val) (make-:array dims (make-vector (apply * dims) val))) ;; all the indices for given dims as a list (define (all-inds dims) (if (null? dims) '(()) (let ((z (all-inds (cdr dims)))) (append-map (lambda (i) (for/list ((u z)) (cons i u))) (for/list ((i (car dims))) i))))) ;; make an array with given dims, whose initial values are valfn of indices (define (build-array dims valfn) (make-:array dims (apply vector (for/list ((inds (all-inds dims))) (apply valfn inds))))) ;; return array element indexed by inds (define (array-ref arr inds) (vector-ref (:array-vec arr) (dope-vector (:array-dims arr) inds))) ;; change array element indexed by inds (define (array-set! arr inds val) (vector-set! (:array-vec arr) (dope-vector (:array-dims arr) inds) val)) ;; make a copy of an array (define (array-copy old) (make-:array (:array-dims old) (vector-copy (:array-vec old)))) ;; copy then set! (define (array-set arr inds val) (let ((new (array-copy arr))) (vector-set! (:array-vec new) (dope-vector (:array-dims new) inds) val) new)) ;; copy then set*! (define (array-set* arr . pairs) (let* ((new (array-copy arr)) (v (:array-vec new)) (d (:array-dims new))) (let loop ((p pairs)) (unless (null? p) (vector-set! v (dope-vector d (car p)) (cadr p)) (loop (cddr p)))) new))
null
https://raw.githubusercontent.com/ssardina/ergo/4225ebb95779d1748f377cf2e4d0a593d6a2a103/System/arrays.scm
scheme
This provides a cheap multi-dimensional array facility. For example calculate a vector index given the multi-dimensional array indices << this is not the most efficient way, but # of dims should be small >> the internal data structure: a list of dimensions and a single vector make an array with given dims, whose initial values are val all the indices for given dims as a list make an array with given dims, whose initial values are valfn of indices return array element indexed by inds change array element indexed by inds make a copy of an array copy then set! copy then set*!
#lang racket ( define x ( build - array ( list 3 5 ) ( lambda ( x y ) 13 ) ) ) ( array - ref x ( list 0 2 ) ) = = > 13 ( array - set ! x ( list 0 3 ) 4 ) then ( array - ref x ( list 0 3 ) ) = = > 4 (provide build-array array-ref array-set array-set* make-array array-set!) (define (dope-vector dims inds) (if (null? (cdr inds)) (car inds) (+ (* (car inds) (apply * (cdr dims))) (dope-vector (cdr dims) (cdr inds))))) (define-struct :array (dims vec) #:prefab) (define (make-array dims val) (make-:array dims (make-vector (apply * dims) val))) (define (all-inds dims) (if (null? dims) '(()) (let ((z (all-inds (cdr dims)))) (append-map (lambda (i) (for/list ((u z)) (cons i u))) (for/list ((i (car dims))) i))))) (define (build-array dims valfn) (make-:array dims (apply vector (for/list ((inds (all-inds dims))) (apply valfn inds))))) (define (array-ref arr inds) (vector-ref (:array-vec arr) (dope-vector (:array-dims arr) inds))) (define (array-set! arr inds val) (vector-set! (:array-vec arr) (dope-vector (:array-dims arr) inds) val)) (define (array-copy old) (make-:array (:array-dims old) (vector-copy (:array-vec old)))) (define (array-set arr inds val) (let ((new (array-copy arr))) (vector-set! (:array-vec new) (dope-vector (:array-dims new) inds) val) new)) (define (array-set* arr . pairs) (let* ((new (array-copy arr)) (v (:array-vec new)) (d (:array-dims new))) (let loop ((p pairs)) (unless (null? p) (vector-set! v (dope-vector d (car p)) (cadr p)) (loop (cddr p)))) new))
71c0a2a3c6a00ca479066337aa250e80a6dcd2e8327f64920a4eb4106f4cb99a
haskell-rewriting/term-rewriting
Substitution.hs
-- This file is part of the 'term-rewriting' library. It is licensed under an MIT license . See the accompanying ' LICENSE ' file for details . -- Authors : -- Tests for Data.Rewriting.Substitution module Substitution where import Arbitrary import Data.Rewriting.Term (Term (..)) import Data.Rewriting.Substitution import Data.Rewriting.Substitution.Type import Control.Applicative import Control.Monad import Data.Maybe import Data.Function import qualified Data.Map as M propCompose :: Subst' -> Subst' -> Term' -> Bool propCompose s1 s2 t = (s1 `compose` s2) `apply` t == s1 `apply` (s2 `apply` t) propUnify1 :: Term' -> Term' -> Bool propUnify1 s t = Just False /= do (\u -> u `apply` s == u `apply` t) <$> unify s t propUnify2 :: Term' -> Term' -> Bool propUnify2 s t = Just False /= do equalSubst <$> unify s t <*> unifyRef s t equalSubst :: (Ord v, Eq f) => Subst f v -> Subst f v -> Bool equalSubst s1 s2 = ((==) `on` toMap) (id' `compose` s1) (id' `compose` s2) where id' = fromMap . M.fromList $ [(v, Var v) | v <- M.keys (toMap s1) ++ M.keys (toMap s2)]
null
https://raw.githubusercontent.com/haskell-rewriting/term-rewriting/d01ee419f9fd3c2011d37b6417326a9373d5ee9c/test/Substitution.hs
haskell
This file is part of the 'term-rewriting' library. It is licensed Tests for Data.Rewriting.Substitution
under an MIT license . See the accompanying ' LICENSE ' file for details . Authors : module Substitution where import Arbitrary import Data.Rewriting.Term (Term (..)) import Data.Rewriting.Substitution import Data.Rewriting.Substitution.Type import Control.Applicative import Control.Monad import Data.Maybe import Data.Function import qualified Data.Map as M propCompose :: Subst' -> Subst' -> Term' -> Bool propCompose s1 s2 t = (s1 `compose` s2) `apply` t == s1 `apply` (s2 `apply` t) propUnify1 :: Term' -> Term' -> Bool propUnify1 s t = Just False /= do (\u -> u `apply` s == u `apply` t) <$> unify s t propUnify2 :: Term' -> Term' -> Bool propUnify2 s t = Just False /= do equalSubst <$> unify s t <*> unifyRef s t equalSubst :: (Ord v, Eq f) => Subst f v -> Subst f v -> Bool equalSubst s1 s2 = ((==) `on` toMap) (id' `compose` s1) (id' `compose` s2) where id' = fromMap . M.fromList $ [(v, Var v) | v <- M.keys (toMap s1) ++ M.keys (toMap s2)]
d4102d1b4c6075d034af7fe3c3d7aa43521baffdf3fee938403919de7316e301
ndmitchell/catch
ReadInt.hs
module ReadInt where main x = read x :: Int
null
https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/examples/Example/ReadInt.hs
haskell
module ReadInt where main x = read x :: Int
c5c649de424fef41f526df3e5b36615d0f3a6a9a44af0e28fce05ab91f685556
incoherentsoftware/defect-process
Dog.hs
module Configs.All.Enemy.Dog ( DogEnemyConfig(..) ) where import Data.Aeson.Types (FromJSON, genericParseJSON, parseJSON) import GHC.Generics (Generic) import Attack.Util import Enemy.DeathEffectData.Types import Enemy.HurtEffectData.Types import Enemy.SpawnEffectData.Types import Util import Window.Graphics.Util data DogEnemyConfig = DogEnemyConfig { _health :: Health , _width :: Float , _height :: Float , _idleSecs :: Secs , _paceSpeed :: Speed , _paceSecs :: Secs , _runSpeed :: Speed , _fallbackRunSecs :: Secs , _minRunFromSecs :: Secs , _maxRunFromSecs :: Secs , _staggerThreshold :: Stagger , _initialAttackCooldown :: Secs , _postAttackCooldown :: Secs , _headbuttRangeX :: Distance , _shootRangeX :: Distance , _shootOffset :: Pos2 , _shootProjectileSpeed :: Speed , _shootProjectileAngle :: Radians , _shootProjectileGravity :: Float , _shootProjectileAliveSecs :: Secs , _willUseProjectileChance :: Float , _groundImpactEffectDrawScale :: DrawScale , _wallImpactEffectDrawScale :: DrawScale , _hurtEffectData :: EnemyHurtEffectData , _deathEffectData :: EnemyDeathEffectData , _spawnEffectData :: EnemySpawnEffectData } deriving Generic instance FromJSON DogEnemyConfig where parseJSON = genericParseJSON aesonFieldDropUnderscore
null
https://raw.githubusercontent.com/incoherentsoftware/defect-process/14ec46dec2c48135bc4e5965b7b75532ef19268e/src/Configs/All/Enemy/Dog.hs
haskell
module Configs.All.Enemy.Dog ( DogEnemyConfig(..) ) where import Data.Aeson.Types (FromJSON, genericParseJSON, parseJSON) import GHC.Generics (Generic) import Attack.Util import Enemy.DeathEffectData.Types import Enemy.HurtEffectData.Types import Enemy.SpawnEffectData.Types import Util import Window.Graphics.Util data DogEnemyConfig = DogEnemyConfig { _health :: Health , _width :: Float , _height :: Float , _idleSecs :: Secs , _paceSpeed :: Speed , _paceSecs :: Secs , _runSpeed :: Speed , _fallbackRunSecs :: Secs , _minRunFromSecs :: Secs , _maxRunFromSecs :: Secs , _staggerThreshold :: Stagger , _initialAttackCooldown :: Secs , _postAttackCooldown :: Secs , _headbuttRangeX :: Distance , _shootRangeX :: Distance , _shootOffset :: Pos2 , _shootProjectileSpeed :: Speed , _shootProjectileAngle :: Radians , _shootProjectileGravity :: Float , _shootProjectileAliveSecs :: Secs , _willUseProjectileChance :: Float , _groundImpactEffectDrawScale :: DrawScale , _wallImpactEffectDrawScale :: DrawScale , _hurtEffectData :: EnemyHurtEffectData , _deathEffectData :: EnemyDeathEffectData , _spawnEffectData :: EnemySpawnEffectData } deriving Generic instance FromJSON DogEnemyConfig where parseJSON = genericParseJSON aesonFieldDropUnderscore
33353767d21650232f8ffee18693f06d1305913c1612259a17547c7512c5ecfc
daypack-dev/daypack-lib
time_slot.mli
exception Time_slot_is_invalid exception Time_slot_is_empty type t = int64 * int64 val lt : t -> t -> bool val le : t -> t -> bool val gt : t -> t -> bool val ge : t -> t -> bool val compare : t -> t -> int val to_string : t -> string val join : t -> t -> t option val overlap_of_a_over_b : a:t -> b:t -> t option * t option * t option module Check : sig val is_valid : t -> bool val is_not_empty : t -> bool val check_if_valid : t -> t val check_if_not_empty : t -> t end module Serialize : sig val pack_time_slot : int64 * int64 -> (int32 * int32) * (int32 * int32) end module Deserialize : sig val unpack_time_slot : (int32 * int32) * (int32 * int32) -> int64 * int64 end
null
https://raw.githubusercontent.com/daypack-dev/daypack-lib/63fa5d85007eca73aa6c51874a839636dd0403d3/src/time_slot.mli
ocaml
exception Time_slot_is_invalid exception Time_slot_is_empty type t = int64 * int64 val lt : t -> t -> bool val le : t -> t -> bool val gt : t -> t -> bool val ge : t -> t -> bool val compare : t -> t -> int val to_string : t -> string val join : t -> t -> t option val overlap_of_a_over_b : a:t -> b:t -> t option * t option * t option module Check : sig val is_valid : t -> bool val is_not_empty : t -> bool val check_if_valid : t -> t val check_if_not_empty : t -> t end module Serialize : sig val pack_time_slot : int64 * int64 -> (int32 * int32) * (int32 * int32) end module Deserialize : sig val unpack_time_slot : (int32 * int32) * (int32 * int32) -> int64 * int64 end
708030be2db253c834b295bcefe5d0f038288e92116dd094ee7fca40933980fd
gigamonkey/monkeylib-prose-diff
diff.lisp
(in-package :com.gigamonkeys.prose-diff) ;;; Generic functions for diffing vectors of objects . ;;; (defun diff-vectors (old new &optional (lcs-frobber #'identity)) "Diff two vectors returning a vector with the elements of old and new wrapped in conses whose CAR is either :LCS, :DELETE, or :ADD. Optionally frob the computed LCS before computing the diff." (loop with output = (make-array (length new) :adjustable t :fill-pointer 0) with old-i = 0 with old-length = (length old) with new-i = 0 with new-length = (length new) for next-lcs across (funcall lcs-frobber (lcs old new)) do (setf old-i (emit-diffs next-lcs old old-i old-length :delete output)) (setf new-i (emit-diffs next-lcs new new-i new-length :add output)) (vector-push-extend (cons :lcs next-lcs) output) finally (emit-diffs (cons nil nil) old old-i old-length :delete output) (emit-diffs (cons nil nil) new new-i new-length :add output) (return output))) (defun emit-diffs (next-lcs v i max-i marker output) (cond ((< i max-i) (let ((idx (or (position next-lcs v :start i) max-i))) (cond ((> idx i) (loop for j from i below idx do (vector-push-extend (cons marker (aref v j)) output)) (1+ idx)) (t (1+ i))))) (t i)))
null
https://raw.githubusercontent.com/gigamonkey/monkeylib-prose-diff/9e393807671ef54b1c9b47f570a93267ac85b62a/diff.lisp
lisp
(in-package :com.gigamonkeys.prose-diff) Generic functions for diffing vectors of objects . (defun diff-vectors (old new &optional (lcs-frobber #'identity)) "Diff two vectors returning a vector with the elements of old and new wrapped in conses whose CAR is either :LCS, :DELETE, or :ADD. Optionally frob the computed LCS before computing the diff." (loop with output = (make-array (length new) :adjustable t :fill-pointer 0) with old-i = 0 with old-length = (length old) with new-i = 0 with new-length = (length new) for next-lcs across (funcall lcs-frobber (lcs old new)) do (setf old-i (emit-diffs next-lcs old old-i old-length :delete output)) (setf new-i (emit-diffs next-lcs new new-i new-length :add output)) (vector-push-extend (cons :lcs next-lcs) output) finally (emit-diffs (cons nil nil) old old-i old-length :delete output) (emit-diffs (cons nil nil) new new-i new-length :add output) (return output))) (defun emit-diffs (next-lcs v i max-i marker output) (cond ((< i max-i) (let ((idx (or (position next-lcs v :start i) max-i))) (cond ((> idx i) (loop for j from i below idx do (vector-push-extend (cons marker (aref v j)) output)) (1+ idx)) (t (1+ i))))) (t i)))
9ab801eb868e20f70e71dfb8b871eb94ce39409a00b11350f7cbb7a30e8c6eb1
achirkin/vulkan
FramebufferCreateFlags.hs
# OPTIONS_HADDOCK ignore - exports # {-# LANGUAGE DataKinds #-} # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # {-# LANGUAGE PatternSynonyms #-} # LANGUAGE StandaloneDeriving # {-# LANGUAGE Strict #-} {-# LANGUAGE TypeSynonymInstances #-} module Graphics.Vulkan.Types.Enum.FramebufferCreateFlags (VkFramebufferCreateBitmask(VkFramebufferCreateBitmask, VkFramebufferCreateFlags, VkFramebufferCreateFlagBits), VkFramebufferCreateFlags, VkFramebufferCreateFlagBits) where import Data.Bits (Bits, FiniteBits) import Foreign.Storable (Storable) import GHC.Read (choose, expectP) import Graphics.Vulkan.Marshal (FlagBit, FlagMask, FlagType) import Graphics.Vulkan.Types.BaseTypes (VkFlags (..)) import Text.ParserCombinators.ReadPrec (prec, step, (+++)) import Text.Read (Read (..), parens) import Text.Read.Lex (Lexeme (..)) newtype VkFramebufferCreateBitmask (a :: FlagType) = VkFramebufferCreateBitmask VkFlags deriving (Eq, Ord, Storable) type VkFramebufferCreateFlags = VkFramebufferCreateBitmask FlagMask type VkFramebufferCreateFlagBits = VkFramebufferCreateBitmask FlagBit pattern VkFramebufferCreateFlagBits :: VkFlags -> VkFramebufferCreateBitmask FlagBit pattern VkFramebufferCreateFlagBits n = VkFramebufferCreateBitmask n pattern VkFramebufferCreateFlags :: VkFlags -> VkFramebufferCreateBitmask FlagMask pattern VkFramebufferCreateFlags n = VkFramebufferCreateBitmask n deriving instance Bits (VkFramebufferCreateBitmask FlagMask) deriving instance FiniteBits (VkFramebufferCreateBitmask FlagMask) instance Show (VkFramebufferCreateBitmask a) where showsPrec p (VkFramebufferCreateBitmask x) = showParen (p >= 11) (showString "VkFramebufferCreateBitmask " . showsPrec 11 x) instance Read (VkFramebufferCreateBitmask a) where readPrec = parens (choose [] +++ prec 10 (expectP (Ident "VkFramebufferCreateBitmask") >> (VkFramebufferCreateBitmask <$> step readPrec)))
null
https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Types/Enum/FramebufferCreateFlags.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE PatternSynonyms # # LANGUAGE Strict # # LANGUAGE TypeSynonymInstances #
# OPTIONS_HADDOCK ignore - exports # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE StandaloneDeriving # module Graphics.Vulkan.Types.Enum.FramebufferCreateFlags (VkFramebufferCreateBitmask(VkFramebufferCreateBitmask, VkFramebufferCreateFlags, VkFramebufferCreateFlagBits), VkFramebufferCreateFlags, VkFramebufferCreateFlagBits) where import Data.Bits (Bits, FiniteBits) import Foreign.Storable (Storable) import GHC.Read (choose, expectP) import Graphics.Vulkan.Marshal (FlagBit, FlagMask, FlagType) import Graphics.Vulkan.Types.BaseTypes (VkFlags (..)) import Text.ParserCombinators.ReadPrec (prec, step, (+++)) import Text.Read (Read (..), parens) import Text.Read.Lex (Lexeme (..)) newtype VkFramebufferCreateBitmask (a :: FlagType) = VkFramebufferCreateBitmask VkFlags deriving (Eq, Ord, Storable) type VkFramebufferCreateFlags = VkFramebufferCreateBitmask FlagMask type VkFramebufferCreateFlagBits = VkFramebufferCreateBitmask FlagBit pattern VkFramebufferCreateFlagBits :: VkFlags -> VkFramebufferCreateBitmask FlagBit pattern VkFramebufferCreateFlagBits n = VkFramebufferCreateBitmask n pattern VkFramebufferCreateFlags :: VkFlags -> VkFramebufferCreateBitmask FlagMask pattern VkFramebufferCreateFlags n = VkFramebufferCreateBitmask n deriving instance Bits (VkFramebufferCreateBitmask FlagMask) deriving instance FiniteBits (VkFramebufferCreateBitmask FlagMask) instance Show (VkFramebufferCreateBitmask a) where showsPrec p (VkFramebufferCreateBitmask x) = showParen (p >= 11) (showString "VkFramebufferCreateBitmask " . showsPrec 11 x) instance Read (VkFramebufferCreateBitmask a) where readPrec = parens (choose [] +++ prec 10 (expectP (Ident "VkFramebufferCreateBitmask") >> (VkFramebufferCreateBitmask <$> step readPrec)))
f780b57da172281c762571f5fbefca6e69d21bb86d512df1a069c71898b7de6e
metabase/metabase
assert_exprs.clj
(ns metabase.test-runner.assert-exprs "Custom implementations of a few [[clojure.test/is]] expressions (i.e., implementations of [[clojure.test/assert-expr]]): `query=` and `sql=`. Other expressions (`re=`, `schema=`, `=?`, and so forth) are implemented with the Hawk test-runner." (:require [clojure.data :as data] [clojure.test :as t] [clojure.walk :as walk])) (defn derecordize "Convert all record types in `form` to plain maps, so tests won't fail." [form] (walk/postwalk (fn [form] (if (record? form) (into {} form) form)) form)) (defn query=-report "Impl for [[t/assert-expr]] `query=`." [message expected actual] (let [expected (derecordize expected) actual (derecordize actual) pass? (= expected actual)] (merge {:type (if pass? :pass :fail) :message message :expected expected :actual actual} ;; don't bother adding names unless the test actually failed (when-not pass? (let [add-names (requiring-resolve 'dev.debug-qp/add-names)] {:expected (add-names expected) :actual (add-names actual) :diffs (let [[only-in-actual only-in-expected] (data/diff actual expected)] [[(add-names actual) [(add-names only-in-expected) (add-names only-in-actual)]]])}))))) basically the same as normal ` = ` but will add comment forms to MBQL queries for Field clauses and source tables telling you the name of the referenced Fields / Tables (defmethod t/assert-expr 'query= [message [_ expected & actuals]] `(do ~@(for [actual actuals] `(t/do-report (query=-report ~message ~expected ~actual))))) (defn sql=-report [message expected query] (let [sql-map ((requiring-resolve 'metabase.driver.sql.query-processor-test-util/query->sql-map) query) pass? (= sql-map expected)] {:type (if pass? :pass :fail) :message message :expected expected :actual sql-map :diffs (when-not pass? (let [[only-in-actual only-in-expected] (data/diff sql-map expected)] [[sql-map [only-in-expected only-in-actual]]]))})) (defmethod t/assert-expr 'sql= [message [_ expected query]] `(let [query# ~query] ;; [[t/testing]] context has to be done around the call to [[t/do-report]] ((requiring-resolve 'metabase.driver.sql.query-processor-test-util/do-with-native-query-testing-context) query# ;; [[t/do-report]] has to be in the expansion, otherwise it picks up the wrong filename and line metadata. (fn [] (t/do-report (sql=-report ~message ~expected query#))))))
null
https://raw.githubusercontent.com/metabase/metabase/dad3d414e5bec482c15d826dcc97772412c98652/test/metabase/test_runner/assert_exprs.clj
clojure
don't bother adding names unless the test actually failed [[t/testing]] context has to be done around the call to [[t/do-report]] [[t/do-report]] has to be in the expansion, otherwise it picks up the wrong filename and line metadata.
(ns metabase.test-runner.assert-exprs "Custom implementations of a few [[clojure.test/is]] expressions (i.e., implementations of [[clojure.test/assert-expr]]): `query=` and `sql=`. Other expressions (`re=`, `schema=`, `=?`, and so forth) are implemented with the Hawk test-runner." (:require [clojure.data :as data] [clojure.test :as t] [clojure.walk :as walk])) (defn derecordize "Convert all record types in `form` to plain maps, so tests won't fail." [form] (walk/postwalk (fn [form] (if (record? form) (into {} form) form)) form)) (defn query=-report "Impl for [[t/assert-expr]] `query=`." [message expected actual] (let [expected (derecordize expected) actual (derecordize actual) pass? (= expected actual)] (merge {:type (if pass? :pass :fail) :message message :expected expected :actual actual} (when-not pass? (let [add-names (requiring-resolve 'dev.debug-qp/add-names)] {:expected (add-names expected) :actual (add-names actual) :diffs (let [[only-in-actual only-in-expected] (data/diff actual expected)] [[(add-names actual) [(add-names only-in-expected) (add-names only-in-actual)]]])}))))) basically the same as normal ` = ` but will add comment forms to MBQL queries for Field clauses and source tables telling you the name of the referenced Fields / Tables (defmethod t/assert-expr 'query= [message [_ expected & actuals]] `(do ~@(for [actual actuals] `(t/do-report (query=-report ~message ~expected ~actual))))) (defn sql=-report [message expected query] (let [sql-map ((requiring-resolve 'metabase.driver.sql.query-processor-test-util/query->sql-map) query) pass? (= sql-map expected)] {:type (if pass? :pass :fail) :message message :expected expected :actual sql-map :diffs (when-not pass? (let [[only-in-actual only-in-expected] (data/diff sql-map expected)] [[sql-map [only-in-expected only-in-actual]]]))})) (defmethod t/assert-expr 'sql= [message [_ expected query]] `(let [query# ~query] ((requiring-resolve 'metabase.driver.sql.query-processor-test-util/do-with-native-query-testing-context) query# (fn [] (t/do-report (sql=-report ~message ~expected query#))))))
8b98d13f83d872806f7b8ae98a18fd09520ca2ab183cb5e836b1bf9e2822a660
arenadotio/pgx
config.ml
open Mirage let packages = [ package "pgx" ~pin:"file://../" ; package "pgx_lwt" ~pin:"file://../" ; package "pgx_lwt_mirage" ~pin:"file://../" ; package "logs" ; package "mirage-logs" ] ;; let stack = generic_stackv4v6 default_network let database = let doc = Key.Arg.info ~doc:"database to use" [ "db"; "pgdatabase" ] in Key.(create "pgdatabase" Arg.(opt string "postgres" doc)) ;; let port = let doc = Key.Arg.info ~doc:"port to use for postgresql" [ "p"; "pgport" ] in Key.(create "pgport" Arg.(opt int 5432 doc)) ;; let hostname = let doc = Key.Arg.info ~doc:"host for postgres database" [ "h"; "pghost" ] in Key.(create "pghost" Arg.(opt string "127.0.0.1" doc)) ;; let user = let doc = Key.Arg.info ~doc:"postgres user" [ "u"; "pguser" ] in Key.(create "pguser" Arg.(required string doc)) ;; let password = let doc = Key.Arg.info ~doc:"postgres password" [ "pgpassword" ] in Key.(create "pgpassword" Arg.(required string doc)) ;; let server = foreign "Unikernel.Make" ~keys: [ Key.abstract port ; Key.abstract hostname ; Key.abstract user ; Key.abstract password ; Key.abstract database ] ~packages (random @-> time @-> pclock @-> mclock @-> stackv4v6 @-> job) ;; let () = register "pgx_unikernel" [ server $ default_random $ default_time $ default_posix_clock $ default_monotonic_clock $ stack ] ;;
null
https://raw.githubusercontent.com/arenadotio/pgx/3f2c0fc385db40d108466df80dad7980587d4342/unikernel/config.ml
ocaml
open Mirage let packages = [ package "pgx" ~pin:"file://../" ; package "pgx_lwt" ~pin:"file://../" ; package "pgx_lwt_mirage" ~pin:"file://../" ; package "logs" ; package "mirage-logs" ] ;; let stack = generic_stackv4v6 default_network let database = let doc = Key.Arg.info ~doc:"database to use" [ "db"; "pgdatabase" ] in Key.(create "pgdatabase" Arg.(opt string "postgres" doc)) ;; let port = let doc = Key.Arg.info ~doc:"port to use for postgresql" [ "p"; "pgport" ] in Key.(create "pgport" Arg.(opt int 5432 doc)) ;; let hostname = let doc = Key.Arg.info ~doc:"host for postgres database" [ "h"; "pghost" ] in Key.(create "pghost" Arg.(opt string "127.0.0.1" doc)) ;; let user = let doc = Key.Arg.info ~doc:"postgres user" [ "u"; "pguser" ] in Key.(create "pguser" Arg.(required string doc)) ;; let password = let doc = Key.Arg.info ~doc:"postgres password" [ "pgpassword" ] in Key.(create "pgpassword" Arg.(required string doc)) ;; let server = foreign "Unikernel.Make" ~keys: [ Key.abstract port ; Key.abstract hostname ; Key.abstract user ; Key.abstract password ; Key.abstract database ] ~packages (random @-> time @-> pclock @-> mclock @-> stackv4v6 @-> job) ;; let () = register "pgx_unikernel" [ server $ default_random $ default_time $ default_posix_clock $ default_monotonic_clock $ stack ] ;;
8bb312bbe6f03ee45ded5fc66b66025b8c63992545d78ac0598d0694fcc51263
helpshift/hydrox
numbers.clj
(ns hydrox.doc.link.numbers) (def new-counter {:chapter 0 :section 0 :subsection 0 :subsubsection 0 :code 0 :image 0 :equation 0 :citation 0}) (defn increment "increments a string for alphanumerics and numbers (increment \"1\") => \"2\" (increment \"A\") => \"B\"" {:added "0.1"} [count] (if (number? count) "A" (->> count first char int inc char str))) (defn link-numbers-loop "main loop logic for generation of numbers" {:added "0.1"} ([elements auto-number] (link-numbers-loop elements auto-number new-counter [])) ([[{:keys [type origin] :as ele} & more :as elements] auto-number {:keys [chapter section subsection subsubsection code image equation citation] :as counter} output] (if (empty? elements) output (let [[numstring counter] (case type :citation [(str (inc citation)) (assoc counter :citation (inc citation))] :chapter [(str (inc chapter)) (assoc counter :chapter (if (number? chapter) (inc chapter) 0) :section 0 :subsection 0 :subsubsection 0 :code 0)] :section [(str chapter "." (inc section)) (assoc counter :section (inc section) :subsection 0 :subsubsection 0)] :subsection [(str chapter "." section "." (inc subsection)) (assoc counter :subsection (inc subsection) :subsubsection 0)] :subsubsection [(str chapter "." section "." subsection "." (inc subsubsection)) (assoc counter :subsubsection (inc subsubsection))] :appendix [(str (increment chapter)) (assoc counter :chapter (increment chapter) :section 0 :subsection 0 :subsubsection 0 :code 0)] (if (and (#{:code :image :equation :block} type) (or (auto-number type) (auto-number origin) (:numbered ele)) (or (:tag ele) (:title ele)) (not (or (:hidden ele) (false? (:numbered ele))))) (case type :code [(str chapter "." (inc code)) (assoc counter :code (inc code))] :block [(str chapter "." (inc code)) (assoc counter :code (inc code))] :image [(str (inc image)) (assoc counter :image (inc image))] :equation [(str (inc equation)) (assoc counter :equation (inc equation))]) [nil counter])) ele (if numstring (assoc ele :number numstring) ele)] (recur more auto-number counter (conj output ele)))))) (defn link-numbers "creates numbers for main sections, images, code and equations (link-numbers {:articles {\"example\" {:elements [{:type :chapter :title \"hello\"} {:type :section :title \"world\"}]}}} \"example\") {:articles {\"example\" {:elements [{:type :chapter, :title \"hello\", :number \"1\"} {:type :section, :title \"world\", :number \"1.1\"}]}}}" {:added "0.1"} [folio name] (update-in folio [:articles name :elements] (fn [elements] (let [auto-number (->> (list (get-in folio [:articles name :meta :link :auto-number]) (get-in folio [:meta :link :auto-number]) true) (drop-while nil?) (first)) auto-number (cond (set? auto-number) auto-number (false? auto-number) #{} (true? auto-number) #{:image :equation :code :block})] (link-numbers-loop elements auto-number)))))
null
https://raw.githubusercontent.com/helpshift/hydrox/2beb3c56fad43bbf16f07db7ee72c5862978350c/src/hydrox/doc/link/numbers.clj
clojure
(ns hydrox.doc.link.numbers) (def new-counter {:chapter 0 :section 0 :subsection 0 :subsubsection 0 :code 0 :image 0 :equation 0 :citation 0}) (defn increment "increments a string for alphanumerics and numbers (increment \"1\") => \"2\" (increment \"A\") => \"B\"" {:added "0.1"} [count] (if (number? count) "A" (->> count first char int inc char str))) (defn link-numbers-loop "main loop logic for generation of numbers" {:added "0.1"} ([elements auto-number] (link-numbers-loop elements auto-number new-counter [])) ([[{:keys [type origin] :as ele} & more :as elements] auto-number {:keys [chapter section subsection subsubsection code image equation citation] :as counter} output] (if (empty? elements) output (let [[numstring counter] (case type :citation [(str (inc citation)) (assoc counter :citation (inc citation))] :chapter [(str (inc chapter)) (assoc counter :chapter (if (number? chapter) (inc chapter) 0) :section 0 :subsection 0 :subsubsection 0 :code 0)] :section [(str chapter "." (inc section)) (assoc counter :section (inc section) :subsection 0 :subsubsection 0)] :subsection [(str chapter "." section "." (inc subsection)) (assoc counter :subsection (inc subsection) :subsubsection 0)] :subsubsection [(str chapter "." section "." subsection "." (inc subsubsection)) (assoc counter :subsubsection (inc subsubsection))] :appendix [(str (increment chapter)) (assoc counter :chapter (increment chapter) :section 0 :subsection 0 :subsubsection 0 :code 0)] (if (and (#{:code :image :equation :block} type) (or (auto-number type) (auto-number origin) (:numbered ele)) (or (:tag ele) (:title ele)) (not (or (:hidden ele) (false? (:numbered ele))))) (case type :code [(str chapter "." (inc code)) (assoc counter :code (inc code))] :block [(str chapter "." (inc code)) (assoc counter :code (inc code))] :image [(str (inc image)) (assoc counter :image (inc image))] :equation [(str (inc equation)) (assoc counter :equation (inc equation))]) [nil counter])) ele (if numstring (assoc ele :number numstring) ele)] (recur more auto-number counter (conj output ele)))))) (defn link-numbers "creates numbers for main sections, images, code and equations (link-numbers {:articles {\"example\" {:elements [{:type :chapter :title \"hello\"} {:type :section :title \"world\"}]}}} \"example\") {:articles {\"example\" {:elements [{:type :chapter, :title \"hello\", :number \"1\"} {:type :section, :title \"world\", :number \"1.1\"}]}}}" {:added "0.1"} [folio name] (update-in folio [:articles name :elements] (fn [elements] (let [auto-number (->> (list (get-in folio [:articles name :meta :link :auto-number]) (get-in folio [:meta :link :auto-number]) true) (drop-while nil?) (first)) auto-number (cond (set? auto-number) auto-number (false? auto-number) #{} (true? auto-number) #{:image :equation :code :block})] (link-numbers-loop elements auto-number)))))
9a82d4ddd474f8c8c0cbcbc18fed23da1778fdebc1915957b4af35a35dd86645
b0-system/b0
b0_cmd_pack.mli
--------------------------------------------------------------------------- Copyright ( c ) 2020 The b0 programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2020 The b0 programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) * [ pack ] command . val cmd : B0_std.Os.Exit.t Cmdliner.Cmd.t (** [cmd] is the command line for [pack]. *) --------------------------------------------------------------------------- Copyright ( c ) 2020 The b0 programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2020 The b0 programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/b0-system/b0/cbe12b8a55da6b50ab01ed058b339dbed3cfe894/tool-b0/b0_cmd_pack.mli
ocaml
* [cmd] is the command line for [pack].
--------------------------------------------------------------------------- Copyright ( c ) 2020 The b0 programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2020 The b0 programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) * [ pack ] command . val cmd : B0_std.Os.Exit.t Cmdliner.Cmd.t --------------------------------------------------------------------------- Copyright ( c ) 2020 The b0 programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2020 The b0 programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
9ced89a2207317c3c4c60735a6dc2c2153005452a1814eba36c192ed0b0fd3dd
mt-caret/io_uring
http.ml
open Core a ( wip ) port of module Handler = struct open Httpaf let request_handler reqd = match Reqd.request reqd with | { Request.meth = `POST; headers; _ } -> let response = let content_type = match Headers.get headers "content-type" with | None -> "application/octet-stream" | Some x -> x in Response.create ~headers: (Headers.of_list [ "content-type", content_type; "connection", "close" ]) `OK in let request_body = Reqd.request_body reqd in let response_body = Reqd.respond_with_streaming reqd response in let rec on_read buffer ~off ~len = Body.write_bigstring response_body buffer ~off ~len; Body.schedule_read request_body ~on_eof ~on_read and on_eof () = Body.close_writer response_body in Body.schedule_read (Reqd.request_body reqd) ~on_eof ~on_read | _ -> let headers = Headers.of_list [ "connection", "close" ] in Reqd.respond_with_string reqd (Response.create ~headers `Method_not_allowed) "" ;; let error_handler ?request:_ error start_response = let response_body = start_response Headers.empty in (match error with | `Exn exn -> Body.write_string response_body (Exn.to_string exn); Body.write_string response_body "\n" | #Status.standard as error -> Body.write_string response_body (Status.default_reason_phrase error)); Body.close_writer response_body ;; end module Buffer = struct type t = { buffer : (Bigstring.t[@sexp.opaque]) ; mutable off : int ; mutable len : int } [@@deriving sexp] let create size = let buffer = Bigstring.create size in { buffer; off = 0; len = 0 } ;; let compress t = if t.len = 0 then ( t.off <- 0; t.len <- 0) else if t.off > 0 then ( Bigstring.blit ~src:t.buffer ~src_pos:t.off ~dst:t.buffer ~dst_pos:0 ~len:t.len; t.off <- 0) ;; let read t ~f = let n = f t.buffer ~off:t.off ~len:t.len in t.off <- t.off + n; t.len <- t.len - n; if t.len = 0 then t.off <- 0 ;; let start_write t ~f = compress t; f t.buffer ~off:(t.off + t.len) ~len:(Bigstring.length t.buffer - t.len) ;; let finish_writing t n = t.len <- t.len + n end module User_data = struct module Reader_context = struct type t = { conn : (Httpaf.Server_connection.t[@sexp.opaque]) ; fd : Unix.File_descr.t ; buf : Buffer.t } [@@deriving sexp_of] end type t = | Accept | Recv of Reader_context.t | Yield_reader of Reader_context.t | Sendmsg of { conn : (Httpaf.Server_connection.t[@sexp.opaque]) ; fd : Unix.File_descr.t ; iovecs : (Bigstring.t[@sexp.opaque]) Unix.IOVec.t array } | Yield_writer of { conn : (Httpaf.Server_connection.t[@sexp.opaque]) ; fd : Unix.File_descr.t } [@@deriving sexp_of] let prepare t ~io_uring ~sockfd ~queued_sockaddr_ref = match t with | Accept -> let queued_sockaddr = Io_uring.prepare_accept io_uring Io_uring.Sqe_flags.none sockfd t in queued_sockaddr_ref := (match queued_sockaddr with | None -> raise_s [%message "accept: submission queue is full"] | Some queued_sockaddr -> Some queued_sockaddr) | Recv { conn = _; fd; buf } -> let sq_full = Buffer.start_write buf ~f:(fun bigstring ~off ~len -> Io_uring.prepare_recv io_uring Io_uring.Sqe_flags.none fd ~pos:off ~len bigstring t) in if sq_full then raise_s [%message "recv: submission queue is full"] | Yield_reader _ -> (* we use nops when yielding to simplify logic *) let sq_full = Io_uring.prepare_nop io_uring Io_uring.Sqe_flags.none t in if sq_full then raise_s [%message "nop: submission queue is full"] | Sendmsg { conn = _; fd; iovecs } -> let sq_full = Io_uring.prepare_sendmsg io_uring Io_uring.Sqe_flags.none fd iovecs t in if sq_full then raise_s [%message "sendmsg: submission queue is full"] | Yield_writer _ -> let sq_full = Io_uring.prepare_nop io_uring Io_uring.Sqe_flags.none t in if sq_full then raise_s [%message "nop: submission queue is full"] ;; end let to_core_iovec_array (iovecs : Bigstring.t Faraday.iovec list) = List.map iovecs ~f:(fun { buffer; off; len } -> Unix.IOVec.of_bigstring ~pos:off ~len buffer) |> List.to_array ;; let run ?(config = Httpaf.Config.default) ~queue_depth ~port ~backlog () = let sockfd = Unix.socket ~domain:PF_INET ~kind:SOCK_STREAM ~protocol:0 () in Unix.setsockopt sockfd SO_REUSEADDR true; let addr = Unix.ADDR_INET (Unix.Inet_addr.localhost, port) in Unix.bind sockfd ~addr; Unix.listen sockfd ~backlog; let io_uring = Io_uring.create ~max_submission_entries:queue_depth ~max_completion_entries:(queue_depth * 2) in let queued_sockaddr_ref = ref None in let prepare = User_data.prepare ~io_uring ~sockfd ~queued_sockaddr_ref in prepare User_data.Accept; let reader_thread ~conn ~fd ~buf = match Httpaf.Server_connection.next_read_operation conn with | `Read -> User_data.Recv { conn; fd; buf } |> prepare | `Yield -> Httpaf.Server_connection.yield_reader conn (fun () -> User_data.Yield_reader { conn; fd; buf } |> prepare) | `Close -> Unix.shutdown fd ~mode:SHUTDOWN_RECEIVE in let writer_thread ~conn ~fd = match Httpaf.Server_connection.next_write_operation conn with | `Write iovecs -> User_data.Sendmsg { conn; fd; iovecs = to_core_iovec_array iovecs } |> prepare | `Yield -> Httpaf.Server_connection.yield_writer conn (fun () -> User_data.Yield_writer { conn; fd } |> prepare) | `Close _ -> Unix.shutdown fd ~mode:SHUTDOWN_SEND in while true do let (_ : int) = Io_uring.submit io_uring in Io_uring.wait io_uring ~timeout:`Never; Io_uring.iter_completions io_uring ~f:(fun ~user_data ~res ~flags -> print_s [%message "" (user_data : User_data.t) (res : int) (flags : int)]; match user_data with | Accept -> if res < 0 then Unix.unix_error (-res) "Io_uring.accept" ""; let sockaddr = Option.value_exn !queued_sockaddr_ref |> Io_uring.Queued_sockaddr.thread_unsafe_get |> Option.value_exn in print_s [%message "client connected" (sockaddr : Unix.sockaddr)]; prepare User_data.Accept; let conn = Handler.( Httpaf.Server_connection.create ~config ~error_handler request_handler) in let fd = Unix.File_descr.of_int res in let buf = Buffer.create config.read_buffer_size in reader_thread ~conn ~fd ~buf; writer_thread ~conn ~fd | Recv { conn; fd; buf } -> (* TODO: fix handling? *) if res < 0 then Unix.unix_error (-res) "Io_uring.recv" ""; Buffer.finish_writing buf res; Buffer.read buf ~f:(fun bigstring ~off ~len -> if res = 0 then Httpaf.Server_connection.read_eof conn bigstring ~off ~len else Httpaf.Server_connection.read conn bigstring ~off ~len); reader_thread ~conn ~fd ~buf | Yield_reader { conn; fd; buf } -> reader_thread ~conn ~fd ~buf | Sendmsg { conn; fd; iovecs = _ } -> if res < 0 then Unix.unix_error (-res) "Io_uring.sendmsg" ""; Httpaf.Server_connection.report_write_result conn (if res = 0 then `Closed else `Ok res); writer_thread ~conn ~fd | Yield_writer { conn; fd } -> writer_thread ~conn ~fd); Io_uring.clear_completions io_uring done ;; let () = Command.run @@ Command.basic ~summary:"toy http server using io_uring" @@ let%map_open.Command queue_depth = flag "queue-depth" (optional_with_default 2048 int) ~doc:"INT submission completion queue depth" and port = flag "port" (required int) ~doc:" port to listen on" and backlog = flag "backlog" (optional_with_default 100 int) ~doc:"INT size of backlog for listen()" in fun () -> run ~queue_depth ~port ~backlog () ;;
null
https://raw.githubusercontent.com/mt-caret/io_uring/78012a69a55faf81ab2fbb710c6d5ae71f6b44f0/example/http.ml
ocaml
we use nops when yielding to simplify logic TODO: fix handling?
open Core a ( wip ) port of module Handler = struct open Httpaf let request_handler reqd = match Reqd.request reqd with | { Request.meth = `POST; headers; _ } -> let response = let content_type = match Headers.get headers "content-type" with | None -> "application/octet-stream" | Some x -> x in Response.create ~headers: (Headers.of_list [ "content-type", content_type; "connection", "close" ]) `OK in let request_body = Reqd.request_body reqd in let response_body = Reqd.respond_with_streaming reqd response in let rec on_read buffer ~off ~len = Body.write_bigstring response_body buffer ~off ~len; Body.schedule_read request_body ~on_eof ~on_read and on_eof () = Body.close_writer response_body in Body.schedule_read (Reqd.request_body reqd) ~on_eof ~on_read | _ -> let headers = Headers.of_list [ "connection", "close" ] in Reqd.respond_with_string reqd (Response.create ~headers `Method_not_allowed) "" ;; let error_handler ?request:_ error start_response = let response_body = start_response Headers.empty in (match error with | `Exn exn -> Body.write_string response_body (Exn.to_string exn); Body.write_string response_body "\n" | #Status.standard as error -> Body.write_string response_body (Status.default_reason_phrase error)); Body.close_writer response_body ;; end module Buffer = struct type t = { buffer : (Bigstring.t[@sexp.opaque]) ; mutable off : int ; mutable len : int } [@@deriving sexp] let create size = let buffer = Bigstring.create size in { buffer; off = 0; len = 0 } ;; let compress t = if t.len = 0 then ( t.off <- 0; t.len <- 0) else if t.off > 0 then ( Bigstring.blit ~src:t.buffer ~src_pos:t.off ~dst:t.buffer ~dst_pos:0 ~len:t.len; t.off <- 0) ;; let read t ~f = let n = f t.buffer ~off:t.off ~len:t.len in t.off <- t.off + n; t.len <- t.len - n; if t.len = 0 then t.off <- 0 ;; let start_write t ~f = compress t; f t.buffer ~off:(t.off + t.len) ~len:(Bigstring.length t.buffer - t.len) ;; let finish_writing t n = t.len <- t.len + n end module User_data = struct module Reader_context = struct type t = { conn : (Httpaf.Server_connection.t[@sexp.opaque]) ; fd : Unix.File_descr.t ; buf : Buffer.t } [@@deriving sexp_of] end type t = | Accept | Recv of Reader_context.t | Yield_reader of Reader_context.t | Sendmsg of { conn : (Httpaf.Server_connection.t[@sexp.opaque]) ; fd : Unix.File_descr.t ; iovecs : (Bigstring.t[@sexp.opaque]) Unix.IOVec.t array } | Yield_writer of { conn : (Httpaf.Server_connection.t[@sexp.opaque]) ; fd : Unix.File_descr.t } [@@deriving sexp_of] let prepare t ~io_uring ~sockfd ~queued_sockaddr_ref = match t with | Accept -> let queued_sockaddr = Io_uring.prepare_accept io_uring Io_uring.Sqe_flags.none sockfd t in queued_sockaddr_ref := (match queued_sockaddr with | None -> raise_s [%message "accept: submission queue is full"] | Some queued_sockaddr -> Some queued_sockaddr) | Recv { conn = _; fd; buf } -> let sq_full = Buffer.start_write buf ~f:(fun bigstring ~off ~len -> Io_uring.prepare_recv io_uring Io_uring.Sqe_flags.none fd ~pos:off ~len bigstring t) in if sq_full then raise_s [%message "recv: submission queue is full"] | Yield_reader _ -> let sq_full = Io_uring.prepare_nop io_uring Io_uring.Sqe_flags.none t in if sq_full then raise_s [%message "nop: submission queue is full"] | Sendmsg { conn = _; fd; iovecs } -> let sq_full = Io_uring.prepare_sendmsg io_uring Io_uring.Sqe_flags.none fd iovecs t in if sq_full then raise_s [%message "sendmsg: submission queue is full"] | Yield_writer _ -> let sq_full = Io_uring.prepare_nop io_uring Io_uring.Sqe_flags.none t in if sq_full then raise_s [%message "nop: submission queue is full"] ;; end let to_core_iovec_array (iovecs : Bigstring.t Faraday.iovec list) = List.map iovecs ~f:(fun { buffer; off; len } -> Unix.IOVec.of_bigstring ~pos:off ~len buffer) |> List.to_array ;; let run ?(config = Httpaf.Config.default) ~queue_depth ~port ~backlog () = let sockfd = Unix.socket ~domain:PF_INET ~kind:SOCK_STREAM ~protocol:0 () in Unix.setsockopt sockfd SO_REUSEADDR true; let addr = Unix.ADDR_INET (Unix.Inet_addr.localhost, port) in Unix.bind sockfd ~addr; Unix.listen sockfd ~backlog; let io_uring = Io_uring.create ~max_submission_entries:queue_depth ~max_completion_entries:(queue_depth * 2) in let queued_sockaddr_ref = ref None in let prepare = User_data.prepare ~io_uring ~sockfd ~queued_sockaddr_ref in prepare User_data.Accept; let reader_thread ~conn ~fd ~buf = match Httpaf.Server_connection.next_read_operation conn with | `Read -> User_data.Recv { conn; fd; buf } |> prepare | `Yield -> Httpaf.Server_connection.yield_reader conn (fun () -> User_data.Yield_reader { conn; fd; buf } |> prepare) | `Close -> Unix.shutdown fd ~mode:SHUTDOWN_RECEIVE in let writer_thread ~conn ~fd = match Httpaf.Server_connection.next_write_operation conn with | `Write iovecs -> User_data.Sendmsg { conn; fd; iovecs = to_core_iovec_array iovecs } |> prepare | `Yield -> Httpaf.Server_connection.yield_writer conn (fun () -> User_data.Yield_writer { conn; fd } |> prepare) | `Close _ -> Unix.shutdown fd ~mode:SHUTDOWN_SEND in while true do let (_ : int) = Io_uring.submit io_uring in Io_uring.wait io_uring ~timeout:`Never; Io_uring.iter_completions io_uring ~f:(fun ~user_data ~res ~flags -> print_s [%message "" (user_data : User_data.t) (res : int) (flags : int)]; match user_data with | Accept -> if res < 0 then Unix.unix_error (-res) "Io_uring.accept" ""; let sockaddr = Option.value_exn !queued_sockaddr_ref |> Io_uring.Queued_sockaddr.thread_unsafe_get |> Option.value_exn in print_s [%message "client connected" (sockaddr : Unix.sockaddr)]; prepare User_data.Accept; let conn = Handler.( Httpaf.Server_connection.create ~config ~error_handler request_handler) in let fd = Unix.File_descr.of_int res in let buf = Buffer.create config.read_buffer_size in reader_thread ~conn ~fd ~buf; writer_thread ~conn ~fd | Recv { conn; fd; buf } -> if res < 0 then Unix.unix_error (-res) "Io_uring.recv" ""; Buffer.finish_writing buf res; Buffer.read buf ~f:(fun bigstring ~off ~len -> if res = 0 then Httpaf.Server_connection.read_eof conn bigstring ~off ~len else Httpaf.Server_connection.read conn bigstring ~off ~len); reader_thread ~conn ~fd ~buf | Yield_reader { conn; fd; buf } -> reader_thread ~conn ~fd ~buf | Sendmsg { conn; fd; iovecs = _ } -> if res < 0 then Unix.unix_error (-res) "Io_uring.sendmsg" ""; Httpaf.Server_connection.report_write_result conn (if res = 0 then `Closed else `Ok res); writer_thread ~conn ~fd | Yield_writer { conn; fd } -> writer_thread ~conn ~fd); Io_uring.clear_completions io_uring done ;; let () = Command.run @@ Command.basic ~summary:"toy http server using io_uring" @@ let%map_open.Command queue_depth = flag "queue-depth" (optional_with_default 2048 int) ~doc:"INT submission completion queue depth" and port = flag "port" (required int) ~doc:" port to listen on" and backlog = flag "backlog" (optional_with_default 100 int) ~doc:"INT size of backlog for listen()" in fun () -> run ~queue_depth ~port ~backlog () ;;
92bf2400fabecbd26e774affbc95a38e6e1dfef841bab461b8fd31234f7f22d1
naveensundarg/prover
wffs.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*- ;;; File: wffs.lisp The contents of this file are subject to the Mozilla Public License ;;; Version 1.1 (the "License"); you may not use this file except in ;;; compliance with the License. You may obtain a copy of the License at ;;; / ;;; Software distributed under the License is distributed on an " AS IS " ;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the ;;; License for the specific language governing rights and limitations ;;; under the License. ;;; The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 . All Rights Reserved . ;;; Contributor(s ): < > . (in-package :snark) wff = well - formed formula ;;; atom = atomic fomula (defun map-atoms-in-clause (cc wff0) (labels ((map-atoms (wff polarity) (dereference wff nil :if-constant (cond ((eq true wff) (when (eq :pos polarity) (not-clause-error wff0))) ((eq false wff) (when (eq :neg polarity) (not-clause-error wff0))) (t (funcall cc wff polarity))) :if-variable (not-clause-error wff0) :if-compound-cons (not-clause-error wff0) :if-compound-appl (case (function-logical-symbol-p (heada wff)) ((nil) (funcall cc wff polarity)) (not (map-atoms (arg1a wff) (if (eq :pos polarity) :neg :pos))) (and (if (eq :pos polarity) (not-clause-error wff0) (dolist (arg (argsa wff)) (map-atoms arg :neg)))) (or (if (eq :neg polarity) (not-clause-error wff0) (dolist (arg (argsa wff)) (map-atoms arg :pos)))) (implies (if (eq :neg polarity) (not-clause-error wff0) (let ((args (argsa wff))) (map-atoms (first args) :neg) (map-atoms (second args) :pos)))) (implied-by (if (eq :neg polarity) (not-clause-error wff0) (let ((args (argsa wff))) (map-atoms (first args) :pos) (map-atoms (second args) :neg)))))))) (map-atoms wff0 :pos))) (defun map-atoms-in-wff (cc wff &optional (polarity :pos)) (dereference wff nil :if-constant (unless (or (eq true wff) (eq false wff)) (funcall cc wff polarity)) :if-variable (not-wff-error wff) :if-compound-cons (not-wff-error wff) :if-compound-appl (let ((head (heada wff))) (if (function-logical-symbol-p head) (map-atoms-in-list-of-wffs cc (argsa wff) (function-polarity-map head) polarity) (funcall cc wff polarity)))) nil) (defun map-atoms-in-wff-and-compose-result (cc wff &optional (polarity :pos)) (dereference wff nil :if-constant (if (or (eq true wff) (eq false wff)) wff (funcall cc wff polarity)) :if-variable (not-wff-error wff) :if-compound-cons (not-wff-error wff) :if-compound-appl (prog-> (heada wff -> head) (cond ((function-logical-symbol-p head) (argsa wff -> args) (cond ((null args) wff) ((null (rest args)) (first args -> arg) (map-atoms-in-wff-and-compose-result cc arg (map-polarity (first (function-polarity-map head)) polarity) -> arg*) (if (eq arg arg*) wff (fancy-make-compound* head (list arg*)))) (t (map-atoms-in-list-of-wffs-and-compose-result cc args (function-polarity-map head) polarity -> args*) (if (eq args args*) wff (fancy-make-compound* head args*))))) (t (funcall cc wff polarity)))))) (defun map-terms-in-wff (cc wff &optional subst (polarity :pos)) (prog-> (map-atoms-in-wff wff polarity ->* atom polarity) (map-terms-in-atom cc atom subst polarity))) (defun map-terms-in-wff-and-compose-result (cc wff &optional subst (polarity :pos)) (prog-> (map-atoms-in-wff-and-compose-result wff polarity ->* atom polarity) (map-terms-in-atom-and-compose-result cc atom subst polarity))) (defun map-terms-in-atom (cc atom &optional subst (polarity :pos)) (dereference atom nil :if-variable (not-wff-error atom) :if-compound-cons (not-wff-error atom) :if-compound-appl (map-terms-in-list-of-terms cc nil (argsa atom) subst polarity))) (defun map-terms-in-atom-and-compose-result (cc atom &optional subst (polarity :pos)) (dereference atom nil :if-constant atom :if-variable (not-wff-error atom) :if-compound-cons (not-wff-error atom) :if-compound-appl (let* ((args (argsa atom)) (args* (map-terms-in-list-of-terms-and-compose-result cc nil args subst polarity))) (if (eq args args*) atom (make-compound* (heada atom) args*))))) (defun map-terms-in-term (cc term &optional subst (polarity :pos)) (dereference term subst :if-constant (funcall cc term polarity) :if-variable (funcall cc term polarity) :if-compound-cons (progn (map-terms-in-term cc (carc term) subst polarity) (map-terms-in-term cc (cdrc term) subst polarity) (funcall cc term polarity)) :if-compound-appl (let* ((head (heada term)) (head-if-associative (and (function-associative head) head))) (map-terms-in-list-of-terms cc head-if-associative (argsa term) subst polarity) (funcall cc term polarity)))) (defun map-terms-in-term-and-compose-result (cc term &optional subst (polarity :pos)) (dereference term subst :if-constant (funcall cc term polarity) :if-variable (funcall cc term polarity) :if-compound-cons (lcons (map-terms-in-term-and-compose-result cc (car term) subst polarity) (map-terms-in-term-and-compose-result cc (cdr term) subst polarity) term) :if-compound-appl (let* ((head (heada term)) (head-if-associative (and (function-associative head) head))) (funcall cc (let* ((args (argsa term)) (args* (map-terms-in-list-of-terms-and-compose-result cc head-if-associative args subst polarity))) (if (eq args args*) term (make-compound* (head term) args*))) polarity)))) (defun map-terms-in-list-of-terms (cc head-if-associative terms subst polarity) (dolist (term terms) (dereference term subst :if-variable (funcall cc term polarity) :if-constant (funcall cc term polarity) :if-compound-cons (progn (map-terms-in-term cc (carc term) subst polarity) (map-terms-in-term cc (cdrc term) subst polarity) (funcall cc term polarity)) :if-compound-appl (let ((head (heada term))) (map-terms-in-list-of-terms cc (and (function-associative head) head) (argsa term) subst polarity) (unless (and head-if-associative (eq head head-if-associative)) (funcall cc term polarity)))))) (defvar map-atoms-first nil) (defun map-atoms-in-list-of-wffs (cc wffs polarity-map polarity) (cond (map-atoms-first (let ((polarity-map polarity-map)) (dolist (wff wffs) (let ((polarity-fun (pop polarity-map))) (unless (head-is-logical-symbol wff) (map-atoms-in-wff cc wff (map-polarity polarity-fun polarity)))))) (let ((polarity-map polarity-map)) (dolist (wff wffs) (let ((polarity-fun (pop polarity-map))) (when (head-is-logical-symbol wff) (map-atoms-in-wff cc wff (map-polarity polarity-fun polarity))))))) (t (let ((polarity-map polarity-map)) (dolist (wff wffs) (let ((polarity-fun (pop polarity-map))) (map-atoms-in-wff cc wff (map-polarity polarity-fun polarity)))))))) (defun map-terms-in-list-of-terms-and-compose-result (cc head-if-associative terms subst polarity) (cond ((null terms) nil) (t (let ((term (first terms))) (dereference term subst :if-constant (lcons (funcall cc term polarity) (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (rest terms) subst polarity) terms) :if-variable (lcons (funcall cc term polarity) (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (rest terms) subst polarity) terms) :if-compound (cond ((and head-if-associative (eq (head term) head-if-associative)) (append (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (args term) subst polarity) (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (rest terms) subst polarity))) (t (lcons (map-terms-in-term-and-compose-result cc term subst polarity) (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (rest terms) subst polarity) terms)))))))) (defun map-atoms-in-list-of-wffs-and-compose-result (cc wffs polarity-map polarity) always called with at least two wffs (let* ((x (first wffs)) (x* (map-atoms-in-wff-and-compose-result cc x (map-polarity (first polarity-map) polarity))) (y (rest wffs))) (cond ((null (rest y)) (let* ((z (first y)) (z* (map-atoms-in-wff-and-compose-result cc z (map-polarity (second polarity-map) polarity)))) (cond ((eq z z*) (cond ((eq x x*) wffs) (t (cons x* y)))) (t (list x* z*))))) (t (lcons x* (map-atoms-in-list-of-wffs-and-compose-result cc (rest wffs) (rest polarity-map) polarity) wffs))))) (defun map-atoms-in-alist-of-wffs-and-compose-result (cc alist &optional polarity) (lcons (let ((p (first alist))) (lcons (car p) (map-atoms-in-wff-and-compose-result cc (cdr p) polarity) p)) (map-atoms-in-alist-of-wffs-and-compose-result cc (rest alist) polarity) alist)) (defun map-terms-in-list-of-wffs-and-compose-result (cc wffs subst polarity) (lcons (map-terms-in-wff-and-compose-result cc (first wffs) subst polarity) (map-terms-in-list-of-wffs-and-compose-result cc (rest wffs) subst polarity) wffs)) (defun map-conjuncts (cc wff) (if (conjunction-p wff) (mapc (lambda (wff) (map-conjuncts cc wff)) (args wff)) (funcall cc wff)) nil) (defun replace-atom-in-wff (wff atom value) (let* ((replaced nil) (wff* (prog-> (map-atoms-in-wff-and-compose-result wff ->* a p) (declare (ignore p)) (if (equal-p atom a) ;would prefer to use eq (progn (setf replaced t) value) a)))) (cl:assert replaced) wff*)) (defun atoms-in-wff (wff &optional subst atoms) (prog-> (last atoms -> atoms-last) (map-atoms-in-wff wff :pos ->* atom polarity) (declare (ignore polarity)) (unless (member-p atom atoms subst) (collect atom atoms))) atoms) (defun atoms-in-wffs (wffs &optional subst atoms) (prog-> (dolist wffs ->* wff) (setf atoms (atoms-in-wff wff subst atoms))) atoms) (defun atoms-in-wff2 (wff &optional subst (polarity :pos) variable-block) (let ((atoms-and-polarities nil) atoms-and-polarities-last) (prog-> (map-atoms-in-wff wff polarity ->* atom polarity) (when variable-block (setf atom (instantiate atom variable-block))) (assoc-p atom atoms-and-polarities subst -> v) (cond ((null v) (collect (list atom polarity) atoms-and-polarities)) ((neq polarity (second v)) (setf (second v) :both)))) atoms-and-polarities)) (defun atoms-in-clause2 (clause &optional except-atom renumber) (let ((atoms-and-polarities nil) atoms-and-polarities-last (except-atom-found nil) (rsubst nil)) (prog-> (map-atoms-in-clause clause ->* atom polarity) (cond ((equal-p except-atom atom) ;would prefer to use eq (setf except-atom-found t)) (t (when renumber (setf (values atom rsubst) (renumber-new atom nil rsubst))) (collect (list atom polarity) atoms-and-polarities)))) (cl:assert (implies except-atom except-atom-found)) atoms-and-polarities)) (defun atoms-to-clause2 (atoms-and-polarities) ;; inverse of atoms-in-clause2 (cond ((null atoms-and-polarities) false) ((null (rest atoms-and-polarities)) (let ((x (first atoms-and-polarities))) (if (eq :pos (second x)) (first x) (make-compound *not* (first x))))) (t (make-compound* *or* (mapcar (lambda (x) (if (eq :pos (second x)) (first x) (make-compound *not* (first x)))) atoms-and-polarities))))) (defun atoms-in-clause3 (clause &optional except-atom renumber) (let ((negatoms nil) negatoms-last (posatoms nil) posatoms-last (except-atom-found nil) (rsubst nil)) (prog-> (map-atoms-in-clause clause ->* atom polarity) (cond ((equal-p except-atom atom) ;would prefer to use eq (setf except-atom-found t)) (t (when renumber (setf (values atom rsubst) (renumber-new atom nil rsubst))) (ecase polarity (:neg (collect atom negatoms)) (:pos (collect atom posatoms)))))) (cl:assert (implies except-atom except-atom-found)) (values negatoms posatoms))) (defun atoms-to-clause3 (negatoms posatoms) inverse of atoms - in - clause3 (let ((literals nil) literals-last) (dolist (atom negatoms) (collect (make-compound *not* atom) literals)) (dolist (atom posatoms) (collect atom literals)) (literals-to-clause literals))) (defun literals-in-clause (clause &optional except-atom renumber) (let ((literals nil) literals-last (except-atom-found nil) (rsubst nil)) (prog-> (map-atoms-in-clause clause ->* atom polarity) (cond ((equal-p except-atom atom) ;would prefer to use eq (setf except-atom-found t)) (t (when renumber (setf (values atom rsubst) (renumber-new atom nil rsubst))) (ecase polarity (:pos (collect atom literals)) (:neg (collect (make-compound *not* atom) literals)))))) (cl:assert (implies except-atom except-atom-found)) literals)) (defun literals-to-clause (literals) ;; inverse of literals-in-clause (cond ((null literals) false) ((null (rest literals)) (first literals)) (t (make-compound* *or* literals)))) (defun first-negative-literal-in-wff (wff) (prog-> (map-atoms-in-wff wff ->* atom polarity) (when (eq :neg polarity) (return-from first-negative-literal-in-wff atom))) nil) (defun first-positive-literal-in-wff (wff) (prog-> (map-atoms-in-wff wff ->* atom polarity) (when (eq :pos polarity) (return-from first-positive-literal-in-wff atom))) nil) (defun do-not-resolve (atom &optional subst) (dereference atom subst :if-compound (function-do-not-resolve (head atom)) :if-constant (constant-do-not-resolve atom))) (defun do-not-factor (atom &optional subst) (dereference atom subst :if-compound (function-do-not-factor (head atom)))) (defun wff-positive-or-negative (wff) : pos if wff contains at least one atom and all atom occurrences are positive : neg if wff contains at least one atom and all atom occurrences are negative ;; nil otherwise (let ((result nil)) (prog-> (map-atoms-in-wff wff ->* atom polarity) (unless (or (do-not-resolve atom) (eq result polarity)) (if (and (null result) (or (eq :pos polarity) (eq :neg polarity))) (setf result polarity) (return-from wff-positive-or-negative nil)))) result)) (defun atom-satisfies-sequential-restriction-p (atom wff &optional subst) (dereference wff nil :if-constant (equal-p atom wff subst) :if-compound (if (function-logical-symbol-p (head wff)) (atom-satisfies-sequential-restriction-p atom (arg1 wff) subst) (equal-p atom wff subst)))) (defun term-satisfies-sequential-restriction-p (term wff &optional subst) (dereference wff nil :if-compound (if (function-logical-symbol-p (head wff)) (term-satisfies-sequential-restriction-p term (arg1 wff) subst) (occurs-p term wff subst)))) (defun salsify (sat wff interpretation continuation) #+(or symbolics ti) (declare (sys:downward-funarg continuation)) SAT = T if trying to satisfy WFF , NIL if trying to falsify WFF (cond ((eq true wff) (when sat (funcall continuation interpretation))) ((eq false wff) (unless sat (funcall continuation interpretation))) (t (let* ((head (and (compound-p wff) (head wff))) (kind (and head (function-logical-symbol-p head)))) (ecase kind (not (salsify (not sat) (arg1 wff) interpretation continuation)) (and (let ((args (args wff))) (cond ((null args) (when sat (funcall continuation interpretation))) ((null (rest args)) (salsify sat (first args) interpretation continuation)) (sat (let ((arg2 (if (null (cddr args)) (second args) (make-compound* *and* (rest args))))) (salsify sat (first args) interpretation (lambda (i) (salsify sat arg2 i continuation))))) (t (dolist (arg args) (salsify sat arg interpretation continuation)))))) (or (let ((args (args wff))) (cond ((null args) (unless sat (funcall continuation interpretation))) ((null (rest args)) (salsify sat (first args) interpretation continuation)) ((not sat) (let ((arg2 (if (null (cddr args)) (second args) (make-compound* *or* (rest args))))) (salsify sat (first args) interpretation (lambda (i) (salsify sat arg2 i continuation))))) (t (dolist (arg args) (salsify sat arg interpretation continuation)))))) (implies (let ((args (args wff))) (cond (sat (salsify nil (first args) interpretation continuation) (salsify t (second args) interpretation continuation)) (t (salsify t (first args) interpretation (lambda (i) (salsify nil (second args) i continuation))))))) (implied-by (let ((args (args wff))) (cond (sat (salsify nil (second args) interpretation continuation) (salsify t (first args) interpretation continuation)) (t (salsify t (second args) interpretation (lambda (i) (salsify nil (first args) i continuation))))))) ((iff xor) (let* ((args (args wff)) (arg1 (first args)) (arg2 (if (null (cddr args)) (second args) (make-compound* head (rest args))))) (salsify (if (eq 'iff kind) sat (not sat)) (make-compound *and* (make-compound *or* (make-compound *not* arg1) arg2) (make-compound *or* (make-compound *not* arg2) arg1)) interpretation continuation))) ((if answer-if) (let ((args (args wff))) (salsify t (first args) interpretation (lambda (i) (salsify sat (second args) i continuation))) (salsify nil (first args) interpretation (lambda (i) (salsify sat (third args) i continuation))))) ((nil) ;atomic (let ((v (assoc wff interpretation :test #'equal-p))) (cond ((null v) (funcall continuation (cons (cons wff (if sat true false)) interpretation))) ((eq (if sat true false) (cdr v)) (funcall continuation interpretation)))))))))) (defun propositional-contradiction-p (wff) (salsify t wff nil (lambda (i) (declare (ignore i)) (return-from propositional-contradiction-p nil))) t) (defun propositional-tautology-p (wff) (propositional-contradiction-p (negate wff))) (defun flatten-term (term subst) (dereference term subst :if-constant term :if-variable term :if-compound (let* ((head (head term)) (head-if-associative (and (function-associative head) head)) (args (args term)) (args* (flatten-list args subst head-if-associative))) CHECK ( < = ( LENGTH ARGS * ) 2 ) ? ? ? ? ? ? term (make-compound* head args*))))) (defun flatten-list (terms subst head-if-associative) (cond ((null terms) nil) (t (let ((term (first terms))) (cond ((and head-if-associative (dereference term subst :if-compound (eq (head term) head-if-associative))) (flatten-list (append (args term) (rest terms)) subst head-if-associative)) (t (lcons (flatten-term term subst) (flatten-list (rest terms) subst head-if-associative) terms))))))) (defun unflatten-term1 (term subst) ;; when f is associative, (f a b c) -> (f a (f b c)); leaves (f) and (f a) alone; doesn't unflatten subterms (dereference term subst :if-constant term :if-variable term :if-compound (let ((head (head term)) (args (args term))) (cond ((and (function-associative head) (rrest args)) (let* ((l (reverse args)) (term* (first l))) (dolist (x (rest l)) (setf term* (make-compound head x term*))) term*)) (t term))))) (defun unflatten-term (term subst) ;; when f is associative, (f a b c) -> (f a (f b c)); leaves (f) and (f a) alone; unflattens subterms too (dereference term subst :if-constant term :if-variable term :if-compound (labels ((unflatten-list (terms) (lcons (unflatten-term (first terms) subst) (unflatten-list (rest terms)) terms))) (let* ((args (args term)) (args* (unflatten-list args))) (unflatten-term1 (if (eq args args*) term (make-compound* (head term) args*)) subst))))) (defun flatten-args (fn args subst) (labels ((fa (args) (if (null args) args (let ((arg (first args))) (cond ((dereference arg subst :if-compound-appl (eq fn (heada arg))) (fa (append (argsa arg) (rest args)))) (t (let* ((args1 (rest args)) (args1* (fa args1))) (if (eq args1 args1*) args (cons arg args1*))))))))) (fa args))) (defun fn-chain-tail (fn x subst &optional (len 0)) ;; for a fn chain, return tail and length ;; (bag a b) = (bag-cons a (bag-cons b empty-bag)) -> empty-bag,2 ;; (bag* a b) = (bag-cons a b) -> b,1 (loop (dereference x subst :if-variable (return-from fn-chain-tail (values x len)) :if-constant (return-from fn-chain-tail (values x len)) :if-compound (if (eq fn (head x)) (setf x (second (args x)) len (+ 1 len)) (return-from fn-chain-tail (values x len)))))) (defun fn-chain-items (fn x subst) ;; (bag a b) = (bag-cons a (bag-cons b empty-bag)) -> (a b) ;; (bag* a b) = (bag-cons a b) -> (a) (let ((items nil) items-last) (loop (dereference x subst :if-variable (return) :if-constant (return) :if-compound (if (eq fn (head x)) (let ((args (args x))) (collect (first args) items) (setf x (second args))) (return)))) items)) (defun make-fn-chain (fn items tail) (labels ((mfc (items) (if (null items) tail (make-compound fn (first items) (mfc (rest items)))))) (mfc items))) (defun make-compound1 (fn identity arg1 arg2) (cond ((eql identity arg1) arg2) ((eql identity arg2) arg1) (t (make-compound fn arg1 arg2)))) wffs.lisp EOF
null
https://raw.githubusercontent.com/naveensundarg/prover/812baf098d8bf77e4d634cef4d12de94dcd1e113/snark-20120808r02/src/wffs.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*- File: wffs.lisp Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. atom = atomic fomula would prefer to use eq would prefer to use eq inverse of atoms-in-clause2 would prefer to use eq would prefer to use eq inverse of literals-in-clause nil otherwise atomic when f is associative, (f a b c) -> (f a (f b c)); leaves (f) and (f a) alone; doesn't unflatten subterms when f is associative, (f a b c) -> (f a (f b c)); leaves (f) and (f a) alone; unflattens subterms too for a fn chain, return tail and length (bag a b) = (bag-cons a (bag-cons b empty-bag)) -> empty-bag,2 (bag* a b) = (bag-cons a b) -> b,1 (bag a b) = (bag-cons a (bag-cons b empty-bag)) -> (a b) (bag* a b) = (bag-cons a b) -> (a)
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 . All Rights Reserved . Contributor(s ): < > . (in-package :snark) wff = well - formed formula (defun map-atoms-in-clause (cc wff0) (labels ((map-atoms (wff polarity) (dereference wff nil :if-constant (cond ((eq true wff) (when (eq :pos polarity) (not-clause-error wff0))) ((eq false wff) (when (eq :neg polarity) (not-clause-error wff0))) (t (funcall cc wff polarity))) :if-variable (not-clause-error wff0) :if-compound-cons (not-clause-error wff0) :if-compound-appl (case (function-logical-symbol-p (heada wff)) ((nil) (funcall cc wff polarity)) (not (map-atoms (arg1a wff) (if (eq :pos polarity) :neg :pos))) (and (if (eq :pos polarity) (not-clause-error wff0) (dolist (arg (argsa wff)) (map-atoms arg :neg)))) (or (if (eq :neg polarity) (not-clause-error wff0) (dolist (arg (argsa wff)) (map-atoms arg :pos)))) (implies (if (eq :neg polarity) (not-clause-error wff0) (let ((args (argsa wff))) (map-atoms (first args) :neg) (map-atoms (second args) :pos)))) (implied-by (if (eq :neg polarity) (not-clause-error wff0) (let ((args (argsa wff))) (map-atoms (first args) :pos) (map-atoms (second args) :neg)))))))) (map-atoms wff0 :pos))) (defun map-atoms-in-wff (cc wff &optional (polarity :pos)) (dereference wff nil :if-constant (unless (or (eq true wff) (eq false wff)) (funcall cc wff polarity)) :if-variable (not-wff-error wff) :if-compound-cons (not-wff-error wff) :if-compound-appl (let ((head (heada wff))) (if (function-logical-symbol-p head) (map-atoms-in-list-of-wffs cc (argsa wff) (function-polarity-map head) polarity) (funcall cc wff polarity)))) nil) (defun map-atoms-in-wff-and-compose-result (cc wff &optional (polarity :pos)) (dereference wff nil :if-constant (if (or (eq true wff) (eq false wff)) wff (funcall cc wff polarity)) :if-variable (not-wff-error wff) :if-compound-cons (not-wff-error wff) :if-compound-appl (prog-> (heada wff -> head) (cond ((function-logical-symbol-p head) (argsa wff -> args) (cond ((null args) wff) ((null (rest args)) (first args -> arg) (map-atoms-in-wff-and-compose-result cc arg (map-polarity (first (function-polarity-map head)) polarity) -> arg*) (if (eq arg arg*) wff (fancy-make-compound* head (list arg*)))) (t (map-atoms-in-list-of-wffs-and-compose-result cc args (function-polarity-map head) polarity -> args*) (if (eq args args*) wff (fancy-make-compound* head args*))))) (t (funcall cc wff polarity)))))) (defun map-terms-in-wff (cc wff &optional subst (polarity :pos)) (prog-> (map-atoms-in-wff wff polarity ->* atom polarity) (map-terms-in-atom cc atom subst polarity))) (defun map-terms-in-wff-and-compose-result (cc wff &optional subst (polarity :pos)) (prog-> (map-atoms-in-wff-and-compose-result wff polarity ->* atom polarity) (map-terms-in-atom-and-compose-result cc atom subst polarity))) (defun map-terms-in-atom (cc atom &optional subst (polarity :pos)) (dereference atom nil :if-variable (not-wff-error atom) :if-compound-cons (not-wff-error atom) :if-compound-appl (map-terms-in-list-of-terms cc nil (argsa atom) subst polarity))) (defun map-terms-in-atom-and-compose-result (cc atom &optional subst (polarity :pos)) (dereference atom nil :if-constant atom :if-variable (not-wff-error atom) :if-compound-cons (not-wff-error atom) :if-compound-appl (let* ((args (argsa atom)) (args* (map-terms-in-list-of-terms-and-compose-result cc nil args subst polarity))) (if (eq args args*) atom (make-compound* (heada atom) args*))))) (defun map-terms-in-term (cc term &optional subst (polarity :pos)) (dereference term subst :if-constant (funcall cc term polarity) :if-variable (funcall cc term polarity) :if-compound-cons (progn (map-terms-in-term cc (carc term) subst polarity) (map-terms-in-term cc (cdrc term) subst polarity) (funcall cc term polarity)) :if-compound-appl (let* ((head (heada term)) (head-if-associative (and (function-associative head) head))) (map-terms-in-list-of-terms cc head-if-associative (argsa term) subst polarity) (funcall cc term polarity)))) (defun map-terms-in-term-and-compose-result (cc term &optional subst (polarity :pos)) (dereference term subst :if-constant (funcall cc term polarity) :if-variable (funcall cc term polarity) :if-compound-cons (lcons (map-terms-in-term-and-compose-result cc (car term) subst polarity) (map-terms-in-term-and-compose-result cc (cdr term) subst polarity) term) :if-compound-appl (let* ((head (heada term)) (head-if-associative (and (function-associative head) head))) (funcall cc (let* ((args (argsa term)) (args* (map-terms-in-list-of-terms-and-compose-result cc head-if-associative args subst polarity))) (if (eq args args*) term (make-compound* (head term) args*))) polarity)))) (defun map-terms-in-list-of-terms (cc head-if-associative terms subst polarity) (dolist (term terms) (dereference term subst :if-variable (funcall cc term polarity) :if-constant (funcall cc term polarity) :if-compound-cons (progn (map-terms-in-term cc (carc term) subst polarity) (map-terms-in-term cc (cdrc term) subst polarity) (funcall cc term polarity)) :if-compound-appl (let ((head (heada term))) (map-terms-in-list-of-terms cc (and (function-associative head) head) (argsa term) subst polarity) (unless (and head-if-associative (eq head head-if-associative)) (funcall cc term polarity)))))) (defvar map-atoms-first nil) (defun map-atoms-in-list-of-wffs (cc wffs polarity-map polarity) (cond (map-atoms-first (let ((polarity-map polarity-map)) (dolist (wff wffs) (let ((polarity-fun (pop polarity-map))) (unless (head-is-logical-symbol wff) (map-atoms-in-wff cc wff (map-polarity polarity-fun polarity)))))) (let ((polarity-map polarity-map)) (dolist (wff wffs) (let ((polarity-fun (pop polarity-map))) (when (head-is-logical-symbol wff) (map-atoms-in-wff cc wff (map-polarity polarity-fun polarity))))))) (t (let ((polarity-map polarity-map)) (dolist (wff wffs) (let ((polarity-fun (pop polarity-map))) (map-atoms-in-wff cc wff (map-polarity polarity-fun polarity)))))))) (defun map-terms-in-list-of-terms-and-compose-result (cc head-if-associative terms subst polarity) (cond ((null terms) nil) (t (let ((term (first terms))) (dereference term subst :if-constant (lcons (funcall cc term polarity) (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (rest terms) subst polarity) terms) :if-variable (lcons (funcall cc term polarity) (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (rest terms) subst polarity) terms) :if-compound (cond ((and head-if-associative (eq (head term) head-if-associative)) (append (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (args term) subst polarity) (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (rest terms) subst polarity))) (t (lcons (map-terms-in-term-and-compose-result cc term subst polarity) (map-terms-in-list-of-terms-and-compose-result cc head-if-associative (rest terms) subst polarity) terms)))))))) (defun map-atoms-in-list-of-wffs-and-compose-result (cc wffs polarity-map polarity) always called with at least two wffs (let* ((x (first wffs)) (x* (map-atoms-in-wff-and-compose-result cc x (map-polarity (first polarity-map) polarity))) (y (rest wffs))) (cond ((null (rest y)) (let* ((z (first y)) (z* (map-atoms-in-wff-and-compose-result cc z (map-polarity (second polarity-map) polarity)))) (cond ((eq z z*) (cond ((eq x x*) wffs) (t (cons x* y)))) (t (list x* z*))))) (t (lcons x* (map-atoms-in-list-of-wffs-and-compose-result cc (rest wffs) (rest polarity-map) polarity) wffs))))) (defun map-atoms-in-alist-of-wffs-and-compose-result (cc alist &optional polarity) (lcons (let ((p (first alist))) (lcons (car p) (map-atoms-in-wff-and-compose-result cc (cdr p) polarity) p)) (map-atoms-in-alist-of-wffs-and-compose-result cc (rest alist) polarity) alist)) (defun map-terms-in-list-of-wffs-and-compose-result (cc wffs subst polarity) (lcons (map-terms-in-wff-and-compose-result cc (first wffs) subst polarity) (map-terms-in-list-of-wffs-and-compose-result cc (rest wffs) subst polarity) wffs)) (defun map-conjuncts (cc wff) (if (conjunction-p wff) (mapc (lambda (wff) (map-conjuncts cc wff)) (args wff)) (funcall cc wff)) nil) (defun replace-atom-in-wff (wff atom value) (let* ((replaced nil) (wff* (prog-> (map-atoms-in-wff-and-compose-result wff ->* a p) (declare (ignore p)) (progn (setf replaced t) value) a)))) (cl:assert replaced) wff*)) (defun atoms-in-wff (wff &optional subst atoms) (prog-> (last atoms -> atoms-last) (map-atoms-in-wff wff :pos ->* atom polarity) (declare (ignore polarity)) (unless (member-p atom atoms subst) (collect atom atoms))) atoms) (defun atoms-in-wffs (wffs &optional subst atoms) (prog-> (dolist wffs ->* wff) (setf atoms (atoms-in-wff wff subst atoms))) atoms) (defun atoms-in-wff2 (wff &optional subst (polarity :pos) variable-block) (let ((atoms-and-polarities nil) atoms-and-polarities-last) (prog-> (map-atoms-in-wff wff polarity ->* atom polarity) (when variable-block (setf atom (instantiate atom variable-block))) (assoc-p atom atoms-and-polarities subst -> v) (cond ((null v) (collect (list atom polarity) atoms-and-polarities)) ((neq polarity (second v)) (setf (second v) :both)))) atoms-and-polarities)) (defun atoms-in-clause2 (clause &optional except-atom renumber) (let ((atoms-and-polarities nil) atoms-and-polarities-last (except-atom-found nil) (rsubst nil)) (prog-> (map-atoms-in-clause clause ->* atom polarity) (cond (setf except-atom-found t)) (t (when renumber (setf (values atom rsubst) (renumber-new atom nil rsubst))) (collect (list atom polarity) atoms-and-polarities)))) (cl:assert (implies except-atom except-atom-found)) atoms-and-polarities)) (defun atoms-to-clause2 (atoms-and-polarities) (cond ((null atoms-and-polarities) false) ((null (rest atoms-and-polarities)) (let ((x (first atoms-and-polarities))) (if (eq :pos (second x)) (first x) (make-compound *not* (first x))))) (t (make-compound* *or* (mapcar (lambda (x) (if (eq :pos (second x)) (first x) (make-compound *not* (first x)))) atoms-and-polarities))))) (defun atoms-in-clause3 (clause &optional except-atom renumber) (let ((negatoms nil) negatoms-last (posatoms nil) posatoms-last (except-atom-found nil) (rsubst nil)) (prog-> (map-atoms-in-clause clause ->* atom polarity) (cond (setf except-atom-found t)) (t (when renumber (setf (values atom rsubst) (renumber-new atom nil rsubst))) (ecase polarity (:neg (collect atom negatoms)) (:pos (collect atom posatoms)))))) (cl:assert (implies except-atom except-atom-found)) (values negatoms posatoms))) (defun atoms-to-clause3 (negatoms posatoms) inverse of atoms - in - clause3 (let ((literals nil) literals-last) (dolist (atom negatoms) (collect (make-compound *not* atom) literals)) (dolist (atom posatoms) (collect atom literals)) (literals-to-clause literals))) (defun literals-in-clause (clause &optional except-atom renumber) (let ((literals nil) literals-last (except-atom-found nil) (rsubst nil)) (prog-> (map-atoms-in-clause clause ->* atom polarity) (cond (setf except-atom-found t)) (t (when renumber (setf (values atom rsubst) (renumber-new atom nil rsubst))) (ecase polarity (:pos (collect atom literals)) (:neg (collect (make-compound *not* atom) literals)))))) (cl:assert (implies except-atom except-atom-found)) literals)) (defun literals-to-clause (literals) (cond ((null literals) false) ((null (rest literals)) (first literals)) (t (make-compound* *or* literals)))) (defun first-negative-literal-in-wff (wff) (prog-> (map-atoms-in-wff wff ->* atom polarity) (when (eq :neg polarity) (return-from first-negative-literal-in-wff atom))) nil) (defun first-positive-literal-in-wff (wff) (prog-> (map-atoms-in-wff wff ->* atom polarity) (when (eq :pos polarity) (return-from first-positive-literal-in-wff atom))) nil) (defun do-not-resolve (atom &optional subst) (dereference atom subst :if-compound (function-do-not-resolve (head atom)) :if-constant (constant-do-not-resolve atom))) (defun do-not-factor (atom &optional subst) (dereference atom subst :if-compound (function-do-not-factor (head atom)))) (defun wff-positive-or-negative (wff) : pos if wff contains at least one atom and all atom occurrences are positive : neg if wff contains at least one atom and all atom occurrences are negative (let ((result nil)) (prog-> (map-atoms-in-wff wff ->* atom polarity) (unless (or (do-not-resolve atom) (eq result polarity)) (if (and (null result) (or (eq :pos polarity) (eq :neg polarity))) (setf result polarity) (return-from wff-positive-or-negative nil)))) result)) (defun atom-satisfies-sequential-restriction-p (atom wff &optional subst) (dereference wff nil :if-constant (equal-p atom wff subst) :if-compound (if (function-logical-symbol-p (head wff)) (atom-satisfies-sequential-restriction-p atom (arg1 wff) subst) (equal-p atom wff subst)))) (defun term-satisfies-sequential-restriction-p (term wff &optional subst) (dereference wff nil :if-compound (if (function-logical-symbol-p (head wff)) (term-satisfies-sequential-restriction-p term (arg1 wff) subst) (occurs-p term wff subst)))) (defun salsify (sat wff interpretation continuation) #+(or symbolics ti) (declare (sys:downward-funarg continuation)) SAT = T if trying to satisfy WFF , NIL if trying to falsify WFF (cond ((eq true wff) (when sat (funcall continuation interpretation))) ((eq false wff) (unless sat (funcall continuation interpretation))) (t (let* ((head (and (compound-p wff) (head wff))) (kind (and head (function-logical-symbol-p head)))) (ecase kind (not (salsify (not sat) (arg1 wff) interpretation continuation)) (and (let ((args (args wff))) (cond ((null args) (when sat (funcall continuation interpretation))) ((null (rest args)) (salsify sat (first args) interpretation continuation)) (sat (let ((arg2 (if (null (cddr args)) (second args) (make-compound* *and* (rest args))))) (salsify sat (first args) interpretation (lambda (i) (salsify sat arg2 i continuation))))) (t (dolist (arg args) (salsify sat arg interpretation continuation)))))) (or (let ((args (args wff))) (cond ((null args) (unless sat (funcall continuation interpretation))) ((null (rest args)) (salsify sat (first args) interpretation continuation)) ((not sat) (let ((arg2 (if (null (cddr args)) (second args) (make-compound* *or* (rest args))))) (salsify sat (first args) interpretation (lambda (i) (salsify sat arg2 i continuation))))) (t (dolist (arg args) (salsify sat arg interpretation continuation)))))) (implies (let ((args (args wff))) (cond (sat (salsify nil (first args) interpretation continuation) (salsify t (second args) interpretation continuation)) (t (salsify t (first args) interpretation (lambda (i) (salsify nil (second args) i continuation))))))) (implied-by (let ((args (args wff))) (cond (sat (salsify nil (second args) interpretation continuation) (salsify t (first args) interpretation continuation)) (t (salsify t (second args) interpretation (lambda (i) (salsify nil (first args) i continuation))))))) ((iff xor) (let* ((args (args wff)) (arg1 (first args)) (arg2 (if (null (cddr args)) (second args) (make-compound* head (rest args))))) (salsify (if (eq 'iff kind) sat (not sat)) (make-compound *and* (make-compound *or* (make-compound *not* arg1) arg2) (make-compound *or* (make-compound *not* arg2) arg1)) interpretation continuation))) ((if answer-if) (let ((args (args wff))) (salsify t (first args) interpretation (lambda (i) (salsify sat (second args) i continuation))) (salsify nil (first args) interpretation (lambda (i) (salsify sat (third args) i continuation))))) (let ((v (assoc wff interpretation :test #'equal-p))) (cond ((null v) (funcall continuation (cons (cons wff (if sat true false)) interpretation))) ((eq (if sat true false) (cdr v)) (funcall continuation interpretation)))))))))) (defun propositional-contradiction-p (wff) (salsify t wff nil (lambda (i) (declare (ignore i)) (return-from propositional-contradiction-p nil))) t) (defun propositional-tautology-p (wff) (propositional-contradiction-p (negate wff))) (defun flatten-term (term subst) (dereference term subst :if-constant term :if-variable term :if-compound (let* ((head (head term)) (head-if-associative (and (function-associative head) head)) (args (args term)) (args* (flatten-list args subst head-if-associative))) CHECK ( < = ( LENGTH ARGS * ) 2 ) ? ? ? ? ? ? term (make-compound* head args*))))) (defun flatten-list (terms subst head-if-associative) (cond ((null terms) nil) (t (let ((term (first terms))) (cond ((and head-if-associative (dereference term subst :if-compound (eq (head term) head-if-associative))) (flatten-list (append (args term) (rest terms)) subst head-if-associative)) (t (lcons (flatten-term term subst) (flatten-list (rest terms) subst head-if-associative) terms))))))) (defun unflatten-term1 (term subst) (dereference term subst :if-constant term :if-variable term :if-compound (let ((head (head term)) (args (args term))) (cond ((and (function-associative head) (rrest args)) (let* ((l (reverse args)) (term* (first l))) (dolist (x (rest l)) (setf term* (make-compound head x term*))) term*)) (t term))))) (defun unflatten-term (term subst) (dereference term subst :if-constant term :if-variable term :if-compound (labels ((unflatten-list (terms) (lcons (unflatten-term (first terms) subst) (unflatten-list (rest terms)) terms))) (let* ((args (args term)) (args* (unflatten-list args))) (unflatten-term1 (if (eq args args*) term (make-compound* (head term) args*)) subst))))) (defun flatten-args (fn args subst) (labels ((fa (args) (if (null args) args (let ((arg (first args))) (cond ((dereference arg subst :if-compound-appl (eq fn (heada arg))) (fa (append (argsa arg) (rest args)))) (t (let* ((args1 (rest args)) (args1* (fa args1))) (if (eq args1 args1*) args (cons arg args1*))))))))) (fa args))) (defun fn-chain-tail (fn x subst &optional (len 0)) (loop (dereference x subst :if-variable (return-from fn-chain-tail (values x len)) :if-constant (return-from fn-chain-tail (values x len)) :if-compound (if (eq fn (head x)) (setf x (second (args x)) len (+ 1 len)) (return-from fn-chain-tail (values x len)))))) (defun fn-chain-items (fn x subst) (let ((items nil) items-last) (loop (dereference x subst :if-variable (return) :if-constant (return) :if-compound (if (eq fn (head x)) (let ((args (args x))) (collect (first args) items) (setf x (second args))) (return)))) items)) (defun make-fn-chain (fn items tail) (labels ((mfc (items) (if (null items) tail (make-compound fn (first items) (mfc (rest items)))))) (mfc items))) (defun make-compound1 (fn identity arg1 arg2) (cond ((eql identity arg1) arg2) ((eql identity arg2) arg1) (t (make-compound fn arg1 arg2)))) wffs.lisp EOF
b7b16f4916688551ed37e84b22a892a80085d11fa1e15a45e9ca6850b1fb1972
Perry961002/SICP
exa4.2.2-thunk.scm
创建槽,包装一个包含表达式和对应环境的表 (define (delay-it exp env) (list 'thunk exp env)) (define (thunk? obj) (tagged-list? obj 'thunk)) (define (thunk-exp thunk) (cadr thunk)) (define (thunk-env thunk) (caddr thunk)) 带记忆化的槽 (define (evaluated-thunk? obj) (tagged-list? obj 'evaluated-thunk)) (define (thunk-value evaluated-thunk) (cadr evaluated-thunk)) (define (force-it obj) (cond ((thunk? obj) (let ((result (actual-value (thunk-exp obj) (thunk-env obj)))) (set-car! obj 'evaluated-thunk) (set-car! (cdr obj) result) (set-cdr! (cdr obj) '()) result)) ((evaluated-thunk? obj) (thunk-value obj)) (else obj))) (define (actual-value exp env) (force-it (eval exp env))) (define (list-of-arg-values exps env) (if (no-operands? exps) '() (cons (actual-value (first-operand exps) env) (list-of-arg-values (rest-operands exps) env)))) (define (list-of-delayed-args exps env) (if (no-operands? exps) '() (cons (delay-it (first-operand exps) env) (list-of-delayed-args (rest-operands exps) env)))) (define (eval-if exp env) (if (true? (actual-value (if-predicatenexp) env)) (eval (if-consequent exp) env) (eval (if-alternative exp) env))) (define (apply procedure arguments env) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure (list-of-arg-values arguments env))) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) (list-of-delayed-args arguments env) (procedure-environment procedure)))) (else (error "Unknown procedure type -- APPLY" procedure))))
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap4/example/exa4.2.2-thunk.scm
scheme
创建槽,包装一个包含表达式和对应环境的表 (define (delay-it exp env) (list 'thunk exp env)) (define (thunk? obj) (tagged-list? obj 'thunk)) (define (thunk-exp thunk) (cadr thunk)) (define (thunk-env thunk) (caddr thunk)) 带记忆化的槽 (define (evaluated-thunk? obj) (tagged-list? obj 'evaluated-thunk)) (define (thunk-value evaluated-thunk) (cadr evaluated-thunk)) (define (force-it obj) (cond ((thunk? obj) (let ((result (actual-value (thunk-exp obj) (thunk-env obj)))) (set-car! obj 'evaluated-thunk) (set-car! (cdr obj) result) (set-cdr! (cdr obj) '()) result)) ((evaluated-thunk? obj) (thunk-value obj)) (else obj))) (define (actual-value exp env) (force-it (eval exp env))) (define (list-of-arg-values exps env) (if (no-operands? exps) '() (cons (actual-value (first-operand exps) env) (list-of-arg-values (rest-operands exps) env)))) (define (list-of-delayed-args exps env) (if (no-operands? exps) '() (cons (delay-it (first-operand exps) env) (list-of-delayed-args (rest-operands exps) env)))) (define (eval-if exp env) (if (true? (actual-value (if-predicatenexp) env)) (eval (if-consequent exp) env) (eval (if-alternative exp) env))) (define (apply procedure arguments env) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure (list-of-arg-values arguments env))) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) (list-of-delayed-args arguments env) (procedure-environment procedure)))) (else (error "Unknown procedure type -- APPLY" procedure))))
2a6fcd46d085c6188daca96eabad33ac482873c55ce776d046803f838eef39f5
tek/helic
Options.hs
{-# options_haddock prune #-} |CLI Options , Internal module Helic.Cli.Options where import Exon (exon) import Options.Applicative ( CommandFields, Mod, Parser, ReadM, argument, auto, command, help, hsubparser, info, long, option, progDesc, readerError, strOption, switch, ) import Options.Applicative.Types (readerAsk) import Path (Abs, File, Path, parseAbsFile) import Prelude hiding (Mod) import Helic.Data.ListConfig (ListConfig (ListConfig)) import Helic.Data.LoadConfig (LoadConfig (LoadConfig)) import Helic.Data.YankConfig (YankConfig (YankConfig)) data Conf = Conf { verbose :: Maybe Bool, configFile :: Maybe (Path Abs File) } deriving stock (Eq, Show) data Command = Listen | Yank YankConfig | List ListConfig | Load LoadConfig deriving stock (Eq, Show) filePathOption :: ReadM (Path Abs File) filePathOption = do raw <- readerAsk either (const (readerError [exon|not an absolute file path: #{show raw}|])) pure (parseAbsFile raw) confParser :: Parser Conf confParser = do verbose <- optional (switch (long "verbose")) configFile <- optional (option filePathOption (long "config-file")) pure (Conf verbose configFile) listenCommand :: Mod CommandFields Command listenCommand = command "listen" (info (pure Listen) (progDesc "Run the daemon")) yankParser :: Parser YankConfig yankParser = YankConfig <$> optional (strOption (long "agent" <> help "Source of the yank")) yankCommand :: Mod CommandFields Command yankCommand = command "yank" (Yank <$> info yankParser (progDesc "Send stdin to the daemon")) listParser :: Parser ListConfig listParser = ListConfig <$> optional (argument auto (help "Maximum number of events to list")) listCommand :: Mod CommandFields Command listCommand = command "list" (List <$> info listParser (progDesc "List clipboard events")) loadParser :: Parser LoadConfig loadParser = LoadConfig <$> argument auto (help "Index of the event") loadCommand :: Mod CommandFields Command loadCommand = command "load" (Load <$> info loadParser (progDesc "Load a history event")) commands :: [Mod CommandFields Command] commands = [ listenCommand, yankCommand, listCommand, loadCommand ] parser :: Parser (Conf, Maybe Command) parser = (,) <$> confParser <*> optional (hsubparser (mconcat commands))
null
https://raw.githubusercontent.com/tek/helic/055b2ffa063936ad4ae6249c9e6e0603482baaa9/packages/helic/lib/Helic/Cli/Options.hs
haskell
# options_haddock prune #
|CLI Options , Internal module Helic.Cli.Options where import Exon (exon) import Options.Applicative ( CommandFields, Mod, Parser, ReadM, argument, auto, command, help, hsubparser, info, long, option, progDesc, readerError, strOption, switch, ) import Options.Applicative.Types (readerAsk) import Path (Abs, File, Path, parseAbsFile) import Prelude hiding (Mod) import Helic.Data.ListConfig (ListConfig (ListConfig)) import Helic.Data.LoadConfig (LoadConfig (LoadConfig)) import Helic.Data.YankConfig (YankConfig (YankConfig)) data Conf = Conf { verbose :: Maybe Bool, configFile :: Maybe (Path Abs File) } deriving stock (Eq, Show) data Command = Listen | Yank YankConfig | List ListConfig | Load LoadConfig deriving stock (Eq, Show) filePathOption :: ReadM (Path Abs File) filePathOption = do raw <- readerAsk either (const (readerError [exon|not an absolute file path: #{show raw}|])) pure (parseAbsFile raw) confParser :: Parser Conf confParser = do verbose <- optional (switch (long "verbose")) configFile <- optional (option filePathOption (long "config-file")) pure (Conf verbose configFile) listenCommand :: Mod CommandFields Command listenCommand = command "listen" (info (pure Listen) (progDesc "Run the daemon")) yankParser :: Parser YankConfig yankParser = YankConfig <$> optional (strOption (long "agent" <> help "Source of the yank")) yankCommand :: Mod CommandFields Command yankCommand = command "yank" (Yank <$> info yankParser (progDesc "Send stdin to the daemon")) listParser :: Parser ListConfig listParser = ListConfig <$> optional (argument auto (help "Maximum number of events to list")) listCommand :: Mod CommandFields Command listCommand = command "list" (List <$> info listParser (progDesc "List clipboard events")) loadParser :: Parser LoadConfig loadParser = LoadConfig <$> argument auto (help "Index of the event") loadCommand :: Mod CommandFields Command loadCommand = command "load" (Load <$> info loadParser (progDesc "Load a history event")) commands :: [Mod CommandFields Command] commands = [ listenCommand, yankCommand, listCommand, loadCommand ] parser :: Parser (Conf, Maybe Command) parser = (,) <$> confParser <*> optional (hsubparser (mconcat commands))
c1377bc8d34f061cf61feeebd14d4839caae3f94a36e1bd83dc8095a70a8118c
no-defun-allowed/concurrent-hash-tables
phony-redis-no-mailbox.lisp
According to a presentation by an Amazon Web Services engineer , ;;; one cannot design an in-memory database using a garbage collected ;;; language implementation, because it would be too slow due to collection . He then goes to use a hash table with just one lock , ;;; copies the data to be stored just 'cause, finds performance similar ;;; to Redis, and calls it a day. ;;; Using structure sharing and a concurrent hash table, we can go much faster . Perhaps a magnitude or two faster - not that I 'm ;;; really taking the problem seriously, by avoiding network ;;; serialisation, and even inter-thread mailboxes; but this should ;;; show that tasteful use of concurrent data structures makes things ;;; go fast. (defpackage :phony-redis (:use :cl) (:export #:make-server #:connect-to-server #:find-value #:close-connection)) (in-package :phony-redis) (defmacro specialize (string body) "Convince the compiler to generate a fast path for simple strings." `(if (typep ,string '(simple-array character 1)) ,body ,body)) (defun djb (string) (declare (string string) (optimize speed)) (let ((hash 5381)) (declare ((and unsigned-byte fixnum) hash)) (specialize string (dotimes (n (min 6 (length string))) (setf hash (logand most-positive-fixnum (logxor (* hash 33) (char-code (schar string n))))))) hash)) (defun make-server () (concurrent-hash-table:make-chash-table :test #'equal :hash-function #'djb)) (defun connect-to-server (server) server) (defun find-value (connection name) (concurrent-hash-table:getchash name connection)) (defun (setf find-value) (value connection name) (setf (concurrent-hash-table:getchash name connection) value)) (defun close-connection (connection) (declare (ignore connection)) (values))
null
https://raw.githubusercontent.com/no-defun-allowed/concurrent-hash-tables/1b9f0b5da54fece4f42296e1bdacfcec0c370a5a/Examples/phony-redis-no-mailbox.lisp
lisp
one cannot design an in-memory database using a garbage collected language implementation, because it would be too slow due to copies the data to be stored just 'cause, finds performance similar to Redis, and calls it a day. Using structure sharing and a concurrent hash table, we can go really taking the problem seriously, by avoiding network serialisation, and even inter-thread mailboxes; but this should show that tasteful use of concurrent data structures makes things go fast.
According to a presentation by an Amazon Web Services engineer , collection . He then goes to use a hash table with just one lock , much faster . Perhaps a magnitude or two faster - not that I 'm (defpackage :phony-redis (:use :cl) (:export #:make-server #:connect-to-server #:find-value #:close-connection)) (in-package :phony-redis) (defmacro specialize (string body) "Convince the compiler to generate a fast path for simple strings." `(if (typep ,string '(simple-array character 1)) ,body ,body)) (defun djb (string) (declare (string string) (optimize speed)) (let ((hash 5381)) (declare ((and unsigned-byte fixnum) hash)) (specialize string (dotimes (n (min 6 (length string))) (setf hash (logand most-positive-fixnum (logxor (* hash 33) (char-code (schar string n))))))) hash)) (defun make-server () (concurrent-hash-table:make-chash-table :test #'equal :hash-function #'djb)) (defun connect-to-server (server) server) (defun find-value (connection name) (concurrent-hash-table:getchash name connection)) (defun (setf find-value) (value connection name) (setf (concurrent-hash-table:getchash name connection) value)) (defun close-connection (connection) (declare (ignore connection)) (values))
f26271e19677e02176fd34c20d03dacc60b93c8008903f017c3e947722199138
facebook/duckling
SV_XX.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory . ----------------------------------------------------------------- -- Auto-generated by regenClassifiers -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING @generated ----------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Duckling.Ranking.Classifiers.SV_XX (classifiers) where import Data.String import Prelude import qualified Data.HashMap.Strict as HashMap import Duckling.Ranking.Types classifiers :: Classifiers classifiers = HashMap.fromList [("<time> timezone", Classifier{okData = ClassData{prior = 0.0, unseen = -3.4339872044851463, likelihoods = HashMap.fromList [("at <time-of-day>", -1.3217558399823195), ("hh:mm", -1.455287232606842), ("hour", -2.0149030205422647), ("minute", -1.0033021088637848)], n = 13}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("integer (numeric)", Classifier{okData = ClassData{prior = -0.8176416508043156, unseen = -4.897839799950911, likelihoods = HashMap.fromList [("", 0.0)], n = 132}, koData = ClassData{prior = -0.5824497609739314, unseen = -5.1298987149230735, likelihoods = HashMap.fromList [("", 0.0)], n = 167}}), ("the day before yesterday", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("lunch", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("Tisdag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("integer (20..90)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time> <part-of-day>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("dayhour", -0.9555114450274363), ("tomorrowevening", -1.8718021769015913), ("tomorrowlunch", -1.8718021769015913), ("yesterdayevening", -1.8718021769015913), ("Mandagmorning", -1.8718021769015913)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.791759469228055, likelihoods = HashMap.fromList [], n = 0}}), ("couple, a pair", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("dd/mm", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -0.916290731874155, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}}), ("sommar", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("today", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("at <time-of-day>", Classifier{okData = ClassData{prior = -0.3014753945841168, unseen = -4.7535901911063645, likelihoods = HashMap.fromList [("<time> timezone", -3.1354942159291497), ("time-of-day (latent)", -1.3437347467010947), ("relative minutes after|past <integer> (hour-of-day)", -3.6463198396951406), ("hh:mm", -1.8545603704670852), ("<time-of-day> sharp", -3.6463198396951406), ("hour", -1.2791962255635234), ("minute", -1.5668782980153044)], n = 54}, koData = ClassData{prior = -1.3460204619819507, unseen = -3.828641396489095, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.8109302162163288), ("hour", -0.8109302162163288)], n = 19}}), ("absorption of , after named day", Classifier{okData = ClassData{prior = 0.0, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("Sondag", -2.3978952727983707), ("Mandag", -1.7047480922384253), ("Lordag", -2.3978952727983707), ("day", -0.8938178760220964), ("Onsdag", -2.3978952727983707), ("Fredag", -1.9924301646902063)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("September", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("tonight", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("on <date>", Classifier{okData = ClassData{prior = -0.48285177172358457, unseen = -4.304065093204169, likelihoods = HashMap.fromList [("on <date>", -3.597312260588446), ("Mandag", -3.597312260588446), ("Torsdag", -2.211017899468555), ("Lordag", -3.597312260588446), ("the <day-of-month> (non ordinal)", -3.1918471524802814), ("<day-of-month>(ordinal) <named-month>", -2.344549292093078), ("day", -0.9231636111619171), ("the <day-of-month> (ordinal)", -3.597312260588446), ("afternoon", -3.597312260588446), ("<day-of-month> (ordinal)", -2.093234863812172), ("hour", -3.597312260588446), ("<day-of-month> (non ordinal) <named-month>", -3.597312260588446)], n = 29}, koData = ClassData{prior = -0.9597758438138939, unseen = -3.951243718581427, likelihoods = HashMap.fromList [("on <date>", -2.322387720290225), ("year (latent)", -1.8523840910444898), ("time-of-day (latent)", -1.8523840910444898), ("year", -1.62924053973028), ("hour", -1.62924053973028)], n = 18}}), ("integer (0..19)", Classifier{okData = ClassData{prior = -0.16251892949777494, unseen = -3.58351893845611, likelihoods = HashMap.fromList [("", 0.0)], n = 34}, koData = ClassData{prior = -1.8971199848858813, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}}), ("between <time-of-day> and <time-of-day> (interval)", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.6094379124341003), ("minuteminute", -1.2039728043259361), ("hh:mmhh:mm", -1.2039728043259361), ("minutehour", -1.6094379124341003)], n = 3}, koData = ClassData{prior = -1.3862943611198906, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.0986122886681098), ("minutehour", -1.0986122886681098)], n = 1}}), ("between <datetime> and <datetime> (interval)", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.7047480922384253), ("minuteminute", -1.2992829841302609), ("hh:mmhh:mm", -1.2992829841302609), ("minutehour", -1.7047480922384253)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.5040773967762742), ("minuteminute", -1.5040773967762742), ("minutehour", -1.5040773967762742), ("hh:mmintersect", -1.5040773967762742)], n = 2}}), ("month (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> more <unit-of-duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("integer (numeric)minute (grain)", -1.252762968495368), ("integer (0..19)minute (grain)", -1.252762968495368), ("minute", -0.8472978603872037)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> o'clock", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("vinter", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("Juli", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("", 0.0)], n = 8}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("hour (grain)", Classifier{okData = ClassData{prior = -0.11778303565638351, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("", 0.0)], n = 8}, koData = ClassData{prior = -2.1972245773362196, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("<ordinal> quarter", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("ordinal (digits)quarter (grain)", -1.252762968495368), ("ordinals (first..twentieth,thirtieth,...)quarter (grain)", -1.252762968495368), ("quarter", -0.8472978603872037)], n = 2}, koData = ClassData{prior = -0.6931471805599453, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("ordinal (digits)quarter (grain)", -1.252762968495368), ("ordinals (first..twentieth,thirtieth,...)quarter (grain)", -1.252762968495368), ("quarter", -0.8472978603872037)], n = 2}}), ("Last year", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect", Classifier{okData = ClassData{prior = -0.35003530316883363, unseen = -5.860786223465865, likelihoods = HashMap.fromList [("Onsdagthis <cycle>", -5.1647859739235145), ("Torsdag<time> timezone", -3.912023005428146), ("<datetime> - <datetime> (interval)on <date>", -4.0661736852554045), ("<time-of-day> - <time-of-day> (interval)on <date>", -4.0661736852554045), ("hourday", -5.1647859739235145), ("dayhour", -2.9134941753170187), ("daymonth", -3.1498829533812494), ("monthyear", -3.1498829533812494), ("Torsdagbetween <time-of-day> and <time-of-day> (interval)", -4.75932086581535), ("Mandagon <date>", -5.1647859739235145), ("yyyy-mm-ddat <time-of-day>", -4.471638793363569), ("intersecthh:mm", -5.1647859739235145), ("Torsdagbetween <datetime> and <datetime> (interval)", -4.75932086581535), ("Torsdagat <time-of-day>", -4.248495242049359), ("Marsyear", -5.1647859739235145), ("intersect by \"of\", \"from\", \"'s\"year", -4.75932086581535), ("Oktoberyear", -3.5553480614894135), ("Torsdagfrom <time-of-day> - <time-of-day> (interval)", -4.471638793363569), ("Torsdagfrom <datetime> - <datetime> (interval)", -4.471638793363569), ("last <day-of-week> of <time>year", -5.1647859739235145), ("todayat <time-of-day>", -4.75932086581535), ("the <day-of-month> (ordinal)Februari", -5.1647859739235145), ("dayday", -3.2929837970219227), ("dd/mmat <time-of-day>", -4.248495242049359), ("intersect by \",\"hh:mm", -4.248495242049359), ("dayyear", -3.5553480614894135), ("tomorrow<time-of-day> sharp", -4.75932086581535), ("<day-of-month>(ordinal) <named-month>year", -4.75932086581535), ("Onsdag<named-month> <day-of-month> (non ordinal)", -5.1647859739235145), ("absorption of , after named day<named-month> <day-of-month> (non ordinal)", -4.0661736852554045), ("tomorrowuntil <time-of-day>", -4.75932086581535), ("absorption of , after named day<day-of-month> (non ordinal) <named-month>", -4.471638793363569), ("after <time-of-day>at <time-of-day>", -4.75932086581535), ("the <day-of-month> (ordinal)Mars", -4.0661736852554045), ("intersect by \",\"<day-of-month> (non ordinal) <named-month>", -4.75932086581535), ("Mandagthis <cycle>", -5.1647859739235145), ("tomorrowafter <time-of-day>", -4.75932086581535), ("from <time-of-day> - <time-of-day> (interval)on <date>", -4.248495242049359), ("dayminute", -2.361425593016979), ("from <datetime> - <datetime> (interval)on <date>", -4.471638793363569), ("on <date>Mars", -4.0661736852554045), ("<ordinal> <cycle> of <time>year", -4.75932086581535), ("minuteday", -2.5620962884791303), ("absorption of , after named dayintersect", -5.1647859739235145), ("yearhh:mm", -5.1647859739235145), ("Tisdagthis <time>", -4.75932086581535), ("Onsdagnext <cycle>", -5.1647859739235145), ("absorption of , after named dayintersect by \",\"", -4.75932086581535), ("Sondaglast <cycle>", -5.1647859739235145), ("Septemberyear", -4.248495242049359), ("at <time-of-day>on <date>", -5.1647859739235145), ("between <time-of-day> and <time-of-day> (interval)on <date>", -5.1647859739235145), ("between <datetime> and <datetime> (interval)on <date>", -5.1647859739235145), ("dayweek", -4.0661736852554045), ("Tisdagthis <cycle>", -5.1647859739235145), ("on <date>Februari", -5.1647859739235145), ("weekyear", -4.248495242049359), ("hh:mmtomorrow", -4.471638793363569), ("tomorrowat <time-of-day>", -3.912023005428146), ("at <time-of-day>tomorrow", -4.75932086581535), ("Sondag<day-of-month> (non ordinal) <named-month>", -5.1647859739235145), ("last <cycle> of <time>year", -4.248495242049359), ("<day-of-month> (non ordinal) <named-month>year", -4.75932086581535), ("yearminute", -5.1647859739235145)], n = 136}, koData = ClassData{prior = -1.2196389210703353, unseen = -5.262690188904886, likelihoods = HashMap.fromList [("OnsdagFebruari", -4.564348191467836), ("dayhour", -2.6184380424125226), ("daymonth", -2.4242820279715653), ("monthyear", -3.648057459593681), ("Mandagon <date>", -4.1588830833596715), ("yyyy-mm-ddat <time-of-day>", -3.871201010907891), ("Torsdagat <time-of-day>", -3.0602707946915624), ("Marsyear", -3.871201010907891), ("intersect by \"of\", \"from\", \"'s\"year", -3.4657359027997265), ("Torsdagfrom <datetime> - <datetime> (interval)", -4.564348191467836), ("Mandagintersect", -4.1588830833596715), ("absorption of , after named dayJuli", -4.1588830833596715), ("hourmonth", -4.1588830833596715), ("dd/mmat <time-of-day>", -3.648057459593681), ("dayyear", -3.1780538303479458), ("Onsdagthis <time>", -3.648057459593681), ("Aprilyear", -4.564348191467836), ("yearmonth", -4.564348191467836), ("until <time-of-day>on <date>", -4.564348191467836), ("Torsdaghh:mm", -4.1588830833596715), ("dayminute", -3.311585222972468), ("minuteday", -3.0602707946915624), ("Tisdagthis <time>", -4.1588830833596715), ("hh:mmon <date>", -3.1780538303479458), ("on <date>Februari", -4.1588830833596715), ("absorption of , after named dayFebruari", -3.871201010907891), ("intersectFebruari", -4.1588830833596715), ("Mandagthis <time>", -4.564348191467836), ("Sondagthis <time>", -4.564348191467836)], n = 57}}), ("<ordinal> <cycle> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.890371757896165, likelihoods = HashMap.fromList [("daymonth", -1.7346010553881064), ("ordinals (first..twentieth,thirtieth,...)week (grain)Oktober", -1.7346010553881064), ("ordinals (first..twentieth,thirtieth,...)week (grain)intersect", -1.7346010553881064), ("weekmonth", -1.2237754316221157), ("ordinals (first..twentieth,thirtieth,...)day (grain)Oktober", -1.7346010553881064)], n = 6}, koData = ClassData{prior = -infinity, unseen = -1.791759469228055, likelihoods = HashMap.fromList [], n = 0}}), ("year (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("from <datetime> - <datetime> (interval)", Classifier{okData = ClassData{prior = -0.8472978603872037, unseen = -3.1780538303479458, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -2.4423470353692043), ("minuteminute", -1.5260563034950494), ("time-of-day (latent)time-of-day (latent)", -2.4423470353692043), ("hh:mmhh:mm", -1.5260563034950494), ("hourhour", -2.4423470353692043), ("minutehour", -2.4423470353692043)], n = 6}, koData = ClassData{prior = -0.5596157879354228, unseen = -3.332204510175204, likelihoods = HashMap.fromList [("yearhour", -2.6026896854443837), ("hh:mmtime-of-day (latent)", -1.9095425048844386), ("minuteminute", -1.9095425048844386), ("yearyear", -2.6026896854443837), ("year (latent)year (latent)", -2.6026896854443837), ("minutehour", -1.9095425048844386), ("hh:mmintersect", -1.9095425048844386), ("year (latent)time-of-day (latent)", -2.6026896854443837)], n = 8}}), ("next <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("week", -1.6094379124341003), ("month (grain)", -2.3025850929940455), ("year (grain)", -2.3025850929940455), ("week (grain)", -1.6094379124341003), ("quarter", -2.3025850929940455), ("year", -2.3025850929940455), ("month", -2.3025850929940455), ("quarter (grain)", -2.3025850929940455)], n = 6}, koData = ClassData{prior = -infinity, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [], n = 0}}), ("number.number hours", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("from <time-of-day> - <time-of-day> (interval)", Classifier{okData = ClassData{prior = -0.45198512374305727, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -2.3025850929940455), ("minuteminute", -1.2039728043259361), ("time-of-day (latent)time-of-day (latent)", -2.3025850929940455), ("hh:mmhh:mm", -1.2039728043259361), ("hourhour", -2.3025850929940455), ("minutehour", -2.3025850929940455)], n = 7}, koData = ClassData{prior = -1.0116009116784799, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.0296194171811581), ("minutehour", -1.0296194171811581)], n = 4}}), ("yyyy-mm-dd", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("year (latent)", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("integer (numeric)", -0.15415067982725836), ("integer (0..19)", -1.9459101490553135)], n = 12}}), ("Sondag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("Mandag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("dd/mm/yyyy", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("yesterday", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<ordinal> quarter <year>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)quarter (grain)year", -1.252762968495368), ("quarteryear", -0.8472978603872037), ("ordinal (digits)quarter (grain)year", -1.252762968495368)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("after lunch", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("hh:mm:ss", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("Torsdag", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("", 0.0)], n = 19}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("quarter to|till|before <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("time-of-day (latent)", -1.0986122886681098), ("noon", -1.5040773967762742), ("hour", -0.8109302162163288)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("Lordag", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("nth <time> of <time>", Classifier{okData = ClassData{prior = -0.5596157879354228, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)TisdagOktober", -1.9924301646902063), ("daymonth", -0.8938178760220964), ("ordinals (first..twentieth,thirtieth,...)Onsdagintersect", -1.4816045409242156), ("ordinals (first..twentieth,thirtieth,...)Tisdagintersect", -1.9924301646902063)], n = 8}, koData = ClassData{prior = -0.8472978603872037, unseen = -2.9444389791664407, likelihoods = HashMap.fromList [("daymonth", -0.9444616088408514), ("ordinals (first..twentieth,thirtieth,...)OnsdagOktober", -1.2809338454620642), ("ordinals (first..twentieth,thirtieth,...)TisdagSeptember", -1.791759469228055)], n = 6}}), ("the <day-of-month> (non ordinal)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("April", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("week (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.295836866004329, likelihoods = HashMap.fromList [("", 0.0)], n = 25}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("now", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}}), ("this <part-of-day>", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("hour", -0.6931471805599453), ("morning", -0.6931471805599453)], n = 1}}), ("<day-of-month>(ordinal) <named-month>", Classifier{okData = ClassData{prior = -9.53101798043249e-2, unseen = -3.258096538021482, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)Mars", -1.6094379124341003), ("ordinal (digits)Februari", -2.120263536200091), ("month", -0.8209805520698302), ("ordinal (digits)Mars", -1.6094379124341003)], n = 10}, koData = ClassData{prior = -2.3978952727983707, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)April", -1.252762968495368), ("month", -1.252762968495368)], n = 1}}), ("numbers prefix with -, negative or minus", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -3.4339872044851463, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 29}}), ("in|during the <part-of-day>", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("hour", -0.6931471805599453), ("morning", -0.6931471805599453)], n = 1}}), ("new year's eve", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("tomorrow", Classifier{okData = ClassData{prior = 0.0, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("", 0.0)], n = 15}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("last <day-of-week>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("Tisdag", -0.6931471805599453), ("day", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("<time> after next", Classifier{okData = ClassData{prior = 0.0, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("day", -1.1786549963416462), ("Mars", -1.8718021769015913), ("month", -1.8718021769015913), ("Onsdag", -1.8718021769015913), ("Fredag", -1.466337068793427)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.791759469228055, likelihoods = HashMap.fromList [], n = 0}}), ("half an hour", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}}), ("the <day-of-month> (ordinal)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)", -0.916290731874155), ("ordinal (digits)", -0.5108256237659907)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("fractional number", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}}), ("afternoon", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<duration> from now", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("second", -1.2039728043259361), ("<integer> <unit-of-duration>", -1.2039728043259361), ("a <unit-of-duration>", -1.6094379124341003), ("minute", -1.6094379124341003)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("this <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("week", -1.3862943611198906), ("year (grain)", -1.8971199848858813), ("week (grain)", -1.3862943611198906), ("quarter", -2.3025850929940455), ("year", -1.8971199848858813), ("quarter (grain)", -2.3025850929940455)], n = 7}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("minute (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("Februari", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("about <time-of-day>", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 2}}), ("time-of-day (latent)", Classifier{okData = ClassData{prior = -0.6567795363890705, unseen = -3.8066624897703196, likelihoods = HashMap.fromList [("integer (numeric)", -4.652001563489282e-2), ("integer (0..19)", -3.0910424533583156)], n = 42}, koData = ClassData{prior = -0.7308875085427924, unseen = -3.7376696182833684, likelihoods = HashMap.fromList [("integer (numeric)", -0.10265415406008334), ("integer (0..19)", -2.327277705584417)], n = 39}}), ("year", Classifier{okData = ClassData{prior = -0.33024168687057687, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 23}, koData = ClassData{prior = -1.2685113254635072, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 9}}), ("last <day-of-week> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("daymonth", -0.916290731874155), ("Sondagintersect", -1.6094379124341003), ("SondagMars", -1.6094379124341003), ("MandagMars", -1.6094379124341003)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> <unit-of-duration>", Classifier{okData = ClassData{prior = -0.6231885919530349, unseen = -4.574710978503383, likelihoods = HashMap.fromList [("week", -2.6184380424125226), ("integer (0..19)year (grain)", -3.871201010907891), ("integer (numeric)day (grain)", -2.772588722239781), ("couple, a pairhour (grain)", -3.871201010907891), ("integer (0..19)hour (grain)", -3.871201010907891), ("second", -3.1780538303479458), ("integer (numeric)second (grain)", -3.871201010907891), ("integer (numeric)year (grain)", -3.871201010907891), ("day", -2.166452918669466), ("year", -3.4657359027997265), ("integer (numeric)week (grain)", -3.1780538303479458), ("integer (0..19)month (grain)", -3.871201010907891), ("integer (0..19)second (grain)", -3.4657359027997265), ("hour", -2.772588722239781), ("month", -3.4657359027997265), ("integer (numeric)minute (grain)", -2.772588722239781), ("integer (0..19)minute (grain)", -2.9549102790337356), ("integer (numeric)month (grain)", -3.871201010907891), ("minute", -2.2617630984737906), ("integer (numeric)hour (grain)", -3.1780538303479458), ("integer (0..19)day (grain)", -2.772588722239781), ("integer (0..19)week (grain)", -3.1780538303479458)], n = 37}, koData = ClassData{prior = -0.7683706017975328, unseen = -4.465908118654584, likelihoods = HashMap.fromList [("week", -2.662587827025453), ("integer (0..19)year (grain)", -3.355735007585398), ("integer (numeric)day (grain)", -3.068052935133617), ("integer (0..19)hour (grain)", -3.7612001156935624), ("second", -2.8449093838194073), ("integer (numeric)second (grain)", -3.355735007585398), ("integer (numeric)year (grain)", -3.068052935133617), ("day", -2.662587827025453), ("year", -2.662587827025453), ("integer (numeric)week (grain)", -3.355735007585398), ("integer (0..19)month (grain)", -3.068052935133617), ("integer (0..19)second (grain)", -3.355735007585398), ("hour", -2.8449093838194073), ("month", -2.662587827025453), ("integer (numeric)minute (grain)", -3.355735007585398), ("integer (0..19)minute (grain)", -3.355735007585398), ("integer (numeric)month (grain)", -3.355735007585398), ("minute", -2.8449093838194073), ("integer (numeric)hour (grain)", -3.068052935133617), ("integer (0..19)day (grain)", -3.355735007585398), ("integer (0..19)week (grain)", -3.068052935133617)], n = 32}}), ("relative minutes after|past <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("hour", -0.8109302162163288), ("integer (numeric)time-of-day (latent)", -1.0986122886681098), ("integer (20..90)time-of-day (latent)", -1.5040773967762742)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("Oktober", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("a <unit-of-duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("week", -2.0794415416798357), ("hour (grain)", -2.4849066497880004), ("second", -2.0794415416798357), ("week (grain)", -2.0794415416798357), ("day", -2.4849066497880004), ("minute (grain)", -2.4849066497880004), ("second (grain)", -2.0794415416798357), ("hour", -2.4849066497880004), ("minute", -2.4849066497880004), ("day (grain)", -2.4849066497880004)], n = 7}, koData = ClassData{prior = -infinity, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [], n = 0}}), ("intersect by \",\"", Classifier{okData = ClassData{prior = -0.1590646946296874, unseen = -4.51085950651685, likelihoods = HashMap.fromList [("at <time-of-day>Lordag", -3.8066624897703196), ("Lordag<day-of-month> (non ordinal) <named-month>", -3.8066624897703196), ("intersect by \",\"year", -3.8066624897703196), ("hh:mmintersect by \",\"", -3.8066624897703196), ("dayday", -2.1019143975318944), ("dayyear", -2.890371757896165), ("<named-month> <day-of-month> (non ordinal)intersect", -3.8066624897703196), ("Onsdag<named-month> <day-of-month> (non ordinal)", -3.8066624897703196), ("Fredagintersect by \",\"", -3.4011973816621555), ("intersect by \",\"<day-of-month> (non ordinal) <named-month>", -3.4011973816621555), ("hh:mmintersect", -3.8066624897703196), ("intersect by \",\"intersect", -3.8066624897703196), ("at <time-of-day>intersect", -3.8066624897703196), ("dayminute", -2.70805020110221), ("intersectyear", -3.8066624897703196), ("minuteday", -2.1019143975318944), ("<named-month> <day-of-month> (non ordinal)Fredag", -3.8066624897703196), ("Fredag<named-month> <day-of-month> (non ordinal)", -3.4011973816621555), ("hh:mmabsorption of , after named day", -3.8066624897703196), ("at <time-of-day>intersect by \",\"", -3.8066624897703196), ("at <time-of-day>absorption of , after named day", -3.8066624897703196), ("intersectintersect", -3.8066624897703196), ("Fredagintersect", -3.8066624897703196), ("Mandag<named-month> <day-of-month> (non ordinal)", -3.4011973816621555), ("Mandag<day-of-month> (non ordinal) <named-month>", -3.8066624897703196), ("Sondag<day-of-month> (non ordinal) <named-month>", -3.8066624897703196), ("<named-month> <day-of-month> (non ordinal)year", -3.4011973816621555), ("hh:mmLordag", -3.8066624897703196)], n = 29}, koData = ClassData{prior = -1.916922612182061, unseen = -3.7612001156935624, likelihoods = HashMap.fromList [("OnsdagFebruari", -3.044522437723423), ("daymonth", -1.9459101490553135), ("MandagFebruari", -2.639057329615259), ("FredagJuli", -2.639057329615259)], n = 5}}), ("hh:mm", Classifier{okData = ClassData{prior = -1.9418085857101627e-2, unseen = -3.970291913552122, likelihoods = HashMap.fromList [("", 0.0)], n = 51}, koData = ClassData{prior = -3.951243718581427, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("quarter after|past <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("second (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("ordinals (first..twentieth,thirtieth,...)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("", 0.0)], n = 19}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> sharp", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("at <time-of-day>", -1.2992829841302609), ("time-of-day (latent)", -1.2992829841302609), ("hour", -0.7884573603642702)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("Mars", Classifier{okData = ClassData{prior = 0.0, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("", 0.0)], n = 14}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect by \"of\", \"from\", \"'s\"", Classifier{okData = ClassData{prior = -0.8649974374866046, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("daymonth", -1.3862943611198906), ("OnsdagOktober", -2.2335922215070942), ("TisdagOktober", -2.2335922215070942), ("Onsdagintersect", -2.2335922215070942), ("Onsdagnext <cycle>", -2.639057329615259), ("Sondaglast <cycle>", -2.639057329615259), ("dayweek", -2.2335922215070942)], n = 8}, koData = ClassData{prior = -0.5465437063680699, unseen = -3.5553480614894135, likelihoods = HashMap.fromList [("daymonth", -1.041453874828161), ("OnsdagOktober", -2.4277482359480516), ("Sondagintersect", -2.833213344056216), ("TisdagSeptember", -2.4277482359480516), ("Tisdagintersect", -2.4277482359480516), ("Onsdagintersect", -2.4277482359480516), ("SondagMars", -2.833213344056216), ("MandagMars", -2.833213344056216)], n = 11}}), ("<duration> ago", Classifier{okData = ClassData{prior = 0.0, unseen = -3.4965075614664802, likelihoods = HashMap.fromList [("week", -1.6739764335716716), ("day", -1.8562979903656263), ("year", -2.367123614131617), ("<integer> <unit-of-duration>", -0.9007865453381898), ("a <unit-of-duration>", -2.772588722239781), ("month", -2.367123614131617)], n = 13}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("last <time>", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("Tisdag", -1.791759469228055), ("Sondag", -1.791759469228055), ("day", -1.3862943611198906), ("hour", -1.791759469228055), ("week-end", -1.791759469228055)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("Sondag", -1.6094379124341003), ("Mandag", -1.6094379124341003), ("day", -1.2039728043259361)], n = 2}}), ("<day-of-month> (ordinal)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)", -0.916290731874155), ("ordinal (digits)", -0.5108256237659907)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("the day after tomorrow", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("noon", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("until <time-of-day>", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -2.890371757896165, likelihoods = HashMap.fromList [("at <time-of-day>", -0.8873031950009028), ("hour", -0.8873031950009028)], n = 6}, koData = ClassData{prior = -1.3862943611198906, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("intersect", -1.5040773967762742), ("hh:mm", -1.5040773967762742), ("minute", -1.0986122886681098)], n = 2}}), ("Augusti", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> and an half hours", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("integer (numeric)", -0.6931471805599453), ("integer (0..19)", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("after <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("<integer> <unit-of-duration>", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("evening", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("decimal number", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("next <time>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("Tisdag", -2.0149030205422647), ("Mandag", -2.0149030205422647), ("day", -1.3217558399823195), ("Mars", -2.0149030205422647), ("month", -2.0149030205422647), ("Onsdag", -2.0149030205422647)], n = 4}, koData = ClassData{prior = -0.6931471805599453, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("day", -1.3217558399823195), ("Mars", -2.0149030205422647), ("month", -2.0149030205422647), ("Onsdag", -2.0149030205422647), ("Fredag", -1.6094379124341003)], n = 4}}), ("last <cycle>", Classifier{okData = ClassData{prior = -0.45198512374305727, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("week", -1.7047480922384253), ("month (grain)", -2.3978952727983707), ("year (grain)", -1.7047480922384253), ("week (grain)", -1.7047480922384253), ("year", -1.7047480922384253), ("month", -2.3978952727983707)], n = 7}, koData = ClassData{prior = -1.0116009116784799, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("week", -1.6739764335716716), ("week (grain)", -1.6739764335716716), ("day", -1.6739764335716716), ("day (grain)", -1.6739764335716716)], n = 4}}), ("Onsdag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("christmas", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("new year's day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("next n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.912023005428146, likelihoods = HashMap.fromList [("week", -2.793208009442517), ("integer (0..19)year (grain)", -3.1986731175506815), ("integer (numeric)day (grain)", -3.1986731175506815), ("integer (0..19)hour (grain)", -3.1986731175506815), ("second", -2.793208009442517), ("integer (numeric)second (grain)", -3.1986731175506815), ("integer (numeric)year (grain)", -3.1986731175506815), ("day", -2.793208009442517), ("year", -2.793208009442517), ("integer (numeric)week (grain)", -3.1986731175506815), ("integer (0..19)month (grain)", -3.1986731175506815), ("integer (0..19)second (grain)", -3.1986731175506815), ("hour", -2.793208009442517), ("month", -2.793208009442517), ("integer (numeric)minute (grain)", -3.1986731175506815), ("integer (0..19)minute (grain)", -3.1986731175506815), ("integer (numeric)month (grain)", -3.1986731175506815), ("minute", -2.793208009442517), ("integer (numeric)hour (grain)", -3.1986731175506815), ("integer (0..19)day (grain)", -3.1986731175506815), ("integer (0..19)week (grain)", -3.1986731175506815)], n = 14}, koData = ClassData{prior = -infinity, unseen = -3.0910424533583156, likelihoods = HashMap.fromList [], n = 0}}), ("Fredag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("", 0.0)], n = 8}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("in <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -4.3694478524670215, likelihoods = HashMap.fromList [("week", -3.258096538021482), ("<integer> more <unit-of-duration>", -3.258096538021482), ("number.number hours", -3.6635616461296463), ("second", -2.9704144655697013), ("day", -2.5649493574615367), ("half an hour", -3.6635616461296463), ("<integer> <unit-of-duration>", -1.3121863889661687), ("a <unit-of-duration>", -2.5649493574615367), ("<integer> and an half hours", -3.258096538021482), ("hour", -2.4107986776342782), ("minute", -1.466337068793427), ("about <duration>", -3.258096538021482)], n = 33}, koData = ClassData{prior = -infinity, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [], n = 0}}), ("<datetime> - <datetime> (interval)", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -3.6109179126442243, likelihoods = HashMap.fromList [("minuteminute", -1.3862943611198906), ("hh:mmhh:mm", -1.3862943611198906), ("dayday", -1.791759469228055), ("<day-of-month> (non ordinal) <named-month><day-of-month> (non ordinal) <named-month>", -1.791759469228055)], n = 13}, koData = ClassData{prior = -0.6931471805599453, unseen = -3.6109179126442243, likelihoods = HashMap.fromList [("Juli<day-of-month> (non ordinal) <named-month>", -2.890371757896165), ("monthday", -1.791759469228055), ("minuteminute", -1.6376087894007967), ("hh:mmhh:mm", -2.890371757896165), ("dayyear", -2.4849066497880004), ("Augusti<day-of-month> (non ordinal) <named-month>", -1.9740810260220096), ("hh:mmintersect", -1.791759469228055), ("dd/mmyear", -2.4849066497880004)], n = 13}}), ("<time-of-day> - <time-of-day> (interval)", Classifier{okData = ClassData{prior = -0.587786664902119, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -2.0794415416798357), ("minuteminute", -0.9808292530117262), ("hh:mmhh:mm", -0.9808292530117262), ("minutehour", -2.0794415416798357)], n = 10}, koData = ClassData{prior = -0.8109302162163288, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -0.916290731874155), ("minuteminute", -2.3025850929940455), ("hh:mmhh:mm", -2.3025850929940455), ("minutehour", -0.916290731874155)], n = 8}}), ("last n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -4.007333185232471, likelihoods = HashMap.fromList [("week", -2.6026896854443837), ("integer (0..19)year (grain)", -3.295836866004329), ("integer (numeric)day (grain)", -2.890371757896165), ("second", -2.890371757896165), ("integer (numeric)second (grain)", -3.295836866004329), ("integer (numeric)year (grain)", -2.890371757896165), ("day", -2.6026896854443837), ("year", -2.6026896854443837), ("integer (numeric)week (grain)", -3.295836866004329), ("integer (0..19)month (grain)", -2.890371757896165), ("integer (0..19)second (grain)", -3.295836866004329), ("hour", -3.295836866004329), ("month", -2.6026896854443837), ("integer (numeric)minute (grain)", -3.295836866004329), ("integer (0..19)minute (grain)", -3.295836866004329), ("integer (numeric)month (grain)", -3.295836866004329), ("minute", -2.890371757896165), ("integer (numeric)hour (grain)", -3.295836866004329), ("integer (0..19)day (grain)", -3.295836866004329), ("integer (0..19)week (grain)", -2.890371757896165)], n = 17}, koData = ClassData{prior = -infinity, unseen = -3.044522437723423, likelihoods = HashMap.fromList [], n = 0}}), ("<named-month> <day-of-month> (non ordinal)", Classifier{okData = ClassData{prior = -0.10536051565782628, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("Aprilinteger (numeric)", -2.3978952727983707), ("Februariinteger (numeric)", -1.2992829841302609), ("month", -0.7884573603642702), ("Juliinteger (numeric)", -1.7047480922384253)], n = 9}, koData = ClassData{prior = -2.3025850929940455, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("Aprilinteger (numeric)", -1.0986122886681098), ("month", -1.0986122886681098)], n = 1}}), ("<day-of-month> (non ordinal) <named-month>", Classifier{okData = ClassData{prior = -0.1466034741918754, unseen = -3.828641396489095, likelihoods = HashMap.fromList [("integer (numeric)September", -3.1135153092103742), ("integer (numeric)Augusti", -1.5040773967762742), ("integer (numeric)April", -3.1135153092103742), ("month", -0.8109302162163288), ("integer (numeric)Februari", -2.1972245773362196), ("integer (numeric)Juli", -2.70805020110221), ("integer (numeric)Mars", -2.70805020110221)], n = 19}, koData = ClassData{prior = -1.9924301646902063, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("month", -1.1786549963416462), ("integer (numeric)Juli", -1.1786549963416462)], n = 3}}), ("this|next <day-of-week>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("Tisdag", -1.7047480922384253), ("Mandag", -1.7047480922384253), ("day", -1.0116009116784799), ("Onsdag", -1.7047480922384253)], n = 3}, koData = ClassData{prior = -0.6931471805599453, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("day", -1.0116009116784799), ("Onsdag", -1.7047480922384253), ("Fredag", -1.2992829841302609)], n = 3}}), ("ordinal (digits)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("", 0.0)], n = 10}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("quarter (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("last <cycle> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("daymonth", -1.4816045409242156), ("day (grain)intersect", -1.9924301646902063), ("weekmonth", -1.4816045409242156), ("day (grain)Oktober", -1.9924301646902063), ("week (grain)intersect", -1.9924301646902063), ("week (grain)September", -1.9924301646902063)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("<day-of-month>(ordinal) <named-month> year", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)April", -1.6094379124341003), ("ordinals (first..twentieth,thirtieth,...)Mars", -1.6094379124341003), ("month", -0.916290731874155), ("ordinal (digits)Mars", -1.6094379124341003)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("morning", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("week-end", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("after <time-of-day>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -3.332204510175204, likelihoods = HashMap.fromList [("at <time-of-day>", -1.6863989535702288), ("intersect", -2.1972245773362196), ("tomorrow", -2.1972245773362196), ("day", -2.1972245773362196), ("hour", -1.349926716949016)], n = 8}, koData = ClassData{prior = -0.6931471805599453, unseen = -3.332204510175204, likelihoods = HashMap.fromList [("lunch", -2.6026896854443837), ("year (latent)", -1.9095425048844386), ("time-of-day (latent)", -1.9095425048844386), ("year", -1.9095425048844386), ("hh:mm", -2.6026896854443837), ("hour", -1.6863989535702288), ("minute", -2.6026896854443837)], n = 8}}), ("day (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("", 0.0)], n = 19}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<month> dd-dd (interval)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("Juli", -0.6931471805599453), ("month", -0.6931471805599453)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("about <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("half an hour", -0.6931471805599453), ("minute", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("this <time>", Classifier{okData = ClassData{prior = -1.0608719606852628, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("sommar", -2.2335922215070942), ("vinter", -2.2335922215070942), ("day", -1.7227665977411035), ("Oktober", -2.2335922215070942), ("hour", -1.9459101490553135), ("month", -2.2335922215070942), ("week-end", -1.9459101490553135)], n = 9}, koData = ClassData{prior = -0.42488319396526597, unseen = -3.8066624897703196, likelihoods = HashMap.fromList [("Tisdag", -3.0910424533583156), ("September", -2.174751721484161), ("day", -3.0910424533583156), ("Oktober", -1.3862943611198906), ("Mars", -2.6855773452501515), ("month", -0.9509762898620451)], n = 17}}), ("within <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("week", -0.6931471805599453), ("<integer> <unit-of-duration>", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}})]
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Ranking/Classifiers/SV_XX.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant --------------------------------------------------------------- Auto-generated by regenClassifiers DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING --------------------------------------------------------------- # LANGUAGE OverloadedStrings #
Copyright ( c ) 2016 - present , Facebook , Inc. of patent rights can be found in the PATENTS file in the same directory . @generated module Duckling.Ranking.Classifiers.SV_XX (classifiers) where import Data.String import Prelude import qualified Data.HashMap.Strict as HashMap import Duckling.Ranking.Types classifiers :: Classifiers classifiers = HashMap.fromList [("<time> timezone", Classifier{okData = ClassData{prior = 0.0, unseen = -3.4339872044851463, likelihoods = HashMap.fromList [("at <time-of-day>", -1.3217558399823195), ("hh:mm", -1.455287232606842), ("hour", -2.0149030205422647), ("minute", -1.0033021088637848)], n = 13}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("integer (numeric)", Classifier{okData = ClassData{prior = -0.8176416508043156, unseen = -4.897839799950911, likelihoods = HashMap.fromList [("", 0.0)], n = 132}, koData = ClassData{prior = -0.5824497609739314, unseen = -5.1298987149230735, likelihoods = HashMap.fromList [("", 0.0)], n = 167}}), ("the day before yesterday", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("lunch", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("Tisdag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("integer (20..90)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time> <part-of-day>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("dayhour", -0.9555114450274363), ("tomorrowevening", -1.8718021769015913), ("tomorrowlunch", -1.8718021769015913), ("yesterdayevening", -1.8718021769015913), ("Mandagmorning", -1.8718021769015913)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.791759469228055, likelihoods = HashMap.fromList [], n = 0}}), ("couple, a pair", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("dd/mm", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -0.916290731874155, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}}), ("sommar", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("today", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("at <time-of-day>", Classifier{okData = ClassData{prior = -0.3014753945841168, unseen = -4.7535901911063645, likelihoods = HashMap.fromList [("<time> timezone", -3.1354942159291497), ("time-of-day (latent)", -1.3437347467010947), ("relative minutes after|past <integer> (hour-of-day)", -3.6463198396951406), ("hh:mm", -1.8545603704670852), ("<time-of-day> sharp", -3.6463198396951406), ("hour", -1.2791962255635234), ("minute", -1.5668782980153044)], n = 54}, koData = ClassData{prior = -1.3460204619819507, unseen = -3.828641396489095, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.8109302162163288), ("hour", -0.8109302162163288)], n = 19}}), ("absorption of , after named day", Classifier{okData = ClassData{prior = 0.0, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("Sondag", -2.3978952727983707), ("Mandag", -1.7047480922384253), ("Lordag", -2.3978952727983707), ("day", -0.8938178760220964), ("Onsdag", -2.3978952727983707), ("Fredag", -1.9924301646902063)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("September", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("tonight", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("on <date>", Classifier{okData = ClassData{prior = -0.48285177172358457, unseen = -4.304065093204169, likelihoods = HashMap.fromList [("on <date>", -3.597312260588446), ("Mandag", -3.597312260588446), ("Torsdag", -2.211017899468555), ("Lordag", -3.597312260588446), ("the <day-of-month> (non ordinal)", -3.1918471524802814), ("<day-of-month>(ordinal) <named-month>", -2.344549292093078), ("day", -0.9231636111619171), ("the <day-of-month> (ordinal)", -3.597312260588446), ("afternoon", -3.597312260588446), ("<day-of-month> (ordinal)", -2.093234863812172), ("hour", -3.597312260588446), ("<day-of-month> (non ordinal) <named-month>", -3.597312260588446)], n = 29}, koData = ClassData{prior = -0.9597758438138939, unseen = -3.951243718581427, likelihoods = HashMap.fromList [("on <date>", -2.322387720290225), ("year (latent)", -1.8523840910444898), ("time-of-day (latent)", -1.8523840910444898), ("year", -1.62924053973028), ("hour", -1.62924053973028)], n = 18}}), ("integer (0..19)", Classifier{okData = ClassData{prior = -0.16251892949777494, unseen = -3.58351893845611, likelihoods = HashMap.fromList [("", 0.0)], n = 34}, koData = ClassData{prior = -1.8971199848858813, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}}), ("between <time-of-day> and <time-of-day> (interval)", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.6094379124341003), ("minuteminute", -1.2039728043259361), ("hh:mmhh:mm", -1.2039728043259361), ("minutehour", -1.6094379124341003)], n = 3}, koData = ClassData{prior = -1.3862943611198906, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.0986122886681098), ("minutehour", -1.0986122886681098)], n = 1}}), ("between <datetime> and <datetime> (interval)", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.7047480922384253), ("minuteminute", -1.2992829841302609), ("hh:mmhh:mm", -1.2992829841302609), ("minutehour", -1.7047480922384253)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.5040773967762742), ("minuteminute", -1.5040773967762742), ("minutehour", -1.5040773967762742), ("hh:mmintersect", -1.5040773967762742)], n = 2}}), ("month (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> more <unit-of-duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("integer (numeric)minute (grain)", -1.252762968495368), ("integer (0..19)minute (grain)", -1.252762968495368), ("minute", -0.8472978603872037)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> o'clock", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("vinter", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("Juli", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("", 0.0)], n = 8}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("hour (grain)", Classifier{okData = ClassData{prior = -0.11778303565638351, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("", 0.0)], n = 8}, koData = ClassData{prior = -2.1972245773362196, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("<ordinal> quarter", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("ordinal (digits)quarter (grain)", -1.252762968495368), ("ordinals (first..twentieth,thirtieth,...)quarter (grain)", -1.252762968495368), ("quarter", -0.8472978603872037)], n = 2}, koData = ClassData{prior = -0.6931471805599453, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("ordinal (digits)quarter (grain)", -1.252762968495368), ("ordinals (first..twentieth,thirtieth,...)quarter (grain)", -1.252762968495368), ("quarter", -0.8472978603872037)], n = 2}}), ("Last year", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect", Classifier{okData = ClassData{prior = -0.35003530316883363, unseen = -5.860786223465865, likelihoods = HashMap.fromList [("Onsdagthis <cycle>", -5.1647859739235145), ("Torsdag<time> timezone", -3.912023005428146), ("<datetime> - <datetime> (interval)on <date>", -4.0661736852554045), ("<time-of-day> - <time-of-day> (interval)on <date>", -4.0661736852554045), ("hourday", -5.1647859739235145), ("dayhour", -2.9134941753170187), ("daymonth", -3.1498829533812494), ("monthyear", -3.1498829533812494), ("Torsdagbetween <time-of-day> and <time-of-day> (interval)", -4.75932086581535), ("Mandagon <date>", -5.1647859739235145), ("yyyy-mm-ddat <time-of-day>", -4.471638793363569), ("intersecthh:mm", -5.1647859739235145), ("Torsdagbetween <datetime> and <datetime> (interval)", -4.75932086581535), ("Torsdagat <time-of-day>", -4.248495242049359), ("Marsyear", -5.1647859739235145), ("intersect by \"of\", \"from\", \"'s\"year", -4.75932086581535), ("Oktoberyear", -3.5553480614894135), ("Torsdagfrom <time-of-day> - <time-of-day> (interval)", -4.471638793363569), ("Torsdagfrom <datetime> - <datetime> (interval)", -4.471638793363569), ("last <day-of-week> of <time>year", -5.1647859739235145), ("todayat <time-of-day>", -4.75932086581535), ("the <day-of-month> (ordinal)Februari", -5.1647859739235145), ("dayday", -3.2929837970219227), ("dd/mmat <time-of-day>", -4.248495242049359), ("intersect by \",\"hh:mm", -4.248495242049359), ("dayyear", -3.5553480614894135), ("tomorrow<time-of-day> sharp", -4.75932086581535), ("<day-of-month>(ordinal) <named-month>year", -4.75932086581535), ("Onsdag<named-month> <day-of-month> (non ordinal)", -5.1647859739235145), ("absorption of , after named day<named-month> <day-of-month> (non ordinal)", -4.0661736852554045), ("tomorrowuntil <time-of-day>", -4.75932086581535), ("absorption of , after named day<day-of-month> (non ordinal) <named-month>", -4.471638793363569), ("after <time-of-day>at <time-of-day>", -4.75932086581535), ("the <day-of-month> (ordinal)Mars", -4.0661736852554045), ("intersect by \",\"<day-of-month> (non ordinal) <named-month>", -4.75932086581535), ("Mandagthis <cycle>", -5.1647859739235145), ("tomorrowafter <time-of-day>", -4.75932086581535), ("from <time-of-day> - <time-of-day> (interval)on <date>", -4.248495242049359), ("dayminute", -2.361425593016979), ("from <datetime> - <datetime> (interval)on <date>", -4.471638793363569), ("on <date>Mars", -4.0661736852554045), ("<ordinal> <cycle> of <time>year", -4.75932086581535), ("minuteday", -2.5620962884791303), ("absorption of , after named dayintersect", -5.1647859739235145), ("yearhh:mm", -5.1647859739235145), ("Tisdagthis <time>", -4.75932086581535), ("Onsdagnext <cycle>", -5.1647859739235145), ("absorption of , after named dayintersect by \",\"", -4.75932086581535), ("Sondaglast <cycle>", -5.1647859739235145), ("Septemberyear", -4.248495242049359), ("at <time-of-day>on <date>", -5.1647859739235145), ("between <time-of-day> and <time-of-day> (interval)on <date>", -5.1647859739235145), ("between <datetime> and <datetime> (interval)on <date>", -5.1647859739235145), ("dayweek", -4.0661736852554045), ("Tisdagthis <cycle>", -5.1647859739235145), ("on <date>Februari", -5.1647859739235145), ("weekyear", -4.248495242049359), ("hh:mmtomorrow", -4.471638793363569), ("tomorrowat <time-of-day>", -3.912023005428146), ("at <time-of-day>tomorrow", -4.75932086581535), ("Sondag<day-of-month> (non ordinal) <named-month>", -5.1647859739235145), ("last <cycle> of <time>year", -4.248495242049359), ("<day-of-month> (non ordinal) <named-month>year", -4.75932086581535), ("yearminute", -5.1647859739235145)], n = 136}, koData = ClassData{prior = -1.2196389210703353, unseen = -5.262690188904886, likelihoods = HashMap.fromList [("OnsdagFebruari", -4.564348191467836), ("dayhour", -2.6184380424125226), ("daymonth", -2.4242820279715653), ("monthyear", -3.648057459593681), ("Mandagon <date>", -4.1588830833596715), ("yyyy-mm-ddat <time-of-day>", -3.871201010907891), ("Torsdagat <time-of-day>", -3.0602707946915624), ("Marsyear", -3.871201010907891), ("intersect by \"of\", \"from\", \"'s\"year", -3.4657359027997265), ("Torsdagfrom <datetime> - <datetime> (interval)", -4.564348191467836), ("Mandagintersect", -4.1588830833596715), ("absorption of , after named dayJuli", -4.1588830833596715), ("hourmonth", -4.1588830833596715), ("dd/mmat <time-of-day>", -3.648057459593681), ("dayyear", -3.1780538303479458), ("Onsdagthis <time>", -3.648057459593681), ("Aprilyear", -4.564348191467836), ("yearmonth", -4.564348191467836), ("until <time-of-day>on <date>", -4.564348191467836), ("Torsdaghh:mm", -4.1588830833596715), ("dayminute", -3.311585222972468), ("minuteday", -3.0602707946915624), ("Tisdagthis <time>", -4.1588830833596715), ("hh:mmon <date>", -3.1780538303479458), ("on <date>Februari", -4.1588830833596715), ("absorption of , after named dayFebruari", -3.871201010907891), ("intersectFebruari", -4.1588830833596715), ("Mandagthis <time>", -4.564348191467836), ("Sondagthis <time>", -4.564348191467836)], n = 57}}), ("<ordinal> <cycle> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.890371757896165, likelihoods = HashMap.fromList [("daymonth", -1.7346010553881064), ("ordinals (first..twentieth,thirtieth,...)week (grain)Oktober", -1.7346010553881064), ("ordinals (first..twentieth,thirtieth,...)week (grain)intersect", -1.7346010553881064), ("weekmonth", -1.2237754316221157), ("ordinals (first..twentieth,thirtieth,...)day (grain)Oktober", -1.7346010553881064)], n = 6}, koData = ClassData{prior = -infinity, unseen = -1.791759469228055, likelihoods = HashMap.fromList [], n = 0}}), ("year (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("from <datetime> - <datetime> (interval)", Classifier{okData = ClassData{prior = -0.8472978603872037, unseen = -3.1780538303479458, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -2.4423470353692043), ("minuteminute", -1.5260563034950494), ("time-of-day (latent)time-of-day (latent)", -2.4423470353692043), ("hh:mmhh:mm", -1.5260563034950494), ("hourhour", -2.4423470353692043), ("minutehour", -2.4423470353692043)], n = 6}, koData = ClassData{prior = -0.5596157879354228, unseen = -3.332204510175204, likelihoods = HashMap.fromList [("yearhour", -2.6026896854443837), ("hh:mmtime-of-day (latent)", -1.9095425048844386), ("minuteminute", -1.9095425048844386), ("yearyear", -2.6026896854443837), ("year (latent)year (latent)", -2.6026896854443837), ("minutehour", -1.9095425048844386), ("hh:mmintersect", -1.9095425048844386), ("year (latent)time-of-day (latent)", -2.6026896854443837)], n = 8}}), ("next <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("week", -1.6094379124341003), ("month (grain)", -2.3025850929940455), ("year (grain)", -2.3025850929940455), ("week (grain)", -1.6094379124341003), ("quarter", -2.3025850929940455), ("year", -2.3025850929940455), ("month", -2.3025850929940455), ("quarter (grain)", -2.3025850929940455)], n = 6}, koData = ClassData{prior = -infinity, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [], n = 0}}), ("number.number hours", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("from <time-of-day> - <time-of-day> (interval)", Classifier{okData = ClassData{prior = -0.45198512374305727, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -2.3025850929940455), ("minuteminute", -1.2039728043259361), ("time-of-day (latent)time-of-day (latent)", -2.3025850929940455), ("hh:mmhh:mm", -1.2039728043259361), ("hourhour", -2.3025850929940455), ("minutehour", -2.3025850929940455)], n = 7}, koData = ClassData{prior = -1.0116009116784799, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -1.0296194171811581), ("minutehour", -1.0296194171811581)], n = 4}}), ("yyyy-mm-dd", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("year (latent)", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("integer (numeric)", -0.15415067982725836), ("integer (0..19)", -1.9459101490553135)], n = 12}}), ("Sondag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("Mandag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("dd/mm/yyyy", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("yesterday", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<ordinal> quarter <year>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)quarter (grain)year", -1.252762968495368), ("quarteryear", -0.8472978603872037), ("ordinal (digits)quarter (grain)year", -1.252762968495368)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("after lunch", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("hh:mm:ss", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("Torsdag", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("", 0.0)], n = 19}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("quarter to|till|before <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("time-of-day (latent)", -1.0986122886681098), ("noon", -1.5040773967762742), ("hour", -0.8109302162163288)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("Lordag", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("nth <time> of <time>", Classifier{okData = ClassData{prior = -0.5596157879354228, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)TisdagOktober", -1.9924301646902063), ("daymonth", -0.8938178760220964), ("ordinals (first..twentieth,thirtieth,...)Onsdagintersect", -1.4816045409242156), ("ordinals (first..twentieth,thirtieth,...)Tisdagintersect", -1.9924301646902063)], n = 8}, koData = ClassData{prior = -0.8472978603872037, unseen = -2.9444389791664407, likelihoods = HashMap.fromList [("daymonth", -0.9444616088408514), ("ordinals (first..twentieth,thirtieth,...)OnsdagOktober", -1.2809338454620642), ("ordinals (first..twentieth,thirtieth,...)TisdagSeptember", -1.791759469228055)], n = 6}}), ("the <day-of-month> (non ordinal)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("April", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("week (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.295836866004329, likelihoods = HashMap.fromList [("", 0.0)], n = 25}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("now", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}}), ("this <part-of-day>", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("hour", -0.6931471805599453), ("morning", -0.6931471805599453)], n = 1}}), ("<day-of-month>(ordinal) <named-month>", Classifier{okData = ClassData{prior = -9.53101798043249e-2, unseen = -3.258096538021482, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)Mars", -1.6094379124341003), ("ordinal (digits)Februari", -2.120263536200091), ("month", -0.8209805520698302), ("ordinal (digits)Mars", -1.6094379124341003)], n = 10}, koData = ClassData{prior = -2.3978952727983707, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)April", -1.252762968495368), ("month", -1.252762968495368)], n = 1}}), ("numbers prefix with -, negative or minus", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -3.4339872044851463, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 29}}), ("in|during the <part-of-day>", Classifier{okData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("hour", -0.6931471805599453), ("morning", -0.6931471805599453)], n = 1}}), ("new year's eve", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("tomorrow", Classifier{okData = ClassData{prior = 0.0, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("", 0.0)], n = 15}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("last <day-of-week>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("Tisdag", -0.6931471805599453), ("day", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("<time> after next", Classifier{okData = ClassData{prior = 0.0, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("day", -1.1786549963416462), ("Mars", -1.8718021769015913), ("month", -1.8718021769015913), ("Onsdag", -1.8718021769015913), ("Fredag", -1.466337068793427)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.791759469228055, likelihoods = HashMap.fromList [], n = 0}}), ("half an hour", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}}), ("the <day-of-month> (ordinal)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)", -0.916290731874155), ("ordinal (digits)", -0.5108256237659907)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("fractional number", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}}), ("afternoon", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<duration> from now", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("second", -1.2039728043259361), ("<integer> <unit-of-duration>", -1.2039728043259361), ("a <unit-of-duration>", -1.6094379124341003), ("minute", -1.6094379124341003)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("this <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("week", -1.3862943611198906), ("year (grain)", -1.8971199848858813), ("week (grain)", -1.3862943611198906), ("quarter", -2.3025850929940455), ("year", -1.8971199848858813), ("quarter (grain)", -2.3025850929940455)], n = 7}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("minute (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("Februari", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("about <time-of-day>", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 2}}), ("time-of-day (latent)", Classifier{okData = ClassData{prior = -0.6567795363890705, unseen = -3.8066624897703196, likelihoods = HashMap.fromList [("integer (numeric)", -4.652001563489282e-2), ("integer (0..19)", -3.0910424533583156)], n = 42}, koData = ClassData{prior = -0.7308875085427924, unseen = -3.7376696182833684, likelihoods = HashMap.fromList [("integer (numeric)", -0.10265415406008334), ("integer (0..19)", -2.327277705584417)], n = 39}}), ("year", Classifier{okData = ClassData{prior = -0.33024168687057687, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 23}, koData = ClassData{prior = -1.2685113254635072, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 9}}), ("last <day-of-week> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("daymonth", -0.916290731874155), ("Sondagintersect", -1.6094379124341003), ("SondagMars", -1.6094379124341003), ("MandagMars", -1.6094379124341003)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> <unit-of-duration>", Classifier{okData = ClassData{prior = -0.6231885919530349, unseen = -4.574710978503383, likelihoods = HashMap.fromList [("week", -2.6184380424125226), ("integer (0..19)year (grain)", -3.871201010907891), ("integer (numeric)day (grain)", -2.772588722239781), ("couple, a pairhour (grain)", -3.871201010907891), ("integer (0..19)hour (grain)", -3.871201010907891), ("second", -3.1780538303479458), ("integer (numeric)second (grain)", -3.871201010907891), ("integer (numeric)year (grain)", -3.871201010907891), ("day", -2.166452918669466), ("year", -3.4657359027997265), ("integer (numeric)week (grain)", -3.1780538303479458), ("integer (0..19)month (grain)", -3.871201010907891), ("integer (0..19)second (grain)", -3.4657359027997265), ("hour", -2.772588722239781), ("month", -3.4657359027997265), ("integer (numeric)minute (grain)", -2.772588722239781), ("integer (0..19)minute (grain)", -2.9549102790337356), ("integer (numeric)month (grain)", -3.871201010907891), ("minute", -2.2617630984737906), ("integer (numeric)hour (grain)", -3.1780538303479458), ("integer (0..19)day (grain)", -2.772588722239781), ("integer (0..19)week (grain)", -3.1780538303479458)], n = 37}, koData = ClassData{prior = -0.7683706017975328, unseen = -4.465908118654584, likelihoods = HashMap.fromList [("week", -2.662587827025453), ("integer (0..19)year (grain)", -3.355735007585398), ("integer (numeric)day (grain)", -3.068052935133617), ("integer (0..19)hour (grain)", -3.7612001156935624), ("second", -2.8449093838194073), ("integer (numeric)second (grain)", -3.355735007585398), ("integer (numeric)year (grain)", -3.068052935133617), ("day", -2.662587827025453), ("year", -2.662587827025453), ("integer (numeric)week (grain)", -3.355735007585398), ("integer (0..19)month (grain)", -3.068052935133617), ("integer (0..19)second (grain)", -3.355735007585398), ("hour", -2.8449093838194073), ("month", -2.662587827025453), ("integer (numeric)minute (grain)", -3.355735007585398), ("integer (0..19)minute (grain)", -3.355735007585398), ("integer (numeric)month (grain)", -3.355735007585398), ("minute", -2.8449093838194073), ("integer (numeric)hour (grain)", -3.068052935133617), ("integer (0..19)day (grain)", -3.355735007585398), ("integer (0..19)week (grain)", -3.068052935133617)], n = 32}}), ("relative minutes after|past <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("hour", -0.8109302162163288), ("integer (numeric)time-of-day (latent)", -1.0986122886681098), ("integer (20..90)time-of-day (latent)", -1.5040773967762742)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("Oktober", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("a <unit-of-duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("week", -2.0794415416798357), ("hour (grain)", -2.4849066497880004), ("second", -2.0794415416798357), ("week (grain)", -2.0794415416798357), ("day", -2.4849066497880004), ("minute (grain)", -2.4849066497880004), ("second (grain)", -2.0794415416798357), ("hour", -2.4849066497880004), ("minute", -2.4849066497880004), ("day (grain)", -2.4849066497880004)], n = 7}, koData = ClassData{prior = -infinity, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [], n = 0}}), ("intersect by \",\"", Classifier{okData = ClassData{prior = -0.1590646946296874, unseen = -4.51085950651685, likelihoods = HashMap.fromList [("at <time-of-day>Lordag", -3.8066624897703196), ("Lordag<day-of-month> (non ordinal) <named-month>", -3.8066624897703196), ("intersect by \",\"year", -3.8066624897703196), ("hh:mmintersect by \",\"", -3.8066624897703196), ("dayday", -2.1019143975318944), ("dayyear", -2.890371757896165), ("<named-month> <day-of-month> (non ordinal)intersect", -3.8066624897703196), ("Onsdag<named-month> <day-of-month> (non ordinal)", -3.8066624897703196), ("Fredagintersect by \",\"", -3.4011973816621555), ("intersect by \",\"<day-of-month> (non ordinal) <named-month>", -3.4011973816621555), ("hh:mmintersect", -3.8066624897703196), ("intersect by \",\"intersect", -3.8066624897703196), ("at <time-of-day>intersect", -3.8066624897703196), ("dayminute", -2.70805020110221), ("intersectyear", -3.8066624897703196), ("minuteday", -2.1019143975318944), ("<named-month> <day-of-month> (non ordinal)Fredag", -3.8066624897703196), ("Fredag<named-month> <day-of-month> (non ordinal)", -3.4011973816621555), ("hh:mmabsorption of , after named day", -3.8066624897703196), ("at <time-of-day>intersect by \",\"", -3.8066624897703196), ("at <time-of-day>absorption of , after named day", -3.8066624897703196), ("intersectintersect", -3.8066624897703196), ("Fredagintersect", -3.8066624897703196), ("Mandag<named-month> <day-of-month> (non ordinal)", -3.4011973816621555), ("Mandag<day-of-month> (non ordinal) <named-month>", -3.8066624897703196), ("Sondag<day-of-month> (non ordinal) <named-month>", -3.8066624897703196), ("<named-month> <day-of-month> (non ordinal)year", -3.4011973816621555), ("hh:mmLordag", -3.8066624897703196)], n = 29}, koData = ClassData{prior = -1.916922612182061, unseen = -3.7612001156935624, likelihoods = HashMap.fromList [("OnsdagFebruari", -3.044522437723423), ("daymonth", -1.9459101490553135), ("MandagFebruari", -2.639057329615259), ("FredagJuli", -2.639057329615259)], n = 5}}), ("hh:mm", Classifier{okData = ClassData{prior = -1.9418085857101627e-2, unseen = -3.970291913552122, likelihoods = HashMap.fromList [("", 0.0)], n = 51}, koData = ClassData{prior = -3.951243718581427, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("quarter after|past <integer> (hour-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("time-of-day (latent)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("second (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("ordinals (first..twentieth,thirtieth,...)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("", 0.0)], n = 19}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> sharp", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("at <time-of-day>", -1.2992829841302609), ("time-of-day (latent)", -1.2992829841302609), ("hour", -0.7884573603642702)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("Mars", Classifier{okData = ClassData{prior = 0.0, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("", 0.0)], n = 14}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect by \"of\", \"from\", \"'s\"", Classifier{okData = ClassData{prior = -0.8649974374866046, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("daymonth", -1.3862943611198906), ("OnsdagOktober", -2.2335922215070942), ("TisdagOktober", -2.2335922215070942), ("Onsdagintersect", -2.2335922215070942), ("Onsdagnext <cycle>", -2.639057329615259), ("Sondaglast <cycle>", -2.639057329615259), ("dayweek", -2.2335922215070942)], n = 8}, koData = ClassData{prior = -0.5465437063680699, unseen = -3.5553480614894135, likelihoods = HashMap.fromList [("daymonth", -1.041453874828161), ("OnsdagOktober", -2.4277482359480516), ("Sondagintersect", -2.833213344056216), ("TisdagSeptember", -2.4277482359480516), ("Tisdagintersect", -2.4277482359480516), ("Onsdagintersect", -2.4277482359480516), ("SondagMars", -2.833213344056216), ("MandagMars", -2.833213344056216)], n = 11}}), ("<duration> ago", Classifier{okData = ClassData{prior = 0.0, unseen = -3.4965075614664802, likelihoods = HashMap.fromList [("week", -1.6739764335716716), ("day", -1.8562979903656263), ("year", -2.367123614131617), ("<integer> <unit-of-duration>", -0.9007865453381898), ("a <unit-of-duration>", -2.772588722239781), ("month", -2.367123614131617)], n = 13}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("last <time>", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("Tisdag", -1.791759469228055), ("Sondag", -1.791759469228055), ("day", -1.3862943611198906), ("hour", -1.791759469228055), ("week-end", -1.791759469228055)], n = 3}, koData = ClassData{prior = -0.916290731874155, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("Sondag", -1.6094379124341003), ("Mandag", -1.6094379124341003), ("day", -1.2039728043259361)], n = 2}}), ("<day-of-month> (ordinal)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)", -0.916290731874155), ("ordinal (digits)", -0.5108256237659907)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("the day after tomorrow", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("noon", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("until <time-of-day>", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -2.890371757896165, likelihoods = HashMap.fromList [("at <time-of-day>", -0.8873031950009028), ("hour", -0.8873031950009028)], n = 6}, koData = ClassData{prior = -1.3862943611198906, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("intersect", -1.5040773967762742), ("hh:mm", -1.5040773967762742), ("minute", -1.0986122886681098)], n = 2}}), ("Augusti", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> and an half hours", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("integer (numeric)", -0.6931471805599453), ("integer (0..19)", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("after <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("<integer> <unit-of-duration>", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("evening", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("decimal number", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("next <time>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("Tisdag", -2.0149030205422647), ("Mandag", -2.0149030205422647), ("day", -1.3217558399823195), ("Mars", -2.0149030205422647), ("month", -2.0149030205422647), ("Onsdag", -2.0149030205422647)], n = 4}, koData = ClassData{prior = -0.6931471805599453, unseen = -2.772588722239781, likelihoods = HashMap.fromList [("day", -1.3217558399823195), ("Mars", -2.0149030205422647), ("month", -2.0149030205422647), ("Onsdag", -2.0149030205422647), ("Fredag", -1.6094379124341003)], n = 4}}), ("last <cycle>", Classifier{okData = ClassData{prior = -0.45198512374305727, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("week", -1.7047480922384253), ("month (grain)", -2.3978952727983707), ("year (grain)", -1.7047480922384253), ("week (grain)", -1.7047480922384253), ("year", -1.7047480922384253), ("month", -2.3978952727983707)], n = 7}, koData = ClassData{prior = -1.0116009116784799, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("week", -1.6739764335716716), ("week (grain)", -1.6739764335716716), ("day", -1.6739764335716716), ("day (grain)", -1.6739764335716716)], n = 4}}), ("Onsdag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [("", 0.0)], n = 11}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("christmas", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("new year's day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("next n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.912023005428146, likelihoods = HashMap.fromList [("week", -2.793208009442517), ("integer (0..19)year (grain)", -3.1986731175506815), ("integer (numeric)day (grain)", -3.1986731175506815), ("integer (0..19)hour (grain)", -3.1986731175506815), ("second", -2.793208009442517), ("integer (numeric)second (grain)", -3.1986731175506815), ("integer (numeric)year (grain)", -3.1986731175506815), ("day", -2.793208009442517), ("year", -2.793208009442517), ("integer (numeric)week (grain)", -3.1986731175506815), ("integer (0..19)month (grain)", -3.1986731175506815), ("integer (0..19)second (grain)", -3.1986731175506815), ("hour", -2.793208009442517), ("month", -2.793208009442517), ("integer (numeric)minute (grain)", -3.1986731175506815), ("integer (0..19)minute (grain)", -3.1986731175506815), ("integer (numeric)month (grain)", -3.1986731175506815), ("minute", -2.793208009442517), ("integer (numeric)hour (grain)", -3.1986731175506815), ("integer (0..19)day (grain)", -3.1986731175506815), ("integer (0..19)week (grain)", -3.1986731175506815)], n = 14}, koData = ClassData{prior = -infinity, unseen = -3.0910424533583156, likelihoods = HashMap.fromList [], n = 0}}), ("Fredag", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3025850929940455, likelihoods = HashMap.fromList [("", 0.0)], n = 8}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("in <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -4.3694478524670215, likelihoods = HashMap.fromList [("week", -3.258096538021482), ("<integer> more <unit-of-duration>", -3.258096538021482), ("number.number hours", -3.6635616461296463), ("second", -2.9704144655697013), ("day", -2.5649493574615367), ("half an hour", -3.6635616461296463), ("<integer> <unit-of-duration>", -1.3121863889661687), ("a <unit-of-duration>", -2.5649493574615367), ("<integer> and an half hours", -3.258096538021482), ("hour", -2.4107986776342782), ("minute", -1.466337068793427), ("about <duration>", -3.258096538021482)], n = 33}, koData = ClassData{prior = -infinity, unseen = -2.5649493574615367, likelihoods = HashMap.fromList [], n = 0}}), ("<datetime> - <datetime> (interval)", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -3.6109179126442243, likelihoods = HashMap.fromList [("minuteminute", -1.3862943611198906), ("hh:mmhh:mm", -1.3862943611198906), ("dayday", -1.791759469228055), ("<day-of-month> (non ordinal) <named-month><day-of-month> (non ordinal) <named-month>", -1.791759469228055)], n = 13}, koData = ClassData{prior = -0.6931471805599453, unseen = -3.6109179126442243, likelihoods = HashMap.fromList [("Juli<day-of-month> (non ordinal) <named-month>", -2.890371757896165), ("monthday", -1.791759469228055), ("minuteminute", -1.6376087894007967), ("hh:mmhh:mm", -2.890371757896165), ("dayyear", -2.4849066497880004), ("Augusti<day-of-month> (non ordinal) <named-month>", -1.9740810260220096), ("hh:mmintersect", -1.791759469228055), ("dd/mmyear", -2.4849066497880004)], n = 13}}), ("<time-of-day> - <time-of-day> (interval)", Classifier{okData = ClassData{prior = -0.587786664902119, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -2.0794415416798357), ("minuteminute", -0.9808292530117262), ("hh:mmhh:mm", -0.9808292530117262), ("minutehour", -2.0794415416798357)], n = 10}, koData = ClassData{prior = -0.8109302162163288, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("hh:mmtime-of-day (latent)", -0.916290731874155), ("minuteminute", -2.3025850929940455), ("hh:mmhh:mm", -2.3025850929940455), ("minutehour", -0.916290731874155)], n = 8}}), ("last n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -4.007333185232471, likelihoods = HashMap.fromList [("week", -2.6026896854443837), ("integer (0..19)year (grain)", -3.295836866004329), ("integer (numeric)day (grain)", -2.890371757896165), ("second", -2.890371757896165), ("integer (numeric)second (grain)", -3.295836866004329), ("integer (numeric)year (grain)", -2.890371757896165), ("day", -2.6026896854443837), ("year", -2.6026896854443837), ("integer (numeric)week (grain)", -3.295836866004329), ("integer (0..19)month (grain)", -2.890371757896165), ("integer (0..19)second (grain)", -3.295836866004329), ("hour", -3.295836866004329), ("month", -2.6026896854443837), ("integer (numeric)minute (grain)", -3.295836866004329), ("integer (0..19)minute (grain)", -3.295836866004329), ("integer (numeric)month (grain)", -3.295836866004329), ("minute", -2.890371757896165), ("integer (numeric)hour (grain)", -3.295836866004329), ("integer (0..19)day (grain)", -3.295836866004329), ("integer (0..19)week (grain)", -2.890371757896165)], n = 17}, koData = ClassData{prior = -infinity, unseen = -3.044522437723423, likelihoods = HashMap.fromList [], n = 0}}), ("<named-month> <day-of-month> (non ordinal)", Classifier{okData = ClassData{prior = -0.10536051565782628, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("Aprilinteger (numeric)", -2.3978952727983707), ("Februariinteger (numeric)", -1.2992829841302609), ("month", -0.7884573603642702), ("Juliinteger (numeric)", -1.7047480922384253)], n = 9}, koData = ClassData{prior = -2.3025850929940455, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("Aprilinteger (numeric)", -1.0986122886681098), ("month", -1.0986122886681098)], n = 1}}), ("<day-of-month> (non ordinal) <named-month>", Classifier{okData = ClassData{prior = -0.1466034741918754, unseen = -3.828641396489095, likelihoods = HashMap.fromList [("integer (numeric)September", -3.1135153092103742), ("integer (numeric)Augusti", -1.5040773967762742), ("integer (numeric)April", -3.1135153092103742), ("month", -0.8109302162163288), ("integer (numeric)Februari", -2.1972245773362196), ("integer (numeric)Juli", -2.70805020110221), ("integer (numeric)Mars", -2.70805020110221)], n = 19}, koData = ClassData{prior = -1.9924301646902063, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("month", -1.1786549963416462), ("integer (numeric)Juli", -1.1786549963416462)], n = 3}}), ("this|next <day-of-week>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("Tisdag", -1.7047480922384253), ("Mandag", -1.7047480922384253), ("day", -1.0116009116784799), ("Onsdag", -1.7047480922384253)], n = 3}, koData = ClassData{prior = -0.6931471805599453, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("day", -1.0116009116784799), ("Onsdag", -1.7047480922384253), ("Fredag", -1.2992829841302609)], n = 3}}), ("ordinal (digits)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("", 0.0)], n = 10}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("quarter (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("last <cycle> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.1354942159291497, likelihoods = HashMap.fromList [("daymonth", -1.4816045409242156), ("day (grain)intersect", -1.9924301646902063), ("weekmonth", -1.4816045409242156), ("day (grain)Oktober", -1.9924301646902063), ("week (grain)intersect", -1.9924301646902063), ("week (grain)September", -1.9924301646902063)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [], n = 0}}), ("<day-of-month>(ordinal) <named-month> year", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("ordinals (first..twentieth,thirtieth,...)April", -1.6094379124341003), ("ordinals (first..twentieth,thirtieth,...)Mars", -1.6094379124341003), ("month", -0.916290731874155), ("ordinal (digits)Mars", -1.6094379124341003)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("morning", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("week-end", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("after <time-of-day>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -3.332204510175204, likelihoods = HashMap.fromList [("at <time-of-day>", -1.6863989535702288), ("intersect", -2.1972245773362196), ("tomorrow", -2.1972245773362196), ("day", -2.1972245773362196), ("hour", -1.349926716949016)], n = 8}, koData = ClassData{prior = -0.6931471805599453, unseen = -3.332204510175204, likelihoods = HashMap.fromList [("lunch", -2.6026896854443837), ("year (latent)", -1.9095425048844386), ("time-of-day (latent)", -1.9095425048844386), ("year", -1.9095425048844386), ("hh:mm", -2.6026896854443837), ("hour", -1.6863989535702288), ("minute", -2.6026896854443837)], n = 8}}), ("day (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("", 0.0)], n = 19}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<month> dd-dd (interval)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("Juli", -0.6931471805599453), ("month", -0.6931471805599453)], n = 3}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("about <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("half an hour", -0.6931471805599453), ("minute", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("this <time>", Classifier{okData = ClassData{prior = -1.0608719606852628, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("sommar", -2.2335922215070942), ("vinter", -2.2335922215070942), ("day", -1.7227665977411035), ("Oktober", -2.2335922215070942), ("hour", -1.9459101490553135), ("month", -2.2335922215070942), ("week-end", -1.9459101490553135)], n = 9}, koData = ClassData{prior = -0.42488319396526597, unseen = -3.8066624897703196, likelihoods = HashMap.fromList [("Tisdag", -3.0910424533583156), ("September", -2.174751721484161), ("day", -3.0910424533583156), ("Oktober", -1.3862943611198906), ("Mars", -2.6855773452501515), ("month", -0.9509762898620451)], n = 17}}), ("within <duration>", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("week", -0.6931471805599453), ("<integer> <unit-of-duration>", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}})]
4243e993f1561740b1a6d9fac686e3c638ad090d997911ecc4f586f2272b1762
CSCfi/rems
catalogue_items.cljs
(ns rems.administration.catalogue-items (:require [cljs-time.coerce :as time-coerce] [re-frame.core :as rf] [rems.administration.administration :as administration] [rems.administration.catalogue-item :as catalogue-item] [rems.administration.status-flags :as status-flags] [rems.atoms :as atoms :refer [readonly-checkbox document-title]] [rems.flash-message :as flash-message] [rems.common.roles :as roles] [rems.spinner :as spinner] [rems.table :as table] [rems.text :refer [localize-time text get-localized-title]] [rems.util :refer [navigate! fetch put!]])) (rf/reg-event-fx ::enter-page (fn [{:keys [db]}] {:db (assoc db ::selected-items (or (::selected-items db) #{})) :dispatch-n [[::fetch-catalogue] [:rems.table/reset] [:rems.administration.administration/remember-current-page]]})) (rf/reg-event-fx ::fetch-catalogue (fn [{:keys [db]}] (let [description [text :t.administration/catalogue-items]] (fetch "/api/catalogue-items" {:url-params {:expand :names :disabled true :expired (status-flags/display-archived? db) :archived (status-flags/display-archived? db)} :handler #(rf/dispatch [::fetch-catalogue-result %]) :error-handler (flash-message/default-error-handler :top description)})) {:db (assoc db ::loading? true)})) (rf/reg-event-db ::fetch-catalogue-result (fn [db [_ catalogue]] (-> db (assoc ::catalogue catalogue) (dissoc ::loading?)))) (rf/reg-sub ::catalogue (fn [db _] (::catalogue db))) (rf/reg-sub ::loading? (fn [db _] (::loading? db))) (rf/reg-event-fx ::set-catalogue-item-archived (fn [_ [_ item description dispatch-on-finished]] (put! "/api/catalogue-items/archived" {:params (select-keys item [:id :archived]) :handler (flash-message/status-update-handler :top description #(rf/dispatch dispatch-on-finished)) :error-handler (flash-message/default-error-handler :top description)}) {})) (rf/reg-event-fx ::set-catalogue-item-enabled (fn [_ [_ item description dispatch-on-finished]] (put! "/api/catalogue-items/enabled" {:params (select-keys item [:id :enabled]) :handler (flash-message/status-update-handler :top description #(rf/dispatch dispatch-on-finished)) :error-handler (flash-message/default-error-handler :top description)}) {})) (rf/reg-event-db ::set-selected-items (fn [db [_ items]] (assoc db ::selected-items items))) (rf/reg-sub ::selected-items (fn [db _] (::selected-items db))) (defn- create-catalogue-item-button [] [atoms/link {:class "btn btn-primary" :id :create-catalogue-item} "/administration/catalogue-items/create" (text :t.administration/create-catalogue-item)]) (defn- change-form-button [items] [:button.btn.btn-primary {:disabled (when (empty? items) :disabled) :on-click (fn [] (rf/dispatch [:rems.administration.change-catalogue-item-form/enter-page items]) (navigate! "/administration/catalogue-items/change-form"))} (text :t.administration/change-form)]) (defn- categories-button [] [atoms/link {:class "btn btn-primary" :id :manage-categories} "/administration/categories" (text :t.administration/manage-categories)]) (defn- view-button [catalogue-item-id] [atoms/link {:class "btn btn-primary"} (str "/administration/catalogue-items/" catalogue-item-id) (text :t.administration/view)]) (rf/reg-sub ::catalogue-table-rows (fn [_ _] [(rf/subscribe [::catalogue]) (rf/subscribe [:language])]) (fn [[catalogue language] _] (map (fn [item] {:key (:id item) :organization {:value (get-in item [:organization :organization/short-name language])} :name {:value (get-localized-title item language) :sort-value [(get-localized-title item language) (- (time-coerce/to-long (:start item)))]} ; secondary sort by created, reverse :resource (let [value (:resource-name item)] {:value value :td [:td.resource [atoms/link nil (str "/administration/resources/" (:resource-id item)) value]]}) :form (if-let [value (:form-name item)] {:value value :td [:td.form [atoms/link nil (str "/administration/forms/" (:formid item)) value]]} {:value (text :t.administration/no-form) :sort-value "" ; push "No form" cases to the top of the list when sorting :td [:td.form [text :t.administration/no-form]]}) :workflow (let [value (:workflow-name item)] {:value value :td [:td.workflow [atoms/link nil (str "/administration/workflows/" (:wfid item)) value]]}) :created (let [value (:start item)] {:value value :display-value (localize-time value)}) :active (let [checked? (status-flags/active? item)] {:td [:td.active [readonly-checkbox {:value checked?}]] :sort-value (if checked? 1 2)}) :commands {:td [:td.commands [view-button (:id item)] [roles/show-when roles/+admin-write-roles+ [catalogue-item/edit-button (:id item)] [status-flags/enabled-toggle item #(rf/dispatch [::set-catalogue-item-enabled %1 %2 [::fetch-catalogue]])] [status-flags/archived-toggle item #(rf/dispatch [::set-catalogue-item-archived %1 %2 [::fetch-catalogue]])]]]}}) catalogue))) (defn- catalogue-list [] (let [catalogue-table {:id ::catalogue :columns [{:key :organization :title (text :t.administration/organization)} {:key :name :title (text :t.administration/title)} {:key :resource :title (text :t.administration/resource)} {:key :form :title (text :t.administration/form)} {:key :workflow :title (text :t.administration/workflow)} {:key :created :title (text :t.administration/created)} {:key :active :title (text :t.administration/active) :filterable? false} {:key :commands :sortable? false :filterable? false}] :rows [::catalogue-table-rows] :default-sort-column :name :selectable? true :on-select #(rf/dispatch [::set-selected-items %])}] [:div.mt-3 [table/search catalogue-table] [table/table catalogue-table]])) (defn- items-by-ids [items ids] (filter (comp ids :id) items)) (defn catalogue-items-page [] (into [:div [administration/navigator] [document-title (text :t.administration/catalogue-items)] [flash-message/component :top]] (if @(rf/subscribe [::loading?]) [[spinner/big]] [[roles/show-when roles/+admin-write-roles+ [:div.commands.text-left.pl-0 [create-catalogue-item-button] [change-form-button (items-by-ids @(rf/subscribe [::catalogue]) @(rf/subscribe [::selected-items]))] [categories-button]] [status-flags/display-archived-toggle #(do (rf/dispatch [::fetch-catalogue]) (rf/dispatch [:rems.table/set-selected-rows {:id ::catalogue} nil]))] [status-flags/disabled-and-archived-explanation]] [catalogue-list]])))
null
https://raw.githubusercontent.com/CSCfi/rems/9abf233b728272c6e99c07a98d0e94da042ec2c7/src/cljs/rems/administration/catalogue_items.cljs
clojure
secondary sort by created, reverse push "No form" cases to the top of the list when sorting
(ns rems.administration.catalogue-items (:require [cljs-time.coerce :as time-coerce] [re-frame.core :as rf] [rems.administration.administration :as administration] [rems.administration.catalogue-item :as catalogue-item] [rems.administration.status-flags :as status-flags] [rems.atoms :as atoms :refer [readonly-checkbox document-title]] [rems.flash-message :as flash-message] [rems.common.roles :as roles] [rems.spinner :as spinner] [rems.table :as table] [rems.text :refer [localize-time text get-localized-title]] [rems.util :refer [navigate! fetch put!]])) (rf/reg-event-fx ::enter-page (fn [{:keys [db]}] {:db (assoc db ::selected-items (or (::selected-items db) #{})) :dispatch-n [[::fetch-catalogue] [:rems.table/reset] [:rems.administration.administration/remember-current-page]]})) (rf/reg-event-fx ::fetch-catalogue (fn [{:keys [db]}] (let [description [text :t.administration/catalogue-items]] (fetch "/api/catalogue-items" {:url-params {:expand :names :disabled true :expired (status-flags/display-archived? db) :archived (status-flags/display-archived? db)} :handler #(rf/dispatch [::fetch-catalogue-result %]) :error-handler (flash-message/default-error-handler :top description)})) {:db (assoc db ::loading? true)})) (rf/reg-event-db ::fetch-catalogue-result (fn [db [_ catalogue]] (-> db (assoc ::catalogue catalogue) (dissoc ::loading?)))) (rf/reg-sub ::catalogue (fn [db _] (::catalogue db))) (rf/reg-sub ::loading? (fn [db _] (::loading? db))) (rf/reg-event-fx ::set-catalogue-item-archived (fn [_ [_ item description dispatch-on-finished]] (put! "/api/catalogue-items/archived" {:params (select-keys item [:id :archived]) :handler (flash-message/status-update-handler :top description #(rf/dispatch dispatch-on-finished)) :error-handler (flash-message/default-error-handler :top description)}) {})) (rf/reg-event-fx ::set-catalogue-item-enabled (fn [_ [_ item description dispatch-on-finished]] (put! "/api/catalogue-items/enabled" {:params (select-keys item [:id :enabled]) :handler (flash-message/status-update-handler :top description #(rf/dispatch dispatch-on-finished)) :error-handler (flash-message/default-error-handler :top description)}) {})) (rf/reg-event-db ::set-selected-items (fn [db [_ items]] (assoc db ::selected-items items))) (rf/reg-sub ::selected-items (fn [db _] (::selected-items db))) (defn- create-catalogue-item-button [] [atoms/link {:class "btn btn-primary" :id :create-catalogue-item} "/administration/catalogue-items/create" (text :t.administration/create-catalogue-item)]) (defn- change-form-button [items] [:button.btn.btn-primary {:disabled (when (empty? items) :disabled) :on-click (fn [] (rf/dispatch [:rems.administration.change-catalogue-item-form/enter-page items]) (navigate! "/administration/catalogue-items/change-form"))} (text :t.administration/change-form)]) (defn- categories-button [] [atoms/link {:class "btn btn-primary" :id :manage-categories} "/administration/categories" (text :t.administration/manage-categories)]) (defn- view-button [catalogue-item-id] [atoms/link {:class "btn btn-primary"} (str "/administration/catalogue-items/" catalogue-item-id) (text :t.administration/view)]) (rf/reg-sub ::catalogue-table-rows (fn [_ _] [(rf/subscribe [::catalogue]) (rf/subscribe [:language])]) (fn [[catalogue language] _] (map (fn [item] {:key (:id item) :organization {:value (get-in item [:organization :organization/short-name language])} :name {:value (get-localized-title item language) :sort-value [(get-localized-title item language) :resource (let [value (:resource-name item)] {:value value :td [:td.resource [atoms/link nil (str "/administration/resources/" (:resource-id item)) value]]}) :form (if-let [value (:form-name item)] {:value value :td [:td.form [atoms/link nil (str "/administration/forms/" (:formid item)) value]]} {:value (text :t.administration/no-form) :td [:td.form [text :t.administration/no-form]]}) :workflow (let [value (:workflow-name item)] {:value value :td [:td.workflow [atoms/link nil (str "/administration/workflows/" (:wfid item)) value]]}) :created (let [value (:start item)] {:value value :display-value (localize-time value)}) :active (let [checked? (status-flags/active? item)] {:td [:td.active [readonly-checkbox {:value checked?}]] :sort-value (if checked? 1 2)}) :commands {:td [:td.commands [view-button (:id item)] [roles/show-when roles/+admin-write-roles+ [catalogue-item/edit-button (:id item)] [status-flags/enabled-toggle item #(rf/dispatch [::set-catalogue-item-enabled %1 %2 [::fetch-catalogue]])] [status-flags/archived-toggle item #(rf/dispatch [::set-catalogue-item-archived %1 %2 [::fetch-catalogue]])]]]}}) catalogue))) (defn- catalogue-list [] (let [catalogue-table {:id ::catalogue :columns [{:key :organization :title (text :t.administration/organization)} {:key :name :title (text :t.administration/title)} {:key :resource :title (text :t.administration/resource)} {:key :form :title (text :t.administration/form)} {:key :workflow :title (text :t.administration/workflow)} {:key :created :title (text :t.administration/created)} {:key :active :title (text :t.administration/active) :filterable? false} {:key :commands :sortable? false :filterable? false}] :rows [::catalogue-table-rows] :default-sort-column :name :selectable? true :on-select #(rf/dispatch [::set-selected-items %])}] [:div.mt-3 [table/search catalogue-table] [table/table catalogue-table]])) (defn- items-by-ids [items ids] (filter (comp ids :id) items)) (defn catalogue-items-page [] (into [:div [administration/navigator] [document-title (text :t.administration/catalogue-items)] [flash-message/component :top]] (if @(rf/subscribe [::loading?]) [[spinner/big]] [[roles/show-when roles/+admin-write-roles+ [:div.commands.text-left.pl-0 [create-catalogue-item-button] [change-form-button (items-by-ids @(rf/subscribe [::catalogue]) @(rf/subscribe [::selected-items]))] [categories-button]] [status-flags/display-archived-toggle #(do (rf/dispatch [::fetch-catalogue]) (rf/dispatch [:rems.table/set-selected-rows {:id ::catalogue} nil]))] [status-flags/disabled-and-archived-explanation]] [catalogue-list]])))
3782e6b7fbd19a8b9ff96e64c917533997d6470211c8b51c8d866425303d1986
esl/MongooseIM
mongoose_service_SUITE.erl
-module(mongoose_service_SUITE). -compile([export_all, nowarn_export_all]). -include_lib("eunit/include/eunit.hrl"). all() -> [starts_and_stops_services, ensures_service, reverts_config_when_service_fails_to_start, does_not_change_config_when_service_fails_to_stop, replaces_services, replaces_services_with_new_deps, replaces_services_with_old_deps, replaces_services_with_same_deps]. init_per_suite(C) -> C. end_per_suite(_C) -> ok. init_per_testcase(_TC, C) -> [mock_service(Service) || Service <- test_services()], C. end_per_testcase(_, _C) -> mongoose_config:unset_opt(services), meck:unload(test_services()). %% Test cases starts_and_stops_services(_Config) -> set_services(Services = #{service_a => #{}, service_b => [{opt, val}]}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), ok = mongoose_service:stop(), check_stopped([service_a, service_b]). ensures_service(_Config) -> set_services(#{}), ?assertEqual({started, start_result}, mongoose_service:ensure_started(service_a, #{})), ?assertEqual(#{service_a => #{}}, get_services()), ?assertEqual(already_started, mongoose_service:ensure_started(service_a, #{})), ?assertEqual(#{service_a => #{}}, get_services()), ?assertEqual({restarted, #{}, start_result}, mongoose_service:ensure_started(service_a, #{opt => val})), ?assertEqual(#{service_a => #{opt => val}}, get_services()), ?assertEqual({stopped, #{opt => val}}, mongoose_service:ensure_stopped(service_a)), ?assertEqual(#{}, get_services()), ?assertEqual(already_stopped, mongoose_service:ensure_stopped(service_a)), ?assertEqual(#{}, get_services()). reverts_config_when_service_fails_to_start(_Config) -> set_services(#{}), meck:expect(service_a, start, fun(_) -> error(something_awful) end), ?assertError(something_awful, mongoose_service:ensure_started(service_a, #{})), ?assertEqual(#{}, get_services()). does_not_change_config_when_service_fails_to_stop(_Config) -> set_services(#{service_a => #{}}), meck:expect(service_a, stop, fun() -> error(something_awful) end), ?assertError(something_awful, mongoose_service:ensure_stopped(service_a)), ?assertEqual(#{service_a => #{}}, get_services()). replaces_services(_Config) -> set_services(Services = #{service_a => #{}, service_b => #{opt => val}, service_c => #{}}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), Stop service_a , change opts for service_b , do not change service_c , start service_d NewServices = #{service_b => #{new_opt => new_val}, service_c => #{}, service_d => #{}}, ok = mongoose_service:replace_services([service_a], NewServices), check_stopped([service_a, service_b]), check_not_stopped([service_c]), check_started([{service_b, #{new_opt => new_val}}, {service_d, #{}}]), ?assertEqual(NewServices, get_services()), ok = mongoose_service:stop(), check_stopped([service_b, service_c, service_d]). replaces_services_with_new_deps(_Config) -> set_deps(#{service_b => [service_c]}), set_services(Services = #{service_a => #{}}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), %% Start service_b, which depends on service_c ok = mongoose_service:replace_services([], #{service_b => #{}}), check_not_stopped([service_a]), check_started([{service_b, #{}}, {service_c, #{}}]), ?assertEqual(Services#{service_b => #{}, service_c => #{}}, get_services()), ok = mongoose_service:stop(), check_stopped([service_a, service_b, service_c]). replaces_services_with_old_deps(_Config) -> set_deps(#{service_a => [service_c]}), set_services(Services = #{service_a => #{}, service_c => #{}}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), Stop service_a , which depends on service_c , and start service_b ok = mongoose_service:replace_services([service_a], #{service_b => #{}}), check_stopped([service_a, service_c]), check_started([{service_b, #{}}]), ?assertEqual(#{service_b => #{}}, get_services()), ok = mongoose_service:stop(), check_stopped([service_b]). replaces_services_with_same_deps(_Config) -> set_deps(#{service_a => [service_c], service_b => [service_c]}), set_services(Services = #{service_a => #{}, service_c => #{}}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), %% Stop service_a, and start service_b, both depending on service_c ok = mongoose_service:replace_services([service_a], #{service_b => #{}}), check_stopped([service_a]), check_not_stopped([service_c]), check_started([{service_b, #{}}]), ?assertEqual(#{service_b => #{}, service_c => #{}}, get_services()), ok = mongoose_service:stop(), check_stopped([service_b]). %% Helpers set_services(Services) -> mongoose_config:set_opt(services, Services). get_services() -> mongoose_config:get_opt(services). check_started(ServicesWithOpts) -> lists:foreach(fun({Service, Opts}) -> ?assert(meck:called(Service, start, [Opts])) end, ServicesWithOpts). check_stopped(Services) -> lists:foreach(fun(Service) -> ?assert(meck:called(Service, stop, [])) end, Services). check_not_stopped(Services) -> lists:foreach(fun(Service) -> ?assertNot(meck:called(Service, stop, [])) end, Services). mock_service(Service) -> meck:new(Service, [non_strict]), meck:expect(Service, start, fun(_) -> start_result end), meck:expect(Service, stop, fun() -> ok end). set_deps(DepsMap) -> maps:fold(fun(Service, Deps, _) -> meck:expect(Service, deps, fun() -> Deps end) end, undefined, DepsMap). test_services() -> [service_a, service_b, service_c, service_d].
null
https://raw.githubusercontent.com/esl/MongooseIM/40d41eebf2e333843aeb3f60a31f92dc5a88591c/test/mongoose_service_SUITE.erl
erlang
Test cases Start service_b, which depends on service_c Stop service_a, and start service_b, both depending on service_c Helpers
-module(mongoose_service_SUITE). -compile([export_all, nowarn_export_all]). -include_lib("eunit/include/eunit.hrl"). all() -> [starts_and_stops_services, ensures_service, reverts_config_when_service_fails_to_start, does_not_change_config_when_service_fails_to_stop, replaces_services, replaces_services_with_new_deps, replaces_services_with_old_deps, replaces_services_with_same_deps]. init_per_suite(C) -> C. end_per_suite(_C) -> ok. init_per_testcase(_TC, C) -> [mock_service(Service) || Service <- test_services()], C. end_per_testcase(_, _C) -> mongoose_config:unset_opt(services), meck:unload(test_services()). starts_and_stops_services(_Config) -> set_services(Services = #{service_a => #{}, service_b => [{opt, val}]}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), ok = mongoose_service:stop(), check_stopped([service_a, service_b]). ensures_service(_Config) -> set_services(#{}), ?assertEqual({started, start_result}, mongoose_service:ensure_started(service_a, #{})), ?assertEqual(#{service_a => #{}}, get_services()), ?assertEqual(already_started, mongoose_service:ensure_started(service_a, #{})), ?assertEqual(#{service_a => #{}}, get_services()), ?assertEqual({restarted, #{}, start_result}, mongoose_service:ensure_started(service_a, #{opt => val})), ?assertEqual(#{service_a => #{opt => val}}, get_services()), ?assertEqual({stopped, #{opt => val}}, mongoose_service:ensure_stopped(service_a)), ?assertEqual(#{}, get_services()), ?assertEqual(already_stopped, mongoose_service:ensure_stopped(service_a)), ?assertEqual(#{}, get_services()). reverts_config_when_service_fails_to_start(_Config) -> set_services(#{}), meck:expect(service_a, start, fun(_) -> error(something_awful) end), ?assertError(something_awful, mongoose_service:ensure_started(service_a, #{})), ?assertEqual(#{}, get_services()). does_not_change_config_when_service_fails_to_stop(_Config) -> set_services(#{service_a => #{}}), meck:expect(service_a, stop, fun() -> error(something_awful) end), ?assertError(something_awful, mongoose_service:ensure_stopped(service_a)), ?assertEqual(#{service_a => #{}}, get_services()). replaces_services(_Config) -> set_services(Services = #{service_a => #{}, service_b => #{opt => val}, service_c => #{}}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), Stop service_a , change opts for service_b , do not change service_c , start service_d NewServices = #{service_b => #{new_opt => new_val}, service_c => #{}, service_d => #{}}, ok = mongoose_service:replace_services([service_a], NewServices), check_stopped([service_a, service_b]), check_not_stopped([service_c]), check_started([{service_b, #{new_opt => new_val}}, {service_d, #{}}]), ?assertEqual(NewServices, get_services()), ok = mongoose_service:stop(), check_stopped([service_b, service_c, service_d]). replaces_services_with_new_deps(_Config) -> set_deps(#{service_b => [service_c]}), set_services(Services = #{service_a => #{}}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), ok = mongoose_service:replace_services([], #{service_b => #{}}), check_not_stopped([service_a]), check_started([{service_b, #{}}, {service_c, #{}}]), ?assertEqual(Services#{service_b => #{}, service_c => #{}}, get_services()), ok = mongoose_service:stop(), check_stopped([service_a, service_b, service_c]). replaces_services_with_old_deps(_Config) -> set_deps(#{service_a => [service_c]}), set_services(Services = #{service_a => #{}, service_c => #{}}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), Stop service_a , which depends on service_c , and start service_b ok = mongoose_service:replace_services([service_a], #{service_b => #{}}), check_stopped([service_a, service_c]), check_started([{service_b, #{}}]), ?assertEqual(#{service_b => #{}}, get_services()), ok = mongoose_service:stop(), check_stopped([service_b]). replaces_services_with_same_deps(_Config) -> set_deps(#{service_a => [service_c], service_b => [service_c]}), set_services(Services = #{service_a => #{}, service_c => #{}}), ok = mongoose_service:start(), check_started(maps:to_list(Services)), ok = mongoose_service:replace_services([service_a], #{service_b => #{}}), check_stopped([service_a]), check_not_stopped([service_c]), check_started([{service_b, #{}}]), ?assertEqual(#{service_b => #{}, service_c => #{}}, get_services()), ok = mongoose_service:stop(), check_stopped([service_b]). set_services(Services) -> mongoose_config:set_opt(services, Services). get_services() -> mongoose_config:get_opt(services). check_started(ServicesWithOpts) -> lists:foreach(fun({Service, Opts}) -> ?assert(meck:called(Service, start, [Opts])) end, ServicesWithOpts). check_stopped(Services) -> lists:foreach(fun(Service) -> ?assert(meck:called(Service, stop, [])) end, Services). check_not_stopped(Services) -> lists:foreach(fun(Service) -> ?assertNot(meck:called(Service, stop, [])) end, Services). mock_service(Service) -> meck:new(Service, [non_strict]), meck:expect(Service, start, fun(_) -> start_result end), meck:expect(Service, stop, fun() -> ok end). set_deps(DepsMap) -> maps:fold(fun(Service, Deps, _) -> meck:expect(Service, deps, fun() -> Deps end) end, undefined, DepsMap). test_services() -> [service_a, service_b, service_c, service_d].
ff7609dfb79612b5a558d59efef14eb1ea5d4c17639f3713da093a9230fabc2a
JAremko/spacetools
core.clj
(ns spacetools.fs-io.core "File-system I/O." (:require [cats.core :as m] [cats.monad.exception :as exc] [clojure.core.reducers :as r] [clojure.java.io :as io] [clojure.set :refer [union]] [clojure.spec.alpha :as s] [clojure.string :as str] [nio2.core :as nio] [orchestra.core :refer [defn-spec]]) (:import java.nio.file.Path)) (def filesystem (nio/default-fs)) (defn-spec path? boolean? "Returns true if X is a `Path` instance." [x any?] (instance? Path x)) (s/def ::file-ref (s/or :string-path (s/and string? (complement str/blank?)) :path path?)) (s/def ::file-refs (s/coll-of ::file-ref :min-count 0)) (s/def ::strings (s/coll-of string?)) (defn-spec file-ref? boolean? "Returns true if X is one of file reference types or a string." [x any?] (s/valid? ::file-ref x)) (defn-spec str->path path? "Construct `Path` form a `String`." [s string?] (nio/path filesystem s)) (defn-spec file-ref->path path? "Construct `Path` from a file reference." [f-ref file-ref?] ((condp #(%1 %2) f-ref string? str->path path? identity (throw (ex-info "Argument isn't a file reference." {:arg f-ref :arg-type (type f-ref)}))) f-ref)) (defn-spec directory? boolean? "Returns true if X is a directory." [x any?] (and (file-ref? x) (some-> x (file-ref->path) (nio/dir?)))) (defn-spec file? boolean? "Returns true if X is a file but not a directory." [x any?] (and (file-ref? x) (some-> x (file-ref->path) (nio/file?)))) (defn-spec error? boolean? "Returns true if X is a `Throwable` instance." [x any?] (instance? Throwable x)) (defn-spec regexp? boolean? "Returns true if X is a regular expression pattern." [x any?] (instance? java.util.regex.Pattern x)) (s/def ::extension (s/and string? #(str/starts-with? % "."))) (s/def ::set-of-strings+ (s/coll-of (s/and string? (complement str/blank?)) :kind set? :min-count 0 :distinct true)) (defn-spec file-with-ext? boolean? "Returns true if X is a `::file-ref` with extension EXT. NOTE: EXT must include .(dot)" [ext ::extension x any?] (true? (when (file? x) (let [fp (file-ref->path x)] (some-> fp (str) (str/ends-with? ext)))))) (defn-spec sdn-file? boolean? "Returns true if X is a `::file-ref` with .sdn extension." [x any?] (file-with-ext? ".sdn" x)) (defn-spec edn-file? boolean? "Returns true if X is a `::file-ref` with .edn expression." [x any?] (file-with-ext? ".edn" x)) (defn-spec absolute path? "Return absolute version of the PATH." [path file-ref?] (-> path (file-ref->path) (nio/absolute))) (defn-spec rebase-path path? "Rebase PATH from OLD-BASE to NEW-BASE." [old-base file-ref? new-base file-ref? path file-ref?] (let [[a-ob a-nb a-p] (map (comp str absolute file-ref->path) [old-base new-base path])] (str->path (str/replace-first a-p a-ob a-nb)))) (s/fdef exception-of? :args (s/cat :pred (s/or :ident ident? :form seq?)) :ret fn?) (defmacro exception-of? "Construct predicate function for testing exception monad value. The predicate returns true if the monad contains `exc/failure` or if `exc/success` wraps value satisfying PRED predicate. PRED also can be a spec or qualified-ident referencing a spec." [pred] `(fn [*val#] (and (exc/exception? *val#) (if (exc/success? *val#) (m/bind *val# #(if (or (qualified-ident? ~pred) (s/spec? ~pred)) (s/valid? ~pred %) (~pred %))) true)))) (defn-spec output-err nat-int? "Print out MSG es into stderr and return 2." [& msg (s/* string?)] (binding [*out* *err*] (println (str/join msg)) 2)) (defn-spec output-ok nat-int? "Print out MSG es into stdout and return 0." [& msg (s/* string?)] (println (str/join msg)) 0) (defn-spec err->msg string? "Format error message ERR." [^Throwable err error?] (let [{:keys [cause data]} (Throwable->map err)] (str/join \newline (interleave (map #(apply str % ": " (repeat (- 78 (count %)) "=")) ["Cause" "File" "Data"]) [cause (or (:file data) "<none>") (or (:problems data) (seq data) "<none>")])))) (defn exit "Call `System/exit` with status-code. NOTE: Useful for mocking." [status-code] (System/exit status-code)) (defn-spec try-m->output any? "Print *OUTPUT value to stderr or stdout and `System/exit` with code 0 or 2." [*output (exception-of? any?)] (exit (let [output (m/extract *output)] (if (exc/failure? *output) (output-err (format "Error:\n%s\nRun with \"-h\" for usage" (err->msg output))) (output-ok (str output)))))) (defn-spec *spit (exception-of? path?) "Spit CONTENT into PATH file and returns path wrapped into `exc/exception`." [path file-ref? content any?] (exc/try-or-recover (let [p (file-ref->path path) a-path (absolute p) parent-dir (nio/parent a-path)] (nio/create-dirs parent-dir) (with-open [output (->> p (nio/buffered-writer) (io/writer))] (.write output (str content))) a-path) (fn [^Exception err] (exc/failure (ex-info "Can't write file" {:path path}))))) (defn-spec *slurp (exception-of? (s/coll-of string?)) "Read content of the PATH file into array of strings (lines)." [path file-ref?] (exc/try-or-recover (if (file? path) (->> path file-ref->path nio/read-all-lines vec) (ex-info "Isn't a file" {:path (str path)})) (fn [^Exception err] (exc/failure (ex-info "Can't read file" {:path path :error err}))))) (defn-spec *fps-in-dir (exception-of? ::set-of-strings+) "Return absolute paths of files with EXT extension in PATH directory. NOTE: EXT must include dot." [ext ::extension path file-ref?] (exc/try-on (let [p (file-ref->path path)] (if (directory? p) (into #{} (comp (map absolute) (filter (partial file-with-ext? ext)) (map str)) (tree-seq nio/dir? #(-> % nio/dir-stream (.iterator) (iterator-seq)) p)) (throw ((cond (not (nio/exists? p)) (partial ex-info "File doesn't exists") (nio/file? p) (partial ex-info "File isn't a directory") (nio/readable? p) (partial ex-info "Directory isn't readable")) {:extension ext :file p})))))) (defn-spec *flatten-fps (exception-of? ::set-of-strings+) "Flatten sequence of EXT file PATHS and directories(searched for files). EXT is a file extension (including dot)." [ext ::extension paths ::file-refs] (exc/try-on (r/fold (r/monoid (m/lift-m 2 union) (exc/wrap hash-set)) (r/map #(cond (file-with-ext? ext %) (exc/success (hash-set %)) (directory? %) (*fps-in-dir ext %) :else (exc/failure (ex-info (str "File doesn't have proper extension" " or isn't a readable directory.") {:expected-extension ext :file %}))) paths)))) (defn-spec normalize path? "Normalize PATH" [path file-ref?] (nio/normalize (file-ref->path path))) (defn-spec join path? "Join PATH and PARENT path." [parent file-ref? path file-ref?] (nio/join (file-ref->path parent) (file-ref->path path))) (defn-spec relativize path? "Relativize PATH relative to OTHER" [path file-ref? other file-ref?] (nio/relativize (file-ref->path path) (file-ref->path other))) (defn-spec parent path? "Return parent dir of the PATH" [path file-ref?] (->> path file-ref->path nio/absolute nio/parent))
null
https://raw.githubusercontent.com/JAremko/spacetools/d047e99689918b5a4ad483022f35802b2015af5f/components/fs-io/src/spacetools/fs_io/core.clj
clojure
(ns spacetools.fs-io.core "File-system I/O." (:require [cats.core :as m] [cats.monad.exception :as exc] [clojure.core.reducers :as r] [clojure.java.io :as io] [clojure.set :refer [union]] [clojure.spec.alpha :as s] [clojure.string :as str] [nio2.core :as nio] [orchestra.core :refer [defn-spec]]) (:import java.nio.file.Path)) (def filesystem (nio/default-fs)) (defn-spec path? boolean? "Returns true if X is a `Path` instance." [x any?] (instance? Path x)) (s/def ::file-ref (s/or :string-path (s/and string? (complement str/blank?)) :path path?)) (s/def ::file-refs (s/coll-of ::file-ref :min-count 0)) (s/def ::strings (s/coll-of string?)) (defn-spec file-ref? boolean? "Returns true if X is one of file reference types or a string." [x any?] (s/valid? ::file-ref x)) (defn-spec str->path path? "Construct `Path` form a `String`." [s string?] (nio/path filesystem s)) (defn-spec file-ref->path path? "Construct `Path` from a file reference." [f-ref file-ref?] ((condp #(%1 %2) f-ref string? str->path path? identity (throw (ex-info "Argument isn't a file reference." {:arg f-ref :arg-type (type f-ref)}))) f-ref)) (defn-spec directory? boolean? "Returns true if X is a directory." [x any?] (and (file-ref? x) (some-> x (file-ref->path) (nio/dir?)))) (defn-spec file? boolean? "Returns true if X is a file but not a directory." [x any?] (and (file-ref? x) (some-> x (file-ref->path) (nio/file?)))) (defn-spec error? boolean? "Returns true if X is a `Throwable` instance." [x any?] (instance? Throwable x)) (defn-spec regexp? boolean? "Returns true if X is a regular expression pattern." [x any?] (instance? java.util.regex.Pattern x)) (s/def ::extension (s/and string? #(str/starts-with? % "."))) (s/def ::set-of-strings+ (s/coll-of (s/and string? (complement str/blank?)) :kind set? :min-count 0 :distinct true)) (defn-spec file-with-ext? boolean? "Returns true if X is a `::file-ref` with extension EXT. NOTE: EXT must include .(dot)" [ext ::extension x any?] (true? (when (file? x) (let [fp (file-ref->path x)] (some-> fp (str) (str/ends-with? ext)))))) (defn-spec sdn-file? boolean? "Returns true if X is a `::file-ref` with .sdn extension." [x any?] (file-with-ext? ".sdn" x)) (defn-spec edn-file? boolean? "Returns true if X is a `::file-ref` with .edn expression." [x any?] (file-with-ext? ".edn" x)) (defn-spec absolute path? "Return absolute version of the PATH." [path file-ref?] (-> path (file-ref->path) (nio/absolute))) (defn-spec rebase-path path? "Rebase PATH from OLD-BASE to NEW-BASE." [old-base file-ref? new-base file-ref? path file-ref?] (let [[a-ob a-nb a-p] (map (comp str absolute file-ref->path) [old-base new-base path])] (str->path (str/replace-first a-p a-ob a-nb)))) (s/fdef exception-of? :args (s/cat :pred (s/or :ident ident? :form seq?)) :ret fn?) (defmacro exception-of? "Construct predicate function for testing exception monad value. The predicate returns true if the monad contains `exc/failure` or if `exc/success` wraps value satisfying PRED predicate. PRED also can be a spec or qualified-ident referencing a spec." [pred] `(fn [*val#] (and (exc/exception? *val#) (if (exc/success? *val#) (m/bind *val# #(if (or (qualified-ident? ~pred) (s/spec? ~pred)) (s/valid? ~pred %) (~pred %))) true)))) (defn-spec output-err nat-int? "Print out MSG es into stderr and return 2." [& msg (s/* string?)] (binding [*out* *err*] (println (str/join msg)) 2)) (defn-spec output-ok nat-int? "Print out MSG es into stdout and return 0." [& msg (s/* string?)] (println (str/join msg)) 0) (defn-spec err->msg string? "Format error message ERR." [^Throwable err error?] (let [{:keys [cause data]} (Throwable->map err)] (str/join \newline (interleave (map #(apply str % ": " (repeat (- 78 (count %)) "=")) ["Cause" "File" "Data"]) [cause (or (:file data) "<none>") (or (:problems data) (seq data) "<none>")])))) (defn exit "Call `System/exit` with status-code. NOTE: Useful for mocking." [status-code] (System/exit status-code)) (defn-spec try-m->output any? "Print *OUTPUT value to stderr or stdout and `System/exit` with code 0 or 2." [*output (exception-of? any?)] (exit (let [output (m/extract *output)] (if (exc/failure? *output) (output-err (format "Error:\n%s\nRun with \"-h\" for usage" (err->msg output))) (output-ok (str output)))))) (defn-spec *spit (exception-of? path?) "Spit CONTENT into PATH file and returns path wrapped into `exc/exception`." [path file-ref? content any?] (exc/try-or-recover (let [p (file-ref->path path) a-path (absolute p) parent-dir (nio/parent a-path)] (nio/create-dirs parent-dir) (with-open [output (->> p (nio/buffered-writer) (io/writer))] (.write output (str content))) a-path) (fn [^Exception err] (exc/failure (ex-info "Can't write file" {:path path}))))) (defn-spec *slurp (exception-of? (s/coll-of string?)) "Read content of the PATH file into array of strings (lines)." [path file-ref?] (exc/try-or-recover (if (file? path) (->> path file-ref->path nio/read-all-lines vec) (ex-info "Isn't a file" {:path (str path)})) (fn [^Exception err] (exc/failure (ex-info "Can't read file" {:path path :error err}))))) (defn-spec *fps-in-dir (exception-of? ::set-of-strings+) "Return absolute paths of files with EXT extension in PATH directory. NOTE: EXT must include dot." [ext ::extension path file-ref?] (exc/try-on (let [p (file-ref->path path)] (if (directory? p) (into #{} (comp (map absolute) (filter (partial file-with-ext? ext)) (map str)) (tree-seq nio/dir? #(-> % nio/dir-stream (.iterator) (iterator-seq)) p)) (throw ((cond (not (nio/exists? p)) (partial ex-info "File doesn't exists") (nio/file? p) (partial ex-info "File isn't a directory") (nio/readable? p) (partial ex-info "Directory isn't readable")) {:extension ext :file p})))))) (defn-spec *flatten-fps (exception-of? ::set-of-strings+) "Flatten sequence of EXT file PATHS and directories(searched for files). EXT is a file extension (including dot)." [ext ::extension paths ::file-refs] (exc/try-on (r/fold (r/monoid (m/lift-m 2 union) (exc/wrap hash-set)) (r/map #(cond (file-with-ext? ext %) (exc/success (hash-set %)) (directory? %) (*fps-in-dir ext %) :else (exc/failure (ex-info (str "File doesn't have proper extension" " or isn't a readable directory.") {:expected-extension ext :file %}))) paths)))) (defn-spec normalize path? "Normalize PATH" [path file-ref?] (nio/normalize (file-ref->path path))) (defn-spec join path? "Join PATH and PARENT path." [parent file-ref? path file-ref?] (nio/join (file-ref->path parent) (file-ref->path path))) (defn-spec relativize path? "Relativize PATH relative to OTHER" [path file-ref? other file-ref?] (nio/relativize (file-ref->path path) (file-ref->path other))) (defn-spec parent path? "Return parent dir of the PATH" [path file-ref?] (->> path file-ref->path nio/absolute nio/parent))
7ac47c64136a61dd5b1da6270d04e39b1be5d4e021e52d3f2b741cc0a3e08d70
polysemy-research/polysemy
Setup.hs
import Distribution.Extra.Doctest (defaultMainWithDoctests) main = defaultMainWithDoctests "polysemy-plugin-test"
null
https://raw.githubusercontent.com/polysemy-research/polysemy/43a67061fb2a6cd2f545c5bd5e8320f2a228fb6b/polysemy-plugin/Setup.hs
haskell
import Distribution.Extra.Doctest (defaultMainWithDoctests) main = defaultMainWithDoctests "polysemy-plugin-test"
c9bf793dfaa82de2fe6f6156ca24ccec5cca10dc991503339ab8cf7990b248ad
hoophq/sequence
security.clj
(ns decimals.security (:import java.security.MessageDigest java.util.Base64) (:require [clojure.tools.logging :as log] [environ.core :refer [env]] [clojure.walk] [clojure.string :as str] [clojure.data.json :as json])) (defn sha256 [string] (let [digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes string "UTF-8"))] (apply str (map (partial format "%02x") digest)))) (defn match-keys [digest keys] (->> keys (filter #(= (:secret-key-hash %) digest)) seq first)) (defn authenticate [k keys] (log/debug "Matching: " k keys) (when-let [key-digest (sha256 k)] (when-let [account (match-keys key-digest keys)] account))) (defn decode [to-decode] (try (String. (.decode (Base64/getDecoder) to-decode)) (catch Exception e))) (defn remove-colon [s] (subs s 0 (- (count s) 1))) (defn authz-header [context] (get-in context [:request :headers "authorization"])) (defn header-key [context] (when-let [header (authz-header context)] (-> header (str/split #" ") second decode remove-colon))) (defn str->map [str] (try (-> str json/read-str clojure.walk/keywordize-keys) (catch Exception e (log/errorf "failde to parse keys %s" (.getMessage e))))) (defn apikey-auth [context] (if-let [key (header-key context)] (if-let [keys (str->map (env :keys))] (if-let [customer (authenticate key keys)] (let [] (log/debug "Got customer: " customer) customer) (log/debug "Invalid credentials")) (log/warn "Error parsing keys from env")) (log/debug "Invalid Authz header: " (authz-header context))))
null
https://raw.githubusercontent.com/hoophq/sequence/f968a88ffdceeb51956e1dc20e487faff416885b/src/decimals/security.clj
clojure
(ns decimals.security (:import java.security.MessageDigest java.util.Base64) (:require [clojure.tools.logging :as log] [environ.core :refer [env]] [clojure.walk] [clojure.string :as str] [clojure.data.json :as json])) (defn sha256 [string] (let [digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes string "UTF-8"))] (apply str (map (partial format "%02x") digest)))) (defn match-keys [digest keys] (->> keys (filter #(= (:secret-key-hash %) digest)) seq first)) (defn authenticate [k keys] (log/debug "Matching: " k keys) (when-let [key-digest (sha256 k)] (when-let [account (match-keys key-digest keys)] account))) (defn decode [to-decode] (try (String. (.decode (Base64/getDecoder) to-decode)) (catch Exception e))) (defn remove-colon [s] (subs s 0 (- (count s) 1))) (defn authz-header [context] (get-in context [:request :headers "authorization"])) (defn header-key [context] (when-let [header (authz-header context)] (-> header (str/split #" ") second decode remove-colon))) (defn str->map [str] (try (-> str json/read-str clojure.walk/keywordize-keys) (catch Exception e (log/errorf "failde to parse keys %s" (.getMessage e))))) (defn apikey-auth [context] (if-let [key (header-key context)] (if-let [keys (str->map (env :keys))] (if-let [customer (authenticate key keys)] (let [] (log/debug "Got customer: " customer) customer) (log/debug "Invalid credentials")) (log/warn "Error parsing keys from env")) (log/debug "Invalid Authz header: " (authz-header context))))
28142af3d66a67a967b65dd26d6fc5818ea9a0307a78c6431ea5f577af1c9850
simmone/racket-simple-xlsx
line-3d-chart-head-test.rkt
#lang racket (require simple-xml) (require rackunit/text-ui rackunit) (require "../../../../lib/lib.rkt") (require"../../../../xl/charts/line-chart.rkt") (require racket/runtime-path) (define-runtime-path line_3d_chart_head_file "line_3d_chart_head.xml") (define test-line-3d-chart-head (test-suite "test-line-3d-chart-head" (test-case "test-line-3d-chart-head" (call-with-input-file line_3d_chart_head_file (lambda (expected) (call-with-input-string (lists->xml_content (line-3d-chart-head)) (lambda (actual) (check-lines? expected actual)))))) )) (run-tests test-line-3d-chart-head)
null
https://raw.githubusercontent.com/simmone/racket-simple-xlsx/e0ac3190b6700b0ee1dd80ed91a8f4318533d012/simple-xlsx/tests/xl/charts/line-chart/line-3d-chart-head-test.rkt
racket
#lang racket (require simple-xml) (require rackunit/text-ui rackunit) (require "../../../../lib/lib.rkt") (require"../../../../xl/charts/line-chart.rkt") (require racket/runtime-path) (define-runtime-path line_3d_chart_head_file "line_3d_chart_head.xml") (define test-line-3d-chart-head (test-suite "test-line-3d-chart-head" (test-case "test-line-3d-chart-head" (call-with-input-file line_3d_chart_head_file (lambda (expected) (call-with-input-string (lists->xml_content (line-3d-chart-head)) (lambda (actual) (check-lines? expected actual)))))) )) (run-tests test-line-3d-chart-head)
1310ad085c7b126eb37061459371c746bbdcfb075bfed8e2e991b97d6ae83f11
returntocorp/semgrep
lib_parsing_php.ml
(*s: lib_parsing_php.ml *) (*s: Facebook copyright *) * * Copyright ( C ) 2009 - 2011 Facebook * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2009-2011 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) (*e: Facebook copyright *) open Common module PI = Parse_info s : basic pfff module open and aliases (*module Ast = Cst_php*) e : basic pfff module open and aliases (*****************************************************************************) (* Wrappers *) (*****************************************************************************) let pr2, _pr2_once = Common2.mk_pr2_wrappers Flag_parsing.verbose_parsing (*****************************************************************************) (* Filenames *) (*****************************************************************************) let is_php_script file = Common.with_open_infile file (fun chan -> try let l = input_line chan in l =~ "#!/usr/.*/php" || l =~ "#!/bin/env php" || l =~ "#!/usr/bin/env php" with | End_of_file -> false) todo : can not include those files for now because * they conflict with data / php_stdlib and generate lots * of DUPE in codegraph * * ( filename = ~ " .*\\.hhi " ) ( * hack uses this extension * they conflict with data/php_stdlib and generate lots * of DUPE in codegraph * * (filename =~ ".*\\.hhi") (* hack uses this extension *) *) let is_php_filename filename = filename =~ ".*\\.php$" || filename =~ ".*\\.phpt$" (* hotcrp uses this extension *) || filename =~ ".*\\.inc" let is_hhi_filename filename = filename =~ ".*\\.hhi$" || false let is_php_filename_phar filename = filename =~ ".*\\.phar$" || false let is_php_file filename = (not (is_php_filename_phar filename)) && (is_php_filename filename || is_php_script filename) * In command line tools like git or mercurial , many operations works * when a file , a set of files , or even dirs are passed as parameters . * We want the same with , hence this small helper function that * transform such files_or_dirs into a flag set of filenames . * In command line tools like git or mercurial, many operations works * when a file, a set of files, or even dirs are passed as parameters. * We want the same with pfff, hence this small helper function that * transform such files_or_dirs into a flag set of filenames. *) let find_source_files_of_dir_or_files ?(verbose = false) ?(include_hack = false) xs = Common.files_of_dir_or_files_no_vcs_nofilter xs |> List.filter (fun filename -> note : there was a possible race here because between the time we * do the ' find ' and the time we call is_php_file ( ) , the file may have * disappeared ( this happens for instance because of watchman ) . * Hence the Sys.file_exists guard . * do the 'find' and the time we call is_php_file(), the file may have * disappeared (this happens for instance because of watchman). * Hence the Sys.file_exists guard. *) let valid = (* note that there is still a race between the call to file_exists * and is_php_file, but this one is far shorter :) *) Sys.file_exists filename && (is_php_file filename || (include_hack && is_hhi_filename filename)) in if (not valid) && verbose then pr2 ("not analyzing: " ^ filename); valid) |> Common.sort (*****************************************************************************) (* Extract infos *) (*****************************************************************************) (*s: extract infos *) let extract_info_visitor recursor = let globals = ref [ ] in let hooks = { V.default_visitor with V.kinfo = ( fun ( _ k , _ ) i - > ( * most of the time when you use ii_of_any , you want to use * functions like max_min_pos which works only on origin tokens * hence the filtering done here . * * ugly : For PHP we use a fakeInfo only for generating a fake left * brace for abstract methods . let extract_info_visitor recursor = let globals = ref [] in let hooks = { V.default_visitor with V.kinfo = (fun (_k, _) i -> (* most of the time when you use ii_of_any, you want to use * functions like max_min_pos which works only on origin tokens * hence the filtering done here. * * ugly: For PHP we use a fakeInfo only for generating a fake left * brace for abstract methods. *) match i.Parse_info.token with | Parse_info.OriginTok _ -> Common.push i globals | _ -> () ) } in begin let vout = V.mk_visitor hooks in recursor vout; List.rev !globals end *) (*x: extract infos *) (* let ii_of_any any = extract_info_visitor (fun visitor -> visitor any) *) (*e: extract infos *) (*****************************************************************************) , range (*****************************************************************************) (*s: max min range *) x : range let (range_of_origin_ii : Cst_php.tok list -> (int * int) option) = fun ii -> let ii = List.filter Parse_info.is_origintok ii in try let min, max = Parse_info.min_max_ii_by_pos ii in assert (PI.is_origintok max); assert (PI.is_origintok min); let strmax = PI.str_of_info max in Some (PI.pos_of_info min, PI.pos_of_info max + String.length strmax) with | _ -> None e : range (*****************************************************************************) (* Ast getters *) (*****************************************************************************) (*s: ast getters *) (* let get_funcalls_any any = let h = Hashtbl.create 101 in let hooks = { V.default_visitor with (* TODO if nested function ??? still wants to report ? *) V.kexpr = (fun (k,_vx) x -> match x with | Call (Id callname, _args) -> let str = Cst_php.str_of_name callname in Hashtbl.replace h str true; k x | _ -> k x ); } in let visitor = V.mk_visitor hooks in visitor any; Common.hashset_to_list h *) (*x: ast getters *) (*x: ast getters *) let get_constant_strings_any any = let h = Hashtbl.create 101 in let hooks = { V.default_visitor with V.kconstant = ( fun ( ) x - > match x with | String ( str,_ii ) - > Hashtbl.replace h str true ; | _ - > k x ) ; V.kencaps = ( fun ( ) x - > match x with | EncapsString ( str , _ ii ) - > Hashtbl.replace h str true ; | _ - > k x ) ; } in ( V.mk_visitor hooks ) any ; Common.hashset_to_list h let get_constant_strings_any any = let h = Hashtbl.create 101 in let hooks = { V.default_visitor with V.kconstant = (fun (k,_vx) x -> match x with | String (str,_ii) -> Hashtbl.replace h str true; | _ -> k x ); V.kencaps = (fun (k,_vx) x -> match x with | EncapsString (str, _ii) -> Hashtbl.replace h str true; | _ -> k x ); } in (V.mk_visitor hooks) any; Common.hashset_to_list h *) (*e: ast getters *) let get_static_vars_any any = any | > V.do_visit_with_ref ( fun aref - > { V.default_visitor with V.kstmt = ( fun ( ) x - > match x with | StaticVars ( _ tok , xs , _ tok2 ) - > xs | > Ast.uncomma | > List.iter ( fun ( dname , _ affect_opt ) - > Common.push ) ; | _ - > k x ) ; } ) ( * todo ? do isomorphism ? let get_static_vars_any any = any |> V.do_visit_with_ref (fun aref -> { V.default_visitor with V.kstmt = (fun (k,_vx) x -> match x with | StaticVars (_tok, xs, _tok2) -> xs |> Ast.uncomma |> List.iter (fun (dname, _affect_opt) -> Common.push dname aref ); | _ -> k x ); }) (* todo? do last_stmt_is_a_return isomorphism ? *) let get_returns_any any = V.do_visit_with_ref (fun aref -> { V.default_visitor with V.kstmt = (fun (k,_vx) x -> match x with | Return (_tok1, Some e, _tok2) -> Common.push e aref | _ -> k x )}) any let get_vars_any any = V.do_visit_with_ref (fun aref -> { V.default_visitor with V.kexpr = (fun (k, _vx) x -> match x with | IdVar (dname, _scope) -> Common.push dname aref (* todo? sure ?? *) | Lambda (l_use, _def) -> l_use |> Common.do_option (fun (_tok, xs) -> xs |> Ast.unparen |> Ast.uncomma |> List.iter (function | LexicalVar (_is_ref, dname) -> Common.push dname aref ) ); k x | _ -> k x ); }) any *) (*****************************************************************************) (* Ast adapters *) (*****************************************************************************) let top_statements_of_program ast = ast | > List.map ( function | StmtList xs - > xs | FinalDef _ |NotParsedCorrectly _ | ClassDef _ | FuncDef _ | ConstantDef _ | TypeDef _ | NamespaceDef _ | _ | NamespaceUse _ - > [ ] ) | > List.flatten ( * We often do some analysis on " unit " of code like a function , * a method , or toplevel statements . One can not use the * ' toplevel ' type for that because it contains Class and Interface which * are too coarse grained ; the method granularity is better . * * For instance it makes sense to have a CFG for a function , a method , * or toplevel statements but a CFG for a class does not make sense . let top_statements_of_program ast = ast |> List.map (function | StmtList xs -> xs | FinalDef _|NotParsedCorrectly _ | ClassDef _| FuncDef _ | ConstantDef _ | TypeDef _ | NamespaceDef _ | NamespaceBracketDef _ | NamespaceUse _ -> [] ) |> List.flatten (* We often do some analysis on "unit" of code like a function, * a method, or toplevel statements. One can not use the * 'toplevel' type for that because it contains Class and Interface which * are too coarse grained; the method granularity is better. * * For instance it makes sense to have a CFG for a function, a method, * or toplevel statements but a CFG for a class does not make sense. *) let functions_methods_or_topstms_of_program prog = let funcs = ref [] in let methods = ref [] in let toplevels = ref [] in let visitor = V.mk_visitor { V.default_visitor with V.kfunc_def = (fun (_k, _) def -> match def.f_type with | FunctionRegular -> Common.push def funcs | MethodRegular | MethodAbstract -> Common.push def methods | FunctionLambda -> () ); V.ktop = (fun (k, _) top -> match top with | StmtList xs -> Common.push xs toplevels | _ -> k top ); } in visitor (Program prog); !funcs, !methods, !toplevels do some isomorphisms for declaration vs let get_vars_assignements_any recursor = (* We want to group later assignement by variables, and * so we want to use function like Common.group_by_xxx * which requires to have identical key. Each dname occurence * below has a different location and so we can use dname as * key, but the name of the variable can be used, hence the use * of Ast.dname *) V.do_visit_with_ref (fun aref -> { V.default_visitor with V.kstmt = (fun (k,_) x -> match x with | StaticVars (_tok, xs, _tok2) -> xs |> Ast.uncomma |> List.iter (fun (dname, affect_opt) -> let s = Ast.str_of_dname dname in affect_opt |> Common.do_option (fun (_tok, scalar) -> Common.push (s, scalar) aref; ); ); | _ -> k x ); V.kexpr = (fun (k,_vx) x -> match x with | Assign (lval, _, e) | AssignOp (lval, _, e) -> (* the expression itself can contain assignements *) k x; (* for now we handle only simple direct assignement to simple * variables *) (match lval with | IdVar (dname, _scope) -> let s = Ast.str_of_dname dname in Common.push (s, e) aref; | _ -> () ) todo ? AssignRef AssignNew ? | _ -> k x ); } ) recursor |> Common.group_assoc_bykey_eff *) (*e: lib_parsing_php.ml *)
null
https://raw.githubusercontent.com/returntocorp/semgrep/db9b44c8a606ffa84f92b45b79d96ed821c420ee/languages/php/ast/lib_parsing_php.ml
ocaml
s: lib_parsing_php.ml s: Facebook copyright e: Facebook copyright module Ast = Cst_php *************************************************************************** Wrappers *************************************************************************** *************************************************************************** Filenames *************************************************************************** hack uses this extension hotcrp uses this extension note that there is still a race between the call to file_exists * and is_php_file, but this one is far shorter :) *************************************************************************** Extract infos *************************************************************************** s: extract infos most of the time when you use ii_of_any, you want to use * functions like max_min_pos which works only on origin tokens * hence the filtering done here. * * ugly: For PHP we use a fakeInfo only for generating a fake left * brace for abstract methods. x: extract infos let ii_of_any any = extract_info_visitor (fun visitor -> visitor any) e: extract infos *************************************************************************** *************************************************************************** s: max min range *************************************************************************** Ast getters *************************************************************************** s: ast getters let get_funcalls_any any = let h = Hashtbl.create 101 in let hooks = { V.default_visitor with (* TODO if nested function ??? still wants to report ? x: ast getters x: ast getters e: ast getters todo? do last_stmt_is_a_return isomorphism ? todo? sure ?? *************************************************************************** Ast adapters *************************************************************************** We often do some analysis on "unit" of code like a function, * a method, or toplevel statements. One can not use the * 'toplevel' type for that because it contains Class and Interface which * are too coarse grained; the method granularity is better. * * For instance it makes sense to have a CFG for a function, a method, * or toplevel statements but a CFG for a class does not make sense. We want to group later assignement by variables, and * so we want to use function like Common.group_by_xxx * which requires to have identical key. Each dname occurence * below has a different location and so we can use dname as * key, but the name of the variable can be used, hence the use * of Ast.dname the expression itself can contain assignements for now we handle only simple direct assignement to simple * variables e: lib_parsing_php.ml
* * Copyright ( C ) 2009 - 2011 Facebook * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2009-2011 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common module PI = Parse_info s : basic pfff module open and aliases e : basic pfff module open and aliases let pr2, _pr2_once = Common2.mk_pr2_wrappers Flag_parsing.verbose_parsing let is_php_script file = Common.with_open_infile file (fun chan -> try let l = input_line chan in l =~ "#!/usr/.*/php" || l =~ "#!/bin/env php" || l =~ "#!/usr/bin/env php" with | End_of_file -> false) todo : can not include those files for now because * they conflict with data / php_stdlib and generate lots * of DUPE in codegraph * * ( filename = ~ " .*\\.hhi " ) ( * hack uses this extension * they conflict with data/php_stdlib and generate lots * of DUPE in codegraph * *) let is_php_filename filename = filename =~ ".*\\.php$" || filename =~ ".*\\.phpt$" || filename =~ ".*\\.inc" let is_hhi_filename filename = filename =~ ".*\\.hhi$" || false let is_php_filename_phar filename = filename =~ ".*\\.phar$" || false let is_php_file filename = (not (is_php_filename_phar filename)) && (is_php_filename filename || is_php_script filename) * In command line tools like git or mercurial , many operations works * when a file , a set of files , or even dirs are passed as parameters . * We want the same with , hence this small helper function that * transform such files_or_dirs into a flag set of filenames . * In command line tools like git or mercurial, many operations works * when a file, a set of files, or even dirs are passed as parameters. * We want the same with pfff, hence this small helper function that * transform such files_or_dirs into a flag set of filenames. *) let find_source_files_of_dir_or_files ?(verbose = false) ?(include_hack = false) xs = Common.files_of_dir_or_files_no_vcs_nofilter xs |> List.filter (fun filename -> note : there was a possible race here because between the time we * do the ' find ' and the time we call is_php_file ( ) , the file may have * disappeared ( this happens for instance because of watchman ) . * Hence the Sys.file_exists guard . * do the 'find' and the time we call is_php_file(), the file may have * disappeared (this happens for instance because of watchman). * Hence the Sys.file_exists guard. *) let valid = Sys.file_exists filename && (is_php_file filename || (include_hack && is_hhi_filename filename)) in if (not valid) && verbose then pr2 ("not analyzing: " ^ filename); valid) |> Common.sort let extract_info_visitor recursor = let globals = ref [ ] in let hooks = { V.default_visitor with V.kinfo = ( fun ( _ k , _ ) i - > ( * most of the time when you use ii_of_any , you want to use * functions like max_min_pos which works only on origin tokens * hence the filtering done here . * * ugly : For PHP we use a fakeInfo only for generating a fake left * brace for abstract methods . let extract_info_visitor recursor = let globals = ref [] in let hooks = { V.default_visitor with V.kinfo = (fun (_k, _) i -> match i.Parse_info.token with | Parse_info.OriginTok _ -> Common.push i globals | _ -> () ) } in begin let vout = V.mk_visitor hooks in recursor vout; List.rev !globals end *) , range x : range let (range_of_origin_ii : Cst_php.tok list -> (int * int) option) = fun ii -> let ii = List.filter Parse_info.is_origintok ii in try let min, max = Parse_info.min_max_ii_by_pos ii in assert (PI.is_origintok max); assert (PI.is_origintok min); let strmax = PI.str_of_info max in Some (PI.pos_of_info min, PI.pos_of_info max + String.length strmax) with | _ -> None e : range V.kexpr = (fun (k,_vx) x -> match x with | Call (Id callname, _args) -> let str = Cst_php.str_of_name callname in Hashtbl.replace h str true; k x | _ -> k x ); } in let visitor = V.mk_visitor hooks in visitor any; Common.hashset_to_list h *) let get_constant_strings_any any = let h = Hashtbl.create 101 in let hooks = { V.default_visitor with V.kconstant = ( fun ( ) x - > match x with | String ( str,_ii ) - > Hashtbl.replace h str true ; | _ - > k x ) ; V.kencaps = ( fun ( ) x - > match x with | EncapsString ( str , _ ii ) - > Hashtbl.replace h str true ; | _ - > k x ) ; } in ( V.mk_visitor hooks ) any ; Common.hashset_to_list h let get_constant_strings_any any = let h = Hashtbl.create 101 in let hooks = { V.default_visitor with V.kconstant = (fun (k,_vx) x -> match x with | String (str,_ii) -> Hashtbl.replace h str true; | _ -> k x ); V.kencaps = (fun (k,_vx) x -> match x with | EncapsString (str, _ii) -> Hashtbl.replace h str true; | _ -> k x ); } in (V.mk_visitor hooks) any; Common.hashset_to_list h *) let get_static_vars_any any = any | > V.do_visit_with_ref ( fun aref - > { V.default_visitor with V.kstmt = ( fun ( ) x - > match x with | StaticVars ( _ tok , xs , _ tok2 ) - > xs | > Ast.uncomma | > List.iter ( fun ( dname , _ affect_opt ) - > Common.push ) ; | _ - > k x ) ; } ) ( * todo ? do isomorphism ? let get_static_vars_any any = any |> V.do_visit_with_ref (fun aref -> { V.default_visitor with V.kstmt = (fun (k,_vx) x -> match x with | StaticVars (_tok, xs, _tok2) -> xs |> Ast.uncomma |> List.iter (fun (dname, _affect_opt) -> Common.push dname aref ); | _ -> k x ); }) let get_returns_any any = V.do_visit_with_ref (fun aref -> { V.default_visitor with V.kstmt = (fun (k,_vx) x -> match x with | Return (_tok1, Some e, _tok2) -> Common.push e aref | _ -> k x )}) any let get_vars_any any = V.do_visit_with_ref (fun aref -> { V.default_visitor with V.kexpr = (fun (k, _vx) x -> match x with | IdVar (dname, _scope) -> Common.push dname aref | Lambda (l_use, _def) -> l_use |> Common.do_option (fun (_tok, xs) -> xs |> Ast.unparen |> Ast.uncomma |> List.iter (function | LexicalVar (_is_ref, dname) -> Common.push dname aref ) ); k x | _ -> k x ); }) any *) let top_statements_of_program ast = ast | > List.map ( function | StmtList xs - > xs | FinalDef _ |NotParsedCorrectly _ | ClassDef _ | FuncDef _ | ConstantDef _ | TypeDef _ | NamespaceDef _ | _ | NamespaceUse _ - > [ ] ) | > List.flatten ( * We often do some analysis on " unit " of code like a function , * a method , or toplevel statements . One can not use the * ' toplevel ' type for that because it contains Class and Interface which * are too coarse grained ; the method granularity is better . * * For instance it makes sense to have a CFG for a function , a method , * or toplevel statements but a CFG for a class does not make sense . let top_statements_of_program ast = ast |> List.map (function | StmtList xs -> xs | FinalDef _|NotParsedCorrectly _ | ClassDef _| FuncDef _ | ConstantDef _ | TypeDef _ | NamespaceDef _ | NamespaceBracketDef _ | NamespaceUse _ -> [] ) |> List.flatten let functions_methods_or_topstms_of_program prog = let funcs = ref [] in let methods = ref [] in let toplevels = ref [] in let visitor = V.mk_visitor { V.default_visitor with V.kfunc_def = (fun (_k, _) def -> match def.f_type with | FunctionRegular -> Common.push def funcs | MethodRegular | MethodAbstract -> Common.push def methods | FunctionLambda -> () ); V.ktop = (fun (k, _) top -> match top with | StmtList xs -> Common.push xs toplevels | _ -> k top ); } in visitor (Program prog); !funcs, !methods, !toplevels do some isomorphisms for declaration vs let get_vars_assignements_any recursor = V.do_visit_with_ref (fun aref -> { V.default_visitor with V.kstmt = (fun (k,_) x -> match x with | StaticVars (_tok, xs, _tok2) -> xs |> Ast.uncomma |> List.iter (fun (dname, affect_opt) -> let s = Ast.str_of_dname dname in affect_opt |> Common.do_option (fun (_tok, scalar) -> Common.push (s, scalar) aref; ); ); | _ -> k x ); V.kexpr = (fun (k,_vx) x -> match x with | Assign (lval, _, e) | AssignOp (lval, _, e) -> k x; (match lval with | IdVar (dname, _scope) -> let s = Ast.str_of_dname dname in Common.push (s, e) aref; | _ -> () ) todo ? AssignRef AssignNew ? | _ -> k x ); } ) recursor |> Common.group_assoc_bykey_eff *)
93350ce6cff2829a7fcdefe6acfb0a8343d2231dd9455208cd484dfdafe97534
exercism/clojurescript
example.cljs
(ns binary-search-tree) (defn value [node] (first node)) (defn left [node] (second node)) (defn right [node] (last node)) (defn singleton [n] [n nil nil]) (defn insert [v node] (if (empty? node) (singleton v) (let [x (value node)] (if (>= x v) [x (insert v (left node)) (right node)] [x (left node) (insert v (right node))])))) (defn from-list [xs] (reduce #(insert %2 %1) nil xs)) (defn to-list [node] (if (empty? node) node (concat (to-list (left node)) [(value node)] (to-list (right node)))))
null
https://raw.githubusercontent.com/exercism/clojurescript/0135bc589c556557397650fe5e52ac7df3d4ddb5/exercises/practice/binary-search-tree/src/example.cljs
clojure
(ns binary-search-tree) (defn value [node] (first node)) (defn left [node] (second node)) (defn right [node] (last node)) (defn singleton [n] [n nil nil]) (defn insert [v node] (if (empty? node) (singleton v) (let [x (value node)] (if (>= x v) [x (insert v (left node)) (right node)] [x (left node) (insert v (right node))])))) (defn from-list [xs] (reduce #(insert %2 %1) nil xs)) (defn to-list [node] (if (empty? node) node (concat (to-list (left node)) [(value node)] (to-list (right node)))))
be629c115df8c081ab0d96c023d9d5ecd574fa3bfacce1d5615cc075db0d1add
alexkazik/qrcode
Kanji.hs
# LANGUAGE BinaryLiterals # # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} module Codec.QRCode.Mode.Kanji ( kanji , kanjiB , kanjiMap ) where import Codec.QRCode.Base import Data.Binary (decode) import qualified Data.Map.Strict as M import qualified Codec.QRCode.Data.ByteStreamBuilder as BSB import Codec.QRCode.Data.QRSegment.Internal import Codec.QRCode.Data.Result import Codec.QRCode.Data.ToInput -- | Generate a segment representing the specified text data encoded as QR code Kanji. -- Since this encoding does neither contain ASCII nor the half width katakana characters -- it may be impossible to encode all text in this encoding. -- -- But it is possible to encode some of it and combine it with others like ISO-8859-1. kanji :: ToText a => a -> Result QRSegment kanji s = case toString s of [] -> pure (constStream mempty) s' -> ((encodeBits 4 0b1000 <> lengthSegment (8, 10, 12) (length s')) <>) . constStream <$> kanjiB s' kanjiB :: [Char] -> Result BSB.ByteStreamBuilder kanjiB s = Result $ mconcat <$> traverse (fmap (BSB.encodeBits 13 . fromIntegral) . (`M.lookup` kanjiMap)) s -- This map is generated, see below on how it was done. kanjiMap :: M.Map Char Word16 kanjiMap = decode "\0\0\0\0\0\0\26ߢ\0Q£\0R§\0X¨\0\14¬\0\138°\0K±\0=´\0\12¶\0·Ã\ \\151\0>÷\0@Î\145\1ßÎ\146\1àÎ\147\1áÎ\148\1âÎ\149\1ãÎ\150\1äÎ\151\1åÎ\ \\152\1æÎ\153\1çÎ\154\1èÎ\155\1éÎ\156\1êÎ\157\1ëÎ\158\1ìÎ\159\1íΠ\1îΡ\1\ \ïΣ\1ðΤ\1ñÎ¥\1òΦ\1óΧ\1ôΨ\1õΩ\1öα\1ÿβ\2\0γ\2\1δ\2\2ε\2\3ζ\2\4Î\ \·\2\5θ\2\6ι\2\7κ\2\8λ\2\9μ\2\10ν\2\11ξ\2\12ο\2\13Ï\128\2\14Ï\129\ \\2\15Ï\131\2\16Ï\132\2\17Ï\133\2\18Ï\134\2\19Ï\135\2\20Ï\136\2\21Ï\137\2\ \\22Ð\129\2FÐ\144\2@Ð\145\2AÐ\146\2BÐ\147\2CÐ\148\2DÐ\149\2EÐ\150\2GÐ\151\ \\2HÐ\152\2IÐ\153\2JÐ\154\2KÐ\155\2LÐ\156\2MÐ\157\2NÐ\158\2OÐ\159\2PР\2Q\ \С\2RТ\2SУ\2TФ\2UÐ¥\2VЦ\2WЧ\2XШ\2YЩ\2ZЪ\2[Ы\2\92Ь\2]Ð\173\2^Ю\ \\2_Я\2`а\2pб\2qв\2rг\2sд\2tе\2uж\2wз\2xи\2yй\2zк\2{л\2|м\2\ \}н\2~о\2\128п\2\129Ñ\128\2\130Ñ\129\2\131Ñ\130\2\132Ñ\131\2\133Ñ\132\ \\2\134Ñ\133\2\135Ñ\134\2\136Ñ\135\2\137Ñ\136\2\138Ñ\137\2\139Ñ\138\2\140\ \Ñ\139\2\141Ñ\140\2\142Ñ\141\2\143Ñ\142\2\144Ñ\143\2\145Ñ\145\2vâ\128\144\ \\0\29â\128\149\0\28â\128\150\0!â\128\152\0%â\128\153\0&â\128\156\0'â\128\ \\157\0(â\128 \0µâ\128¡\0¶â\128¥\0$â\128¦\0#â\128°\0±â\128²\0Lâ\128³\0Mâ\ \\128»\0fâ\132\131\0Nâ\132«\0°â\134\144\0iâ\134\145\0jâ\134\146\0hâ\134\ \\147\0kâ\135\146\0\139â\135\148\0\140â\136\128\0\141â\136\130\0\157â\136\ \\131\0\142â\136\135\0\158â\136\136\0xâ\136\139\0yâ\136\146\0<â\136\154\0\ \£â\136\157\0¥â\136\158\0Gâ\136 \0\154â\136§\0\136â\136¨\0\137â\136©\0\ \\127â\136ª\0~â\136«\0§â\136¬\0¨â\136´\0Hâ\136µ\0¦â\136½\0¤â\137\146\0 â\ \\137 \0Bâ\137¡\0\159â\137¦\0Eâ\137§\0Fâ\137ª\0¡â\137«\0¢â\138\130\0|â\ \\138\131\0}â\138\134\0zâ\138\135\0{â\138¥\0\155â\140\146\0\156â\148\128\ \\2\159â\148\129\2ªâ\148\130\2 â\148\131\2«â\148\140\2¡â\148\143\2¬â\148\ \\144\2¢â\148\147\2\173â\148\148\2¤â\148\151\2¯â\148\152\2£â\148\155\2®â\ \\148\156\2¥â\148\157\2ºâ\148 \2µâ\148£\2°â\148¤\2§â\148¥\2¼â\148¨\2·â\ \\148«\2²â\148¬\2¦â\148¯\2¶â\148°\2»â\148³\2±â\148´\2¨â\148·\2¸â\148¸\2½â\ \\148»\2³â\148¼\2©â\148¿\2¹â\149\130\2¾â\149\139\2´â\150 \0aâ\150¡\0`â\ \\150²\0câ\150³\0bâ\150¼\0eâ\150½\0dâ\151\134\0_â\151\135\0^â\151\139\0[â\ \\151\142\0]â\151\143\0\92â\151¯\0¼â\152\133\0Zâ\152\134\0Yâ\153\128\0Jâ\ \\153\130\0Iâ\153ª\0´â\153\173\0³â\153¯\0²ã\128\128\0\0ã\128\129\0\1ã\128\ \\130\0\2ã\128\131\0\22ã\128\133\0\24ã\128\134\0\25ã\128\135\0\26ã\128\ \\136\01ã\128\137\02ã\128\138\03ã\128\139\04ã\128\140\05ã\128\141\06ã\128\ \\142\07ã\128\143\08ã\128\144\09ã\128\145\0:ã\128\146\0gã\128\147\0lã\128\ \\148\0+ã\128\149\0,ã\128\156\0 ã\129\129\1\31ã\129\130\1 ã\129\131\1!ã\ \\129\132\1\34ã\129\133\1#ã\129\134\1$ã\129\135\1%ã\129\136\1&ã\129\137\1\ \'ã\129\138\1(ã\129\139\1)ã\129\140\1*ã\129\141\1+ã\129\142\1,ã\129\143\1\ \-ã\129\144\1.ã\129\145\1/ã\129\146\10ã\129\147\11ã\129\148\12ã\129\149\1\ \3ã\129\150\14ã\129\151\15ã\129\152\16ã\129\153\17ã\129\154\18ã\129\155\1\ \9ã\129\156\1:ã\129\157\1;ã\129\158\1<ã\129\159\1=ã\129 \1>ã\129¡\1?ã\129\ \¢\1@ã\129£\1Aã\129¤\1Bã\129¥\1Cã\129¦\1Dã\129§\1Eã\129¨\1Fã\129©\1Gã\129\ \ª\1Hã\129«\1Iã\129¬\1Jã\129\173\1Kã\129®\1Lã\129¯\1Mã\129°\1Nã\129±\1Oã\ \\129²\1Pã\129³\1Qã\129´\1Rã\129µ\1Sã\129¶\1Tã\129·\1Uã\129¸\1Vã\129¹\1Wã\ \\129º\1Xã\129»\1Yã\129¼\1Zã\129½\1[ã\129¾\1\92ã\129¿\1]ã\130\128\1^ã\130\ \\129\1_ã\130\130\1`ã\130\131\1aã\130\132\1bã\130\133\1cã\130\134\1dã\130\ \\135\1eã\130\136\1fã\130\137\1gã\130\138\1hã\130\139\1iã\130\140\1jã\130\ \\141\1kã\130\142\1lã\130\143\1mã\130\144\1nã\130\145\1oã\130\146\1pã\130\ \\147\1qã\130\155\0\10ã\130\156\0\11ã\130\157\0\20ã\130\158\0\21ã\130¡\1\ \\128ã\130¢\1\129ã\130£\1\130ã\130¤\1\131ã\130¥\1\132ã\130¦\1\133ã\130§\1\ \\134ã\130¨\1\135ã\130©\1\136ã\130ª\1\137ã\130«\1\138ã\130¬\1\139ã\130\ \\173\1\140ã\130®\1\141ã\130¯\1\142ã\130°\1\143ã\130±\1\144ã\130²\1\145ã\ \\130³\1\146ã\130´\1\147ã\130µ\1\148ã\130¶\1\149ã\130·\1\150ã\130¸\1\151ã\ \\130¹\1\152ã\130º\1\153ã\130»\1\154ã\130¼\1\155ã\130½\1\156ã\130¾\1\157ã\ \\130¿\1\158ã\131\128\1\159ã\131\129\1 ã\131\130\1¡ã\131\131\1¢ã\131\132\ \\1£ã\131\133\1¤ã\131\134\1¥ã\131\135\1¦ã\131\136\1§ã\131\137\1¨ã\131\138\ \\1©ã\131\139\1ªã\131\140\1«ã\131\141\1¬ã\131\142\1\173ã\131\143\1®ã\131\ \\144\1¯ã\131\145\1°ã\131\146\1±ã\131\147\1²ã\131\148\1³ã\131\149\1´ã\131\ \\150\1µã\131\151\1¶ã\131\152\1·ã\131\153\1¸ã\131\154\1¹ã\131\155\1ºã\131\ \\156\1»ã\131\157\1¼ã\131\158\1½ã\131\159\1¾ã\131 \1Àã\131¡\1Áã\131¢\1Âã\ \\131£\1Ãã\131¤\1Äã\131¥\1Åã\131¦\1Æã\131§\1Çã\131¨\1Èã\131©\1Éã\131ª\1Êã\ \\131«\1Ëã\131¬\1Ìã\131\173\1Íã\131®\1Îã\131¯\1Ïã\131°\1Ðã\131±\1Ñã\131²\ \\1Òã\131³\1Óã\131´\1Ôã\131µ\1Õã\131¶\1Öã\131»\0\5ã\131¼\0\27ã\131½\0\18ã\ \\131¾\0\19ä¸\128\5êä¸\129\13\26ä¸\131\105ä¸\135\16\28ä¸\136\11$ä¸\137\9Ï\ \ä¸\138\11#ä¸\139\6zä¸\141\153ä¸\142\16\158ä¸\144\17 ä¸\145\6\14ä¸\148\7\ \\14ä¸\149\17¡ä¸\150\11¢ä¸\151\18\128ä¸\152\7µä¸\153\15xä¸\158\11%両\16ü\ \並\15\128个\17¢ä¸\173\13\6丱\17£ä¸²\88丶\17¤ä¸¸\7[丹\12Ï主\10e丼\ \\17¥ä¸¿\17¦ä¹\130\17§ä¹\131\14Tä¹\133\7¶ä¹\139\14Vä¹\141\14!ä¹\142\8Áä¹\ \\143\15Òä¹\149\27(ä¹\150\17¨ä¹\151\11&ä¹\152\17©ä¹\153\6sä¹\157\8#ä¹\158\ \\8îä¹\159\16gä¹¢\19ää¹±\16Ðä¹³\14;ä¹¾\7#äº\128\7\148äº\130\17ªäº\133\17«\ \äº\134\16ùäº\136\16\156äº\137\12Häº\138\17\173äº\139\10\22äº\140\141äº\ \\142\17°äº\145\6\29äº\146\8Ýäº\148\8Üäº\149\5ääº\152\17jäº\153\17iäº\155\ \\9qäº\156\5\159äº\158\17±äº\159\17²äº \17³äº¡\15Ó亢\17´äº¤\8ð亥\5å亦\ \\16\18亨\7Ü享\7Ý京\7Þäº\173\13`亮\16ú亰\17µäº³\17¶äº¶\17·äºº\11lä»\ \\128\10\153ä»\129\11mä»\130\17¼ä»\132\17ºä»\134\17»ä»\135\7·ä»\138\9aä»\ \\139\6®ä»\141\17¹ä»\142\17¸ä»\143\15gä»\148\9åä»\149\9ää»\150\12|ä»\151\ \\17½ä»\152\154ä»\153\11åä»\157\0\23ä»\158\17¾ä»\159\17À代\12£ä»¤\17\31ä\ \»¥\5Èä»\173\17¿ä»®\6|ä»°\8\2仲\13\7ä»¶\8\143ä»·\17Áä»»\14Cä¼\129\7iä¼\ \\137\17Âä¼\138\5Éä¼\141\8Þä¼\142\7jä¼\143\15Zä¼\144\14°ä¼\145\7¸ä¼\154\6\ \¯ä¼\156\17åä¼\157\13 ä¼¯\14\140ä¼°\17Ää¼´\14ºä¼¶\17 伸\11L伺\9æä¼¼\10\ \\23ä¼½\6~ä½\131\13Oä½\134\12Áä½\135\17Èä½\141\5Êä½\142\13aä½\143\10\154ä\ \½\144\9rä½\145\16\131ä½\147\12\140ä½\149\6}ä½\151\17Çä½\153\16\157ä½\154\ \\17Ãä½\155\17Åä½\156\9¬ä½\157\17Æä½\158\19\131佩\17Î佯\17Ñä½°\17Ïä½³\6\ \\128ä½µ\15yä½¶\17Éä½»\17Íä½¼\8ñ使\9çä¾\131\7$ä¾\134\17Òä¾\136\17Êä¾\139\ \\17!ä¾\141\10\24ä¾\143\17Ëä¾\145\17Ðä¾\150\17Óä¾\152\17Ìä¾\155\7ßä¾\157\ \\5Ëä¾ \7à価\6\127侫\19\132ä¾\173\16\25ä¾®\15N侯\8òä¾µ\11Nä¾¶\16õ便\ \\15\150ä¿\130\8Wä¿\131\12cä¿\132\6¢ä¿\138\10²ä¿\142\17×ä¿\144\17Üä¿\145\ \\17Úä¿\148\17Õä¿\151\12mä¿\152\17Øä¿\154\17Ûä¿\155\17Ùä¿\157\15\155ä¿\ \\159\17Öä¿¡\11Mä¿£\16\19俤\17Ýä¿¥\17Þä¿®\10\131俯\17ë俳\14o俵\15\21ä\ \¿¶\17æä¿¸\15®ä¿º\6t俾\17êå\128\133\17äå\128\134\17íå\128\137\121å\128\ \\139\8Âå\128\141\14{å\128\143\23Åå\128\145\17ìå\128\146\13¼å\128\148\17á\ \å\128\150\8ôå\128\153\8óå\128\154\17ßå\128\159\10Xå\128¡\17çå\128£\15\ \\173å\128¤\12ìå\128¥\17ãå\128¦\8\145å\128¨\17àå\128©\17èå\128ª\17âå\128«\ \\17\15å\128¬\17éå\128\173\17`å\128¶\8$å\128¹\8\144å\129\131\17îå\129\135\ \\17ïå\129\136\17óå\129\137\5Ìå\129\143\15\142å\129\144\17òå\129\149\17ñå\ \\129\150\17õå\129\154\17ôå\129\156\13bå\129¥\8\146å\129¬\17öå\129²\10Cå\ \\129´\12då\129µ\13cå\129¶\84å\129¸\17÷å\129½\7\149å\130\128\17øå\130\133\ \\17úå\130\141\15Ôå\130\145\8\134å\130\152\9Ðå\130\153\14õå\130\154\17ùå\ \\130¬\9\131å\130\173\16¢å\130²\17üå\130³\18\2å\130´\17ûå\130µ\9\130å\130\ \·\10Ýå\130¾\8Xå\131\130\18\3å\131\133\8\13å\131\137\18\0å\131\138\18\1å\ \\131\141\13íå\131\143\12\92å\131\145\7áå\131\149\15ìå\131\150\18\4å\131\ \\154\16ûå\131\158\18\5å\131£\18\8å\131¥\18\6å\131§\12-å\131\173\18\7å\ \\131®\18\9å\131µ\18\11å\131¹\18\10å\131»\15\134å\132\128\7\150å\132\129\ \\18\13å\132\130\18\14å\132\132\6må\132\137\18\12å\132\146\10rå\132\148\ \\18\17å\132\149\18\16å\132\150\18\15å\132\152\17Ôå\132\154\18\18å\132\ \\159\10Þå\132¡\18\19å\132ª\16\132å\132²\16Wå\132·\18\21å\132º\18\20å\132\ \»\18\23å\132¼\18\22å\132¿\18\24å\133\128\18\25å\133\129\5òå\133\131\8³å\ \\133\132\8Zå\133\133\10\155å\133\134\13\27å\133\135\7âå\133\136\11æå\133\ \\137\8õå\133\139\9Nå\133\140\18\27å\133\141\16Få\133\142\13¥å\133\144\10\ \\25å\133\146\18\26å\133\148\18\28å\133\154\13½å\133\156\7\21å\133¢\18\29\ \å\133¥\14<å\133¨\12\19å\133©\18\31å\133ª\18 å\133«\14ªå\133¬\8öå\133\173\ \\17Zå\133®\18!å\133±\7äå\133µ\15zå\133¶\12tå\133·\8/å\133¸\13\148å\133¼\ \\8\147å\134\128\18\34å\134\130\18#å\134\133\14 å\134\134\6>å\134\137\18&\ \å\134\138\9»å\134\140\18%å\134\141\9\132å\134\143\18'å\134\144\26,å\134\ \\145\18(å\134\146\15àå\134\147\18)å\134\149\18*å\134\150\18+å\134\151\11\ \'å\134\153\10Jå\134 \7%å\134¢\18.å\134¤\18,å\134¥\16;å\134¦\18-å\134¨\15\ \9å\134©\18/å\134ª\180å\134«\181å\134¬\13¾å\134°\185å\134±\183å\134²\184å\ \\134³\182å\134´\9¡å\134µ\186å\134¶\16hå\134·\17\34å\134½\187å\135\132\11\ \¦å\135\133\188å\135\134\10¹å\135\137\189å\135\139\13\28å\135\140\16ýå\ \\135\141\13Àå\135\150\18\131å\135\155\18:å\135\156\31#å\135\157\8\3å\135\ \ \18;å\135¡\15ýå\135¦\10Èå\135§\12ºå\135©\18=å\135ª\14\34å\135\173\18>å\ \\135°\18@å\135±\6Íå\135µ\18Aå\135¶\7åå\135¸\14\10å\135¹\6Zå\135º\10¯å\ \\135½\14\159å\135¾\18Bå\136\128\13Áå\136\131\11nå\136\132\18Cå\136\134\ \\15jå\136\135\11Øå\136\136\7 å\136\138\7'å\136\139\18Då\136\142\18Få\136\ \\145\8Yå\136\148\18Eå\136\151\171å\136\157\10Éå\136¤\14»å\136¥\15\138å\ \\136§\18Gå\136©\16Øå\136ª\18Hå\136®\18Iå\136°\13Þå\136³\18Jå\136¶\11§å\ \\136·\9¼å\136¸\8\148å\136¹\18Kå\136º\9èå\136»\9Oå\137\131\13då\137\132\ \\18Må\137\135\12eå\137\138\9\173å\137\139\18Nå\137\140\18Oå\137\141\12\ \\15å\137\143\18Lå\137\148\18Qå\137\150\15Õå\137\155\9Då\137\158\18På\137\ \£\8\149å\137¤\9\156å\137¥\14\141å\137©\18Tå\137ª\18Rå\137¯\15[å\137°\11(\ \å\137±\18[å\137²\7\4å\137³\18Uå\137´\18Så\137µ\12.å\137½\18Wå\137¿\18Vå\ \\138\131\6ãå\138\135\8\128å\138\136\18\92å\138\137\16ëå\138\141\18Xå\138\ \\145\18]å\138\146\18Zå\138\148\18Yå\138\155\17\13å\138\159\8÷å\138 \6\ \\129å\138£\172å\138©\10Õå\138ª\13·å\138«\9Eå\138¬\18`å\138\173\18aå\138±\ \\17#å\138´\17Jå\138µ\18cå\138¹\8øå\138¼\18bå\138¾\6Îå\139\129\18då\139\ \\131\15õå\139\133\13:å\139\135\16\133å\139\137\15\151å\139\141\18eå\139\ \\146\29Óå\139\149\13îå\139\151\18få\139\152\7(å\139\153\161å\139\157\10ß\ \å\139\158\18gå\139\159\15¥å\139 \18kå\139¢\11¨å\139£\18hå\139¤\8\14å\139\ \¦\18iå\139§\7)å\139²\8Må\139³\18lå\139µ\18må\139¸\18nå\139¹\18oå\139º\10\ \Yå\139¾\8ùå\139¿\16\92å\140\129\16få\140\130\145å\140\133\15¯å\140\134\ \\18på\140\136\18qå\140\141\18så\140\143\18uå\140\144\18tå\140\149\18vå\ \\140\150\6{å\140\151\15ëå\140\153\9ºå\140\154\18wå\140\157\128å\140 \10à\ \å\140¡\7çå\140£\18xå\140ª\14Ùå\140¯\18yå\140±\18zå\140³\18{å\140¸\18|å\ \\140¹\15\3å\140º\8&å\140»\5ãå\140¿\13ýå\141\128\18}å\141\129\10\156å\141\ \\131\11çå\141\133\18\127å\141\134\18~å\141\135\10áå\141\136\8ßå\141\137\ \\18\129å\141\138\14¼å\141\141\18\130å\141\145\14Úå\141\146\12rå\141\147\ \\12¬å\141\148\7æå\141\151\14,å\141\152\12Ðå\141\154\14\142å\141\156\15íå\ \\141\158\18\132å\141 \11èå\141¦\8Tå\141©\18\133å\141®\18\134å\141¯\6\11å\ \\141°\5óå\141±\7kå\141³\12få\141´\7°å\141µ\16Ñå\141·\18\137å\141¸\6uå\ \\141»\18\136å\141¿\7èå\142\130\18\138å\142\132\16oå\142\150\18\139å\142\ \\152\17\16å\142\154\8úå\142\159\8´å\142 \18\140å\142¥\18\142å\142¦\18\ \\141å\142¨\11~å\142©\6\24å\142\173\6=å\142®\18\143å\142°\18\144å\142³\8µ\ \å\142¶\18\145å\142»\7Îå\143\130\9Ñå\143\131\18\146å\143\136\16\20å\143\ \\137\9så\143\138\7¹å\143\139\16\134å\143\140\12/å\143\141\14½å\143\142\ \\10{å\143\148\10¦å\143\150\10få\143\151\10så\143\153\10Öå\143\155\14¾å\ \\143\159\18\149å\143¡\6\34å\143¢\120å\143£\8ûå\143¤\8Ãå\143¥\8%å\143¨\18\ \\153å\143©\12Àå\143ª\12¼å\143«\7éå\143¬\10âå\143\173\18\154å\143®\18\152\ \å\143¯\6\130å\143°\12¤å\143±\106å\143²\9êå\143³\6\5å\143¶\7\16å\143·\9Få\ \\143¸\9éå\143º\18\155å\144\129\18\156å\144\131\7¨å\144\132\6åå\144\136\9\ \Gå\144\137\7§å\144\138\13]å\144\139\6\4å\144\140\13ïå\144\141\16<å\144\ \\142\9\0å\144\143\16Ùå\144\144\13¦å\144\145\8üå\144\155\8Nå\144\157\18¥å\ \\144\159\8!å\144 \15éå\144¦\14Ûå\144©\18¤å\144«\7\92å\144¬\18\159å\144\ \\173\18 å\144®\18¢å\144¶\18£å\144¸\7ºå\144¹\11\129å\144»\15kå\144¼\18¡å\ \\144½\18\157å\144¾\8áå\145\128\18\158å\145\130\17Cå\145\134\15°å\145\136\ \\13få\145\137\8àå\145\138\9På\145\142\18¦å\145\145\14\27å\145\159\18ªå\ \\145¨\10|å\145ª\10tå\145°\18\173å\145±\18«å\145³\16!å\145µ\18¨å\145¶\18±\ \å\145·\18¬å\145»\18¯å\145¼\8Äå\145½\16=å\146\128\18°å\146\132\18²å\146\ \\134\18´å\146\139\9®å\146\140\17aå\146\142\18©å\146\143\18§å\146\144\18³\ \å\146\146\18®å\146¢\18¶å\146¤\18Âå\146¥\18¸å\146¨\18¼å\146«\18Àå\146¬\18\ \¹å\146¯\18Ýå\146²\9§å\146³\6Ðå\146¸\18·å\146¼\18Äå\146½\5ôå\146¾\18Ãå\ \\147\128\5£å\147\129\15)å\147\130\18Áå\147\132\18ºå\147\135\18µå\147\136\ \\18»å\147\137\9\134å\147\152\18Åå\147¡\5õå\147¢\18Îå\147¥\18Æå\147¦\18Çå\ \\147¨\10ãå\147©\16\9å\147\173\18Ìå\147®\18Ëå\147²\13\142å\147º\18Íå\147½\ \\18Êå\148\132\6\19å\148\134\9tå\148\135\11Oå\148\143\18Èå\148\144\13Âå\ \\148\148\18Éå\148\150\5 å\148®\18Óå\148¯\16\130å\148±\10åå\148³\18Ùå\148\ \¸\18Øå\148¹\18Ïå\148¾\12\129å\149\128\18Ðå\149\132\12\173å\149\133\18Õå\ \\149\134\10äå\149\140\18Òå\149\143\16bå\149\147\8[å\149\150\18Öå\149\151\ \\18×å\149\156\18Ôå\149\157\18Úå\149£\18Ñå\149»\18àå\149¼\18åå\149¾\18áå\ \\150\128\18Üå\150\131\18æå\150\132\12\16å\150\135\18èå\150\137\9\1å\150\ \\138\18Þå\150\139\13\29å\150\152\18âå\150\153\18Ûå\150\154\7+å\150\156\7\ \lå\150\157\7\5å\150\158\18ãå\150\159\18ßå\150§\8\150å\150¨\18éå\150©\18ç\ \å\150ª\122å\150«\7©å\150¬\7êå\150®\18äå\150°\82å\150¶\6#å\151\132\18íå\ \\151\133\18ëå\151\135\19%å\151\148\18ðå\151\154\18êå\151\156\18îå\151\ \\159\18ìå\151£\9ëå\151¤\18ïå\151·\18òå\151¹\18÷å\151½\18õå\151¾\18ôå\152\ \\134\12Ñå\152\137\6\131å\152\148\18ñå\152\150\18óå\152\151\10æå\152\152\ \\6\18å\152\155\18öå\152©\6\156å\152¯\19\2å\152±\11:å\152²\18ýå\152´\18ûå\ \\152¶\18üå\152¸\18þå\153\130\6\28å\153\140\12\24å\153\142\18øå\153\144\ \\18ùå\153\155\7\26å\153¤\19\1å\153¨\7må\153ª\19\4å\153«\19\0å\153¬\19\3å\ \\153´\15lå\153¸\14\19å\153º\14¶å\154\128\19\6å\154\134\19\5å\154\135\6äå\ \\154\138\19\7å\154\143\19\10å\154\148\19\9å\154 \19\8å\154¢\14Xå\154¥\19\ \\11å\154®\19\12å\154´\19\14å\154¶\19\13å\154¼\19\16å\155\128\19\19å\155\ \\129\19\17å\155\130\19\15å\155\131\19\18å\155\136\19\20å\155\142\19\21å\ \\155\145\19\22å\155\147\19\23å\155\151\19\24å\155\152\18$å\155\154\10zå\ \\155\155\9ìå\155\158\6±å\155 \5öå\155£\12ãå\155®\19\25å\155°\9bå\155²\5Í\ \å\155³\11}å\155¹\19\26å\155º\8Åå\155½\9Qå\155¿\19\28å\156\128\19\27å\156\ \\131\15\158å\156\132\19\29å\156\136\19\31å\156\137\19\30å\156\139\19 å\ \\156\141\19!å\156\143\8\151å\156\146\6@å\156\147\19\34å\156\150\19$å\156\ \\152\19#å\156\156\19&å\156\159\13¹å\156¦\19'å\156§\5³å\156¨\9\157å\156\ \\173\8\92å\156°\12îå\156·\19(å\156¸\19)å\156»\19+å\157\128\19,å\157\130\ \\9¢å\157\135\8\15å\157\138\15Öå\157\142\19*å\157\143\19-å\157\144\9\127å\ \\157\145\9\2å\157¡\191å\157¤\9cå\157¦\12Òå\157©\19.å\157ª\13Xå\157¿\192å\ \\158\130\11\130å\158\136\190å\158\137\193å\158\139\8^å\158\147\194å\158 \ \\195å\158¢\9\3å\158£\6ßå\158¤\197å\158ª\198å\158°\199å\158³\196å\159\128\ \\19/å\159\131\19:å\159\134\19;å\159\139\16\4å\159\142\11)å\159\146\19=å\ \\159\147\19>å\159\148\19<å\159\150\19@å\159\156\14Wå\159\159\5æå\159 \15\ \5å\159£\19Aå\159´\11;å\159·\107å\159¹\14|å\159º\7nå\159¼\9©å \128\15øå \ \\130\13ðå \133\8\152å \134\12\141å \138\19?å \139\19Bå \149\12\130å \153\ \\19Cå \157\19Då ¡\19Få ¤\13gå ª\7,å ¯\31\31å °\6Aå ±\15±å ´\11*å µ\13§å \ \º\9¤å ½\19Lå¡\128\15{å¡\129\17\27å¡\138\6²å¡\139\19Hå¡\145\12\25å¡\146\ \\19Kå¡\148\13Ãå¡\151\13¨å¡\152\13Äå¡\153\14·å¡\154\13Kå¡\158\9\135å¡¢\19\ \Gå¡©\6Vå¡«\13\149å¡°\19I塲\19E塵\11o塹\19M塾\10\173å¢\131\7ëå¢\133\ \\19Nå¢\147\15¦å¢\151\12]å¢\156\13Då¢\159\19P墨\15î墫\19Q墮\19V墳\15m\ \墸\19U墹\19O墺\19R墻\19T墾\9då£\129\15\135å£\133\19Wå£\135\12äå£\ \\138\6³å£\140\11+å£\145\19Yå£\147\19Xå£\149\9Hå£\151\19Zå£\152\19\92å£\ \\153\19[å£\156\19^å£\158\19Så£\159\19`壤\19_壥\19]士\9í壬\11p壮\123\ \壯\19a声\11ºå£±\5ë売\14\132壷\13Y壹\19c壺\19b壻\19d壼\19e壽\19f\ \å¤\130\19gå¤\137\15\143å¤\138\19hå¤\143\6\132å¤\144\19iå¤\149\16\155å¤\ \\150\6Ïå¤\152\18\135å¤\153\10§å¤\154\12}å¤\155\19jå¤\156\16i夢\162夥\ \\19l大\12¥å¤©\13\150太\12~夫\156夬\19må¤\173\19n央\6[失\108夲\19o\ \夷\5Î夸\19p夾\19qå¥\132\6Bå¥\135\7oå¥\136\14\30å¥\137\15²å¥\142\19uå¥\ \\143\124å¥\144\19tå¥\145\8_å¥\148\15úå¥\149\19så¥\151\13Åå¥\152\19wå¥\ \\154\19v奠\19y奢\19x奥\6\92奧\19z奨\10ç奩\19|奪\12Ä奬\19{奮\15q\ \女\10×奴\13ºå¥¸\19\128好\9\4å¦\129\19\129å¦\130\14@å¦\131\14Üå¦\132\ \\16Oå¦\138\14Då¦\141\19\138å¦\147\7\151å¦\150\16¤å¦\153\16-å¦\155\19êå¦\ \\157\19\130妣\19\133妥\12\131妨\15×妬\13©å¦²\19\134妹\16\5妻\9\136\ \妾\10èå§\134\19\135å§\137\9ïå§\139\9îå§\144\5·å§\145\8Æå§\147\11©å§\148\ \\5Ïå§\153\19\139å§\154\19\140å§\156\19\137å§¥\6\23姦\7-姨\19\136姪\16\ \Cå§«\15\16å§¶\5¦å§»\5÷å§¿\9ðå¨\129\5Ðå¨\131\5¡å¨\137\19\145å¨\145\19\143\ \å¨\152\16:å¨\154\19\146å¨\156\19\144å¨\159\19\142娠\11P娥\19\141娩\15\ \\152娯\8â娵\19\150娶\19\151娼\10éå©\128\19\147å©\129\17Kå©\134\14kå©\ \\137\19\149å©\154\9eå©¢\19\152婦\157婪\19\153婬\19\148å©¿\169åª\146\ \\14}åª\154\19\154åª\155\15\17媼\19\155媽\19\159媾\19\156å«\129\6\133å\ \«\130\19\158å«\137\109å«\139\19\157å«\140\8\153å«\144\19«å«\150\19¤å«\ \\151\19¡å«¡\13\4å«£\19 å«¦\19¢å«©\19£å«º\19¥å«»\19¦å¬\137\7på¬\139\19¨å¬\ \\140\19§å¬\150\19©å¬¢\11,嬪\19¬å¬¬\13Z嬰\6$嬲\19ªå¬¶\19\173嬾\19®å\ \\173\128\19±å\173\131\19¯å\173\133\19°å\173\144\9ñå\173\145\19²å\173\148\ \\9\5å\173\149\19³å\173\151\10\26å\173\152\12vå\173\154\19´å\173\155\19µå\ \\173\156\9ùå\173\157\9\6å\173\159\16På\173£\7\135å\173¤\8Çå\173¥\19¶å\ \\173¦\6÷å\173©\19·å\173«\12wå\173°\19¸å\173±\19áå\173³\19¹å\173µ\19ºå\ \\173¸\19»å\173º\19½å®\128\19¾å®\131\19Àå®\133\12®å®\135\6\6å®\136\10gå®\ \\137\5Àå®\139\126å®\140\7.å®\141\103å®\143\9\7å®\149\13Æå®\151\10\128å®\ \\152\7/å®\153\13\8å®\154\13hå®\155\5¶å®\156\7\152å®\157\15³å®\159\10@客\ \\7±å®£\11é室\10:宥\16\135宦\19Áå®®\7»å®°\9\137害\6Ñå®´\6C宵\10êå®¶\ \\6\134宸\19Â容\16¥å®¿\10¨å¯\130\10bå¯\131\19Ãå¯\132\7qå¯\133\14\16å¯\ \\134\16'å¯\135\19Äå¯\137\19Åå¯\140\158å¯\144\19Çå¯\146\7&å¯\147\85å¯\148\ \\19Æå¯\155\70å¯\157\11Qå¯\158\19Ëå¯\159\9À寡\6\135寢\19Ê寤\19È寥\19Ì\ \實\19É寧\14J寨\22K審\11R寫\19Í寮\16þ寰\19Î寳\19Ð寵\13\30寶\19Ï\ \寸\11¡å¯º\10\27対\12\142寿\10uå°\129\15Uå°\130\11êå°\132\10Kå°\133\19\ \Ñå°\134\10ëå°\135\19Òå°\136\19Óå°\137\5Ñå°\138\12xå°\139\11qå°\141\19Ôå°\ \\142\13ñå°\143\10ìå°\145\10íå°\147\19Õå°\150\11ëå°\154\10îå° \19Öå°¢\19×\ \å°¤\16^å°¨\19Øå°\173\8\4å°±\10\129å°¸\19Ùå°¹\19Úå°º\10Zå°»\11Kå°¼\142å°½\ \\11så°¾\14öå°¿\14Aå±\128\8\7å±\129\19Ûå±\133\7Ïå±\134\19Üå±\136\8<å±\138\ \\14\13å±\139\6nå±\141\9òå±\142\19Ýå±\143\19àå±\144\19ßå±\145\8;å±\147\19\ \Þå±\149\13\151å±\158\12nå± \13ªå±¡\10F層\127å±¥\16Ú屬\19âå±®\19ã屯\14\ \\20å±±\9Òå±¶\19åå±¹\19æå²\140\19çå²\144\7rå²\145\19èå²\148\19é岡\6j岨\ \\12\26岩\7b岫\19ë岬\16&å²±\12\144å²³\6øå²¶\19íå²·\19ï岸\7]å²»\19ìå²¼\ \\19îå²¾\19ñå³\133\19ðå³\135\19òå³\153\19óå³ \13û峡\7ì峨\6£å³©\19ô峪\ \\19ùå³\173\19÷峯\15µå³°\15´å³¶\13Ç峺\19öå³»\10³å³½\19õå´\135\11\146å´\ \\139\19úå´\142\9¨å´\145\20\0å´\148\20\1å´\149\19ûå´\150\6Òå´\151\19üå´\ \\152\20\5å´\153\20\4å´\154\20\3å´\155\19ÿå´\159\19þå´¢\20\2å´©\15¶åµ\139\ \\20\9åµ\140\20\6åµ\142\20\8åµ\144\16Òåµ\146\20\7åµ\156\19ý嵩\11\147嵬\ \\20\10嵯\9uåµ³\20\11åµ¶\20\12å¶\130\20\15å¶\132\20\14å¶\135\20\13å¶\139\ \\13Èå¶\140\19øå¶\144\20\21å¶\157\20\17å¶¢\20\16嶬\20\18å¶®\20\19å¶·\20\ \\22嶺\17$å¶¼\20\23å¶½\20\20å·\137\20\24å·\140\7^å·\141\20\25å·\146\20\ \\27å·\147\20\26å·\150\20\28å·\155\20\29å·\157\11ìå·\158\10\130å·¡\10Äå·£\ \\12Cå·¥\9\8å·¦\9vå·§\9\9å·¨\7Ðå·«\20\30å·®\9wå·±\8Èå·²\20\31å·³\16$å·´\ \\14bå·µ\20 å··\9\10å·»\7*å·½\12Æå·¾\8\16å¸\130\9óå¸\131\15:å¸\134\14¿å¸\ \\139\20!å¸\140\7så¸\145\20$å¸\150\13\31å¸\153\20#å¸\154\20\34å¸\155\20%å\ \¸\157\13i帥\11\131師\9ôå¸\173\11È帯\12\145帰\7\129帳\13 帶\20&帷\ \\20'常\11-帽\15Øå¹\128\20*å¹\131\20)å¹\132\20(å¹\133\15]å¹\135\201å¹\ \\140\15ùå¹\142\20+å¹\148\20-å¹\149\16\11å¹\151\20,å¹\159\20.幡\14¦å¹¢\ \\20/å¹£\15|幤\200å¹²\71å¹³\15}å¹´\14Nå¹µ\202å¹¶\203幸\9\11å¹¹\72幺\20\ \4å¹»\8¶å¹¼\16£å¹½\16\136å¹¾\7t广\206åº\129\13!åº\131\9\12åº\132\10ïåº\ \\135\14Ýåº\138\10ðåº\143\10Øåº\149\13jåº\150\15·åº\151\13\152åº\154\9\13\ \åº\156\15;庠\207度\13¸åº§\9\128庫\8Éåº\173\13k庵\5Á庶\10Î康\9\14åº\ \¸\16¦å»\129\208å»\130\209å»\131\14på»\136\20:å»\137\175å»\138\17Lå»\143\ \\20<å»\144\20;å»\147\6æå»\150\20@å»\154\20Cå»\155\20Då»\157\20Bå»\159\15\ \\31å» \10ñ廡\20F廢\20E廣\20A廨\20G廩\20H廬\20Iå»°\20Lå»±\20J廳\20\ \Kå»´\20Må»¶\6Då»·\13l廸\20N建\8\154å»»\6´å»¼\14U廾\20O廿\149å¼\129\ \\15\153å¼\131\20På¼\132\17Må¼\137\20Qå¼\138\15~å¼\139\20Tå¼\140\17\159å¼\ \\141\17¯å¼\143\10.å¼\144\143å¼\145\20Uå¼\147\7¼å¼\148\13\34å¼\149\5øå¼\ \\150\20Vå¼\151\15då¼\152\9\15å¼\155\12ïå¼\159\13må¼¥\16m弦\8·å¼§\8Ê弩\ \\20Wå¼\173\20X弯\20^å¼±\10cå¼µ\13#å¼·\7í弸\20Yå¼¼\15\10å¼¾\12åå½\129\ \\20Zå½\136\20[å½\138\7îå½\140\20\92å½\142\20]å½\145\20_å½\147\13Öå½\150\ \\20`å½\151\20aå½\153\20bå½\156\20Så½\157\20R彡\20cå½¢\8`彦\15\6彩\9\ \\138彪\15\22彫\13$彬\15*å½\173\20då½°\10òå½±\6%å½³\20eå½·\20få½¹\16på\ \½¼\14Þ彿\20iå¾\128\6]å¾\129\11ªå¾\130\20hå¾\131\20gå¾\132\8aå¾\133\12\ \\146å¾\135\20må¾\136\20kå¾\138\20jå¾\139\16åå¾\140\8ãå¾\144\10Ùå¾\145\20\ \lå¾\146\13«å¾\147\10\157å¾\151\13þå¾\152\20på¾\153\20oå¾\158\20nå¾ \20qå\ \¾¡\8ä徨\20r復\15\92循\10ºå¾\173\20så¾®\14÷å¾³\13ÿå¾´\13%å¾¹\13\143å¾¼\ \\20tå¾½\7\138å¿\131\11Så¿\133\15\11å¿\140\7uå¿\141\14Eå¿\150\20uå¿\151\9\ \õå¿\152\15Ùå¿\153\15Úå¿\156\6^å¿\157\20zå¿ \13\9忤\20wå¿«\6µå¿°\20«å¿±\ \\20y念\14O忸\20xå¿»\20v忽\9Zå¿¿\20|æ\128\142\20\131æ\128\143\20\137æ\ \\128\144\20\129æ\128\146\13»æ\128\149\20\134æ\128\150\15<æ\128\153\20\ \\128æ\128\155\20\133æ\128\156\17%æ\128\157\9öæ\128 \12\147æ\128¡\20}æ\ \\128¥\7½æ\128¦\20\136æ\128§\11«æ\128¨\6Eæ\128©\20\130æ\128ª\6¶æ\128«\20\ \\135æ\128¯\7ïæ\128±\20\132æ\128º\20\138æ\129\129\20\140æ\129\130\20\150æ\ \\129\131\20\148æ\129\134\20\145æ\129\138\20\144æ\129\139\176æ\129\141\20\ \\146æ\129\144\7ðæ\129\146\9\16æ\129\149\10Úæ\129\153\20\153æ\129\154\20\ \\139æ\129\159\20\143æ\129 \20~æ\129¢\6¸æ\129£\20\147æ\129¤\20\149æ\129¥\ \\12ðæ\129¨\9fæ\129©\6væ\129ª\20\141æ\129«\20\152æ\129¬\20\151æ\129\173\7\ \ñæ\129¯\12gæ\129°\7\6æ\129µ\8bæ\129·\20\142æ\130\129\20\154æ\130\131\20\ \\157æ\130\132\20\159æ\130\137\10;æ\130\139\20¥æ\130\140\13næ\130\141\20\ \\155æ\130\146\20£æ\130\148\6·æ\130\150\20¡æ\130\151\20¢æ\130\154\20\158æ\ \\130\155\20 æ\130\159\8åæ\130 \16\137æ\130£\73æ\130¦\68æ\130§\20¤æ\130©\ \\14Yæ\130ª\5«æ\130²\14ßæ\130³\20{æ\130´\20ªæ\130µ\20®æ\130¶\16cæ\130¸\20\ \§æ\130¼\13Éæ\130½\20¬æ\131\133\11.æ\131\134\20\173æ\131\135\14\21æ\131\ \\145\17fæ\131\147\20©æ\131\152\20¯æ\131\154\9[æ\131\156\11Éæ\131\159\5Òæ\ \\131 \20¨æ\131¡\20¦æ\131£\129æ\131§\20\156æ\131¨\9Óæ\131°\12\132æ\131±\ \\20»æ\131³\12:æ\131´\20¶æ\131¶\20³æ\131·\20´æ\131¹\10dæ\131º\20·æ\131»\ \\20ºæ\132\128\20µæ\132\129\10\132æ\132\131\20¸æ\132\134\20²æ\132\136\16z\ \æ\132\137\16yæ\132\141\20¼æ\132\142\20½æ\132\143\5Óæ\132\149\20±æ\132\ \\154\80æ\132\155\5¤æ\132\159\74æ\132¡\20¹æ\132§\20Áæ\132¨\20Àæ\132¬\20Åæ\ \\132´\20Ææ\132¼\20Äæ\132½\20Çæ\132¾\20¿æ\132¿\20Ãæ\133\130\20Èæ\133\132\ \\20Éæ\133\135\20¾æ\133\136\10\28æ\133\138\20Âæ\133\139\12\148æ\133\140\9\ \\17æ\133\141\20°æ\133\142\11Tæ\133\147\20Öæ\133\149\15§æ\133\152\20Ìæ\ \\133\153\20Íæ\133\154\20Îæ\133\157\20Õæ\133\159\20Ôæ\133¢\16\29æ\133£\75\ \æ\133¥\20Òæ\133§\8dæ\133¨\6Óæ\133«\20Ïæ\133®\16öæ\133¯\20Ñæ\133°\5Ôæ\133\ \±\20Óæ\133³\20Êæ\133´\20Ðæ\133µ\20׿\133¶\8cæ\133·\20Ëæ\133¾\16¼æ\134\ \\130\16\138æ\134\135\20Úæ\134\138\20Þæ\134\142\12^æ\134\144\177æ\134\145\ \\20ßæ\134\148\20Üæ\134\150\20Ùæ\134\153\20Øæ\134\154\20Ýæ\134¤\15næ\134§\ \\13òæ\134©\8eæ\134«\20àæ\134¬\20Ûæ\134®\20áæ\134²\8\155æ\134¶\6oæ\134º\ \\20éæ\134¾\76æ\135\131\20çæ\135\134\20èæ\135\135\9gæ\135\136\20ææ\135\ \\137\20äæ\135\138\20ãæ\135\139\20êæ\135\140\20âæ\135\141\20ìæ\135\144\6¹\ \æ\135£\20îæ\135¦\20íæ\135²\13&æ\135´\20ñæ\135¶\20ïæ\135·\20åæ\135¸\8\156\ \æ\135º\20ðæ\135¼\20ôæ\135½\20óæ\135¾\20õæ\135¿\20òæ\136\128\20öæ\136\136\ \\20÷æ\136\137\20øæ\136\138\15¨æ\136\140\20úæ\136\141\20ùæ\136\142\10\158\ \æ\136\144\11¬æ\136\145\6¤æ\136\146\6ºæ\136\148\20ûæ\136\150\5½æ\136\154\ \\11Êæ\136\155\20üæ\136\157\28Aæ\136\158\21\0æ\136\159\8\129æ\136¡\21\1æ\ \\136¦\11íæ\136ª\21\2æ\136®\21\3æ\136¯\7\153æ\136°\21\4æ\136²\21\5æ\136³\ \\21\6æ\136´\12\149æ\136¸\8Ëæ\136»\16_æ\136¿\15Ûæ\137\128\10Êæ\137\129\21\ \\7æ\137\135\11îæ\137\136\28ûæ\137\137\14àæ\137\139\10hæ\137\141\9\139æ\ \\137\142\21\8æ\137\147\12\133æ\137\149\15eæ\137\152\12¯æ\137\155\21\11æ\ \\137\158\21\9æ\137 \21\12æ\137£\21\10æ\137¨\21\13æ\137®\15oæ\137±\5µæ\ \\137¶\15=æ\137¹\14áæ\137¼\21\14æ\137¾\21\17æ\137¿\10óæ\138\128\7\154æ\ \\138\130\21\15æ\138\131\21\22æ\138\132\10ôæ\138\137\21\16æ\138\138\14cæ\ \\138\145\16½æ\138\146\21\18æ\138\147\21\19æ\138\148\21\23æ\138\149\13Êæ\ \\138\150\21\20æ\138\151\9\18æ\138\152\11Üæ\138\155\21%æ\138\156\14²æ\138\ \\158\12°æ\138«\14âæ\138¬\21kæ\138±\15¸æ\138µ\13oæ\138¹\16\21æ\138»\21\26\ \æ\138¼\6_æ\138½\13\10æ\139\130\21#æ\139\133\12Óæ\139\134\21\29æ\139\135\ \\21$æ\139\136\21\31æ\139\137\21&æ\139\138\21\34æ\139\140\21!æ\139\141\14\ \\143æ\139\143\21\27æ\139\144\6»æ\139\145\21\25æ\139\146\7Ñæ\139\147\12±æ\ \\139\148\21\21æ\139\151\21\24æ\139\152\9\19æ\139\153\11Ùæ\139\155\10õæ\ \\139\156\21 æ\139\157\14qæ\139 \7Òæ\139¡\6çæ\139¬\7\7æ\139\173\11@æ\139®\ \\21(æ\139¯\21-æ\139±\21)æ\139³\8\157æ\139µ\21.æ\139¶\9Áæ\139·\9Iæ\139¾\ \\10\133æ\139¿\21\28æ\140\129\10\29æ\140\130\21+æ\140\135\9÷æ\140\136\21,\ \æ\140\137\5Âæ\140\140\21'æ\140\145\13'æ\140\153\7Óæ\140\159\7òæ\140§\21*\ \æ\140¨\5¥æ\140«\9\129æ\140¯\11Uæ\140º\13pæ\140½\14Òæ\140¾\210æ\140¿\12=æ\ \\141\137\12hæ\141\140\9Êæ\141\141\211æ\141\143\213æ\141\144\21/æ\141\149\ \\15\159æ\141\151\13;æ\141\156\12;æ\141§\15¹æ\141¨\10Læ\141©\21@æ\141«\21\ \>æ\141®\11\152æ\141²\8\158æ\141¶\218æ\141·\10÷æ\141º\14&æ\141»\14Pæ\142\ \\128\216æ\142\131\12<æ\142\136\10væ\142\137\21;æ\142\140\10öæ\142\142\21\ \5æ\142\143\21:æ\142\146\14ræ\142\150\214æ\142\152\8@æ\142\155\6üæ\142\ \\159\21<æ\142 \16éæ\142¡\9\140æ\142¢\12Ôæ\142£\219æ\142¥\11Úæ\142§\9\20æ\ \\142¨\11\132æ\142©\6Fæ\142ª\12\27æ\142«\217æ\142¬\7¤æ\142²\8fæ\142´\13Mæ\ \\142µ\21=æ\142»\12>æ\142¾\21Aæ\143\128\21Cæ\143\131\12uæ\143\132\21Iæ\ \\143\134\21Dæ\143\137\21Fæ\143\143\15 æ\143\144\13qæ\143\146\21Gæ\143\ \\150\16\139æ\143\154\16§æ\143\155\77æ\143¡\5¬æ\143£\21Eæ\143©\21Bæ\143®\ \\7væ\143´\6Gæ\143¶\21Hæ\143º\16¨æ\144\134\21Læ\144\141\12yæ\144\143\21Sæ\ \\144\147\21Mæ\144\150\21Jæ\144\151\21Qæ\144\156\212æ\144¦\21Næ\144¨\21Ræ\ \\144¬\14Àæ\144\173\13Ëæ\144´\21Kæ\144¶\21Oæ\144º\8gæ\144¾\9¯æ\145\130\11\ \Ûæ\145\142\21Wæ\145\152\13\133æ\145§\21Tæ\145©\16\0æ\145¯\21Uæ\145¶\21Væ\ \\145¸\16Læ\145º\11 æ\146\131\8\130æ\146\136\21]æ\146\146\9Ôæ\146\147\21Z\ \æ\146\149\21Yæ\146\154\14Qæ\146\158\13óæ\146¤\13\144æ\146¥\21[æ\146©\21\ \\92æ\146«\15Oæ\146\173\14dæ\146®\9Âæ\146°\11ïæ\146²\15ïæ\146¹\6èæ\146»\ \\21cæ\146¼\21^æ\147\129\16©æ\147\130\21eæ\147\133\21aæ\147\135\21bæ\147\ \\141\12@æ\147\146\21`æ\147\148\21\30æ\147\152\21dæ\147\154\21_æ\147 \21i\ \æ\147¡\21jæ\147¢\13\134æ\147£\21læ\147¦\9Ãæ\147§\21gæ\147¬\7\155æ\147¯\ \\21mæ\147±\21fæ\147²\21qæ\147´\21pæ\147¶\21oæ\147º\21ræ\147½\21tæ\147¾\ \\11/æ\148\128\21sæ\148\133\21wæ\148\152\21uæ\148\156\21væ\148\157\21Pæ\ \\148£\21yæ\148¤\21xæ\148ª\21Xæ\148«\21zæ\148¬\21næ\148¯\9øæ\148´\21{æ\ \\148µ\21|æ\148¶\21~æ\148·\21}æ\148¸\21\127æ\148¹\6¼æ\148»\9\21æ\148¾\15º\ \æ\148¿\11\173æ\149\133\8Ìæ\149\136\21\129æ\149\141\21\132æ\149\143\151æ\ \\149\145\7¾æ\149\149\21\131æ\149\150\21\130æ\149\151\14sæ\149\152\21\133\ \æ\149\153\7óæ\149\157\21\135æ\149\158\21\134æ\149¢\78æ\149£\9Õæ\149¦\14\ \\22æ\149¬\8hæ\149°\11\148æ\149²\21\136æ\149´\11®æ\149µ\13\135æ\149·\15>æ\ \\149¸\21\137æ\150\130\21\138æ\150\131\21\139æ\150\135\15væ\150\136\19¼æ\ \\150\137\11Äæ\150\140\15+æ\150\142\9\150æ\150\144\14ãæ\150\145\14Áæ\150\ \\151\13¬æ\150\153\16ÿæ\150\155\21\141æ\150\156\10Næ\150\159\21\142æ\150¡\ \\5´æ\150¤\8\18æ\150¥\11Ëæ\150§\15@æ\150«\21\143æ\150¬\9áæ\150\173\12ææ\ \\150¯\9úæ\150°\11Væ\150·\21\144æ\150¹\15»æ\150¼\6Wæ\150½\9ûæ\151\129\21\ \\147æ\151\131\21\145æ\151\132\21\148æ\151\133\16÷æ\151\134\21\146æ\151\ \\139\11ùæ\151\140\21\149æ\151\143\12pæ\151\146\21\150æ\151\151\7xæ\151\ \\153\21\152æ\151\155\21\151æ\151 \21\153æ\151¡\21\154æ\151¢\7yæ\151¥\14:\ \æ\151¦\12Õæ\151§\7Ìæ\151¨\9üæ\151©\12Aæ\151¬\10»æ\151\173\5®æ\151±\21\ \\155æ\151º\6`æ\151»\21\159æ\152\130\9\22æ\152\131\21\158æ\152\134\9iæ\ \\152\135\10øæ\152\138\21\157æ\152\140\10ùæ\152\142\16>æ\152\143\9hæ\152\ \\147\5Õæ\152\148\11Ìæ\152\156\21¤æ\152\159\11¯æ\152 \6&æ\152¥\10´æ\152§\ \\16\6æ\152¨\9°æ\152\173\10úæ\152¯\11¥æ\152´\21£æ\152µ\21¡æ\152¶\21¢æ\152\ \¼\13\11æ\152¿\21Åæ\153\129\21¨æ\153\130\10\30æ\153\131\9\23æ\153\132\21¦\ \æ\153\137\21§æ\153\139\11Wæ\153\143\21¥æ\153\146\9Îæ\153\157\21ªæ\153\ \\158\21©æ\153\159\21®æ\153¢\21¯æ\153¤\21«æ\153¦\6Áæ\153§\21¬æ\153¨\21\ \\173æ\153©\14Óæ\153®\15Aæ\153¯\8iæ\153°\21°æ\153´\11°æ\153¶\10ûæ\153º\12\ \ñæ\154\129\8\5æ\154\131\21±æ\154\132\21µæ\154\135\6\137æ\154\136\21²æ\ \\154\137\21´æ\154\142\21³æ\154\145\10Ëæ\154\150\12çæ\154\151\5Ãæ\154\152\ \\21¶æ\154\157\21·æ\154¢\13(æ\154¦\17/æ\154«\9âæ\154®\15©æ\154´\15Üæ\154¸\ \\21Áæ\154¹\21¹æ\154¼\21¼æ\154¾\21»æ\155\129\21¸æ\155\132\21Àæ\155\135\14\ \\28æ\155\137\21ºæ\155\150\21Âæ\155\153\10Ìæ\155\154\21Ãæ\155\156\16ªæ\ \\155\157\14\152æ\155 \21Äæ\155¦\21Ææ\155©\21Çæ\155°\21Èæ\155²\8\8æ\155³\ \\6'æ\155´\9\24æ\155µ\21Éæ\155·\21Êæ\155¸\10Ñæ\155¹\12Bæ\155¼\18\150æ\155\ \½\12\29æ\155¾\12\28æ\155¿\12\150æ\156\128\9\133æ\156\131\17ðæ\156\136\8\ \\142æ\156\137\16\140æ\156\139\15¼æ\156\141\15^æ\156\143\21Ëæ\156\148\9±æ\ \\156\149\13=æ\156\150\21Ìæ\156\151\17Næ\156\155\15Ýæ\156\157\13)æ\156\ \\158\21Íæ\156\159\7zæ\156¦\21Îæ\156§\21Ïæ\156¨\16Xæ\156ª\16\34æ\156«\16\ \\22æ\156¬\15ûæ\156\173\9Äæ\156®\21Ñæ\156±\10iæ\156´\15ðæ\156¶\21Óæ\156·\ \\21Öæ\156¸\21Õæ\156º\7wæ\156½\7Àæ\156¿\21Òæ\157\129\21Ôæ\157\134\21׿\ \\157\137\11\153æ\157\142\16Ûæ\157\143\5Çæ\157\144\9\158æ\157\145\12zæ\ \\157\147\10[æ\157\150\111æ\157\153\21Úæ\157\156\13\173æ\157\158\21Øæ\157\ \\159\12iæ\157 \21Ùæ\157¡\110æ\157¢\16[æ\157£\21Ûæ\157¤\21Üæ\157¥\16Èæ\ \\157ª\21áæ\157\173\9\25æ\157¯\14tæ\157°\21Þæ\157±\13Ìæ\157²\21\156æ\157³\ \\21 æ\157µ\7®æ\157·\14fæ\157¼\21àæ\157¾\10üæ\157¿\14Âæ\158\133\21ææ\158\ \\135\14øæ\158\137\21Ýæ\158\139\21ãæ\158\140\21âæ\158\144\11Íæ\158\149\16\ \\13æ\158\151\17\17æ\158\154\16\7æ\158\156\6\138æ\158\157\9ýæ\158 \17gæ\ \\158¡\21åæ\158¢\11\149æ\158¦\21äæ\158©\21ßæ\158¯\8Íæ\158³\21ëæ\158´\21éæ\ \\158¶\6\139æ\158·\21çæ\158¸\21íæ\158¹\21óæ\159\129\12\134æ\159\132\15\ \\127æ\159\134\21õæ\159\138\15\1æ\159\142\21ôæ\159\143\14\144æ\159\144\15\ \Þæ\159\145\79æ\159\147\11õæ\159\148\10\159æ\159\152\13Qæ\159\154\16\141æ\ \\159\157\21ðæ\159\158\21ïæ\159¢\21ñæ\159¤\21îæ\159§\21öæ\159©\21ìæ\159¬\ \\21êæ\159®\21òæ\159¯\21èæ\159±\13\12æ\159³\16væ\159´\10Dæ\159µ\9²æ\159»\ \\9xæ\159¾\16\15æ\159¿\6àæ \130\13Læ \131\14\8æ \132\6(æ \147\11ðæ \150\ \\11²æ \151\8Iæ \158\21øæ ¡\9\26æ ¢\7\28æ ©\21úæ ª\7\20æ «\22\1æ ²\21ýæ ´\ \\11ñæ ¸\6êæ ¹\9jæ ¼\6éæ ½\9\141æ¡\128\21ûæ¡\129\8\133æ¡\130\8jæ¡\131\13Í\ \æ¡\134\21ùæ¡\136\5Äæ¡\141\21üæ¡\142\21þæ¡\144\8\11æ¡\145\8Kæ¡\147\7:æ¡\ \\148\7ªæ¡\153\22\2æ¡\156\9·æ¡\157\16\17æ¡\159\9Öæ¡£\22\3æ¡§\15\15æ¡´\22\ \\15æ¡¶\6qæ¡·\22\4桾\22\21æ¡¿\22\5æ¢\129\17\0æ¢\131\22\12æ¢\133\14~æ¢\ \\141\22\20æ¢\143\22\7æ¢\147\5²æ¢\148\22\9æ¢\151\9\27æ¢\155\22\11æ¢\157\ \\22\10æ¢\159\22\6梠\22\17梢\10ý梦\19k梧\8ææ¢¨\16Üæ¢\173\22\8梯\13ræ\ \¢°\6Âæ¢±\9k梳\22\0梵\22\16梶\7\1梹\22\14梺\22\18梼\13Îæ£\132\7|æ£\ \\134\220æ£\137\16Gæ£\138\22\23æ£\139\7{æ£\141\22\30æ£\146\15ßæ£\148\22\ \\31æ£\149\22!æ£\151\22%æ£\152\22\25æ£\154\12Éæ£\159\13Ïæ£ \22)棡\22\28æ\ \££\22&棧\22 森\11X棯\22*棲\11±æ£¹\22(棺\7;æ¤\128\17oæ¤\129\22\22æ¤\ \\132\22$æ¤\133\5Öæ¤\136\22\24æ¤\139\168æ¤\140\22\29æ¤\141\11Aæ¤\142\13Eæ\ \¤\143\22\19æ¤\146\22#æ¤\153\11\154æ¤\154\22-æ¤\155\7\17æ¤\156\8\159椡\ \\22/椢\22\26椣\22.椥\22'椦\22\27椨\22+椪\22,椰\22=椴\14\12椶\22\ \\34椹\229椽\22;椿\13Væ¥\138\16«æ¥\147\15Væ¥\148\226æ¥\149\12\136æ¥\ \\153\22<æ¥\154\12\30æ¥\156\223æ¥\157\22@æ¥\158\22?楠\14-楡\22>楢\14(æ\ \¥ª\22B楫\225æ¥\173\8\6楮\228楯\10¼æ¥³\14\128楴\22:極\8\9楷\222楸\ \\224楹\221楼\17O楽\6ù楾\227æ¦\129\22Aæ¦\130\6Ôæ¦\138\9¥æ¦\142\6<æ¦\ \\145\22Ræ¦\148\17Pæ¦\149\22Uæ¦\155\11Yæ¦\156\22T榠\22S榧\22P榮\22D榱\ \\22a榲\22C榴\22V榻\22N榾\22I榿\22Fæ§\129\22Gæ§\131\22Oæ§\135\31 æ§\ \\138\22Læ§\139\9\28æ§\140\13Fæ§\141\12Dæ§\142\22Jæ§\144\22Eæ§\147\22Hæ§\ \\152\16¬æ§\153\16\10æ§\157\22Mæ§\158\22Wæ§§\22_槨\22Xæ§«\22eæ§\173\22cæ\ \§²\22^æ§¹\22]æ§»\13Næ§½\12Eæ§¿\22[æ¨\130\22Yæ¨\133\22`æ¨\138\22fæ¨\139\ \\14óæ¨\140\22læ¨\146\22gæ¨\147\22jæ¨\148\22dæ¨\151\13\20æ¨\153\15\23æ¨\ \\155\22Zæ¨\158\22bæ¨\159\10þ模\16M樢\22v樣\22i権\8 æ¨ª\6a樫\6þ樮\ \\22Q樵\10ÿ樶\22n樸\22u樹\10w樺\7\18樽\12Íæ©\132\22kæ©\135\22pæ©\ \\136\22tæ©\139\7ôæ©\152\7«æ©\153\22ræ©\159\7\128æ©¡\14\9æ©¢\22q橦\22sæ©\ \²\22m橸\22oæ©¿\7\0æª\128\12èæª\132\22zæª\141\22xæª\142\8çæª\144\22wæª\ \\151\22\128æª\156\21÷檠\22y檢\22{檣\22|檪\22\139檬\22\135檮\22\13æ\ \ª³\22\134檸\22\133檻\22\130æ«\129\22hæ«\130\22\132æ«\131\22\131æ«\145\ \\22\137æ«\147\17Eæ«\154\22\140æ«\155\89æ«\158\22\136æ«\159\22\138櫨\14¥\ \櫪\22\141櫺\22\145æ«»\22\142æ¬\132\16Óæ¬\133\22\143æ¬\138\22\92æ¬\146\ \\22\146æ¬\150\22\147æ¬\157\6\20æ¬\159\22\149欠\8\135次\10\31欣\8\19æ¬\ \§\6b欲\16¾æ¬·\22\151欸\22\150欹\22\153欺\7\156欽\8\20款\7<æ\173\ \\131\22\156æ\173\135\22\155æ\173\137\22\157æ\173\140\6\140æ\173\142\12Öæ\ \\173\144\22\158æ\173\147\7=æ\173\148\22 æ\173\153\22\159æ\173\155\22¡æ\ \\173\159\22¢æ\173¡\22£æ\173¢\9þæ\173£\11³æ\173¤\9_æ\173¦\15Pæ\173©\15 æ\ \\173ª\17cæ\173¯\10\21æ\173³\9\142æ\173´\170æ\173¸\22¤æ\173¹\22¥æ\173»\10\ \\0æ\173¿\22¦æ®\128\22§æ®\131\22©æ®\132\22¨æ®\134\15÷æ®\137\10½æ®\138\10j\ \æ®\139\9ãæ®\141\22ªæ®\149\22¬æ®\150\11Bæ®\152\22«æ®\158\22\173殤\22®æ®ª\ \\22¯æ®«\22°æ®¯\22±æ®±\22³æ®²\22²æ®³\22´æ®´\6c段\12éæ®·\22µæ®º\9Åæ®»\6ëæ\ \®¼\22¶æ®¿\13¡æ¯\128\19Jæ¯\133\7\130æ¯\134\22·æ¯\139\22¸æ¯\141\15ªæ¯\142\ \\16\8æ¯\146\14\5æ¯\147\22¹æ¯\148\14保\152\14ùæ¯\155\16Qæ¯\159\22ºæ¯«\22\ \¼æ¯¬\22»æ¯¯\22¾æ¯³\22½æ°\136\22Áæ°\143\10\1æ°\145\16/æ°\147\22Âæ°\148\22\ \Ãæ°\151\7\131æ°\155\22Äæ°£\22Ææ°¤\22Åæ°´\11\133æ°·\15\24æ°¸\6)æ°¾\14Ãæ±\ \\128\13sæ±\129\10 æ±\130\7Áæ±\142\14Äæ±\144\10,æ±\149\22Èæ±\151\7>æ±\154\ \\6Xæ±\157\140æ±\158\22Çæ±\159\9\29æ± \12òæ±¢\22Éæ±¨\22Ñæ±ª\22Êæ±°\12\127\ \æ±²\7Âæ±³\22Òæ±º\8\136æ±½\7\132æ±¾\22Ðæ²\129\22Îæ²\130\22Ëæ²\131\16Àæ²\ \\136\13>æ²\140\14\23æ²\141\22Ìæ²\144\22Ôæ²\146\22Óæ²\147\8Bæ²\150\6kæ²\ \\153\9yæ²\154\22Íæ²\155\22Ïæ²¡\15öæ²¢\12²æ²«\16\23æ²®\22Üæ²±\22Ýæ²³\6\ \\141沸\15fæ²¹\16{沺\22ßæ²»\10!æ²¼\11\0æ²½\22Øæ²¾\22Þæ²¿\6Hæ³\129\7õæ³\ \\132\22Õæ³\133\22Úæ³\137\11òæ³\138\14\145æ³\140\14åæ³\147\22׿³\149\15Àæ\ \³\151\22Ùæ³\153\22âæ³\155\22àæ³\157\22Ûæ³¡\15Áæ³¢\14gæ³£\7Ãæ³¥\13\132注\ \\13\13泪\22ãæ³¯\22áæ³°\12\151æ³±\22Öæ³³\6*æ´\139\16\173æ´\140\22îæ´\146\ \\22íæ´\151\11ôæ´\153\22êæ´\155\16Ìæ´\158\13ôæ´\159\22äæ´¥\13Cæ´©\6+æ´ª\9\ \\30æ´«\22çæ´²\10\134æ´³\22ìæ´µ\22ëæ´¶\22ææ´¸\22éæ´»\7\8æ´½\22èæ´¾\14hæµ\ \\129\16ìæµ\132\112æµ\133\11óæµ\153\22ôæµ\154\22òæµ\156\15,æµ£\22ïæµ¤\22ñ\ \浦\6\25浩\9\31浪\17Q浬\6Üæµ®\15Bæµ´\16Áæµ·\6Ãæµ¸\11Zæµ¹\22óæ¶\133\22\ \øæ¶\136\11\1æ¶\140\16\143æ¶\142\22õæ¶\147\22ðæ¶\149\22öæ¶\153\17\28æ¶\ \\155\13Óæ¶\156\14\0涯\6Õæ¶²\64æ¶µ\22ü涸\22ÿæ¶¼\17\1æ·\128\16Äæ·\133\23\ \\6æ·\134\23\0æ·\135\22ýæ·\139\17\18æ·\140\23\3æ·\145\10©æ·\146\23\5æ·\ \\149\23\10æ·\152\13Ñæ·\153\23\8æ·\158\23\2æ·¡\12׿·¤\23\9æ·¦\22þæ·¨\23\4\ \æ·ª\23\11æ·«\5úæ·¬\23\1æ·®\23\12æ·±\11[æ·³\10¾æ·µ\15cæ··\9læ·¹\22ùæ·º\23\ \\7æ·»\13\153æ¸\133\11´æ¸\135\7\9æ¸\136\9\143æ¸\137\11\2æ¸\138\22ûæ¸\139\ \\10¡æ¸\147\8kæ¸\149\22úæ¸\153\23\16æ¸\154\10Íæ¸\155\8¸æ¸\157\23\31æ¸\159\ \\23\25渠\7Ôæ¸¡\13®æ¸£\23\20渤\23\29渥\5\173渦\6\17温\6w渫\23\22測\ \\12jæ¸\173\23\13渮\23\15港\9 游\23 渺\23\27渾\23\19æ¹\131\23\26æ¹\ \\138\16)æ¹\141\23\24æ¹\142\23\28æ¹\150\8Îæ¹\152\11\3æ¹\155\12Øæ¹\159\23\ \\18æ¹§\16\142湫\23\21æ¹®\23\14湯\13Òæ¹²\23\17æ¹¶\23\23æ¹¾\17p湿\10<æº\ \\128\16\30æº\130\23!æº\140\14¬æº\143\23-æº\144\8¹æº\150\10Àæº\152\23#æº\ \\156\16íæº\157\9!æº\159\230溢\5ìæº¥\23.溪\23\34溯\23(溲\23*溶\16®æº\ \·\23%溺\13\141溽\23'æ»\130\23/æ»\132\23)æ»\133\16Eæ»\137\23$æ»\139\10 \ \æ»\140\23<æ»\145\7\10æ»\147\23&æ»\148\23+æ»\149\23,æ»\157\12ªæ»\158\12\ \\152滬\234滯\23:滲\238æ»´\13\136æ»·\23B滸\235滾\236滿\23\30æ¼\129\ \\7Ùæ¼\130\15\25æ¼\134\10=æ¼\137\9Wæ¼\143\17Ræ¼\145\232æ¼\147\23Aæ¼\148\6\ \Iæ¼\149\12Fæ¼ \14\153æ¼¢\7?æ¼£\178漫\16\31漬\13Pæ¼±\239æ¼²\23;漸\12\ \\17æ¼¾\23@漿\237æ½\129\231æ½\133\7Aæ½\148\8\137æ½\152\23Næ½\155\23Iæ½\ \\156\11öæ½\159\7\3潤\10Á潦\23Ræ½\173\23Kæ½®\13*潯\23Hæ½°\13Wæ½´\23kæ½\ \¸\23E潺\23Dæ½¼\23Mæ¾\128\23Gæ¾\129\23Fæ¾\130\23Læ¾\132\11\159æ¾\134\23C\ \æ¾\142\23Oæ¾\145\23Pæ¾\151\7@澡\23Uæ¾£\23T澤\23V澪\23Yæ¾±\13¢æ¾³\23Sæ\ \¾¹\23Wæ¿\128\8\131æ¿\129\12·æ¿\130\23Qæ¿\131\14Zæ¿\134\23Xæ¿\148\23]æ¿\ \\149\23[æ¿\152\23^æ¿\155\23aæ¿\159\23Zæ¿ \9Jæ¿¡\14G濤\22÷æ¿«\16Ôæ¿¬\23\ \\92æ¿®\23`濯\12³æ¿±\23_濳\23Jæ¿¶\29\137濺\23d濾\23hç\128\129\23fç\ \\128\137\23bç\128\139\23cç\128\143\23gç\128\145\23eç\128\149\15-ç\128\ \\152\23mç\128\154\23jç\128\155\23iç\128\157\23lç\128\158\14\18ç\128\159\ \\23nç\128¦\13\21ç\128§\12«ç\128¬\11£ç\128°\23oç\128²\23qç\128¾\23pç\129\ \\140\233ç\129\145\23rç\129\152\14%ç\129£\23sç\129«\6\142ç\129¯\13Ôç\129°\ \\6Äç\129¸\7Äç\129¼\10\92ç\129½\9\144ç\130\137\17Fç\130\138\11\134ç\130\ \\142\6Jç\130\146\23uç\130\153\23tç\130¬\23xç\130\173\12Ùç\130®\23{ç\130¯\ \\23vç\130³\23zç\130¸\23yç\130¹\13\159ç\130º\5×ç\131\136\173ç\131\139\23}\ \ç\131\143\6\7ç\131\153\23\128ç\131\157\23~ç\131\159\23|ç\131±\23wç\131¹\ \\15Âç\131½\23\130ç\132\137\23\129ç\132\148\6Kç\132\153\23\132ç\132\154\ \\15pç\132\156\23\131ç\132¡\163ç\132¦\11\5ç\132¶\12\18ç\132¼\11\4ç\133\ \\137\179ç\133\140\23\138ç\133\142\11÷ç\133\149\23\134ç\133\150\23\139ç\ \\133\153\6Lç\133¢\23\137ç\133¤\14\129ç\133¥\23\133ç\133¦\23\136ç\133§\11\ \\6ç\133©\14Ïç\133¬\23\140ç\133®\10Oç\133½\11øç\134\132\23\143ç\134\136\ \\23\135ç\134\138\8Fç\134\143\23\141ç\134\148\16¯ç\134\149\23\144ç\134\ \\153\31$ç\134\159\10®ç\134¨\23\145ç\134¬\23\146ç\134±\14Mç\134¹\23\148ç\ \\134¾\23\149ç\135\131\14Rç\135\136\13Õç\135\137\23\151ç\135\142\23\153ç\ \\135\144\17\19ç\135\146\23\150ç\135\148\23\152ç\135\149\6Mç\135\151\23\ \\147ç\135\159\18úç\135 \23\154ç\135¥\12Gç\135¦\9×ç\135§\23\156ç\135¬\23\ \\155ç\135\173\11Cç\135®\18\151ç\135µ\23\157ç\135¹\23\159ç\135»\23\142ç\ \\135¼\23\158ç\135¿\23 ç\136\134\14\154ç\136\141\23¡ç\136\144\23¢ç\136\ \\155\23£ç\136¨\23¤ç\136ª\13\92ç\136¬\23¦ç\136\173\23¥ç\136°\23§ç\136²\23\ \¨ç\136µ\10]ç\136¶\15Cç\136º\16jç\136»\23©ç\136¼\23ªç\136½\125ç\136¾\10\ \\34ç\136¿\23«ç\137\128\23¬ç\137\134\23\173ç\137\135\15\144ç\137\136\14Åç\ \\137\139\23®ç\137\140\14vç\137\146\13+ç\137\152\23¯ç\137\153\6¥ç\137\155\ \\7Íç\137\157\16Dç\137\159\164ç\137¡\6rç\137¢\17Sç\137§\15ñç\137©\15hç\ \\137²\11µç\137´\23°ç\137¹\14\1ç\137½\8¡ç\137¾\23±ç\138\128\9\146ç\138\ \\129\23³ç\138\130\23²ç\138\135\23´ç\138\146\23µç\138\150\23¶ç\138 \7\157\ \ç\138¢\23·ç\138§\23¸ç\138¬\8¢ç\138¯\14Æç\138²\23ºç\138¶\113ç\138¹\23¹ç\ \\139\130\7öç\139\131\23»ç\139\132\23½ç\139\134\23¼ç\139\142\23¾ç\139\144\ \\8Ïç\139\146\23¿ç\139\151\8'ç\139\153\12\31ç\139\155\9]ç\139 \23Áç\139¡\ \\23Âç\139¢\23Àç\139©\10kç\139¬\14\6ç\139\173\7÷ç\139·\23Äç\139¸\12Ëç\139\ \¹\23Ãç\139¼\17Tç\139½\14\130ç\140\138\23Çç\140\150\23Éç\140\151\23Æç\140\ \\155\16Rç\140\156\23Èç\140\157\23Êç\140\159\17\2ç\140¥\23Îç\140©\23Íç\ \\140ª\13\22ç\140«\14Lç\140®\8£ç\140¯\23Ìç\140´\23Ëç\140¶\16\144ç\140·\16\ \\145ç\140¾\23Ïç\140¿\6Nç\141\132\9Vç\141\133\10\2ç\141\142\23Ðç\141\143\ \\23Ñç\141\151\23Óç\141£\10¢ç\141¨\23Õç\141ª\23Ôç\141°\23Öç\141²\6ìç\141µ\ \\23Øç\141¸\23×ç\141º\23Úç\141»\23Ùç\142\132\8ºç\142\135\16æç\142\137\8\ \\10ç\142\139\6dç\142\150\8(ç\142©\7_ç\142²\17&ç\142³\23Üç\142»\23Þç\143\ \\128\23ßç\143\130\6\143ç\143\136\23Ûç\143\138\9Øç\143\141\13?ç\143\142\ \\23Ýç\143\158\23âç\143 \10lç\143¥\23àç\143ª\8]ç\143\173\14Çç\143®\23áç\ \\143±\23üç\143¸\23çç\143¾\8»ç\144\131\7Åç\144\133\23äç\144\134\16Ýç\144\ \\137\16îç\144¢\12´ç\144¥\23æç\144²\23èç\144³\17\20ç\144´\8\21ç\144µ\14úç\ \\144¶\14iç\144º\23éç\144¿\23ëç\145\129\23îç\145\149\23êç\145\153\23íç\ \\145\154\8èç\145\155\6,ç\145\156\23ïç\145\158\11\144ç\145\159\23ìç\145 \ \\17\26ç\145£\23òç\145¤\31\34ç\145©\23ðç\145ª\23óç\145¯\23åç\145°\23ñç\ \\145³\9zç\145¶\23ôç\145¾\23õç\146\131\16Þç\146\139\23öç\146\158\23÷ç\146\ \¢\23ãç\146§\23øç\146°\7Bç\146½\10#ç\147\138\23ùç\147\143\23úç\147\148\23\ \ûç\147\156\6\26ç\147 \24\0ç\147¢\15\26ç\147£\24\1ç\147¦\7\34ç\147§\24\2ç\ \\147©\24\3ç\147®\24\4ç\147°\24\6ç\147±\24\7ç\147²\24\5ç\147¶\152ç\147·\ \\24\9ç\147¸\24\8ç\148\131\24\11ç\148\132\24\10ç\148\133\24\12ç\148\140\ \\24\13ç\148\141\24\15ç\148\142\24\14ç\148\145\9Yç\148\147\24\17ç\148\149\ \\24\16ç\148\152\7Cç\148\154\11rç\148\156\13\155ç\148\158\24\18ç\148\159\ \\11¶ç\148£\9Ùç\148¥\6Yç\148¦\24\19ç\148¨\16°ç\148«\15¡ç\148¬\24\20ç\148°\ \\13£ç\148±\16\146ç\148²\9\34ç\148³\11\92ç\148·\12êç\148¸\18rç\148º\13,ç\ \\148»\6¦ç\148¼\24\21ç\149\132\24\22ç\149\134\24\27ç\149\137\24\25ç\149\ \\138\24\24ç\149\139\21\128ç\149\140\6Åç\149\141\24\23ç\149\143\5Øç\149\ \\145\14¨ç\149\148\14Èç\149\153\16ïç\149\154\24\28ç\149\155\24\26ç\149\ \\156\12ûç\149\157\11¤ç\149 \14©ç\149¢\15\12ç\149¤\24\30ç\149¥\16êç\149¦\ \\8lç\149§\24\31ç\149©\24\29ç\149ª\14Ôç\149«\24 ç\149\173\24!ç\149°\5Ùç\ \\149³\114ç\149´\24&ç\149¶\24#ç\149·\14+ç\149¸\24\34ç\149¿\7\133ç\150\130\ \\24)ç\150\134\24$ç\150\135\24%ç\150\137\24(ç\150\138\24'ç\150\139\15\4ç\ \\150\142\12!ç\150\143\12 ç\150\145\7\158ç\150\148\24*ç\150\154\24+ç\150\ \\157\24,ç\150£\24.ç\150¥\24-ç\150«\65ç\150±\246ç\150²\14æç\150³\240ç\150\ \µ\242ç\150¸\244ç\150¹\11]ç\150¼\245ç\150½\243ç\150¾\10>ç\151\130\24/ç\ \\151\131\241ç\151\133\15!ç\151\135\11\7ç\151\138\248ç\151\141\247ç\151\ \\146\249ç\151\148\10$ç\151\149\9mç\151\152\13×ç\151\153\24:ç\151\155\13I\ \ç\151\158\24<ç\151¢\16ßç\151£\24;ç\151©\12Iç\151°\24Bç\151²\24Dç\151³\24\ \Eç\151´\12óç\151º\24Cç\151¼\24@ç\151¾\24=ç\151¿\24>ç\152\129\24Aç\152\ \\137\24Hç\152\139\24Fç\152\141\24Gç\152\159\24Iç\152 \24Kç\152¡\24Lç\152\ \¢\24Mç\152¤\24Nç\152§\24Jç\152°\24Pç\152´\24Oç\152»\24Qç\153\130\17\3ç\ \\153\134\24Tç\153\135\24Rç\153\136\24Sç\153\140\7`ç\153\146\16|ç\153\150\ \\15\136ç\153\152\24Vç\153\156\24Uç\153¡\24Wç\153¢\24Xç\153§\24\92ç\153¨\ \\24Yç\153©\24Zç\153ª\24[ç\153¬\24]ç\153°\24^ç\153²\24_ç\153¶\24`ç\153¸\ \\24aç\153º\14\173ç\153»\13¯ç\153¼\24bç\153½\14\146ç\153¾\15\19ç\154\128\ \\24cç\154\131\24dç\154\132\13\137ç\154\134\6Æç\154\135\9#ç\154\136\24eç\ \\154\139\24fç\154\142\24gç\154\144\9Èç\154\147\24iç\154\150\24hç\154\153\ \\24jç\154\154\24kç\154®\14çç\154°\24lç\154´\24mç\154·\31\9ç\154¸\24nç\ \\154¹\24oç\154º\24pç\154¿\9Íç\155\130\24qç\155\131\14uç\155\134\15þç\155\ \\136\6-ç\155\138\66ç\155\141\24rç\155\146\24tç\155\150\24sç\155\151\13Ðç\ \\155\155\11·ç\155\156\22\152ç\155\158\24uç\155\159\16?ç\155¡\24vç\155£\7\ \Dç\155¤\14Õç\155¥\24wç\155§\24xç\155ª\24yç\155®\16Zç\155²\16Sç\155´\13<ç\ \\155¸\12Jç\155»\24{ç\155¾\10Âç\156\129\11\8ç\156\132\24~ç\156\135\24}ç\ \\156\136\24|ç\156\137\14ûç\156\139\7Eç\156\140\8§ç\156\155\24\132ç\156\ \\158\24\129ç\156\159\11^ç\156 \160ç\156¤\24\128ç\156¥\24\130ç\156¦\24\ \\131ç\156©\24\127ç\156·\24\133ç\156¸\24\134ç\156º\13-ç\156¼\7aç\157\128\ \\13\5ç\157\135\24\135ç\157\154\24\136ç\157\155\24\139ç\157¡\11\135ç\157£\ \\14\2ç\157¥\24\140ç\157¦\15òç\157¨\24\137ç\157«\24\138ç\157¹\24\143ç\157\ \¾\24\142ç\157¿\24\141ç\158\139\24\145ç\158\142\24\144ç\158\145\24\146ç\ \\158\158\24\148ç\158 \24\147ç\158¥\15\139ç\158¬\10µç\158\173\17\4ç\158°\ \\24\149ç\158³\13õç\158¶\24\150ç\158¹\24\151ç\158»\24\155ç\158¼\24\153ç\ \\158½\24\154ç\158¿\24\152ç\159\135\24\156ç\159\141\24\157ç\159\151\24\ \\158ç\159\154\24\159ç\159\155\165ç\159\156\24 ç\159¢\16nç\159£\24¡ç\159¥\ \\12íç\159§\14\138ç\159©\8)ç\159\173\12Úç\159®\24¢ç\159¯\7øç\159³\11Îç\ \\159¼\24£ç \130\9{ç \140\24¤ç \146\24¥ç \148\8¤ç \149\9\147ç  \24§ç ¥\13\ \µç ¦\9\148ç §\7\173ç ²\15Ãç ´\14jç º\13¶ç ¿\9;ç¡\133\24©ç¡\157\11\9ç¡«\ \\16ð硬\9$硯\8¥ç¡²\14¡ç¡´\24«ç¡¼\24\173ç¢\129\8éç¢\134\24¬ç¢\135\13tç¢\ \\140\24¯ç¢\141\6Öç¢\142\24ªç¢\145\14èç¢\147\6\15ç¢\149\9ªç¢\151\17qç¢\ \\154\24®ç¢£\24°ç¢§\15\137碩\11×碪\24²ç¢¯\24³ç¢µ\24±ç¢º\6í碼\24¹ç¢¾\24\ \¸ç£\129\10%ç£\133\24ºç£\134\24µç£\138\24»ç£\139\24¶ç£\144\14Öç£\145\24´ç\ \£\148\24·ç£\154\24Á磧\24À磨\16\1磬\24¼ç£¯\5é磴\24Ã磽\24Âç¤\129\11\ \\10ç¤\135\24Äç¤\142\12\34ç¤\145\24Æç¤\146\24Åç¤\153\24Ç礦\24¦ç¤ª\24¨ç¤«\ \\24É礬\24È示\10&礼\17'社\10Pç¥\128\24Êç¥\129\8Vç¥\135\7\159ç¥\136\7\ \\134ç¥\137\10\3ç¥\144\16\147ç¥\147\24Ðç¥\149\24Ïç¥\150\12#ç¥\151\24Ìç¥\ \\154\24Îç¥\157\10ªç¥\158\11_ç¥\159\24Í祠\24Ë祢\14I祥\11\11票\15\27ç¥\ \\173\9\149祷\13Øç¥º\24Ñ祿\24Òç¦\128\24èç¦\129\8\22ç¦\132\17\92ç¦\133\ \\12\20ç¦\138\24Óç¦\141\6\144ç¦\142\13uç¦\143\15_ç¦\157\24Ô禦\7Ú禧\24Õç\ \¦ª\24×禮\24Øç¦°\14H禳\24Ù禹\24Ú禺\24Û禽\8\23禾\6\145禿\14\3ç§\128\ \\10\135ç§\129\10\4ç§\137\24Üç§\139\10\136ç§\145\6\136ç§\146\15\34ç§\149\ \\24Ýç§\152\14éç§\159\12$ç§¡\24àç§£\24á秤\14\137秦\11`ç§§\24Þç§©\13\1ç§\ \¬\24ßç§°\11\12ç§»\5Úç¨\128\7\136ç¨\136\24âç¨\139\13vç¨\141\24ãç¨\142\11Å\ \ç¨\148\16+ç¨\151\15\2ç¨\152\24äç¨\153\24åç¨\154\12ôç¨\156\17\5ç¨\159\24ç\ \稠\24æç¨®\10m稱\24é稲\5î稷\24ì稻\24ê稼\6\146稽\8m稾\24ë稿\9%ç©\ \\128\9Rç©\130\15¤ç©\131\24íç©\134\15óç©\137\24ïç©\141\11Ïç©\142\6.ç©\143\ \\6xç©\144\5ªç©\151\24îç©¡\24ðç©¢\24ñç©£\115ç©©\24òç©«\6îç©°\24ôç©´\8\138\ \ç©¶\7Æç©¹\24õ空\83穽\24öç©¿\11úçª\129\14\11çª\131\11Þçª\132\9³çª\136\ \\24÷çª\146\13\2çª\147\12Kçª\149\24ùçª\150\24ûçª\151\24øçª\152\24úçª\159\ \\8A窩\24ü窪\8E窮\7Ç窯\16±çª°\24þ窶\25\0窺\6\13窿\25\3ç«\131\7\22ç\ \«\132\25\2ç«\133\25\1ç«\135\25\5ç«\136\24ýç«\138\25\6ç«\139\16çç«\141\25\ \\7ç«\143\25\8ç«\146\19rç«\147\25\10ç«\149\25\9ç«\153\25\11ç«\154\25\12ç«\ \\156\16óç«\157\25\13ç«\159\29íç« \11\13ç«¡\25\14ç«¢\25\15ç«£\10¶ç«¥\13öç\ \«¦\25\16竪\12Çç«\173\25\17端\12Ûç«°\25\18ç«¶\7ã竸\18\30竹\12ü竺\101\ \ç«¿\7Fç¬\130\25\19ç¬\132\25 ç¬\134\25\22ç¬\136\7Èç¬\138\25\21ç¬\139\25\ \\34ç¬\143\25\20ç¬\145\11\14ç¬\152\25\24ç¬\153\25\25ç¬\155\13\138ç¬\158\ \\25\26笠\6ý笥\11y符\15D笨\25\28第\12¦ç¬³\25\23笵\25\27笶\25\29笹\ \\9¹ç\173\133\25$ç\173\134\15\13ç\173\136\14¤ç\173\137\13Ùç\173\139\8\24ç\ \\173\140\25#ç\173\141\25!ç\173\143\14³ç\173\144\25\30ç\173\145\12ýç\173\ \\146\13Ûç\173\148\13Úç\173\150\9´ç\173\157\256ç\173¥\25&ç\173§\25(ç\173¬\ \\25+ç\173®\25,ç\173°\25)ç\173±\25*ç\173´\25'ç\173µ\25%ç\173º\25\31ç®\134\ \\15\141ç®\135\6\147ç®\139\253ç®\141\250ç®\143\255ç®\146\254ç®\148\14\147\ \ç®\149\16%ç®\151\9Úç®\152\25.ç®\153\257ç®\154\252ç®\156\251ç®\157\25-ç®\ \\159\25/管\7G箪\12Üç®\173\11ûç®±\14 ç®´\25<箸\14¢ç¯\128\11ßç¯\129\259\ \ç¯\132\14Íç¯\134\25=ç¯\135\15\145ç¯\137\12úç¯\139\258ç¯\140\25:ç¯\143\25\ \;ç¯\157\25>篠\10B篤\14\4篥\25C篦\25B篩\25?ç¯\173\17U篳\25H篶\25Lç\ \¯·\25Iç°\128\25Eç°\135\25Fç°\141\25Kç°\145\25@ç°\146\18\147ç°\147\25Gç°\ \\148\25Aç°\151\25Jç°\159\25Pç°¡\7Hç°£\25Mç°§\25Nç°ª\25Oç°«\25Rç°·\25Qç°¸\ \\14ôç°½\25Sç°¾\17:ç°¿\15«ç±\128\25Xç±\131\25Uç±\140\25Tç±\141\11Ðç±\143\ \\25Wç±\144\25Yç±\148\25Vç±\150\25]ç±\152\25Zç±\159\25[ç± \25D籤\25\92ç±\ \¥\25^籬\25_ç±³\15\132ç±µ\25`ç±¾\16`ç²\129\8\12ç²\130\8Hç²\131\25aç²\137\ \\15rç²\139\11\136ç²\141\16.ç²\144\25bç²\146\16ñç²\149\14\148ç²\151\12%ç²\ \\152\14Sç²\155\10¬ç²\159\5¾ç²¡\25gç²¢\25e粤\25cç²¥\7\31ç²§\11\15粨\25h\ \粫\25fç²\173\25dç²®\25lç²±\25kç²²\25jç²³\25iç²¹\25mç²½\25nç²¾\11¸ç³\128\ \\25oç³\130\25qç³\133\25pç³\138\8Ðç³\142\12\23ç³\146\25sç³\150\13Üç³\152\ \\25rç³\156\25tç³\158\15sç³\159\12Lç³ \9&ç³¢\25uç³§\17\6糯\25wç³²\25xç³´\ \\25yç³¶\25z糸\10\5糺\25{ç³»\8nç³¾\7Êç´\128\7\137ç´\130\25\128ç´\132\16\ \qç´\133\9'ç´\134\25|ç´\138\25\131ç´\139\16dç´\141\14[ç´\144\15\18ç´\148\ \\10Ãç´\149\25\130ç´\151\10Qç´\152\9(ç´\153\10\6ç´\154\7Éç´\155\15tç´\156\ \\25\129ç´ \12&ç´¡\15áç´¢\9µç´«\10\7ç´¬\13[ç´®\25\134ç´¯\17\29ç´°\9\151ç´\ \²\25\135ç´³\11aç´µ\25\137ç´¹\11\16ç´º\9nç´¿\25\136çµ\130\10\137çµ\131\8¼\ \çµ\132\12'çµ\133\25\132çµ\134\25\138çµ\139\25\133çµ\140\8oçµ\142\25\141ç\ \µ\143\25\145çµ\144\8\139çµ\150\25\140çµ\155\25\149çµ\158\9)絡\16Íçµ¢\5º\ \çµ£\25\146給\7Ë絨\25\143çµ®\25\144çµ±\13Ýçµ²\25\142çµ³\25\139çµµ\6Ççµ¶\ \\11âçµ¹\8¦çµ½\25\151ç¶\137\25\148ç¶\143\25\150ç¶\147\25\147ç¶\153\8pç¶\ \\154\12qç¶\155\25\152ç¶\156\12Nç¶\159\25¥ç¶¢\25¡ç¶£\25\155ç¶«\25\159綬\ \\10xç¶\173\5Ûç¶®\25\154綯\25¢ç¶°\25¦ç¶±\9*ç¶²\16Tç¶´\13Tç¶µ\25\156綸\ \\25¤ç¶º\25\153ç¶»\12Ýç¶½\25\158ç¶¾\5»ç¶¿\16Hç·\135\25\157ç·\138\8\25ç·\ \\139\14êç·\143\12Mç·\145\17\14ç·\146\10Ïç·\149\25Îç·\152\25§ç·\154\11üç·\ \\156\25£ç·\157\25¨ç·\158\25ªç· \13wç·¡\25\173ç·¤\25©ç·¨\15\146ç·©\7Iç·¬\ \\16Iç·¯\5Üç·²\25¬ç·´\17;ç·»\25«ç¸\129\6Oç¸\132\14*ç¸\133\25®ç¸\137\25µç¸\ \\138\25¯ç¸\139\25¶ç¸\146\25²ç¸\155\14\155ç¸\158\10Hç¸\159\25´ç¸¡\25±ç¸¢\ \\25·ç¸£\25°ç¸¦\10£ç¸«\15Ä縮\10«ç¸±\25³ç¸²\25À縵\25»ç¸·\25¾ç¸¹\25¼ç¸º\ \\25Á縻\25ºç¸½\25 ç¸¾\11Ñç¹\129\14Éç¹\131\25½ç¹\134\25¸ç¹\138\12\0ç¹\139\ \\8qç¹\141\10\138ç¹\148\11Dç¹\149\12\21ç¹\150\25Äç¹\153\25Æç¹\154\25Çç¹\ \\157\25Ãç¹\158\25Å繦\25¹ç¹§\25Â繩\25Ê繪\25Éç¹\173\16\26ç¹°\8Jç¹¹\25Èç\ \¹»\25Ìç¹¼\25Ëç¹½\25Ï繿\25Ñçº\130\9Ûçº\131\25Íçº\136\25Òçº\137\25Óçº\140\ \\25Ôçº\142\25Úçº\143\13\154çº\144\25Öçº\146\25Õçº\147\25×çº\148\25Øçº\ \\150\25Ùçº\155\25Ûçº\156\25Üç¼¶\7J缸\25Ý缺\25Þç½\133\25ßç½\140\25àç½\ \\141\25áç½\142\25âç½\144\25ãç½\145\25äç½\148\25æç½\149\25åç½\152\25çç½\ \\159\25èç½ \25éç½§\25ì罨\25ê罩\25ë罪\9\159罫\8rç½®\12õç½°\14±ç½²\10Ð\ \ç½µ\14lç½·\14ë罸\25íç½¹\20ëç¾\130\25îç¾\131\25ðç¾\133\16Åç¾\134\25ïç¾\ \\135\25òç¾\136\25ñç¾\138\16²ç¾\140\25óç¾\142\14üç¾\148\25ôç¾\154\25÷ç¾\ \\157\25öç¾\158\25õç¾£\25øç¾¤\8Q羨\12\1義\7 ç¾®\25ü羯\25ùç¾²\25úç¾¶\25\ \ý羸\25þç¾¹\25ûç¾½\6\8ç¿\129\6eç¿\133\26\0ç¿\134\26\1ç¿\138\26\2ç¿\140\ \\16Âç¿\146\10\139ç¿\148\26\4ç¿\149\26\3ç¿ \11\137ç¿¡\26\5翦\26\6ç¿©\26\ \\7ç¿«\7cç¿°\7K翳\26\8翹\26\9ç¿»\15ü翼\16Ãè\128\128\16³è\128\129\17Vè\ \\128\131\9,è\128\132\26\12è\128\133\10Rè\128\134\26\11è\128\139\26\13è\ \\128\140\10'è\128\144\12\143è\128\146\26\14è\128\149\9+è\128\151\16Uè\ \\128\152\26\15è\128\153\26\16è\128\156\26\17è\128¡\26\18è\128¨\26\19è\ \\128³\10(è\128¶\16kè\128»\26\21è\128½\12Þè\128¿\26\20è\129\134\26\23è\ \\129\138\26\22è\129\146\26\24è\129\150\11¹è\129\152\26\25è\129\154\26\26\ \è\129\158\15wè\129\159\26\27è\129¡\12Oè\129¢\26\28è\129¨\26\29è\129¯\17<\ \è\129°\26 è\129²\26\31è\129³\26\30è\129´\13.è\129¶\26!è\129·\11Eè\129¹\ \\26\34è\129½\26#è\129¾\17Wè\129¿\26$è\130\132\26%è\130\133\26'è\130\134\ \\26&è\130\135\14£è\130\137\147è\130\139\17]è\130\140\14§è\130\147\26)è\ \\130\150\11\17è\130\152\15\9è\130\154\26*è\130\155\26(è\130\157\7Lè\130¡\ \\8Òè\130¢\10\8è\130¥\14ìè\130©\8¨è\130ª\15âè\130¬\26-è\130\173\26+è\130¯\ \\9-è\130±\9.è\130²\5çè\130´\9¦è\130º\14xè\131\131\5Ýè\131\132\262è\131\ \\134\12ßè\131\140\14wè\131\142\12\153è\131\150\264è\131\153\260è\131\154\ \\263è\131\155\26.è\131\157\261è\131\158\15Åè\131¡\8Óè\131¤\5ûè\131¥\26/è\ \\131¯\266è\131±\267è\131´\13÷è\131¸\7ùè\131¼\26Eè\131½\14\92è\132\130\10\ \\9è\132\133\7úè\132\134\11Æè\132\135\17eè\132\136\16,è\132\137\265è\132\ \\138\11Òè\132\154\7²è\132\155\268è\132£\26:è\132©\269è\132¯\26;è\132±\12\ \Åè\132³\14]è\132¹\13/è\132¾\26Bè\133\134\26Aè\133\139\26<è\133\142\11tè\ \\133\144\15Eè\133\145\26Dè\133\147\26Cè\133\148\9/è\133\149\17rè\133\159\ \\26Tè\133¥\26Hè\133¦\26Iè\133«\10nè\133®\26Gè\133°\9Xè\133±\26Fè\133´\26\ \Jè\133¸\130è\133¹\15`è\133º\12\2è\133¿\12\154è\134\128\26Nè\134\130\26Oè\ \\134\131\26Kè\134\136\26Lè\134\138\26Mè\134\143\90è\134\147\26Uè\134\149\ \\26Qè\134\154\15Fè\134\156\16\12è\134\157\15\7è\134 \26Pè\134£\26Sè\134¤\ \\26Rè\134¨\15ãè\134©\26Vè\134°\26Wè\134³\12\22è\134µ\26Xè\134¸\26Zè\134º\ \\26^è\134½\26[è\134¾\26Yè\134¿\14^è\135\128\26\92è\135\130\26]è\135\134\ \\6pè\135\136\26dè\135\137\26_è\135\141\26`è\135\145\26aè\135\147\12_è\ \\135\152\26cè\135\153\26bè\135\154\26eè\135\159\26fè\135 \26gè\135£\11bè\ \\135¥\6§è\135§\26hè\135¨\17\21è\135ª\10)è\135\173\10\140è\135³\10\10è\ \\135´\12öè\135º\26iè\135»\26jè\135¼\6\16è\135¾\26kè\136\129\26lè\136\130\ \\26mè\136\133\26nè\136\135\26oè\136\136\7ûè\136\137\21hè\136\138\26pè\ \\136\140\11ãè\136\141\26qè\136\142\10Iè\136\144\26rè\136\146\17®è\136\ \\150\26sè\136\151\15\156è\136\152\7Zè\136\155\12\3è\136\156\10·è\136\158\ \\15Qè\136\159\10\141è\136©\26tè\136ª\91è\136«\26uè\136¬\14Êè\136®\26\132\ \è\136³\26wè\136µ\12\135è\136¶\14\149è\136·\8½è\136¸\26vè\136¹\12\4è\137\ \\128\26xè\137\135\13xè\137\152\26zè\137\153\26yè\137\154\26|è\137\157\26\ \{è\137\159\26}è\137¢\26\128è\137¤\26~è\137¦\7Mè\137¨\26\129è\137ª\26\130\ \è\137«\26\131è\137®\9oè\137¯\17\7è\137±\26\133è\137²\11Fè\137¶\6Pè\137·\ \\26\134è\137¸\26\135è\137¾\26\136è\138\139\5ðè\138\141\26\137è\138\146\ \\26\138è\138\153\15Gè\138\157\10Eè\138\159\26\140è\138¥\6Èè\138¦\5°è\138\ \«\26\139è\138¬\26\142è\138\173\14mè\138¯\11cè\138±\6\148è\138³\15Æè\138¸\ \\8|è\138¹\8\26è\138»\26\141è\138½\6¨è\139\133\7!è\139\145\6Qè\139\146\26\ \\146è\139\147\17(è\139\148\12\155è\139\151\15#è\139\153\26\158è\139\155\ \\6\149è\139\156\26\156è\139\158\26\154è\139\159\26\145è\139¡\26\143è\139\ \£\26\144è\139¥\10aè\139¦\8*è\139§\13\23è\139«\14\15è\139±\60è\139³\26\ \\148è\139´\26\147è\139¹\26\153è\139º\26\149è\139»\26\152è\140\130\16Nè\ \\140\131\26\151è\140\132\6\150è\140\133\7\29è\140\134\26\155è\140\137\26\ \\157è\140\142\8sè\140\150\26¡è\140\151\26ªè\140\152\26«è\140\156\5©è\140\ \£\26²è\140¨\5ïè\140«\26©è\140¯\26¨è\140±\26£è\140²\26¢è\140´\26 è\140µ\ \\26\159è\140¶\13\3è\140¸\12¹è\140¹\26¥è\141\128\26¤è\141\133\26§è\141\ \\137\12Pè\141\138\8tè\141\143\6 è\141\144\26¦è\141\146\92è\141\152\12Qè\ \\141³\26¸è\141µ\26¹è\141·\6\151è\141»\6lè\141¼\26¶è\142\133\26¬è\142\135\ \\26´è\142\137\26»è\142\138\26µè\142\142\26³è\142\147\26\150è\142\150\26±\ \è\142\154\26\173è\142\158\7Nè\142\159\26¯è\142 \26ºè\142¢\26°è\142¨\26¼è\ \\142ª\26®è\142«\14\156è\142±\16Éè\142µ\26·è\142½\26Íè\143\129\26Åè\143\ \\133\11\155è\143\138\7¥è\143\140\8\27è\143\142\26Àè\143\147\6\153è\143\ \\150\11\18è\143\152\26Ãè\143\156\9\152è\143\159\13°è\143 \26Èè\143©\15¬è\ \\143«\26¿è\143¯\6\152è\143°\8Ôè\143±\15\8è\143²\26Éè\143´\26½è\143·\26Æè\ \\143»\26Ðè\143½\26Áè\144\131\26Âè\144\132\13øè\144\135\26Çè\144\139\26Äè\ \\144\140\15Çè\144\141\26Êè\144\142\5Þè\144\147\26¾è\144 \26Ìè\144¢\26Ëè\ \\144©\14\139è\144ª\26Òè\144¬\26Ýè\144±\7\30è\144µ\26àè\144¸\26Îè\144¼\26\ \Óè\144½\16Îè\145\134\26Üè\145\137\16´è\145\142\16èè\145\151\13\24è\145\ \\155\7\11è\145¡\15Rè\145¢\26âè\145£\13ßè\145¦\5¯è\145©\26Ûè\145«\26×è\ \\145¬\12Rè\145\173\26Ñè\145®\26Ùè\145¯\26Þè\145±\14Kè\145µ\5¨è\145·\26Öè\ \\145¹\26ßè\145º\15Xè\146\130\26Úè\146\132\26Õè\146\139\11\19è\146\144\10\ \\142è\146\148\10*è\146\153\16Vè\146\156\15&è\146\159\26åè\146¡\26îè\146\ \\173\26Øè\146²\7\23è\146¸\116è\146¹\26ãè\146»\26èè\146¼\12Sè\146¿\26äè\ \\147\129\26ëè\147\132\12þè\147\134\26ìè\147\137\16µè\147\138\26áè\147\ \\139\6×è\147\141\26çè\147\144\26êè\147\145\16*è\147\150\26íè\147\153\26æ\ \è\147\154\26éè\147¬\15Èè\147®\17@è\147´\26ñè\147¼\26øè\147¿\26ðè\148\128\ \\10Aè\148\134\26Ïè\148\145\15\140è\148\147\16 è\148\148\26÷è\148\149\26ö\ \è\148\151\26òè\148\152\26óè\148\154\6\21è\148\159\26õè\148¡\26ïè\148¦\13\ \Sè\148¬\26ôè\148\173\5üè\148µ\12`è\148½\15\129è\149\128\26ùè\149\129\27\ \\0è\149\131\14×è\149\136\26üè\149\137\11\20è\149\138\10Gè\149\139\27\2è\ \\149\142\7üè\149\149\27\3è\149\151\15Yè\149\152\26ûè\149\154\26Ôè\149£\ \\26úè\149¨\17nè\149©\13àè\149ª\15Sè\149\173\27\10è\149·\27\16è\149¾\27\ \\17è\150\128\27\4è\150\132\14\150è\150\135\27\14è\150\136\27\6è\150\138\ \\27\8è\150\144\27\18è\150\145\27\7è\150\148\27\11è\150\151\6Rè\150\153\ \\14#è\150\155\27\12è\150\156\27\15è\150¤\27\5è\150¦\12\5è\150¨\27\9è\150\ \©\9Æè\150ª\11dè\150«\8Oè\150¬\16rè\150®\16wè\150¯\10Òè\150¹\27\22è\150º\ \\27\20è\151\129\17mè\151\137\27\19è\151\141\16Õè\151\143\27\21è\151\144\ \\27\23è\151\149\27\24è\151\156\27\27è\151\157\27\25è\151¤\13áè\151¥\27\ \\26è\151©\14Ëè\151ª\27\13è\151·\10Óè\151¹\27\28è\151º\27!è\151»\12Tè\151\ \¾\27 è\152\130\27\1è\152\134\27\34è\152\135\12(è\152\138\27\29è\152\139\ \\27\31è\152\147\27\30è\152\150\22\144è\152\151\22\129è\152\154\27$è\152¢\ \\27#è\152\173\16Öè\152¯\24zè\152°\27%è\152¿\27&è\153\141\27'è\153\142\8Õ\ \è\153\144\7³è\153\148\27)è\153\149\18<è\153\154\7Õè\153\156\16øè\153\158\ \\81è\153\159\27*è\153§\27+è\153«\13\14è\153±\27,è\153¹\148è\153»\5¸è\154\ \\138\6¡è\154\139\271è\154\140\272è\154\147\27-è\154\149\9Üè\154£\27.è\ \\154¤\14aè\154©\27/è\154ª\270è\154«\27:è\154¯\274è\154°\277è\154¶\273è\ \\155\132\275è\155\134\276è\155\135\10Vè\155\137\278è\155\139\12àè\155\ \\141\8uè\155\142\6áè\155\148\27;è\155\153\6Þè\155\155\27Aè\155\158\27<è\ \\155\159\27@è\155¤\14¸è\155©\27=è\155¬\27>è\155\173\15'è\155®\14Øè\155¯\ \\27Bè\155¸\12»è\155¹\27Lè\155»\27Hè\155¾\6©è\156\128\27Fè\156\130\15Éè\ \\156\131\27Gè\156\134\27Dè\156\136\27Eè\156\137\27Jè\156\138\27Mè\156\ \\141\27Kè\156\145\27Iè\156\146\27Cè\156\152\12÷è\156\154\27Tè\156\156\16\ \(è\156¥\27Rè\156©\27Sè\156´\27Nè\156·\27Pè\156»\27Qè\156¿\27Oè\157\137\ \\11äè\157\139\17Xè\157\140\27Xè\157\142\27Yè\157\147\27_è\157\149\11Iè\ \\157\151\27[è\157\153\27^è\157\159\27Vè\157 \27Uè\157£\27`è\157¦\6\154è\ \\157¨\27\92è\157ª\27aè\157®\27]è\157´\27Zè\157¶\131è\157¸\27Wè\157¿\14\ \\136è\158\130\27eè\158\141\16\154è\158\159\27dè\158¢\27cè\158«\27lè\158¯\ \\27fè\158³\27nè\158º\16Æè\158»\27qè\158½\27hè\159\128\27iè\159\132\27mè\ \\159\134\27pè\159\135\27oè\159\139\27gè\159\144\27jè\159\146\27{è\159 \ \\27tè\159¯\27rè\159²\27sè\159¶\27xè\159·\27yè\159¹\6Éè\159»\7¡è\159¾\27w\ \è \133\27bè \141\27vè \142\27zè \143\27uè \145\27|è \149\27~è \150\27}è \ \¡\27\128è ¢\27\127è £\279è §\27\132è ±\27\129è ¶\27\130è ¹\27\131è »\27\ \\133è¡\128\8\140è¡\130\27\135è¡\132\27\134è¡\134\10\143è¡\140\93è¡\141\ \\22åè¡\146\27\136è¡\147\10°è¡\151\6Øè¡\153\27\137è¡\155\61è¡\157\11\21è¡\ \\158\27\138è¡¡\94è¡¢\27\139è¡£\5ß表\15\28è¡«\27\140è¡°\11\138衲\27\147\ \衵\27\144è¡·\13\15衽\27\145衾\27\142è¡¿\8\28è¢\129\27\141è¢\130\27\ \\148è¢\136\8Uè¢\139\12\156è¢\141\27\154è¢\146\27\150è¢\150\12sè¢\151\27\ \\149è¢\153\27\152è¢\158\27\143袢\27\153袤\27\155被\14í袮\27\151袰\ \\27\156袱\27\158袴\8Ñ袵\27\146袷\5¿è¢¿\27\157è£\129\9\153è£\130\174è\ \£\131\27\159è£\132\27 è£\133\12Uè£\143\16àè£\148\27¡è£\149\16\148è£\152\ \\27¢è£\153\27£è£\156\15¢è£\157\27¤è£\159\9~裡\16á裨\27©è£²\27ªè£³\11\ \\22裴\27¨è£¸\16Ç裹\27¥è£¼\27§è£½\11»è£¾\11\158è¤\130\27¦è¤\132\27«è¤\ \\135\15aè¤\138\27\173è¤\140\27¬è¤\144\7\12è¤\146\15Êè¤\147\27®è¤\157\27º\ \è¤\158\27°è¤¥\27±è¤ª\27²è¤«\27³è¤¶\27·è¤¸\27¸è¤»\27¶è¥\129\27´è¥\131\27¯\ \è¥\132\27µè¥\140\27¹è¥\141\29µè¥\150\6fè¥\158\27¼è¥\159\8\29襠\27»è¥¤\ \\27Á襦\27À襪\27Ãè¥\173\27Â襯\27Ä襲\10\144襴\27Å襷\27Æè¥¾\27Ç西\11\ \¼è¦\129\16¶è¦\131\27Èè¦\134\15bè¦\135\14eè¦\136\27Éè¦\138\27Êè¦\139\8©è¦\ \\143\7\139è¦\147\27Ëè¦\150\10\11è¦\151\14`è¦\152\27Ìè¦\154\6ï覡\27Í覦\ \\27Ï覧\16×覩\27Î親\11e覬\27Ð覯\27Ñ覲\27Ò観\7O覺\27Ó覽\27Ô覿\27\ \Õè§\128\27Öè§\146\6ðè§\154\27×è§\156\27Øè§\157\27Ùè§£\6°è§¦\11Gè§§\27Úè§\ \´\27Û觸\27Üè¨\128\8¾è¨\130\13yè¨\131\27Ýè¨\136\8vè¨\138\11uè¨\140\27àè¨\ \\142\13âè¨\144\27ßè¨\147\8Pè¨\150\27Þè¨\151\12µè¨\152\7\140è¨\155\27áè¨\ \\157\27âè¨\159\11\23訣\8\141訥\27ã訪\15Ëè¨\173\11Ý許\7Ö訳\16s訴\12\ \)訶\27ä診\11f註\13\16証\11\24è©\129\27åè©\134\27èè©\136\27éè©\144\9|\ \è©\145\12\128è©\146\27çè©\148\11\25è©\149\15\29è©\155\27æè©\158\10\12è© \ \\62è©¢\27íè©£\8w試\10\14è©©\10\13è©«\17l詬\27ìè©\173\27ëè©®\12\6è©°\7¬\ \話\17b該\6Ù詳\11\26詼\27êèª\130\27ïèª\132\27ðèª\133\27îèª\135\8Öèª\ \\137\16\159èª\140\10\15èª\141\14Fèª\145\27óèª\147\11¾èª\149\12áèª\152\16\ \\149èª\154\27öèª\158\8ê誠\11½èª¡\27ò誣\27÷誤\8ë誥\27ô誦\27õ誨\27ñè\ \ª¬\11àèª\173\14\7誰\12Î課\6\155誹\14î誼\7¢èª¿\132è«\130\27úè«\132\27\ \øè«\135\12ëè«\139\11¿è«\140\7Pè«\141\27ùè«\143\11zè«\146\17\8è«\150\17_è\ \«\154\27ûè«\155\28\7è«\156\133è«\158\28\6è« \28\3è«¡\28\11è«¢\28\4諤\28\ \\0諦\13zè«§\27þè««\27üè«\173\16\128è«®\10\16諱\28\1諳\27ýè«·\28\5諸\ \\10Ô諺\8¿è«¾\12¸è¬\128\15äè¬\129\69è¬\130\5àè¬\132\13ãè¬\135\28\9è¬\140\ \\28\8è¬\142\14$è¬\144\28\13è¬\148\28\2è¬\150\28\12è¬\151\28\14è¬\153\8ªè\ \¬\154\28\10è¬\155\95è¬\157\10S謠\28\15謡\16·è¬¦\28\18謨\28\21謫\28\ \\19謬\15\20謳\28\16謹\8\30謾\28\20è\173\129\28\22è\173\137\28\26è\ \\173\140\28\23è\173\142\28\25è\173\143\28\24è\173\150\28\27è\173\152\10/\ \è\173\154\28\29è\173\155\28\28è\173\156\15Hè\173\159\28\31è\173¦\8xè\173\ \«\28\30è\173¬\28 è\173¯\28!è\173°\7£è\173±\25ÿè\173²\117è\173´\28\34è\ \\173·\8ìè\173½\28#è®\128\28$è®\131\9Ýè®\138\21\140è®\140\28%è®\142\28&è®\ \\144\10\145è®\146\28'è®\147\28(è®\150\28)è®\153\28*è®\154\28+è°·\12Êè°º\ \\28,è°¿\28.è±\129\28-è±\134\13äè±\136\28/è±\138\15Ìè±\140\280è±\142\281è\ \±\144\282è±\149\283è±\154\14\24象\11\27è±¢\284豪\9K豫\17¬è±¬\285豸\ \\286è±¹\15\30豺\287è±¼\28?è²\130\288è²\133\28:è²\137\289è²\138\28;è²\ \\140\15åè²\141\28<è²\142\28=è²\148\28>è²\152\28@è²\157\6Ìè²\158\13eè² \ \\15I財\9 è²¢\96è²§\15.貨\6\157販\14Ì貪\28C貫\7Q責\11Óè²\173\28Bè²®\ \\28G貯\13\25è²°\16aè²²\28Eè²³\28Fè²´\7\141è²¶\28Hè²·\14\131貸\12\157è²\ \»\14ïè²¼\13\156è²½\28D貿\15æè³\128\6ªè³\129\28Jè³\130\17Gè³\131\13@è³\ \\132\17dè³\135\10\17è³\136\28Iè³\138\12oè³\141\28Zè³\142\12\7è³\145\146è\ \³\147\15/è³\154\28Mè³\155\9Þè³\156\10\18è³\158\11\28è³ \14\133è³¢\8«è³£\ \\28L賤\28K賦\15J質\10?è³\173\13±è³º\28Oè³»\28Pè³¼\97è³½\28Nè´\132\28Q\ \è´\133\28Rè´\135\28Tè´\136\12aè´\138\28Sè´\139\7dè´\141\28Vè´\143\28Uè´\ \\144\28Wè´\147\28Yè´\148\28[è´\150\28\92赤\11Ô赦\10Mèµ§\28]赫\6ñèµ\ \\173\28^èµ°\12Vèµ±\28_èµ³\28`èµ´\15Kèµ·\7\142è¶\129\28aè¶\133\134è¶\138\ \\6:è¶\153\28bè¶£\10o趨\11\150è¶³\12k趺\28eè¶¾\28dè·\130\28cè·\139\28kè\ \·\140\28iè·\143\28fè·\150\28hè·\154\28gè·\155\28jè·\157\7×è·\159\28nè·¡\ \\11Õè·£\28oè·¨\8×è·ª\28lè·«\28mè·¯\17Hè·³\135è·µ\12\8è·¼\28pè·¿\28sè¸\ \\136\28qè¸\137\28rè¸\138\16¸è¸\143\13åè¸\144\28vè¸\157\28tè¸\158\28uè¸\ \\159\28w踪\28\136踰\28z踴\28{踵\28yè¹\130\28xè¹\132\13{è¹\135\28\128\ \è¹\136\28\132è¹\137\28\129è¹\138\28|è¹\140\28\130è¹\144\28\131è¹\149\28\ \\138è¹\153\28\133è¹\159\11Öè¹ \28\135è¹£\28\137蹤\28\134è¹²\28\140è¹´\ \\10\146è¹¶\28\139è¹¼\28\141èº\129\28\142èº\132\28\145èº\133\28\144èº\135\ \\28\143èº\138\28\147èº\139\28\146èº\141\16tèº\145\28\149èº\147\28\148èº\ \\148\28\150èº\153\28\151躡\28\153躪\28\152身\11g躬\28\154躯\8+躰\ \\28\155躱\28\157躾\28\158è»\133\28\159è»\134\28\156è»\136\28 è»\138\10\ \Tè»\139\28¡è»\140\7\143è»\141\8Rè»\146\8¬è»\155\28¢è»\159\14.転\13\157è\ \»£\28£è»«\28¦è»¸\102è»»\28¥è»¼\28¤è»½\8y軾\28§è¼\131\6òè¼\133\28©è¼\137\ \\9\154è¼\138\28¨è¼\140\28±è¼\146\28«è¼\147\28\173è¼\148\15£è¼\149\28ªè¼\ \\153\28¬è¼\155\28°è¼\156\28®è¼\157\7\144è¼\159\28¯è¼¦\28²è¼©\14y輪\17\ \\22輯\10\147è¼³\28³è¼¸\16\129è¼¹\28µè¼»\28´è¼¾\28¸è¼¿\16 è½\130\28·è½\ \\132\7\13è½\133\28¶è½\134\28»è½\137\28ºè½\140\28¹è½\141\13\145è½\142\28¼\ \è½\151\28½è½\156\28¾è½\159\9L轡\8Dè½¢\28Àè½£\28Á轤\28Âè¾\155\11hè¾\156\ \\28Ãè¾\158\10+è¾\159\28Äè¾£\28Åè¾§\18_辨\18^è¾\173\28Æè¾®\25Ð辯\28Çè¾°\ \\12Ãè¾±\11Jè¾²\14_è¾·\28È辺\15\147è¾»\13Rè¾¼\9^辿\12Èè¿\130\6\9è¿\132\ \\16\24è¿\133\11vè¿\142\8}è¿\145\8\31è¿\148\15\148è¿\154\28Éè¿¢\28Ëè¿¥\28\ \Ê迦\6\158è¿©\144迪\28Ìè¿«\14\151è¿\173\13\146迯\28Íè¿°\10±è¿´\28Ïè¿·\ \\16@迸\28Þ迹\28Ñ迺\28Ò追\13Gé\128\128\12\158é\128\129\12Wé\128\131\ \\13æé\128\133\28Ðé\128\134\7´é\128\139\28Ùé\128\141\28Öé\128\142\28ãé\ \\128\143\13çé\128\144\13\0é\128\145\28Óé\128\147\13|é\128\148\13²é\128\ \\149\28Ôé\128\150\28Øé\128\151\11\128é\128\153\14\135é\128\154\13Jé\128\ \\157\11Àé\128\158\28×é\128\159\12lé\128 \12bé\128¡\28Õé\128¢\5§é\128£\17\ \Aé\128§\28Úé\128®\12\159é\128±\10\148é\128²\11ié\128µ\28Üé\128¶\28Ûé\128\ \¸\5íé\128¹\28Ýé\128¼\15\14é\128¾\28åé\129\129\14\25é\129\130\11\139é\129\ \\133\12øé\129\135\86é\129\137\28äé\129\138\16\150é\129\139\6\30é\129\141\ \\15\149é\129\142\6\159é\129\143\28ßé\129\144\28àé\129\145\28áé\129\146\ \\28âé\129\147\13ùé\129\148\12Âé\129\149\5áé\129\150\28æé\129\152\28çé\ \\129\153\31!é\129\156\12{é\129\158\28èé\129 \6Sé\129¡\12+é\129£\8\173é\ \\129¥\16¹é\129¨\28éé\129©\13\139é\129\173\12Xé\129®\10Ué\129¯\28êé\129²\ \\28íé\129µ\10Åé\129¶\28ëé\129·\12\10é\129¸\12\9é\129º\5âé\129¼\17\9é\129\ \½\28ïé\129¿\14ðé\130\128\28ñé\130\129\28ðé\130\130\28îé\130\131\25\4é\ \\130\132\7Ré\130\135\28Îé\130\137\28óé\130\138\28òé\130\143\28ôé\130\145\ \\16\151é\130£\14\31é\130¦\15Íé\130¨\28õé\130ª\10Wé\130¯\28öé\130±\28÷é\ \\130µ\28øé\130¸\13\128é\131\129\5èé\131\138\98é\131\142\17Yé\131\155\28ü\ \é\131¡\8Sé\131¢\28ùé\131¤\28úé\131¨\15Té\131\173\6óé\131µ\16\152é\131·\7\ \ýé\131½\13³é\132\130\28ýé\132\146\28þé\132\153\28ÿé\132\173\13\129é\132°\ \\29\1é\132²\29\0é\133\137\14\17é\133\138\29\2é\133\139\10\149é\133\140\ \\10^é\133\141\14zé\133\142\13\17é\133\146\10pé\133\148\11\140é\133\150\ \\29\3é\133\152\29\4é\133¢\11|é\133£\29\5é\133¥\29\6é\133©\29\7é\133ª\16Ï\ \é\133¬\10\150é\133²\29\9é\133³\29\8é\133µ\99é\133·\9Sé\133¸\9ßé\134\130\ \\29\12é\134\135\10Æé\134\137\29\11é\134\139\29\10é\134\141\12§é\134\144\ \\8íé\134\146\11Áé\134\151\14®é\134\156\10\152é\134¢\29\13é\134¤\11\29é\ \\134ª\29\16é\134«\29\14é\134¯\29\15é\134´\29\18é\134µ\29\17é\134¸\118é\ \\134º\29\19é\135\128\29\20é\135\129\29\21é\135\134\14Îé\135\135\9\145é\ \\135\136\10_é\135\137\29\22é\135\139\29\23é\135\140\16âé\135\141\10¤é\ \\135\142\16lé\135\143\17\10é\135\144\29\24é\135\145\8 é\135\150\29\25é\ \\135\152\13\130é\135\155\29\28é\135\156\7\24é\135\157\11jé\135\159\29\26\ \é\135¡\29\27é\135£\13^é\135¦\15ôé\135§\8:é\135µ\29\30é\135¶\29\31é\135¼\ \\29\29é\135¿\29!é\136\141\14\29é\136\142\6âé\136\145\29%é\136\148\29\34é\ \\136\149\29$é\136\158\29 é\136©\29né\136¬\29#é\136´\17)é\136·\8Øé\136¿\ \\29-é\137\132\13\147é\137\133\29(é\137\136\29+é\137\137\29)é\137\139\29.\ \é\137\144\29/é\137\151\29'é\137\154\294é\137\155\6Té\137\158\29&é\137¢\ \\14«é\137¤\29*é\137¦\11\30é\137±\9:é\137¾\15çé\138\128\8\34é\138\131\10¥\ \é\138\133\13úé\138\145\12\12é\138\147\292é\138\149\29,é\138\150\291é\138\ \\152\16Aé\138\154\136é\138\155\293é\138\156\290é\138\173\12\11é\138·\297\ \é\138¹\296é\139\143\295é\139\146\15Îé\139¤\10Ûé\139©\298é\139ª\15\157é\ \\139\173\63é\139²\15%é\139³\13\18é\139¸\7Øé\139º\29:é\139¼\9<é\140\134\9\ \Ëé\140\143\299é\140\144\11\141é\140\152\11\142é\140\153\29@é\140\154\29B\ \é\140 \119é\140¢\29Aé\140£\29Cé\140¦\8\17é\140¨\15$é\140«\10`é\140¬\17Bé\ \\140®\29<é\140¯\9¶é\140²\17^é\140µ\29Eé\140º\29Dé\140»\29Fé\141\132\29;é\ \\141\139\14'é\141\141\13´é\141\148\13Ué\141\150\29Ké\141\155\12âé\141\ \\156\29Gé\141 \29Hé\141¬\8Lé\141®\29Jé\141µ\8®é\141¼\29Ié\141¾\11\31é\ \\142\140\7\25é\142\148\29Oé\142\150\9}é\142\151\12Yé\142\154\13Hé\142§\6\ \Úé\142¬\29Mé\142\173\29Né\142®\13Aé\142°\29Lé\142¹\29Pé\143\131\29Vé\143\ \\136\29Yé\143\144\29Xé\143\145\13\140é\143\150\29Qé\143\151\29Ré\143\152\ \\29Ué\143\157\29Wé\143¡\7þé\143¤\29Zé\143¥\29Té\143¨\29Sé\144\131\29^é\ \\144\135\29_é\144\144\29`é\144\147\29]é\144\148\29\92é\144\152\11 é\144\ \\153\13èé\144\154\29[é\144¡\29dé\144«\29bé\144µ\29cé\144¶\29aé\144¸\12¶é\ \\144º\29eé\145\129\29fé\145\132\29hé\145\145\7Sé\145\146\29gé\145\147\16\ \xé\145\154\29sé\145\155\29ié\145\158\29lé\145 \29jé\145¢\29ké\145ª\29mé\ \\145°\29oé\145µ\29pé\145·\29qé\145¼\29té\145½\29ré\145¾\29ué\145¿\29wé\ \\146\129\29vé\149·\137é\150\128\16eé\150\130\29xé\150\131\12\13é\150\135\ \\29yé\150\137\15\130é\150\138\29zé\150\139\6Êé\150\143\6\27é\150\145\7Ué\ \\150\147\7Té\150\148\29{é\150\150\29|é\150\152\29}é\150\153\29~é\150 \29\ \\128é\150¢\7Vé\150£\6ôé\150¤\9=é\150¥\14´é\150§\29\130é\150¨\29\129é\150\ \\173\29\131é\150²\6;é\150¹\29\134é\150»\29\133é\150¼\29\132é\150¾\29\135\ \é\151\131\29\138é\151\135\5Åé\151\138\29\136é\151\140\29\140é\151\141\29\ \\139é\151\148\29\142é\151\149\29\141é\151\150\29\143é\151\152\13ìé\151\ \\156\29\144é\151¡\29\145é\151¢\29\147é\151¥\29\146é\152\156\15Lé\152¡\29\ \\148é\152¨\29\149é\152ª\9£é\152®\29\150é\152¯\29\151é\152²\15èé\152»\12*\ \é\152¿\5¢é\153\128\12\137é\153\130\29\152é\153\132\15Mé\153\139\29\155é\ \\153\140\29\153é\153\141\9>é\153\143\29\154é\153\144\8Àé\153\155\15\131é\ \\153\156\29\157é\153\157\29\159é\153\158\29\158é\153\159\29 é\153¢\6\0é\ \\153£\11wé\153¤\10Üé\153¥\7Wé\153¦\29¡é\153ª\14\134é\153¬\29£é\153°\6\1é\ \\153²\29¢é\153³\13Bé\153µ\17\11é\153¶\13éé\153·\29\156é\153¸\16äé\153º\8\ \¯é\153½\16ºé\154\133\87é\154\134\16òé\154\136\8Gé\154\138\12 é\154\139\ \\26@é\154\141\29¤é\154\142\6Ëé\154\143\11\143é\154\148\6õé\154\149\29¦é\ \\154\151\29§é\154\152\29¥é\154\153\8\132é\154\155\9\155é\154\156\11!é\ \\154 \6\2é\154£\17\23é\154§\29©é\154¨\28ìé\154ª\29¨é\154°\29¬é\154±\29ªé\ \\154²\29«é\154´\29\173é\154¶\29®é\154·\17*é\154¸\29¯é\154¹\29°é\154»\11Ç\ \é\154¼\14¹é\155\128\11\157é\155\129\7eé\155\132\16\153é\155\133\6«é\155\ \\134\10\151é\155\135\8Ùé\155\137\29³é\155\139\29²é\155\140\10\19é\155\ \\141\29´é\155\142\29±é\155\145\9Çé\155\149\29¸é\155\150\27ké\155\153\18\ \\148é\155\155\11\151é\155\156\29¶é\155¢\16ãé\155£\14/é\155¨\6\10é\155ª\ \\11áé\155«\104é\155°\15ué\155²\6\31é\155¶\17+é\155·\16Ëé\155¹\29¹é\155»\ \\13¤é\156\128\10yé\156\132\29ºé\156\134\29»é\156\135\11ké\156\136\29¼é\ \\156\138\17,é\156\141\29·é\156\142\29¾é\156\143\29Àé\156\145\29¿é\156\ \\147\29½é\156\150\29Áé\156\153\29Âé\156\156\12Zé\156\158\6 é\156¤\29Ãé\ \\156§\166é\156ª\29Äé\156°\29Åé\156²\17Ié\156¸\21Ðé\156¹\29Æé\156½\29Çé\ \\156¾\29Èé\157\130\29Ìé\157\132\29Éé\157\134\29Êé\157\136\29Ëé\157\137\ \\29Íé\157\146\11Âé\157\150\16ué\157\153\11Ãé\157\156\29Îé\157\158\14ñé\ \\157 \29Ïé\157¡\30òé\157¢\16Jé\157¤\29Ðé\157¦\29Ñé\157¨\29Òé\157©\6öé\ \\157«\29Ôé\157\173\11xé\157±\29Õé\157´\8Cé\157¹\29Öé\157º\29Úé\157¼\29Øé\ \\158\129\29Ùé\158\132\7\19é\158\133\29×é\158\134\29Ûé\158\139\29Üé\158\ \\141\5Æé\158\143\29Ýé\158\144\29Þé\158\152\11\34é\158\156\29ßé\158 \7¦é\ \\158£\29âé\158¦\29áé\158¨\29àé\158«\28\17é\158\173\15\154é\158³\29ãé\158\ \´\29äé\159\131\29åé\159\134\29æé\159\136\29çé\159\139\29èé\159\147\7Xé\ \\159\156\29éé\159\173\29êé\159®\14Bé\159²\29ìé\159³\6yé\159µ\29ïé\159¶\ \\29îé\159»\6\3é\159¿\7ÿé \129\15\133é \130\138é \131\9`é \133\9@é \134\ \\10Çé \136\11{é \140\29ñé \143\29ðé \144\16¡é \145\7fé \146\14Ðé \147\14\ \\26é \151\11\156é \152\17\12é \154\8zé ¡\29ôé ¤\29óé ¬\15êé \173\13êé ´\ \\6/é ·\29õé ¸\29òé »\150é ¼\16Êé ½\29öé¡\134\29÷é¡\139\29ùé¡\140\12¨é¡\ \\141\6úé¡\142\6ûé¡\143\29øé¡\148\7gé¡\149\8°é¡\152\7hé¡\155\13\158é¡\158\ \\17\30é¡§\8Úé¡«\29ú顯\29ûé¡°\29ü顱\30\0顳\30\2é¡´\30\1風\15W颪\30\3\ \颯\30\4颱\30\5颶\30\6é£\131\30\8é£\132\30\7é£\134\30\9é£\155\14òé£\ \\156\26\10é£\159\11H飢\7\145飩\30\10飫\30\11é£\173\18j飮\22\154飯\ \\14Ñ飲\5ù飴\5¹é£¼\10\20飽\15Ï飾\11<é¤\131\30\12é¤\133\16]é¤\137\30\ \\13é¤\138\16»é¤\140\6!é¤\144\9àé¤\146\30\14é¤\147\6¬é¤\148\30\15é¤\152\ \\30\16é¤\157\30\18é¤\158\30\19餠\30\21餡\30\17餤\30\20館\7Y餬\30\22\ \餮\30\23餽\30\24餾\30\25é¥\130\30\26é¥\133\30\28é¥\137\30\27é¥\139\30\ \\30é¥\140\30!é¥\144\30\29é¥\145\30\31é¥\146\30 é¥\149\30\34é¥\151\8\0é¦\ \\150\10qé¦\151\30#é¦\152\30$é¦\153\9A馥\30%馨\6Ý馬\14né¦\173\30&馮\ \\30'馳\12ù馴\14)馼\30(é§\129\14\157é§\132\12\138é§\133\67é§\134\8,é§\ \\136\8-é§\144\13\19é§\145\30-é§\146\8.é§\149\6\173é§\152\30,é§\155\30*é§\ \\157\30+é§\159\30)é§¢\307é§\173\30.é§®\30/é§±\300é§²\301駸\303é§»\302é§\ \¿\10¸é¨\129\304é¨\133\306é¨\142\7\146é¨\143\305é¨\146\12[é¨\147\8±é¨\153\ \\308騨\12\139騫\309騰\13ë騷\30:騾\30@é©\128\30=é©\130\30<é©\131\30>\ \é©\133\30;é©\141\30Bé©\149\30Aé©\151\30Dé©\154\8\1é©\155\30Cé©\159\30Eé©\ \¢\30F驤\30Hé©¥\30Gé©©\30I驪\30Ké©«\30J骨\9\92éª\173\30L骰\30M骸\6Ûé\ \ª¼\30Né«\128\30Oé«\132\11\145é«\143\30Pé«\145\30Qé«\147\30Ré«\148\30Sé«\ \\152\9Bé«\158\30Té«\159\30Ué«¢\30Vé«£\30W髦\30X髪\14¯é««\30Zé«\173\15\ \\5é«®\30[髯\30Y髱\30]é«´\30\92é«·\30^é«»\30_é¬\134\30`é¬\152\30aé¬\154\ \\30bé¬\159\30c鬢\30d鬣\30e鬥\30f鬧\30g鬨\30h鬩\30i鬪\30j鬮\30ké¬\ \¯\30l鬱\22\148鬲\30m鬻\25v鬼\7\147é\173\129\6Àé\173\130\9pé\173\131\ \\30oé\173\132\30né\173\133\16#é\173\141\30qé\173\142\30ré\173\143\30pé\ \\173\145\30sé\173\148\16\2é\173\152\30té\173\154\7Ûé\173¯\17Dé\173´\30ué\ \®\131\30wé®\142\5¼é®\145\30xé®\146\15ié®\147\30vé®\150\30yé®\151\30zé®\ \\159\30{é® \30|鮨\30}鮪\16\14鮫\9Ìé®\173\9¸é®®\12\14é®´\30~鮹\30\129\ \é¯\128\30\127é¯\134\30\130é¯\137\8ïé¯\138\30\128é¯\143\30\131é¯\145\30\ \\132é¯\146\30\133é¯\148\30\137é¯\150\9Éé¯\155\12¢é¯¡\30\138鯢\30\135鯣\ \\30\134鯤\30\136鯨\8~鯰\30\142鯱\30\141鯲\30\140鯵\5±é°\132\30\152\ \é°\134\30\148é°\136\30\149é°\137\30\145é°\138\30\151é°\140\30\147é°\141\ \\7\2é°\144\17ké°\146\30\150é°\147\30\146é°\148\30\144é°\149\30\143é°\155\ \\30\154é°¡\30\157é°¤\30\156é°¥\30\155é°\173\15(é°®\30\153é°¯\5ñé°°\30\ \\158é°²\30 é°¹\7\15é°º\30\139é°»\6\22é°¾\30¢é±\134\30¡é±\135\30\159é±\ \\136\12Ìé±\146\16\16é±\151\17\24é±\154\30£é± \30¤é±§\30¥é±¶\30¦é±¸\30§é³\ \¥\139é³§\30¨é³©\14µé³«\30\173鳬\30©é³°\30ªé³³\15Ðé³´\16Bé³¶\14\14é´\131\ \\30®é´\134\30¯é´\135\13üé´\136\30¬é´\137\30«é´\142\6hé´\146\30·é´\149\30\ \¶é´\155\6Ué´\159\30´é´£\30³é´¦\30±é´¨\7\27é´ª\30°é´«\100é´¬\6gé´»\9Cé´¾\ \\30ºé´¿\30¹éµ\129\30¸éµ\132\30µéµ\134\30»éµ\136\30¼éµ\144\30Äéµ\145\30Ãé\ \µ\153\30Åéµ\156\6\12éµ\157\30Àéµ\158\30Áéµ \9T鵡\167鵤\30Â鵬\15Ñ鵯\ \\30Êéµ²\30Æéµº\30Ëé¶\135\30Èé¶\137\30Çé¶\143\8{é¶\154\30Ì鶤\30Íé¶©\30Îé\ \¶«\30É鶯\30²é¶²\30Ïé¶´\13_鶸\30Ó鶺\30Ôé¶»\30Òé·\129\30Ñé·\130\30×é·\ \\132\30Ðé·\134\30Õé·\143\30Öé·\147\30Ùé·\153\30Øé·¦\30Ûé·\173\30Üé·¯\30Ý\ \é·²\17hé·¸\30Úé·¹\12©é·º\9«é·½\30Þé¸\154\30ßé¸\155\30àé¸\158\30áé¹µ\30âé\ \¹¸\8²é¹¹\30ãé¹½\30ä鹿\10-éº\129\30åéº\136\30æéº\139\30çéº\140\30èéº\145\ \\30ëéº\146\30ééº\147\17[éº\149\30êéº\151\17-éº\157\30ìéº\159\17\25麥\30\ \í麦\14\158麩\30î麪\30ðéº\173\30ñ麸\30ï麹\9M麺\16K麻\16\3麼\205éº\ \¾\22À麿\16\27é»\132\6ié»\140\30óé»\141\7¯é»\142\30ôé»\143\30õé»\144\30ö\ \é»\146\9Ué»\148\30÷é»\152\23Òé»\153\16Yé»\155\12¡é»\156\30øé»\157\30úé»\ \\158\30ùé» \30û黥\30ü黨\30ý黯\30þé»´\31\0é»¶\31\1é»·\31\2黹\31\3é»»\ \\31\4黼\31\5黽\31\6é¼\135\31\7é¼\136\31\8é¼\142\13\131é¼\147\8Ûé¼\149\ \\31\10é¼ \12,鼡\31\11鼬\31\12é¼»\15\0é¼¾\31\13é½\138\31\14é½\139\24Öé½\ \\142\28Xé½\143\29ëé½\146\31\15é½\148\31\16é½\159\31\18é½ \31\19齡\31\20\ \é½¢\17.é½£\31\17齦\31\21é½§\31\22齪\31\24齬\31\23é½²\31\26é½¶\31\27é½\ \·\31\25é¾\141\16ôé¾\149\31\28é¾\156\31\29é¾\157\24óé¾ \31\30ï¼\129\0\9ï¼\ \\131\0Tï¼\132\0Pï¼\133\0Sï¼\134\0Uï¼\136\0)ï¼\137\0*ï¼\138\0Vï¼\139\0;ï¼\ \\140\0\3ï¼\142\0\4ï¼\143\0\30ï¼\144\0Ïï¼\145\0Ðï¼\146\0Ñï¼\147\0Òï¼\148\ \\0Óï¼\149\0Ôï¼\150\0Õï¼\151\0Öï¼\152\0×ï¼\153\0Øï¼\154\0\6ï¼\155\0\7ï¼\ \\156\0Cï¼\157\0Aï¼\158\0Dï¼\159\0\8ï¼ \0WA\0àï¼¢\0áï¼£\0âD\0ãï¼¥\0äï\ \¼¦\0åï¼§\0æï¼¨\0çI\0èJ\0éK\0êL\0ëï¼\173\0ìï¼®\0íO\0îï¼°\0ïï¼±\ \\0ðï¼²\0ñï¼³\0òï¼´\0óï¼µ\0ôï¼¶\0õï¼·\0öX\0÷ï¼¹\0øï¼º\0ùï¼»\0-ï¼¼\0\31ï\ \¼½\0.ï¼¾\0\15_\0\17ï½\128\0\13ï½\129\1\1ï½\130\1\2ï½\131\1\3ï½\132\1\4\ \ï½\133\1\5ï½\134\1\6ï½\135\1\7ï½\136\1\8ï½\137\1\9ï½\138\1\10ï½\139\1\11\ \ï½\140\1\12ï½\141\1\13ï½\142\1\14ï½\143\1\15ï½\144\1\16ï½\145\1\17ï½\146\ \\1\18ï½\147\1\19ï½\148\1\20ï½\149\1\21ï½\150\1\22ï½\151\1\23ï½\152\1\24ï\ \½\153\1\25ï½\154\1\26ï½\155\0/ï½\156\0\34ï½\157\00ï¿£\0\16ï¿¥\0O" -- Compile with : -- stack ghc --package iconv --package bytestring --package containers --package binary -- < name>.hs module where import Codec . Text . IConv ( convertStrictly ) import Data . Binary ( encode ) import Data . Bits ( shiftL , shiftR , ( . & . ) ) import qualified Data . ByteString . Lazy as BL import Data . ( chr , isDigit ) import Data . List ( intercalate ) import qualified Data . Map as M import Data . Maybe ( mapMaybe ) import Data . Word ( , , Word8 ) unicodeToKanji : : Word32 - > Maybe ( , ) unicodeToKanji cw = case convertStrictly " UTF-32BE " " Shift_JIS " cb of Left kc | BL.length kc = = 2 - > case fromIntegral ( kc ` BL.index ` 0 ) ` shiftL ` 8 + fromIntegral ( kc ` BL.index ` 1 ) of k | k > = 0x8140 & & k < = 0x9ffc - > Just ( cc , go ( k - 0x8140 ) ) | k > = 0xe040 & & k < = 0xebbf - > Just ( cc , go ( k - 0xc140 ) ) | otherwise - > Nothing _ - > Nothing where go : : Word16 go k = ( k ` shiftR ` 8) * 0xc0 + ( k . & . 0xff ) cc : : = chr ( fromIntegral cw ) cb : : [ fromIntegral ( cw ` shiftR ` 24 ) , fromIntegral ( cw ` shiftR ` 16 ) , fromIntegral ( cw ` shiftR ` 8) , fromIntegral cw ] showB : : Word8 - > String showB c -- c0 - ctrl quote backslash del + c1 - ctrl - chars shy | c < 0x20 || c = = 0x22 || c = = 0x5c || ( c > = 0x7f & & c < 0xa0 ) || c = = 0xad = ' \\ ' : show c | otherwise = -- This character can be encoded directly [ chr ( fromIntegral c ) ] addEmptyString : : [ String ] - > [ String ] addEmptyString ( x@('\\ ' : _ ) : y@(y1 : _ ) : zs ) | isDigit y1 = x : " \ & " : y : addEmptyString zs addEmptyString ( x : xs ) = x : addEmptyString xs addEmptyString [ ] = [ ] chunksOf : : Int - > [ [ a ] ] - > [ [ a ] ] chunksOf = go [ ] where go : : [ a ] - > Int - > [ [ a ] ] - > [ [ a ] ] go p _ [ ] = [ p ] go p n ( x : xs ) = let n ' = n - length x in case n ' ` compare ` 0 of LT - > p : go [ ] n0 ( x : xs ) EQ - > ( p++x ) : go [ ] n0 xs GT - > go ( p++x ) n ' xs main : : IO ( ) main = do let kanjiMap : : M.Map kanjiMap = M.fromList ( mapMaybe unicodeToKanji [ 0 .. 0x10ffff ] ) stream : : [ String ] stream = addEmptyString ( map showB ( ( encode kanjiMap ) ) ) putStrLn " kanjiMap : : M.Map " putStrLn " kanjiMap = decode " putStrLn ( " \ " " + + intercalate " \\\n \\ " ( chunksOf 72 stream ) + + " \ " " ) -- Compile with: -- stack ghc --package iconv --package bytestring --package containers --package binary -- <name>.hs module Main where import Codec.Text.IConv (convertStrictly) import Data.Binary (encode) import Data.Bits (shiftL, shiftR, (.&.)) import qualified Data.ByteString.Lazy as BL import Data.Char (chr, isDigit) import Data.List (intercalate) import qualified Data.Map as M import Data.Maybe (mapMaybe) import Data.Word (Word16, Word32, Word8) unicodeToKanji :: Word32 -> Maybe (Char, Word16) unicodeToKanji cw = case convertStrictly "UTF-32BE" "Shift_JIS" cb of Left kc | BL.length kc == 2 -> case fromIntegral (kc `BL.index` 0) `shiftL` 8 + fromIntegral (kc `BL.index` 1) of k | k >= 0x8140 && k <= 0x9ffc -> Just (cc, go (k - 0x8140)) | k >= 0xe040 && k <= 0xebbf -> Just (cc, go (k - 0xc140)) | otherwise -> Nothing _ -> Nothing where go :: Word16 -> Word16 go k = (k `shiftR` 8) * 0xc0 + (k .&. 0xff) cc :: Char cc = chr (fromIntegral cw) cb :: BL.ByteString cb = BL.pack [ fromIntegral (cw `shiftR` 24) , fromIntegral (cw `shiftR` 16) , fromIntegral (cw `shiftR` 8) , fromIntegral cw ] showB :: Word8 -> String showB c -- c0-ctrl quote backslash del + c1-ctrl-chars shy | c < 0x20 || c == 0x22 || c == 0x5c || (c >= 0x7f && c < 0xa0) || c == 0xad = '\\' : show c | otherwise = -- This character can be encoded directly [chr (fromIntegral c)] addEmptyString :: [String] -> [String] addEmptyString (x@('\\':_) : y@(y1:_) : zs) | isDigit y1 = x : "\&" : y : addEmptyString zs addEmptyString (x:xs) = x : addEmptyString xs addEmptyString [] = [] chunksOf :: Int -> [[a]] -> [[a]] chunksOf n0 x0 = go [] n0 x0 where go :: [a] -> Int -> [[a]] -> [[a]] go p _ [] = [p] go p n (x:xs) = let n' = n - length x in case n' `compare` 0 of LT -> p : go [] n0 (x:xs) EQ -> (p++x) : go [] n0 xs GT -> go (p++x) n' xs main :: IO () main = do let kanjiMap :: M.Map Char Word16 kanjiMap = M.fromList (mapMaybe unicodeToKanji [0 .. 0x10ffff]) stream :: [String] stream = addEmptyString (map showB (BL.unpack (encode kanjiMap))) putStrLn "kanjiMap :: M.Map Char Word16" putStrLn "kanjiMap = decode" putStrLn (" \"" ++ intercalate "\\\n \\" (chunksOf 72 stream) ++ "\"") -}
null
https://raw.githubusercontent.com/alexkazik/qrcode/7ee12de893c856a968dc1397602a7f81f8ea2c68/qrcode-core/src/Codec/QRCode/Mode/Kanji.hs
haskell
# LANGUAGE OverloadedStrings # | Generate a segment representing the specified text data encoded as QR code Kanji. it may be impossible to encode all text in this encoding. But it is possible to encode some of it and combine it with others like ISO-8859-1. This map is generated, see below on how it was done. Compile with : stack ghc --package iconv --package bytestring --package containers --package binary -- < name>.hs c0 - ctrl quote backslash del + c1 - ctrl - chars shy This character can be encoded directly Compile with: stack ghc --package iconv --package bytestring --package containers --package binary -- <name>.hs c0-ctrl quote backslash del + c1-ctrl-chars shy This character can be encoded directly
# LANGUAGE BinaryLiterals # # LANGUAGE NoImplicitPrelude # module Codec.QRCode.Mode.Kanji ( kanji , kanjiB , kanjiMap ) where import Codec.QRCode.Base import Data.Binary (decode) import qualified Data.Map.Strict as M import qualified Codec.QRCode.Data.ByteStreamBuilder as BSB import Codec.QRCode.Data.QRSegment.Internal import Codec.QRCode.Data.Result import Codec.QRCode.Data.ToInput Since this encoding does neither contain ASCII nor the half width katakana characters kanji :: ToText a => a -> Result QRSegment kanji s = case toString s of [] -> pure (constStream mempty) s' -> ((encodeBits 4 0b1000 <> lengthSegment (8, 10, 12) (length s')) <>) . constStream <$> kanjiB s' kanjiB :: [Char] -> Result BSB.ByteStreamBuilder kanjiB s = Result $ mconcat <$> traverse (fmap (BSB.encodeBits 13 . fromIntegral) . (`M.lookup` kanjiMap)) s kanjiMap :: M.Map Char Word16 kanjiMap = decode "\0\0\0\0\0\0\26ߢ\0Q£\0R§\0X¨\0\14¬\0\138°\0K±\0=´\0\12¶\0·Ã\ \\151\0>÷\0@Î\145\1ßÎ\146\1àÎ\147\1áÎ\148\1âÎ\149\1ãÎ\150\1äÎ\151\1åÎ\ \\152\1æÎ\153\1çÎ\154\1èÎ\155\1éÎ\156\1êÎ\157\1ëÎ\158\1ìÎ\159\1íΠ\1îΡ\1\ \ïΣ\1ðΤ\1ñÎ¥\1òΦ\1óΧ\1ôΨ\1õΩ\1öα\1ÿβ\2\0γ\2\1δ\2\2ε\2\3ζ\2\4Î\ \·\2\5θ\2\6ι\2\7κ\2\8λ\2\9μ\2\10ν\2\11ξ\2\12ο\2\13Ï\128\2\14Ï\129\ \\2\15Ï\131\2\16Ï\132\2\17Ï\133\2\18Ï\134\2\19Ï\135\2\20Ï\136\2\21Ï\137\2\ \\22Ð\129\2FÐ\144\2@Ð\145\2AÐ\146\2BÐ\147\2CÐ\148\2DÐ\149\2EÐ\150\2GÐ\151\ \\2HÐ\152\2IÐ\153\2JÐ\154\2KÐ\155\2LÐ\156\2MÐ\157\2NÐ\158\2OÐ\159\2PР\2Q\ \С\2RТ\2SУ\2TФ\2UÐ¥\2VЦ\2WЧ\2XШ\2YЩ\2ZЪ\2[Ы\2\92Ь\2]Ð\173\2^Ю\ \\2_Я\2`а\2pб\2qв\2rг\2sд\2tе\2uж\2wз\2xи\2yй\2zк\2{л\2|м\2\ \}н\2~о\2\128п\2\129Ñ\128\2\130Ñ\129\2\131Ñ\130\2\132Ñ\131\2\133Ñ\132\ \\2\134Ñ\133\2\135Ñ\134\2\136Ñ\135\2\137Ñ\136\2\138Ñ\137\2\139Ñ\138\2\140\ \Ñ\139\2\141Ñ\140\2\142Ñ\141\2\143Ñ\142\2\144Ñ\143\2\145Ñ\145\2vâ\128\144\ \\0\29â\128\149\0\28â\128\150\0!â\128\152\0%â\128\153\0&â\128\156\0'â\128\ \\157\0(â\128 \0µâ\128¡\0¶â\128¥\0$â\128¦\0#â\128°\0±â\128²\0Lâ\128³\0Mâ\ \\128»\0fâ\132\131\0Nâ\132«\0°â\134\144\0iâ\134\145\0jâ\134\146\0hâ\134\ \\147\0kâ\135\146\0\139â\135\148\0\140â\136\128\0\141â\136\130\0\157â\136\ \\131\0\142â\136\135\0\158â\136\136\0xâ\136\139\0yâ\136\146\0<â\136\154\0\ \£â\136\157\0¥â\136\158\0Gâ\136 \0\154â\136§\0\136â\136¨\0\137â\136©\0\ \\127â\136ª\0~â\136«\0§â\136¬\0¨â\136´\0Hâ\136µ\0¦â\136½\0¤â\137\146\0 â\ \\137 \0Bâ\137¡\0\159â\137¦\0Eâ\137§\0Fâ\137ª\0¡â\137«\0¢â\138\130\0|â\ \\138\131\0}â\138\134\0zâ\138\135\0{â\138¥\0\155â\140\146\0\156â\148\128\ \\2\159â\148\129\2ªâ\148\130\2 â\148\131\2«â\148\140\2¡â\148\143\2¬â\148\ \\144\2¢â\148\147\2\173â\148\148\2¤â\148\151\2¯â\148\152\2£â\148\155\2®â\ \\148\156\2¥â\148\157\2ºâ\148 \2µâ\148£\2°â\148¤\2§â\148¥\2¼â\148¨\2·â\ \\148«\2²â\148¬\2¦â\148¯\2¶â\148°\2»â\148³\2±â\148´\2¨â\148·\2¸â\148¸\2½â\ \\148»\2³â\148¼\2©â\148¿\2¹â\149\130\2¾â\149\139\2´â\150 \0aâ\150¡\0`â\ \\150²\0câ\150³\0bâ\150¼\0eâ\150½\0dâ\151\134\0_â\151\135\0^â\151\139\0[â\ \\151\142\0]â\151\143\0\92â\151¯\0¼â\152\133\0Zâ\152\134\0Yâ\153\128\0Jâ\ \\153\130\0Iâ\153ª\0´â\153\173\0³â\153¯\0²ã\128\128\0\0ã\128\129\0\1ã\128\ \\130\0\2ã\128\131\0\22ã\128\133\0\24ã\128\134\0\25ã\128\135\0\26ã\128\ \\136\01ã\128\137\02ã\128\138\03ã\128\139\04ã\128\140\05ã\128\141\06ã\128\ \\142\07ã\128\143\08ã\128\144\09ã\128\145\0:ã\128\146\0gã\128\147\0lã\128\ \\148\0+ã\128\149\0,ã\128\156\0 ã\129\129\1\31ã\129\130\1 ã\129\131\1!ã\ \\129\132\1\34ã\129\133\1#ã\129\134\1$ã\129\135\1%ã\129\136\1&ã\129\137\1\ \'ã\129\138\1(ã\129\139\1)ã\129\140\1*ã\129\141\1+ã\129\142\1,ã\129\143\1\ \-ã\129\144\1.ã\129\145\1/ã\129\146\10ã\129\147\11ã\129\148\12ã\129\149\1\ \3ã\129\150\14ã\129\151\15ã\129\152\16ã\129\153\17ã\129\154\18ã\129\155\1\ \9ã\129\156\1:ã\129\157\1;ã\129\158\1<ã\129\159\1=ã\129 \1>ã\129¡\1?ã\129\ \¢\1@ã\129£\1Aã\129¤\1Bã\129¥\1Cã\129¦\1Dã\129§\1Eã\129¨\1Fã\129©\1Gã\129\ \ª\1Hã\129«\1Iã\129¬\1Jã\129\173\1Kã\129®\1Lã\129¯\1Mã\129°\1Nã\129±\1Oã\ \\129²\1Pã\129³\1Qã\129´\1Rã\129µ\1Sã\129¶\1Tã\129·\1Uã\129¸\1Vã\129¹\1Wã\ \\129º\1Xã\129»\1Yã\129¼\1Zã\129½\1[ã\129¾\1\92ã\129¿\1]ã\130\128\1^ã\130\ \\129\1_ã\130\130\1`ã\130\131\1aã\130\132\1bã\130\133\1cã\130\134\1dã\130\ \\135\1eã\130\136\1fã\130\137\1gã\130\138\1hã\130\139\1iã\130\140\1jã\130\ \\141\1kã\130\142\1lã\130\143\1mã\130\144\1nã\130\145\1oã\130\146\1pã\130\ \\147\1qã\130\155\0\10ã\130\156\0\11ã\130\157\0\20ã\130\158\0\21ã\130¡\1\ \\128ã\130¢\1\129ã\130£\1\130ã\130¤\1\131ã\130¥\1\132ã\130¦\1\133ã\130§\1\ \\134ã\130¨\1\135ã\130©\1\136ã\130ª\1\137ã\130«\1\138ã\130¬\1\139ã\130\ \\173\1\140ã\130®\1\141ã\130¯\1\142ã\130°\1\143ã\130±\1\144ã\130²\1\145ã\ \\130³\1\146ã\130´\1\147ã\130µ\1\148ã\130¶\1\149ã\130·\1\150ã\130¸\1\151ã\ \\130¹\1\152ã\130º\1\153ã\130»\1\154ã\130¼\1\155ã\130½\1\156ã\130¾\1\157ã\ \\130¿\1\158ã\131\128\1\159ã\131\129\1 ã\131\130\1¡ã\131\131\1¢ã\131\132\ \\1£ã\131\133\1¤ã\131\134\1¥ã\131\135\1¦ã\131\136\1§ã\131\137\1¨ã\131\138\ \\1©ã\131\139\1ªã\131\140\1«ã\131\141\1¬ã\131\142\1\173ã\131\143\1®ã\131\ \\144\1¯ã\131\145\1°ã\131\146\1±ã\131\147\1²ã\131\148\1³ã\131\149\1´ã\131\ \\150\1µã\131\151\1¶ã\131\152\1·ã\131\153\1¸ã\131\154\1¹ã\131\155\1ºã\131\ \\156\1»ã\131\157\1¼ã\131\158\1½ã\131\159\1¾ã\131 \1Àã\131¡\1Áã\131¢\1Âã\ \\131£\1Ãã\131¤\1Äã\131¥\1Åã\131¦\1Æã\131§\1Çã\131¨\1Èã\131©\1Éã\131ª\1Êã\ \\131«\1Ëã\131¬\1Ìã\131\173\1Íã\131®\1Îã\131¯\1Ïã\131°\1Ðã\131±\1Ñã\131²\ \\1Òã\131³\1Óã\131´\1Ôã\131µ\1Õã\131¶\1Öã\131»\0\5ã\131¼\0\27ã\131½\0\18ã\ \\131¾\0\19ä¸\128\5êä¸\129\13\26ä¸\131\105ä¸\135\16\28ä¸\136\11$ä¸\137\9Ï\ \ä¸\138\11#ä¸\139\6zä¸\141\153ä¸\142\16\158ä¸\144\17 ä¸\145\6\14ä¸\148\7\ \\14ä¸\149\17¡ä¸\150\11¢ä¸\151\18\128ä¸\152\7µä¸\153\15xä¸\158\11%両\16ü\ \並\15\128个\17¢ä¸\173\13\6丱\17£ä¸²\88丶\17¤ä¸¸\7[丹\12Ï主\10e丼\ \\17¥ä¸¿\17¦ä¹\130\17§ä¹\131\14Tä¹\133\7¶ä¹\139\14Vä¹\141\14!ä¹\142\8Áä¹\ \\143\15Òä¹\149\27(ä¹\150\17¨ä¹\151\11&ä¹\152\17©ä¹\153\6sä¹\157\8#ä¹\158\ \\8îä¹\159\16gä¹¢\19ää¹±\16Ðä¹³\14;ä¹¾\7#äº\128\7\148äº\130\17ªäº\133\17«\ \äº\134\16ùäº\136\16\156äº\137\12Häº\138\17\173äº\139\10\22äº\140\141äº\ \\142\17°äº\145\6\29äº\146\8Ýäº\148\8Üäº\149\5ääº\152\17jäº\153\17iäº\155\ \\9qäº\156\5\159äº\158\17±äº\159\17²äº \17³äº¡\15Ó亢\17´äº¤\8ð亥\5å亦\ \\16\18亨\7Ü享\7Ý京\7Þäº\173\13`亮\16ú亰\17µäº³\17¶äº¶\17·äºº\11lä»\ \\128\10\153ä»\129\11mä»\130\17¼ä»\132\17ºä»\134\17»ä»\135\7·ä»\138\9aä»\ \\139\6®ä»\141\17¹ä»\142\17¸ä»\143\15gä»\148\9åä»\149\9ää»\150\12|ä»\151\ \\17½ä»\152\154ä»\153\11åä»\157\0\23ä»\158\17¾ä»\159\17À代\12£ä»¤\17\31ä\ \»¥\5Èä»\173\17¿ä»®\6|ä»°\8\2仲\13\7ä»¶\8\143ä»·\17Áä»»\14Cä¼\129\7iä¼\ \\137\17Âä¼\138\5Éä¼\141\8Þä¼\142\7jä¼\143\15Zä¼\144\14°ä¼\145\7¸ä¼\154\6\ \¯ä¼\156\17åä¼\157\13 ä¼¯\14\140ä¼°\17Ää¼´\14ºä¼¶\17 伸\11L伺\9æä¼¼\10\ \\23ä¼½\6~ä½\131\13Oä½\134\12Áä½\135\17Èä½\141\5Êä½\142\13aä½\143\10\154ä\ \½\144\9rä½\145\16\131ä½\147\12\140ä½\149\6}ä½\151\17Çä½\153\16\157ä½\154\ \\17Ãä½\155\17Åä½\156\9¬ä½\157\17Æä½\158\19\131佩\17Î佯\17Ñä½°\17Ïä½³\6\ \\128ä½µ\15yä½¶\17Éä½»\17Íä½¼\8ñ使\9çä¾\131\7$ä¾\134\17Òä¾\136\17Êä¾\139\ \\17!ä¾\141\10\24ä¾\143\17Ëä¾\145\17Ðä¾\150\17Óä¾\152\17Ìä¾\155\7ßä¾\157\ \\5Ëä¾ \7à価\6\127侫\19\132ä¾\173\16\25ä¾®\15N侯\8òä¾µ\11Nä¾¶\16õ便\ \\15\150ä¿\130\8Wä¿\131\12cä¿\132\6¢ä¿\138\10²ä¿\142\17×ä¿\144\17Üä¿\145\ \\17Úä¿\148\17Õä¿\151\12mä¿\152\17Øä¿\154\17Ûä¿\155\17Ùä¿\157\15\155ä¿\ \\159\17Öä¿¡\11Mä¿£\16\19俤\17Ýä¿¥\17Þä¿®\10\131俯\17ë俳\14o俵\15\21ä\ \¿¶\17æä¿¸\15®ä¿º\6t俾\17êå\128\133\17äå\128\134\17íå\128\137\121å\128\ \\139\8Âå\128\141\14{å\128\143\23Åå\128\145\17ìå\128\146\13¼å\128\148\17á\ \å\128\150\8ôå\128\153\8óå\128\154\17ßå\128\159\10Xå\128¡\17çå\128£\15\ \\173å\128¤\12ìå\128¥\17ãå\128¦\8\145å\128¨\17àå\128©\17èå\128ª\17âå\128«\ \\17\15å\128¬\17éå\128\173\17`å\128¶\8$å\128¹\8\144å\129\131\17îå\129\135\ \\17ïå\129\136\17óå\129\137\5Ìå\129\143\15\142å\129\144\17òå\129\149\17ñå\ \\129\150\17õå\129\154\17ôå\129\156\13bå\129¥\8\146å\129¬\17öå\129²\10Cå\ \\129´\12då\129µ\13cå\129¶\84å\129¸\17÷å\129½\7\149å\130\128\17øå\130\133\ \\17úå\130\141\15Ôå\130\145\8\134å\130\152\9Ðå\130\153\14õå\130\154\17ùå\ \\130¬\9\131å\130\173\16¢å\130²\17üå\130³\18\2å\130´\17ûå\130µ\9\130å\130\ \·\10Ýå\130¾\8Xå\131\130\18\3å\131\133\8\13å\131\137\18\0å\131\138\18\1å\ \\131\141\13íå\131\143\12\92å\131\145\7áå\131\149\15ìå\131\150\18\4å\131\ \\154\16ûå\131\158\18\5å\131£\18\8å\131¥\18\6å\131§\12-å\131\173\18\7å\ \\131®\18\9å\131µ\18\11å\131¹\18\10å\131»\15\134å\132\128\7\150å\132\129\ \\18\13å\132\130\18\14å\132\132\6må\132\137\18\12å\132\146\10rå\132\148\ \\18\17å\132\149\18\16å\132\150\18\15å\132\152\17Ôå\132\154\18\18å\132\ \\159\10Þå\132¡\18\19å\132ª\16\132å\132²\16Wå\132·\18\21å\132º\18\20å\132\ \»\18\23å\132¼\18\22å\132¿\18\24å\133\128\18\25å\133\129\5òå\133\131\8³å\ \\133\132\8Zå\133\133\10\155å\133\134\13\27å\133\135\7âå\133\136\11æå\133\ \\137\8õå\133\139\9Nå\133\140\18\27å\133\141\16Få\133\142\13¥å\133\144\10\ \\25å\133\146\18\26å\133\148\18\28å\133\154\13½å\133\156\7\21å\133¢\18\29\ \å\133¥\14<å\133¨\12\19å\133©\18\31å\133ª\18 å\133«\14ªå\133¬\8öå\133\173\ \\17Zå\133®\18!å\133±\7äå\133µ\15zå\133¶\12tå\133·\8/å\133¸\13\148å\133¼\ \\8\147å\134\128\18\34å\134\130\18#å\134\133\14 å\134\134\6>å\134\137\18&\ \å\134\138\9»å\134\140\18%å\134\141\9\132å\134\143\18'å\134\144\26,å\134\ \\145\18(å\134\146\15àå\134\147\18)å\134\149\18*å\134\150\18+å\134\151\11\ \'å\134\153\10Jå\134 \7%å\134¢\18.å\134¤\18,å\134¥\16;å\134¦\18-å\134¨\15\ \9å\134©\18/å\134ª\180å\134«\181å\134¬\13¾å\134°\185å\134±\183å\134²\184å\ \\134³\182å\134´\9¡å\134µ\186å\134¶\16hå\134·\17\34å\134½\187å\135\132\11\ \¦å\135\133\188å\135\134\10¹å\135\137\189å\135\139\13\28å\135\140\16ýå\ \\135\141\13Àå\135\150\18\131å\135\155\18:å\135\156\31#å\135\157\8\3å\135\ \ \18;å\135¡\15ýå\135¦\10Èå\135§\12ºå\135©\18=å\135ª\14\34å\135\173\18>å\ \\135°\18@å\135±\6Íå\135µ\18Aå\135¶\7åå\135¸\14\10å\135¹\6Zå\135º\10¯å\ \\135½\14\159å\135¾\18Bå\136\128\13Áå\136\131\11nå\136\132\18Cå\136\134\ \\15jå\136\135\11Øå\136\136\7 å\136\138\7'å\136\139\18Då\136\142\18Få\136\ \\145\8Yå\136\148\18Eå\136\151\171å\136\157\10Éå\136¤\14»å\136¥\15\138å\ \\136§\18Gå\136©\16Øå\136ª\18Hå\136®\18Iå\136°\13Þå\136³\18Jå\136¶\11§å\ \\136·\9¼å\136¸\8\148å\136¹\18Kå\136º\9èå\136»\9Oå\137\131\13då\137\132\ \\18Må\137\135\12eå\137\138\9\173å\137\139\18Nå\137\140\18Oå\137\141\12\ \\15å\137\143\18Lå\137\148\18Qå\137\150\15Õå\137\155\9Då\137\158\18På\137\ \£\8\149å\137¤\9\156å\137¥\14\141å\137©\18Tå\137ª\18Rå\137¯\15[å\137°\11(\ \å\137±\18[å\137²\7\4å\137³\18Uå\137´\18Så\137µ\12.å\137½\18Wå\137¿\18Vå\ \\138\131\6ãå\138\135\8\128å\138\136\18\92å\138\137\16ëå\138\141\18Xå\138\ \\145\18]å\138\146\18Zå\138\148\18Yå\138\155\17\13å\138\159\8÷å\138 \6\ \\129å\138£\172å\138©\10Õå\138ª\13·å\138«\9Eå\138¬\18`å\138\173\18aå\138±\ \\17#å\138´\17Jå\138µ\18cå\138¹\8øå\138¼\18bå\138¾\6Îå\139\129\18då\139\ \\131\15õå\139\133\13:å\139\135\16\133å\139\137\15\151å\139\141\18eå\139\ \\146\29Óå\139\149\13îå\139\151\18få\139\152\7(å\139\153\161å\139\157\10ß\ \å\139\158\18gå\139\159\15¥å\139 \18kå\139¢\11¨å\139£\18hå\139¤\8\14å\139\ \¦\18iå\139§\7)å\139²\8Må\139³\18lå\139µ\18må\139¸\18nå\139¹\18oå\139º\10\ \Yå\139¾\8ùå\139¿\16\92å\140\129\16få\140\130\145å\140\133\15¯å\140\134\ \\18på\140\136\18qå\140\141\18så\140\143\18uå\140\144\18tå\140\149\18vå\ \\140\150\6{å\140\151\15ëå\140\153\9ºå\140\154\18wå\140\157\128å\140 \10à\ \å\140¡\7çå\140£\18xå\140ª\14Ùå\140¯\18yå\140±\18zå\140³\18{å\140¸\18|å\ \\140¹\15\3å\140º\8&å\140»\5ãå\140¿\13ýå\141\128\18}å\141\129\10\156å\141\ \\131\11çå\141\133\18\127å\141\134\18~å\141\135\10áå\141\136\8ßå\141\137\ \\18\129å\141\138\14¼å\141\141\18\130å\141\145\14Úå\141\146\12rå\141\147\ \\12¬å\141\148\7æå\141\151\14,å\141\152\12Ðå\141\154\14\142å\141\156\15íå\ \\141\158\18\132å\141 \11èå\141¦\8Tå\141©\18\133å\141®\18\134å\141¯\6\11å\ \\141°\5óå\141±\7kå\141³\12få\141´\7°å\141µ\16Ñå\141·\18\137å\141¸\6uå\ \\141»\18\136å\141¿\7èå\142\130\18\138å\142\132\16oå\142\150\18\139å\142\ \\152\17\16å\142\154\8úå\142\159\8´å\142 \18\140å\142¥\18\142å\142¦\18\ \\141å\142¨\11~å\142©\6\24å\142\173\6=å\142®\18\143å\142°\18\144å\142³\8µ\ \å\142¶\18\145å\142»\7Îå\143\130\9Ñå\143\131\18\146å\143\136\16\20å\143\ \\137\9så\143\138\7¹å\143\139\16\134å\143\140\12/å\143\141\14½å\143\142\ \\10{å\143\148\10¦å\143\150\10få\143\151\10så\143\153\10Öå\143\155\14¾å\ \\143\159\18\149å\143¡\6\34å\143¢\120å\143£\8ûå\143¤\8Ãå\143¥\8%å\143¨\18\ \\153å\143©\12Àå\143ª\12¼å\143«\7éå\143¬\10âå\143\173\18\154å\143®\18\152\ \å\143¯\6\130å\143°\12¤å\143±\106å\143²\9êå\143³\6\5å\143¶\7\16å\143·\9Få\ \\143¸\9éå\143º\18\155å\144\129\18\156å\144\131\7¨å\144\132\6åå\144\136\9\ \Gå\144\137\7§å\144\138\13]å\144\139\6\4å\144\140\13ïå\144\141\16<å\144\ \\142\9\0å\144\143\16Ùå\144\144\13¦å\144\145\8üå\144\155\8Nå\144\157\18¥å\ \\144\159\8!å\144 \15éå\144¦\14Ûå\144©\18¤å\144«\7\92å\144¬\18\159å\144\ \\173\18 å\144®\18¢å\144¶\18£å\144¸\7ºå\144¹\11\129å\144»\15kå\144¼\18¡å\ \\144½\18\157å\144¾\8áå\145\128\18\158å\145\130\17Cå\145\134\15°å\145\136\ \\13få\145\137\8àå\145\138\9På\145\142\18¦å\145\145\14\27å\145\159\18ªå\ \\145¨\10|å\145ª\10tå\145°\18\173å\145±\18«å\145³\16!å\145µ\18¨å\145¶\18±\ \å\145·\18¬å\145»\18¯å\145¼\8Äå\145½\16=å\146\128\18°å\146\132\18²å\146\ \\134\18´å\146\139\9®å\146\140\17aå\146\142\18©å\146\143\18§å\146\144\18³\ \å\146\146\18®å\146¢\18¶å\146¤\18Âå\146¥\18¸å\146¨\18¼å\146«\18Àå\146¬\18\ \¹å\146¯\18Ýå\146²\9§å\146³\6Ðå\146¸\18·å\146¼\18Äå\146½\5ôå\146¾\18Ãå\ \\147\128\5£å\147\129\15)å\147\130\18Áå\147\132\18ºå\147\135\18µå\147\136\ \\18»å\147\137\9\134å\147\152\18Åå\147¡\5õå\147¢\18Îå\147¥\18Æå\147¦\18Çå\ \\147¨\10ãå\147©\16\9å\147\173\18Ìå\147®\18Ëå\147²\13\142å\147º\18Íå\147½\ \\18Êå\148\132\6\19å\148\134\9tå\148\135\11Oå\148\143\18Èå\148\144\13Âå\ \\148\148\18Éå\148\150\5 å\148®\18Óå\148¯\16\130å\148±\10åå\148³\18Ùå\148\ \¸\18Øå\148¹\18Ïå\148¾\12\129å\149\128\18Ðå\149\132\12\173å\149\133\18Õå\ \\149\134\10äå\149\140\18Òå\149\143\16bå\149\147\8[å\149\150\18Öå\149\151\ \\18×å\149\156\18Ôå\149\157\18Úå\149£\18Ñå\149»\18àå\149¼\18åå\149¾\18áå\ \\150\128\18Üå\150\131\18æå\150\132\12\16å\150\135\18èå\150\137\9\1å\150\ \\138\18Þå\150\139\13\29å\150\152\18âå\150\153\18Ûå\150\154\7+å\150\156\7\ \lå\150\157\7\5å\150\158\18ãå\150\159\18ßå\150§\8\150å\150¨\18éå\150©\18ç\ \å\150ª\122å\150«\7©å\150¬\7êå\150®\18äå\150°\82å\150¶\6#å\151\132\18íå\ \\151\133\18ëå\151\135\19%å\151\148\18ðå\151\154\18êå\151\156\18îå\151\ \\159\18ìå\151£\9ëå\151¤\18ïå\151·\18òå\151¹\18÷å\151½\18õå\151¾\18ôå\152\ \\134\12Ñå\152\137\6\131å\152\148\18ñå\152\150\18óå\152\151\10æå\152\152\ \\6\18å\152\155\18öå\152©\6\156å\152¯\19\2å\152±\11:å\152²\18ýå\152´\18ûå\ \\152¶\18üå\152¸\18þå\153\130\6\28å\153\140\12\24å\153\142\18øå\153\144\ \\18ùå\153\155\7\26å\153¤\19\1å\153¨\7må\153ª\19\4å\153«\19\0å\153¬\19\3å\ \\153´\15lå\153¸\14\19å\153º\14¶å\154\128\19\6å\154\134\19\5å\154\135\6äå\ \\154\138\19\7å\154\143\19\10å\154\148\19\9å\154 \19\8å\154¢\14Xå\154¥\19\ \\11å\154®\19\12å\154´\19\14å\154¶\19\13å\154¼\19\16å\155\128\19\19å\155\ \\129\19\17å\155\130\19\15å\155\131\19\18å\155\136\19\20å\155\142\19\21å\ \\155\145\19\22å\155\147\19\23å\155\151\19\24å\155\152\18$å\155\154\10zå\ \\155\155\9ìå\155\158\6±å\155 \5öå\155£\12ãå\155®\19\25å\155°\9bå\155²\5Í\ \å\155³\11}å\155¹\19\26å\155º\8Åå\155½\9Qå\155¿\19\28å\156\128\19\27å\156\ \\131\15\158å\156\132\19\29å\156\136\19\31å\156\137\19\30å\156\139\19 å\ \\156\141\19!å\156\143\8\151å\156\146\6@å\156\147\19\34å\156\150\19$å\156\ \\152\19#å\156\156\19&å\156\159\13¹å\156¦\19'å\156§\5³å\156¨\9\157å\156\ \\173\8\92å\156°\12îå\156·\19(å\156¸\19)å\156»\19+å\157\128\19,å\157\130\ \\9¢å\157\135\8\15å\157\138\15Öå\157\142\19*å\157\143\19-å\157\144\9\127å\ \\157\145\9\2å\157¡\191å\157¤\9cå\157¦\12Òå\157©\19.å\157ª\13Xå\157¿\192å\ \\158\130\11\130å\158\136\190å\158\137\193å\158\139\8^å\158\147\194å\158 \ \\195å\158¢\9\3å\158£\6ßå\158¤\197å\158ª\198å\158°\199å\158³\196å\159\128\ \\19/å\159\131\19:å\159\134\19;å\159\139\16\4å\159\142\11)å\159\146\19=å\ \\159\147\19>å\159\148\19<å\159\150\19@å\159\156\14Wå\159\159\5æå\159 \15\ \5å\159£\19Aå\159´\11;å\159·\107å\159¹\14|å\159º\7nå\159¼\9©å \128\15øå \ \\130\13ðå \133\8\152å \134\12\141å \138\19?å \139\19Bå \149\12\130å \153\ \\19Cå \157\19Då ¡\19Få ¤\13gå ª\7,å ¯\31\31å °\6Aå ±\15±å ´\11*å µ\13§å \ \º\9¤å ½\19Lå¡\128\15{å¡\129\17\27å¡\138\6²å¡\139\19Hå¡\145\12\25å¡\146\ \\19Kå¡\148\13Ãå¡\151\13¨å¡\152\13Äå¡\153\14·å¡\154\13Kå¡\158\9\135å¡¢\19\ \Gå¡©\6Vå¡«\13\149å¡°\19I塲\19E塵\11o塹\19M塾\10\173å¢\131\7ëå¢\133\ \\19Nå¢\147\15¦å¢\151\12]å¢\156\13Då¢\159\19P墨\15î墫\19Q墮\19V墳\15m\ \墸\19U墹\19O墺\19R墻\19T墾\9då£\129\15\135å£\133\19Wå£\135\12äå£\ \\138\6³å£\140\11+å£\145\19Yå£\147\19Xå£\149\9Hå£\151\19Zå£\152\19\92å£\ \\153\19[å£\156\19^å£\158\19Så£\159\19`壤\19_壥\19]士\9í壬\11p壮\123\ \壯\19a声\11ºå£±\5ë売\14\132壷\13Y壹\19c壺\19b壻\19d壼\19e壽\19f\ \å¤\130\19gå¤\137\15\143å¤\138\19hå¤\143\6\132å¤\144\19iå¤\149\16\155å¤\ \\150\6Ïå¤\152\18\135å¤\153\10§å¤\154\12}å¤\155\19jå¤\156\16i夢\162夥\ \\19l大\12¥å¤©\13\150太\12~夫\156夬\19må¤\173\19n央\6[失\108夲\19o\ \夷\5Î夸\19p夾\19qå¥\132\6Bå¥\135\7oå¥\136\14\30å¥\137\15²å¥\142\19uå¥\ \\143\124å¥\144\19tå¥\145\8_å¥\148\15úå¥\149\19så¥\151\13Åå¥\152\19wå¥\ \\154\19v奠\19y奢\19x奥\6\92奧\19z奨\10ç奩\19|奪\12Ä奬\19{奮\15q\ \女\10×奴\13ºå¥¸\19\128好\9\4å¦\129\19\129å¦\130\14@å¦\131\14Üå¦\132\ \\16Oå¦\138\14Då¦\141\19\138å¦\147\7\151å¦\150\16¤å¦\153\16-å¦\155\19êå¦\ \\157\19\130妣\19\133妥\12\131妨\15×妬\13©å¦²\19\134妹\16\5妻\9\136\ \妾\10èå§\134\19\135å§\137\9ïå§\139\9îå§\144\5·å§\145\8Æå§\147\11©å§\148\ \\5Ïå§\153\19\139å§\154\19\140å§\156\19\137å§¥\6\23姦\7-姨\19\136姪\16\ \Cå§«\15\16å§¶\5¦å§»\5÷å§¿\9ðå¨\129\5Ðå¨\131\5¡å¨\137\19\145å¨\145\19\143\ \å¨\152\16:å¨\154\19\146å¨\156\19\144å¨\159\19\142娠\11P娥\19\141娩\15\ \\152娯\8â娵\19\150娶\19\151娼\10éå©\128\19\147å©\129\17Kå©\134\14kå©\ \\137\19\149å©\154\9eå©¢\19\152婦\157婪\19\153婬\19\148å©¿\169åª\146\ \\14}åª\154\19\154åª\155\15\17媼\19\155媽\19\159媾\19\156å«\129\6\133å\ \«\130\19\158å«\137\109å«\139\19\157å«\140\8\153å«\144\19«å«\150\19¤å«\ \\151\19¡å«¡\13\4å«£\19 å«¦\19¢å«©\19£å«º\19¥å«»\19¦å¬\137\7på¬\139\19¨å¬\ \\140\19§å¬\150\19©å¬¢\11,嬪\19¬å¬¬\13Z嬰\6$嬲\19ªå¬¶\19\173嬾\19®å\ \\173\128\19±å\173\131\19¯å\173\133\19°å\173\144\9ñå\173\145\19²å\173\148\ \\9\5å\173\149\19³å\173\151\10\26å\173\152\12vå\173\154\19´å\173\155\19µå\ \\173\156\9ùå\173\157\9\6å\173\159\16På\173£\7\135å\173¤\8Çå\173¥\19¶å\ \\173¦\6÷å\173©\19·å\173«\12wå\173°\19¸å\173±\19áå\173³\19¹å\173µ\19ºå\ \\173¸\19»å\173º\19½å®\128\19¾å®\131\19Àå®\133\12®å®\135\6\6å®\136\10gå®\ \\137\5Àå®\139\126å®\140\7.å®\141\103å®\143\9\7å®\149\13Æå®\151\10\128å®\ \\152\7/å®\153\13\8å®\154\13hå®\155\5¶å®\156\7\152å®\157\15³å®\159\10@客\ \\7±å®£\11é室\10:宥\16\135宦\19Áå®®\7»å®°\9\137害\6Ñå®´\6C宵\10êå®¶\ \\6\134宸\19Â容\16¥å®¿\10¨å¯\130\10bå¯\131\19Ãå¯\132\7qå¯\133\14\16å¯\ \\134\16'å¯\135\19Äå¯\137\19Åå¯\140\158å¯\144\19Çå¯\146\7&å¯\147\85å¯\148\ \\19Æå¯\155\70å¯\157\11Qå¯\158\19Ëå¯\159\9À寡\6\135寢\19Ê寤\19È寥\19Ì\ \實\19É寧\14J寨\22K審\11R寫\19Í寮\16þ寰\19Î寳\19Ð寵\13\30寶\19Ï\ \寸\11¡å¯º\10\27対\12\142寿\10uå°\129\15Uå°\130\11êå°\132\10Kå°\133\19\ \Ñå°\134\10ëå°\135\19Òå°\136\19Óå°\137\5Ñå°\138\12xå°\139\11qå°\141\19Ôå°\ \\142\13ñå°\143\10ìå°\145\10íå°\147\19Õå°\150\11ëå°\154\10îå° \19Öå°¢\19×\ \å°¤\16^å°¨\19Øå°\173\8\4å°±\10\129å°¸\19Ùå°¹\19Úå°º\10Zå°»\11Kå°¼\142å°½\ \\11så°¾\14öå°¿\14Aå±\128\8\7å±\129\19Ûå±\133\7Ïå±\134\19Üå±\136\8<å±\138\ \\14\13å±\139\6nå±\141\9òå±\142\19Ýå±\143\19àå±\144\19ßå±\145\8;å±\147\19\ \Þå±\149\13\151å±\158\12nå± \13ªå±¡\10F層\127å±¥\16Ú屬\19âå±®\19ã屯\14\ \\20å±±\9Òå±¶\19åå±¹\19æå²\140\19çå²\144\7rå²\145\19èå²\148\19é岡\6j岨\ \\12\26岩\7b岫\19ë岬\16&å²±\12\144å²³\6øå²¶\19íå²·\19ï岸\7]å²»\19ìå²¼\ \\19îå²¾\19ñå³\133\19ðå³\135\19òå³\153\19óå³ \13û峡\7ì峨\6£å³©\19ô峪\ \\19ùå³\173\19÷峯\15µå³°\15´å³¶\13Ç峺\19öå³»\10³å³½\19õå´\135\11\146å´\ \\139\19úå´\142\9¨å´\145\20\0å´\148\20\1å´\149\19ûå´\150\6Òå´\151\19üå´\ \\152\20\5å´\153\20\4å´\154\20\3å´\155\19ÿå´\159\19þå´¢\20\2å´©\15¶åµ\139\ \\20\9åµ\140\20\6åµ\142\20\8åµ\144\16Òåµ\146\20\7åµ\156\19ý嵩\11\147嵬\ \\20\10嵯\9uåµ³\20\11åµ¶\20\12å¶\130\20\15å¶\132\20\14å¶\135\20\13å¶\139\ \\13Èå¶\140\19øå¶\144\20\21å¶\157\20\17å¶¢\20\16嶬\20\18å¶®\20\19å¶·\20\ \\22嶺\17$å¶¼\20\23å¶½\20\20å·\137\20\24å·\140\7^å·\141\20\25å·\146\20\ \\27å·\147\20\26å·\150\20\28å·\155\20\29å·\157\11ìå·\158\10\130å·¡\10Äå·£\ \\12Cå·¥\9\8å·¦\9vå·§\9\9å·¨\7Ðå·«\20\30å·®\9wå·±\8Èå·²\20\31å·³\16$å·´\ \\14bå·µ\20 å··\9\10å·»\7*å·½\12Æå·¾\8\16å¸\130\9óå¸\131\15:å¸\134\14¿å¸\ \\139\20!å¸\140\7så¸\145\20$å¸\150\13\31å¸\153\20#å¸\154\20\34å¸\155\20%å\ \¸\157\13i帥\11\131師\9ôå¸\173\11È帯\12\145帰\7\129帳\13 帶\20&帷\ \\20'常\11-帽\15Øå¹\128\20*å¹\131\20)å¹\132\20(å¹\133\15]å¹\135\201å¹\ \\140\15ùå¹\142\20+å¹\148\20-å¹\149\16\11å¹\151\20,å¹\159\20.幡\14¦å¹¢\ \\20/å¹£\15|幤\200å¹²\71å¹³\15}å¹´\14Nå¹µ\202å¹¶\203幸\9\11å¹¹\72幺\20\ \4å¹»\8¶å¹¼\16£å¹½\16\136å¹¾\7t广\206åº\129\13!åº\131\9\12åº\132\10ïåº\ \\135\14Ýåº\138\10ðåº\143\10Øåº\149\13jåº\150\15·åº\151\13\152åº\154\9\13\ \åº\156\15;庠\207度\13¸åº§\9\128庫\8Éåº\173\13k庵\5Á庶\10Î康\9\14åº\ \¸\16¦å»\129\208å»\130\209å»\131\14på»\136\20:å»\137\175å»\138\17Lå»\143\ \\20<å»\144\20;å»\147\6æå»\150\20@å»\154\20Cå»\155\20Då»\157\20Bå»\159\15\ \\31å» \10ñ廡\20F廢\20E廣\20A廨\20G廩\20H廬\20Iå»°\20Lå»±\20J廳\20\ \Kå»´\20Må»¶\6Då»·\13l廸\20N建\8\154å»»\6´å»¼\14U廾\20O廿\149å¼\129\ \\15\153å¼\131\20På¼\132\17Må¼\137\20Qå¼\138\15~å¼\139\20Tå¼\140\17\159å¼\ \\141\17¯å¼\143\10.å¼\144\143å¼\145\20Uå¼\147\7¼å¼\148\13\34å¼\149\5øå¼\ \\150\20Vå¼\151\15då¼\152\9\15å¼\155\12ïå¼\159\13må¼¥\16m弦\8·å¼§\8Ê弩\ \\20Wå¼\173\20X弯\20^å¼±\10cå¼µ\13#å¼·\7í弸\20Yå¼¼\15\10å¼¾\12åå½\129\ \\20Zå½\136\20[å½\138\7îå½\140\20\92å½\142\20]å½\145\20_å½\147\13Öå½\150\ \\20`å½\151\20aå½\153\20bå½\156\20Så½\157\20R彡\20cå½¢\8`彦\15\6彩\9\ \\138彪\15\22彫\13$彬\15*å½\173\20då½°\10òå½±\6%å½³\20eå½·\20få½¹\16på\ \½¼\14Þ彿\20iå¾\128\6]å¾\129\11ªå¾\130\20hå¾\131\20gå¾\132\8aå¾\133\12\ \\146å¾\135\20må¾\136\20kå¾\138\20jå¾\139\16åå¾\140\8ãå¾\144\10Ùå¾\145\20\ \lå¾\146\13«å¾\147\10\157å¾\151\13þå¾\152\20på¾\153\20oå¾\158\20nå¾ \20qå\ \¾¡\8ä徨\20r復\15\92循\10ºå¾\173\20så¾®\14÷å¾³\13ÿå¾´\13%å¾¹\13\143å¾¼\ \\20tå¾½\7\138å¿\131\11Så¿\133\15\11å¿\140\7uå¿\141\14Eå¿\150\20uå¿\151\9\ \õå¿\152\15Ùå¿\153\15Úå¿\156\6^å¿\157\20zå¿ \13\9忤\20wå¿«\6µå¿°\20«å¿±\ \\20y念\14O忸\20xå¿»\20v忽\9Zå¿¿\20|æ\128\142\20\131æ\128\143\20\137æ\ \\128\144\20\129æ\128\146\13»æ\128\149\20\134æ\128\150\15<æ\128\153\20\ \\128æ\128\155\20\133æ\128\156\17%æ\128\157\9öæ\128 \12\147æ\128¡\20}æ\ \\128¥\7½æ\128¦\20\136æ\128§\11«æ\128¨\6Eæ\128©\20\130æ\128ª\6¶æ\128«\20\ \\135æ\128¯\7ïæ\128±\20\132æ\128º\20\138æ\129\129\20\140æ\129\130\20\150æ\ \\129\131\20\148æ\129\134\20\145æ\129\138\20\144æ\129\139\176æ\129\141\20\ \\146æ\129\144\7ðæ\129\146\9\16æ\129\149\10Úæ\129\153\20\153æ\129\154\20\ \\139æ\129\159\20\143æ\129 \20~æ\129¢\6¸æ\129£\20\147æ\129¤\20\149æ\129¥\ \\12ðæ\129¨\9fæ\129©\6væ\129ª\20\141æ\129«\20\152æ\129¬\20\151æ\129\173\7\ \ñæ\129¯\12gæ\129°\7\6æ\129µ\8bæ\129·\20\142æ\130\129\20\154æ\130\131\20\ \\157æ\130\132\20\159æ\130\137\10;æ\130\139\20¥æ\130\140\13næ\130\141\20\ \\155æ\130\146\20£æ\130\148\6·æ\130\150\20¡æ\130\151\20¢æ\130\154\20\158æ\ \\130\155\20 æ\130\159\8åæ\130 \16\137æ\130£\73æ\130¦\68æ\130§\20¤æ\130©\ \\14Yæ\130ª\5«æ\130²\14ßæ\130³\20{æ\130´\20ªæ\130µ\20®æ\130¶\16cæ\130¸\20\ \§æ\130¼\13Éæ\130½\20¬æ\131\133\11.æ\131\134\20\173æ\131\135\14\21æ\131\ \\145\17fæ\131\147\20©æ\131\152\20¯æ\131\154\9[æ\131\156\11Éæ\131\159\5Òæ\ \\131 \20¨æ\131¡\20¦æ\131£\129æ\131§\20\156æ\131¨\9Óæ\131°\12\132æ\131±\ \\20»æ\131³\12:æ\131´\20¶æ\131¶\20³æ\131·\20´æ\131¹\10dæ\131º\20·æ\131»\ \\20ºæ\132\128\20µæ\132\129\10\132æ\132\131\20¸æ\132\134\20²æ\132\136\16z\ \æ\132\137\16yæ\132\141\20¼æ\132\142\20½æ\132\143\5Óæ\132\149\20±æ\132\ \\154\80æ\132\155\5¤æ\132\159\74æ\132¡\20¹æ\132§\20Áæ\132¨\20Àæ\132¬\20Åæ\ \\132´\20Ææ\132¼\20Äæ\132½\20Çæ\132¾\20¿æ\132¿\20Ãæ\133\130\20Èæ\133\132\ \\20Éæ\133\135\20¾æ\133\136\10\28æ\133\138\20Âæ\133\139\12\148æ\133\140\9\ \\17æ\133\141\20°æ\133\142\11Tæ\133\147\20Öæ\133\149\15§æ\133\152\20Ìæ\ \\133\153\20Íæ\133\154\20Îæ\133\157\20Õæ\133\159\20Ôæ\133¢\16\29æ\133£\75\ \æ\133¥\20Òæ\133§\8dæ\133¨\6Óæ\133«\20Ïæ\133®\16öæ\133¯\20Ñæ\133°\5Ôæ\133\ \±\20Óæ\133³\20Êæ\133´\20Ðæ\133µ\20׿\133¶\8cæ\133·\20Ëæ\133¾\16¼æ\134\ \\130\16\138æ\134\135\20Úæ\134\138\20Þæ\134\142\12^æ\134\144\177æ\134\145\ \\20ßæ\134\148\20Üæ\134\150\20Ùæ\134\153\20Øæ\134\154\20Ýæ\134¤\15næ\134§\ \\13òæ\134©\8eæ\134«\20àæ\134¬\20Ûæ\134®\20áæ\134²\8\155æ\134¶\6oæ\134º\ \\20éæ\134¾\76æ\135\131\20çæ\135\134\20èæ\135\135\9gæ\135\136\20ææ\135\ \\137\20äæ\135\138\20ãæ\135\139\20êæ\135\140\20âæ\135\141\20ìæ\135\144\6¹\ \æ\135£\20îæ\135¦\20íæ\135²\13&æ\135´\20ñæ\135¶\20ïæ\135·\20åæ\135¸\8\156\ \æ\135º\20ðæ\135¼\20ôæ\135½\20óæ\135¾\20õæ\135¿\20òæ\136\128\20öæ\136\136\ \\20÷æ\136\137\20øæ\136\138\15¨æ\136\140\20úæ\136\141\20ùæ\136\142\10\158\ \æ\136\144\11¬æ\136\145\6¤æ\136\146\6ºæ\136\148\20ûæ\136\150\5½æ\136\154\ \\11Êæ\136\155\20üæ\136\157\28Aæ\136\158\21\0æ\136\159\8\129æ\136¡\21\1æ\ \\136¦\11íæ\136ª\21\2æ\136®\21\3æ\136¯\7\153æ\136°\21\4æ\136²\21\5æ\136³\ \\21\6æ\136´\12\149æ\136¸\8Ëæ\136»\16_æ\136¿\15Ûæ\137\128\10Êæ\137\129\21\ \\7æ\137\135\11îæ\137\136\28ûæ\137\137\14àæ\137\139\10hæ\137\141\9\139æ\ \\137\142\21\8æ\137\147\12\133æ\137\149\15eæ\137\152\12¯æ\137\155\21\11æ\ \\137\158\21\9æ\137 \21\12æ\137£\21\10æ\137¨\21\13æ\137®\15oæ\137±\5µæ\ \\137¶\15=æ\137¹\14áæ\137¼\21\14æ\137¾\21\17æ\137¿\10óæ\138\128\7\154æ\ \\138\130\21\15æ\138\131\21\22æ\138\132\10ôæ\138\137\21\16æ\138\138\14cæ\ \\138\145\16½æ\138\146\21\18æ\138\147\21\19æ\138\148\21\23æ\138\149\13Êæ\ \\138\150\21\20æ\138\151\9\18æ\138\152\11Üæ\138\155\21%æ\138\156\14²æ\138\ \\158\12°æ\138«\14âæ\138¬\21kæ\138±\15¸æ\138µ\13oæ\138¹\16\21æ\138»\21\26\ \æ\138¼\6_æ\138½\13\10æ\139\130\21#æ\139\133\12Óæ\139\134\21\29æ\139\135\ \\21$æ\139\136\21\31æ\139\137\21&æ\139\138\21\34æ\139\140\21!æ\139\141\14\ \\143æ\139\143\21\27æ\139\144\6»æ\139\145\21\25æ\139\146\7Ñæ\139\147\12±æ\ \\139\148\21\21æ\139\151\21\24æ\139\152\9\19æ\139\153\11Ùæ\139\155\10õæ\ \\139\156\21 æ\139\157\14qæ\139 \7Òæ\139¡\6çæ\139¬\7\7æ\139\173\11@æ\139®\ \\21(æ\139¯\21-æ\139±\21)æ\139³\8\157æ\139µ\21.æ\139¶\9Áæ\139·\9Iæ\139¾\ \\10\133æ\139¿\21\28æ\140\129\10\29æ\140\130\21+æ\140\135\9÷æ\140\136\21,\ \æ\140\137\5Âæ\140\140\21'æ\140\145\13'æ\140\153\7Óæ\140\159\7òæ\140§\21*\ \æ\140¨\5¥æ\140«\9\129æ\140¯\11Uæ\140º\13pæ\140½\14Òæ\140¾\210æ\140¿\12=æ\ \\141\137\12hæ\141\140\9Êæ\141\141\211æ\141\143\213æ\141\144\21/æ\141\149\ \\15\159æ\141\151\13;æ\141\156\12;æ\141§\15¹æ\141¨\10Læ\141©\21@æ\141«\21\ \>æ\141®\11\152æ\141²\8\158æ\141¶\218æ\141·\10÷æ\141º\14&æ\141»\14Pæ\142\ \\128\216æ\142\131\12<æ\142\136\10væ\142\137\21;æ\142\140\10öæ\142\142\21\ \5æ\142\143\21:æ\142\146\14ræ\142\150\214æ\142\152\8@æ\142\155\6üæ\142\ \\159\21<æ\142 \16éæ\142¡\9\140æ\142¢\12Ôæ\142£\219æ\142¥\11Úæ\142§\9\20æ\ \\142¨\11\132æ\142©\6Fæ\142ª\12\27æ\142«\217æ\142¬\7¤æ\142²\8fæ\142´\13Mæ\ \\142µ\21=æ\142»\12>æ\142¾\21Aæ\143\128\21Cæ\143\131\12uæ\143\132\21Iæ\ \\143\134\21Dæ\143\137\21Fæ\143\143\15 æ\143\144\13qæ\143\146\21Gæ\143\ \\150\16\139æ\143\154\16§æ\143\155\77æ\143¡\5¬æ\143£\21Eæ\143©\21Bæ\143®\ \\7væ\143´\6Gæ\143¶\21Hæ\143º\16¨æ\144\134\21Læ\144\141\12yæ\144\143\21Sæ\ \\144\147\21Mæ\144\150\21Jæ\144\151\21Qæ\144\156\212æ\144¦\21Næ\144¨\21Ræ\ \\144¬\14Àæ\144\173\13Ëæ\144´\21Kæ\144¶\21Oæ\144º\8gæ\144¾\9¯æ\145\130\11\ \Ûæ\145\142\21Wæ\145\152\13\133æ\145§\21Tæ\145©\16\0æ\145¯\21Uæ\145¶\21Væ\ \\145¸\16Læ\145º\11 æ\146\131\8\130æ\146\136\21]æ\146\146\9Ôæ\146\147\21Z\ \æ\146\149\21Yæ\146\154\14Qæ\146\158\13óæ\146¤\13\144æ\146¥\21[æ\146©\21\ \\92æ\146«\15Oæ\146\173\14dæ\146®\9Âæ\146°\11ïæ\146²\15ïæ\146¹\6èæ\146»\ \\21cæ\146¼\21^æ\147\129\16©æ\147\130\21eæ\147\133\21aæ\147\135\21bæ\147\ \\141\12@æ\147\146\21`æ\147\148\21\30æ\147\152\21dæ\147\154\21_æ\147 \21i\ \æ\147¡\21jæ\147¢\13\134æ\147£\21læ\147¦\9Ãæ\147§\21gæ\147¬\7\155æ\147¯\ \\21mæ\147±\21fæ\147²\21qæ\147´\21pæ\147¶\21oæ\147º\21ræ\147½\21tæ\147¾\ \\11/æ\148\128\21sæ\148\133\21wæ\148\152\21uæ\148\156\21væ\148\157\21Pæ\ \\148£\21yæ\148¤\21xæ\148ª\21Xæ\148«\21zæ\148¬\21næ\148¯\9øæ\148´\21{æ\ \\148µ\21|æ\148¶\21~æ\148·\21}æ\148¸\21\127æ\148¹\6¼æ\148»\9\21æ\148¾\15º\ \æ\148¿\11\173æ\149\133\8Ìæ\149\136\21\129æ\149\141\21\132æ\149\143\151æ\ \\149\145\7¾æ\149\149\21\131æ\149\150\21\130æ\149\151\14sæ\149\152\21\133\ \æ\149\153\7óæ\149\157\21\135æ\149\158\21\134æ\149¢\78æ\149£\9Õæ\149¦\14\ \\22æ\149¬\8hæ\149°\11\148æ\149²\21\136æ\149´\11®æ\149µ\13\135æ\149·\15>æ\ \\149¸\21\137æ\150\130\21\138æ\150\131\21\139æ\150\135\15væ\150\136\19¼æ\ \\150\137\11Äæ\150\140\15+æ\150\142\9\150æ\150\144\14ãæ\150\145\14Áæ\150\ \\151\13¬æ\150\153\16ÿæ\150\155\21\141æ\150\156\10Næ\150\159\21\142æ\150¡\ \\5´æ\150¤\8\18æ\150¥\11Ëæ\150§\15@æ\150«\21\143æ\150¬\9áæ\150\173\12ææ\ \\150¯\9úæ\150°\11Væ\150·\21\144æ\150¹\15»æ\150¼\6Wæ\150½\9ûæ\151\129\21\ \\147æ\151\131\21\145æ\151\132\21\148æ\151\133\16÷æ\151\134\21\146æ\151\ \\139\11ùæ\151\140\21\149æ\151\143\12pæ\151\146\21\150æ\151\151\7xæ\151\ \\153\21\152æ\151\155\21\151æ\151 \21\153æ\151¡\21\154æ\151¢\7yæ\151¥\14:\ \æ\151¦\12Õæ\151§\7Ìæ\151¨\9üæ\151©\12Aæ\151¬\10»æ\151\173\5®æ\151±\21\ \\155æ\151º\6`æ\151»\21\159æ\152\130\9\22æ\152\131\21\158æ\152\134\9iæ\ \\152\135\10øæ\152\138\21\157æ\152\140\10ùæ\152\142\16>æ\152\143\9hæ\152\ \\147\5Õæ\152\148\11Ìæ\152\156\21¤æ\152\159\11¯æ\152 \6&æ\152¥\10´æ\152§\ \\16\6æ\152¨\9°æ\152\173\10úæ\152¯\11¥æ\152´\21£æ\152µ\21¡æ\152¶\21¢æ\152\ \¼\13\11æ\152¿\21Åæ\153\129\21¨æ\153\130\10\30æ\153\131\9\23æ\153\132\21¦\ \æ\153\137\21§æ\153\139\11Wæ\153\143\21¥æ\153\146\9Îæ\153\157\21ªæ\153\ \\158\21©æ\153\159\21®æ\153¢\21¯æ\153¤\21«æ\153¦\6Áæ\153§\21¬æ\153¨\21\ \\173æ\153©\14Óæ\153®\15Aæ\153¯\8iæ\153°\21°æ\153´\11°æ\153¶\10ûæ\153º\12\ \ñæ\154\129\8\5æ\154\131\21±æ\154\132\21µæ\154\135\6\137æ\154\136\21²æ\ \\154\137\21´æ\154\142\21³æ\154\145\10Ëæ\154\150\12çæ\154\151\5Ãæ\154\152\ \\21¶æ\154\157\21·æ\154¢\13(æ\154¦\17/æ\154«\9âæ\154®\15©æ\154´\15Üæ\154¸\ \\21Áæ\154¹\21¹æ\154¼\21¼æ\154¾\21»æ\155\129\21¸æ\155\132\21Àæ\155\135\14\ \\28æ\155\137\21ºæ\155\150\21Âæ\155\153\10Ìæ\155\154\21Ãæ\155\156\16ªæ\ \\155\157\14\152æ\155 \21Äæ\155¦\21Ææ\155©\21Çæ\155°\21Èæ\155²\8\8æ\155³\ \\6'æ\155´\9\24æ\155µ\21Éæ\155·\21Êæ\155¸\10Ñæ\155¹\12Bæ\155¼\18\150æ\155\ \½\12\29æ\155¾\12\28æ\155¿\12\150æ\156\128\9\133æ\156\131\17ðæ\156\136\8\ \\142æ\156\137\16\140æ\156\139\15¼æ\156\141\15^æ\156\143\21Ëæ\156\148\9±æ\ \\156\149\13=æ\156\150\21Ìæ\156\151\17Næ\156\155\15Ýæ\156\157\13)æ\156\ \\158\21Íæ\156\159\7zæ\156¦\21Îæ\156§\21Ïæ\156¨\16Xæ\156ª\16\34æ\156«\16\ \\22æ\156¬\15ûæ\156\173\9Äæ\156®\21Ñæ\156±\10iæ\156´\15ðæ\156¶\21Óæ\156·\ \\21Öæ\156¸\21Õæ\156º\7wæ\156½\7Àæ\156¿\21Òæ\157\129\21Ôæ\157\134\21׿\ \\157\137\11\153æ\157\142\16Ûæ\157\143\5Çæ\157\144\9\158æ\157\145\12zæ\ \\157\147\10[æ\157\150\111æ\157\153\21Úæ\157\156\13\173æ\157\158\21Øæ\157\ \\159\12iæ\157 \21Ùæ\157¡\110æ\157¢\16[æ\157£\21Ûæ\157¤\21Üæ\157¥\16Èæ\ \\157ª\21áæ\157\173\9\25æ\157¯\14tæ\157°\21Þæ\157±\13Ìæ\157²\21\156æ\157³\ \\21 æ\157µ\7®æ\157·\14fæ\157¼\21àæ\157¾\10üæ\157¿\14Âæ\158\133\21ææ\158\ \\135\14øæ\158\137\21Ýæ\158\139\21ãæ\158\140\21âæ\158\144\11Íæ\158\149\16\ \\13æ\158\151\17\17æ\158\154\16\7æ\158\156\6\138æ\158\157\9ýæ\158 \17gæ\ \\158¡\21åæ\158¢\11\149æ\158¦\21äæ\158©\21ßæ\158¯\8Íæ\158³\21ëæ\158´\21éæ\ \\158¶\6\139æ\158·\21çæ\158¸\21íæ\158¹\21óæ\159\129\12\134æ\159\132\15\ \\127æ\159\134\21õæ\159\138\15\1æ\159\142\21ôæ\159\143\14\144æ\159\144\15\ \Þæ\159\145\79æ\159\147\11õæ\159\148\10\159æ\159\152\13Qæ\159\154\16\141æ\ \\159\157\21ðæ\159\158\21ïæ\159¢\21ñæ\159¤\21îæ\159§\21öæ\159©\21ìæ\159¬\ \\21êæ\159®\21òæ\159¯\21èæ\159±\13\12æ\159³\16væ\159´\10Dæ\159µ\9²æ\159»\ \\9xæ\159¾\16\15æ\159¿\6àæ \130\13Læ \131\14\8æ \132\6(æ \147\11ðæ \150\ \\11²æ \151\8Iæ \158\21øæ ¡\9\26æ ¢\7\28æ ©\21úæ ª\7\20æ «\22\1æ ²\21ýæ ´\ \\11ñæ ¸\6êæ ¹\9jæ ¼\6éæ ½\9\141æ¡\128\21ûæ¡\129\8\133æ¡\130\8jæ¡\131\13Í\ \æ¡\134\21ùæ¡\136\5Äæ¡\141\21üæ¡\142\21þæ¡\144\8\11æ¡\145\8Kæ¡\147\7:æ¡\ \\148\7ªæ¡\153\22\2æ¡\156\9·æ¡\157\16\17æ¡\159\9Öæ¡£\22\3æ¡§\15\15æ¡´\22\ \\15æ¡¶\6qæ¡·\22\4桾\22\21æ¡¿\22\5æ¢\129\17\0æ¢\131\22\12æ¢\133\14~æ¢\ \\141\22\20æ¢\143\22\7æ¢\147\5²æ¢\148\22\9æ¢\151\9\27æ¢\155\22\11æ¢\157\ \\22\10æ¢\159\22\6梠\22\17梢\10ý梦\19k梧\8ææ¢¨\16Üæ¢\173\22\8梯\13ræ\ \¢°\6Âæ¢±\9k梳\22\0梵\22\16梶\7\1梹\22\14梺\22\18梼\13Îæ£\132\7|æ£\ \\134\220æ£\137\16Gæ£\138\22\23æ£\139\7{æ£\141\22\30æ£\146\15ßæ£\148\22\ \\31æ£\149\22!æ£\151\22%æ£\152\22\25æ£\154\12Éæ£\159\13Ïæ£ \22)棡\22\28æ\ \££\22&棧\22 森\11X棯\22*棲\11±æ£¹\22(棺\7;æ¤\128\17oæ¤\129\22\22æ¤\ \\132\22$æ¤\133\5Öæ¤\136\22\24æ¤\139\168æ¤\140\22\29æ¤\141\11Aæ¤\142\13Eæ\ \¤\143\22\19æ¤\146\22#æ¤\153\11\154æ¤\154\22-æ¤\155\7\17æ¤\156\8\159椡\ \\22/椢\22\26椣\22.椥\22'椦\22\27椨\22+椪\22,椰\22=椴\14\12椶\22\ \\34椹\229椽\22;椿\13Væ¥\138\16«æ¥\147\15Væ¥\148\226æ¥\149\12\136æ¥\ \\153\22<æ¥\154\12\30æ¥\156\223æ¥\157\22@æ¥\158\22?楠\14-楡\22>楢\14(æ\ \¥ª\22B楫\225æ¥\173\8\6楮\228楯\10¼æ¥³\14\128楴\22:極\8\9楷\222楸\ \\224楹\221楼\17O楽\6ù楾\227æ¦\129\22Aæ¦\130\6Ôæ¦\138\9¥æ¦\142\6<æ¦\ \\145\22Ræ¦\148\17Pæ¦\149\22Uæ¦\155\11Yæ¦\156\22T榠\22S榧\22P榮\22D榱\ \\22a榲\22C榴\22V榻\22N榾\22I榿\22Fæ§\129\22Gæ§\131\22Oæ§\135\31 æ§\ \\138\22Læ§\139\9\28æ§\140\13Fæ§\141\12Dæ§\142\22Jæ§\144\22Eæ§\147\22Hæ§\ \\152\16¬æ§\153\16\10æ§\157\22Mæ§\158\22Wæ§§\22_槨\22Xæ§«\22eæ§\173\22cæ\ \§²\22^æ§¹\22]æ§»\13Næ§½\12Eæ§¿\22[æ¨\130\22Yæ¨\133\22`æ¨\138\22fæ¨\139\ \\14óæ¨\140\22læ¨\146\22gæ¨\147\22jæ¨\148\22dæ¨\151\13\20æ¨\153\15\23æ¨\ \\155\22Zæ¨\158\22bæ¨\159\10þ模\16M樢\22v樣\22i権\8 æ¨ª\6a樫\6þ樮\ \\22Q樵\10ÿ樶\22n樸\22u樹\10w樺\7\18樽\12Íæ©\132\22kæ©\135\22pæ©\ \\136\22tæ©\139\7ôæ©\152\7«æ©\153\22ræ©\159\7\128æ©¡\14\9æ©¢\22q橦\22sæ©\ \²\22m橸\22oæ©¿\7\0æª\128\12èæª\132\22zæª\141\22xæª\142\8çæª\144\22wæª\ \\151\22\128æª\156\21÷檠\22y檢\22{檣\22|檪\22\139檬\22\135檮\22\13æ\ \ª³\22\134檸\22\133檻\22\130æ«\129\22hæ«\130\22\132æ«\131\22\131æ«\145\ \\22\137æ«\147\17Eæ«\154\22\140æ«\155\89æ«\158\22\136æ«\159\22\138櫨\14¥\ \櫪\22\141櫺\22\145æ«»\22\142æ¬\132\16Óæ¬\133\22\143æ¬\138\22\92æ¬\146\ \\22\146æ¬\150\22\147æ¬\157\6\20æ¬\159\22\149欠\8\135次\10\31欣\8\19æ¬\ \§\6b欲\16¾æ¬·\22\151欸\22\150欹\22\153欺\7\156欽\8\20款\7<æ\173\ \\131\22\156æ\173\135\22\155æ\173\137\22\157æ\173\140\6\140æ\173\142\12Öæ\ \\173\144\22\158æ\173\147\7=æ\173\148\22 æ\173\153\22\159æ\173\155\22¡æ\ \\173\159\22¢æ\173¡\22£æ\173¢\9þæ\173£\11³æ\173¤\9_æ\173¦\15Pæ\173©\15 æ\ \\173ª\17cæ\173¯\10\21æ\173³\9\142æ\173´\170æ\173¸\22¤æ\173¹\22¥æ\173»\10\ \\0æ\173¿\22¦æ®\128\22§æ®\131\22©æ®\132\22¨æ®\134\15÷æ®\137\10½æ®\138\10j\ \æ®\139\9ãæ®\141\22ªæ®\149\22¬æ®\150\11Bæ®\152\22«æ®\158\22\173殤\22®æ®ª\ \\22¯æ®«\22°æ®¯\22±æ®±\22³æ®²\22²æ®³\22´æ®´\6c段\12éæ®·\22µæ®º\9Åæ®»\6ëæ\ \®¼\22¶æ®¿\13¡æ¯\128\19Jæ¯\133\7\130æ¯\134\22·æ¯\139\22¸æ¯\141\15ªæ¯\142\ \\16\8æ¯\146\14\5æ¯\147\22¹æ¯\148\14保\152\14ùæ¯\155\16Qæ¯\159\22ºæ¯«\22\ \¼æ¯¬\22»æ¯¯\22¾æ¯³\22½æ°\136\22Áæ°\143\10\1æ°\145\16/æ°\147\22Âæ°\148\22\ \Ãæ°\151\7\131æ°\155\22Äæ°£\22Ææ°¤\22Åæ°´\11\133æ°·\15\24æ°¸\6)æ°¾\14Ãæ±\ \\128\13sæ±\129\10 æ±\130\7Áæ±\142\14Äæ±\144\10,æ±\149\22Èæ±\151\7>æ±\154\ \\6Xæ±\157\140æ±\158\22Çæ±\159\9\29æ± \12òæ±¢\22Éæ±¨\22Ñæ±ª\22Êæ±°\12\127\ \æ±²\7Âæ±³\22Òæ±º\8\136æ±½\7\132æ±¾\22Ðæ²\129\22Îæ²\130\22Ëæ²\131\16Àæ²\ \\136\13>æ²\140\14\23æ²\141\22Ìæ²\144\22Ôæ²\146\22Óæ²\147\8Bæ²\150\6kæ²\ \\153\9yæ²\154\22Íæ²\155\22Ïæ²¡\15öæ²¢\12²æ²«\16\23æ²®\22Üæ²±\22Ýæ²³\6\ \\141沸\15fæ²¹\16{沺\22ßæ²»\10!æ²¼\11\0æ²½\22Øæ²¾\22Þæ²¿\6Hæ³\129\7õæ³\ \\132\22Õæ³\133\22Úæ³\137\11òæ³\138\14\145æ³\140\14åæ³\147\22׿³\149\15Àæ\ \³\151\22Ùæ³\153\22âæ³\155\22àæ³\157\22Ûæ³¡\15Áæ³¢\14gæ³£\7Ãæ³¥\13\132注\ \\13\13泪\22ãæ³¯\22áæ³°\12\151æ³±\22Öæ³³\6*æ´\139\16\173æ´\140\22îæ´\146\ \\22íæ´\151\11ôæ´\153\22êæ´\155\16Ìæ´\158\13ôæ´\159\22äæ´¥\13Cæ´©\6+æ´ª\9\ \\30æ´«\22çæ´²\10\134æ´³\22ìæ´µ\22ëæ´¶\22ææ´¸\22éæ´»\7\8æ´½\22èæ´¾\14hæµ\ \\129\16ìæµ\132\112æµ\133\11óæµ\153\22ôæµ\154\22òæµ\156\15,æµ£\22ïæµ¤\22ñ\ \浦\6\25浩\9\31浪\17Q浬\6Üæµ®\15Bæµ´\16Áæµ·\6Ãæµ¸\11Zæµ¹\22óæ¶\133\22\ \øæ¶\136\11\1æ¶\140\16\143æ¶\142\22õæ¶\147\22ðæ¶\149\22öæ¶\153\17\28æ¶\ \\155\13Óæ¶\156\14\0涯\6Õæ¶²\64æ¶µ\22ü涸\22ÿæ¶¼\17\1æ·\128\16Äæ·\133\23\ \\6æ·\134\23\0æ·\135\22ýæ·\139\17\18æ·\140\23\3æ·\145\10©æ·\146\23\5æ·\ \\149\23\10æ·\152\13Ñæ·\153\23\8æ·\158\23\2æ·¡\12׿·¤\23\9æ·¦\22þæ·¨\23\4\ \æ·ª\23\11æ·«\5úæ·¬\23\1æ·®\23\12æ·±\11[æ·³\10¾æ·µ\15cæ··\9læ·¹\22ùæ·º\23\ \\7æ·»\13\153æ¸\133\11´æ¸\135\7\9æ¸\136\9\143æ¸\137\11\2æ¸\138\22ûæ¸\139\ \\10¡æ¸\147\8kæ¸\149\22úæ¸\153\23\16æ¸\154\10Íæ¸\155\8¸æ¸\157\23\31æ¸\159\ \\23\25渠\7Ôæ¸¡\13®æ¸£\23\20渤\23\29渥\5\173渦\6\17温\6w渫\23\22測\ \\12jæ¸\173\23\13渮\23\15港\9 游\23 渺\23\27渾\23\19æ¹\131\23\26æ¹\ \\138\16)æ¹\141\23\24æ¹\142\23\28æ¹\150\8Îæ¹\152\11\3æ¹\155\12Øæ¹\159\23\ \\18æ¹§\16\142湫\23\21æ¹®\23\14湯\13Òæ¹²\23\17æ¹¶\23\23æ¹¾\17p湿\10<æº\ \\128\16\30æº\130\23!æº\140\14¬æº\143\23-æº\144\8¹æº\150\10Àæº\152\23#æº\ \\156\16íæº\157\9!æº\159\230溢\5ìæº¥\23.溪\23\34溯\23(溲\23*溶\16®æº\ \·\23%溺\13\141溽\23'æ»\130\23/æ»\132\23)æ»\133\16Eæ»\137\23$æ»\139\10 \ \æ»\140\23<æ»\145\7\10æ»\147\23&æ»\148\23+æ»\149\23,æ»\157\12ªæ»\158\12\ \\152滬\234滯\23:滲\238æ»´\13\136æ»·\23B滸\235滾\236滿\23\30æ¼\129\ \\7Ùæ¼\130\15\25æ¼\134\10=æ¼\137\9Wæ¼\143\17Ræ¼\145\232æ¼\147\23Aæ¼\148\6\ \Iæ¼\149\12Fæ¼ \14\153æ¼¢\7?æ¼£\178漫\16\31漬\13Pæ¼±\239æ¼²\23;漸\12\ \\17æ¼¾\23@漿\237æ½\129\231æ½\133\7Aæ½\148\8\137æ½\152\23Næ½\155\23Iæ½\ \\156\11öæ½\159\7\3潤\10Á潦\23Ræ½\173\23Kæ½®\13*潯\23Hæ½°\13Wæ½´\23kæ½\ \¸\23E潺\23Dæ½¼\23Mæ¾\128\23Gæ¾\129\23Fæ¾\130\23Læ¾\132\11\159æ¾\134\23C\ \æ¾\142\23Oæ¾\145\23Pæ¾\151\7@澡\23Uæ¾£\23T澤\23V澪\23Yæ¾±\13¢æ¾³\23Sæ\ \¾¹\23Wæ¿\128\8\131æ¿\129\12·æ¿\130\23Qæ¿\131\14Zæ¿\134\23Xæ¿\148\23]æ¿\ \\149\23[æ¿\152\23^æ¿\155\23aæ¿\159\23Zæ¿ \9Jæ¿¡\14G濤\22÷æ¿«\16Ôæ¿¬\23\ \\92æ¿®\23`濯\12³æ¿±\23_濳\23Jæ¿¶\29\137濺\23d濾\23hç\128\129\23fç\ \\128\137\23bç\128\139\23cç\128\143\23gç\128\145\23eç\128\149\15-ç\128\ \\152\23mç\128\154\23jç\128\155\23iç\128\157\23lç\128\158\14\18ç\128\159\ \\23nç\128¦\13\21ç\128§\12«ç\128¬\11£ç\128°\23oç\128²\23qç\128¾\23pç\129\ \\140\233ç\129\145\23rç\129\152\14%ç\129£\23sç\129«\6\142ç\129¯\13Ôç\129°\ \\6Äç\129¸\7Äç\129¼\10\92ç\129½\9\144ç\130\137\17Fç\130\138\11\134ç\130\ \\142\6Jç\130\146\23uç\130\153\23tç\130¬\23xç\130\173\12Ùç\130®\23{ç\130¯\ \\23vç\130³\23zç\130¸\23yç\130¹\13\159ç\130º\5×ç\131\136\173ç\131\139\23}\ \ç\131\143\6\7ç\131\153\23\128ç\131\157\23~ç\131\159\23|ç\131±\23wç\131¹\ \\15Âç\131½\23\130ç\132\137\23\129ç\132\148\6Kç\132\153\23\132ç\132\154\ \\15pç\132\156\23\131ç\132¡\163ç\132¦\11\5ç\132¶\12\18ç\132¼\11\4ç\133\ \\137\179ç\133\140\23\138ç\133\142\11÷ç\133\149\23\134ç\133\150\23\139ç\ \\133\153\6Lç\133¢\23\137ç\133¤\14\129ç\133¥\23\133ç\133¦\23\136ç\133§\11\ \\6ç\133©\14Ïç\133¬\23\140ç\133®\10Oç\133½\11øç\134\132\23\143ç\134\136\ \\23\135ç\134\138\8Fç\134\143\23\141ç\134\148\16¯ç\134\149\23\144ç\134\ \\153\31$ç\134\159\10®ç\134¨\23\145ç\134¬\23\146ç\134±\14Mç\134¹\23\148ç\ \\134¾\23\149ç\135\131\14Rç\135\136\13Õç\135\137\23\151ç\135\142\23\153ç\ \\135\144\17\19ç\135\146\23\150ç\135\148\23\152ç\135\149\6Mç\135\151\23\ \\147ç\135\159\18úç\135 \23\154ç\135¥\12Gç\135¦\9×ç\135§\23\156ç\135¬\23\ \\155ç\135\173\11Cç\135®\18\151ç\135µ\23\157ç\135¹\23\159ç\135»\23\142ç\ \\135¼\23\158ç\135¿\23 ç\136\134\14\154ç\136\141\23¡ç\136\144\23¢ç\136\ \\155\23£ç\136¨\23¤ç\136ª\13\92ç\136¬\23¦ç\136\173\23¥ç\136°\23§ç\136²\23\ \¨ç\136µ\10]ç\136¶\15Cç\136º\16jç\136»\23©ç\136¼\23ªç\136½\125ç\136¾\10\ \\34ç\136¿\23«ç\137\128\23¬ç\137\134\23\173ç\137\135\15\144ç\137\136\14Åç\ \\137\139\23®ç\137\140\14vç\137\146\13+ç\137\152\23¯ç\137\153\6¥ç\137\155\ \\7Íç\137\157\16Dç\137\159\164ç\137¡\6rç\137¢\17Sç\137§\15ñç\137©\15hç\ \\137²\11µç\137´\23°ç\137¹\14\1ç\137½\8¡ç\137¾\23±ç\138\128\9\146ç\138\ \\129\23³ç\138\130\23²ç\138\135\23´ç\138\146\23µç\138\150\23¶ç\138 \7\157\ \ç\138¢\23·ç\138§\23¸ç\138¬\8¢ç\138¯\14Æç\138²\23ºç\138¶\113ç\138¹\23¹ç\ \\139\130\7öç\139\131\23»ç\139\132\23½ç\139\134\23¼ç\139\142\23¾ç\139\144\ \\8Ïç\139\146\23¿ç\139\151\8'ç\139\153\12\31ç\139\155\9]ç\139 \23Áç\139¡\ \\23Âç\139¢\23Àç\139©\10kç\139¬\14\6ç\139\173\7÷ç\139·\23Äç\139¸\12Ëç\139\ \¹\23Ãç\139¼\17Tç\139½\14\130ç\140\138\23Çç\140\150\23Éç\140\151\23Æç\140\ \\155\16Rç\140\156\23Èç\140\157\23Êç\140\159\17\2ç\140¥\23Îç\140©\23Íç\ \\140ª\13\22ç\140«\14Lç\140®\8£ç\140¯\23Ìç\140´\23Ëç\140¶\16\144ç\140·\16\ \\145ç\140¾\23Ïç\140¿\6Nç\141\132\9Vç\141\133\10\2ç\141\142\23Ðç\141\143\ \\23Ñç\141\151\23Óç\141£\10¢ç\141¨\23Õç\141ª\23Ôç\141°\23Öç\141²\6ìç\141µ\ \\23Øç\141¸\23×ç\141º\23Úç\141»\23Ùç\142\132\8ºç\142\135\16æç\142\137\8\ \\10ç\142\139\6dç\142\150\8(ç\142©\7_ç\142²\17&ç\142³\23Üç\142»\23Þç\143\ \\128\23ßç\143\130\6\143ç\143\136\23Ûç\143\138\9Øç\143\141\13?ç\143\142\ \\23Ýç\143\158\23âç\143 \10lç\143¥\23àç\143ª\8]ç\143\173\14Çç\143®\23áç\ \\143±\23üç\143¸\23çç\143¾\8»ç\144\131\7Åç\144\133\23äç\144\134\16Ýç\144\ \\137\16îç\144¢\12´ç\144¥\23æç\144²\23èç\144³\17\20ç\144´\8\21ç\144µ\14úç\ \\144¶\14iç\144º\23éç\144¿\23ëç\145\129\23îç\145\149\23êç\145\153\23íç\ \\145\154\8èç\145\155\6,ç\145\156\23ïç\145\158\11\144ç\145\159\23ìç\145 \ \\17\26ç\145£\23òç\145¤\31\34ç\145©\23ðç\145ª\23óç\145¯\23åç\145°\23ñç\ \\145³\9zç\145¶\23ôç\145¾\23õç\146\131\16Þç\146\139\23öç\146\158\23÷ç\146\ \¢\23ãç\146§\23øç\146°\7Bç\146½\10#ç\147\138\23ùç\147\143\23úç\147\148\23\ \ûç\147\156\6\26ç\147 \24\0ç\147¢\15\26ç\147£\24\1ç\147¦\7\34ç\147§\24\2ç\ \\147©\24\3ç\147®\24\4ç\147°\24\6ç\147±\24\7ç\147²\24\5ç\147¶\152ç\147·\ \\24\9ç\147¸\24\8ç\148\131\24\11ç\148\132\24\10ç\148\133\24\12ç\148\140\ \\24\13ç\148\141\24\15ç\148\142\24\14ç\148\145\9Yç\148\147\24\17ç\148\149\ \\24\16ç\148\152\7Cç\148\154\11rç\148\156\13\155ç\148\158\24\18ç\148\159\ \\11¶ç\148£\9Ùç\148¥\6Yç\148¦\24\19ç\148¨\16°ç\148«\15¡ç\148¬\24\20ç\148°\ \\13£ç\148±\16\146ç\148²\9\34ç\148³\11\92ç\148·\12êç\148¸\18rç\148º\13,ç\ \\148»\6¦ç\148¼\24\21ç\149\132\24\22ç\149\134\24\27ç\149\137\24\25ç\149\ \\138\24\24ç\149\139\21\128ç\149\140\6Åç\149\141\24\23ç\149\143\5Øç\149\ \\145\14¨ç\149\148\14Èç\149\153\16ïç\149\154\24\28ç\149\155\24\26ç\149\ \\156\12ûç\149\157\11¤ç\149 \14©ç\149¢\15\12ç\149¤\24\30ç\149¥\16êç\149¦\ \\8lç\149§\24\31ç\149©\24\29ç\149ª\14Ôç\149«\24 ç\149\173\24!ç\149°\5Ùç\ \\149³\114ç\149´\24&ç\149¶\24#ç\149·\14+ç\149¸\24\34ç\149¿\7\133ç\150\130\ \\24)ç\150\134\24$ç\150\135\24%ç\150\137\24(ç\150\138\24'ç\150\139\15\4ç\ \\150\142\12!ç\150\143\12 ç\150\145\7\158ç\150\148\24*ç\150\154\24+ç\150\ \\157\24,ç\150£\24.ç\150¥\24-ç\150«\65ç\150±\246ç\150²\14æç\150³\240ç\150\ \µ\242ç\150¸\244ç\150¹\11]ç\150¼\245ç\150½\243ç\150¾\10>ç\151\130\24/ç\ \\151\131\241ç\151\133\15!ç\151\135\11\7ç\151\138\248ç\151\141\247ç\151\ \\146\249ç\151\148\10$ç\151\149\9mç\151\152\13×ç\151\153\24:ç\151\155\13I\ \ç\151\158\24<ç\151¢\16ßç\151£\24;ç\151©\12Iç\151°\24Bç\151²\24Dç\151³\24\ \Eç\151´\12óç\151º\24Cç\151¼\24@ç\151¾\24=ç\151¿\24>ç\152\129\24Aç\152\ \\137\24Hç\152\139\24Fç\152\141\24Gç\152\159\24Iç\152 \24Kç\152¡\24Lç\152\ \¢\24Mç\152¤\24Nç\152§\24Jç\152°\24Pç\152´\24Oç\152»\24Qç\153\130\17\3ç\ \\153\134\24Tç\153\135\24Rç\153\136\24Sç\153\140\7`ç\153\146\16|ç\153\150\ \\15\136ç\153\152\24Vç\153\156\24Uç\153¡\24Wç\153¢\24Xç\153§\24\92ç\153¨\ \\24Yç\153©\24Zç\153ª\24[ç\153¬\24]ç\153°\24^ç\153²\24_ç\153¶\24`ç\153¸\ \\24aç\153º\14\173ç\153»\13¯ç\153¼\24bç\153½\14\146ç\153¾\15\19ç\154\128\ \\24cç\154\131\24dç\154\132\13\137ç\154\134\6Æç\154\135\9#ç\154\136\24eç\ \\154\139\24fç\154\142\24gç\154\144\9Èç\154\147\24iç\154\150\24hç\154\153\ \\24jç\154\154\24kç\154®\14çç\154°\24lç\154´\24mç\154·\31\9ç\154¸\24nç\ \\154¹\24oç\154º\24pç\154¿\9Íç\155\130\24qç\155\131\14uç\155\134\15þç\155\ \\136\6-ç\155\138\66ç\155\141\24rç\155\146\24tç\155\150\24sç\155\151\13Ðç\ \\155\155\11·ç\155\156\22\152ç\155\158\24uç\155\159\16?ç\155¡\24vç\155£\7\ \Dç\155¤\14Õç\155¥\24wç\155§\24xç\155ª\24yç\155®\16Zç\155²\16Sç\155´\13<ç\ \\155¸\12Jç\155»\24{ç\155¾\10Âç\156\129\11\8ç\156\132\24~ç\156\135\24}ç\ \\156\136\24|ç\156\137\14ûç\156\139\7Eç\156\140\8§ç\156\155\24\132ç\156\ \\158\24\129ç\156\159\11^ç\156 \160ç\156¤\24\128ç\156¥\24\130ç\156¦\24\ \\131ç\156©\24\127ç\156·\24\133ç\156¸\24\134ç\156º\13-ç\156¼\7aç\157\128\ \\13\5ç\157\135\24\135ç\157\154\24\136ç\157\155\24\139ç\157¡\11\135ç\157£\ \\14\2ç\157¥\24\140ç\157¦\15òç\157¨\24\137ç\157«\24\138ç\157¹\24\143ç\157\ \¾\24\142ç\157¿\24\141ç\158\139\24\145ç\158\142\24\144ç\158\145\24\146ç\ \\158\158\24\148ç\158 \24\147ç\158¥\15\139ç\158¬\10µç\158\173\17\4ç\158°\ \\24\149ç\158³\13õç\158¶\24\150ç\158¹\24\151ç\158»\24\155ç\158¼\24\153ç\ \\158½\24\154ç\158¿\24\152ç\159\135\24\156ç\159\141\24\157ç\159\151\24\ \\158ç\159\154\24\159ç\159\155\165ç\159\156\24 ç\159¢\16nç\159£\24¡ç\159¥\ \\12íç\159§\14\138ç\159©\8)ç\159\173\12Úç\159®\24¢ç\159¯\7øç\159³\11Îç\ \\159¼\24£ç \130\9{ç \140\24¤ç \146\24¥ç \148\8¤ç \149\9\147ç  \24§ç ¥\13\ \µç ¦\9\148ç §\7\173ç ²\15Ãç ´\14jç º\13¶ç ¿\9;ç¡\133\24©ç¡\157\11\9ç¡«\ \\16ð硬\9$硯\8¥ç¡²\14¡ç¡´\24«ç¡¼\24\173ç¢\129\8éç¢\134\24¬ç¢\135\13tç¢\ \\140\24¯ç¢\141\6Öç¢\142\24ªç¢\145\14èç¢\147\6\15ç¢\149\9ªç¢\151\17qç¢\ \\154\24®ç¢£\24°ç¢§\15\137碩\11×碪\24²ç¢¯\24³ç¢µ\24±ç¢º\6í碼\24¹ç¢¾\24\ \¸ç£\129\10%ç£\133\24ºç£\134\24µç£\138\24»ç£\139\24¶ç£\144\14Öç£\145\24´ç\ \£\148\24·ç£\154\24Á磧\24À磨\16\1磬\24¼ç£¯\5é磴\24Ã磽\24Âç¤\129\11\ \\10ç¤\135\24Äç¤\142\12\34ç¤\145\24Æç¤\146\24Åç¤\153\24Ç礦\24¦ç¤ª\24¨ç¤«\ \\24É礬\24È示\10&礼\17'社\10Pç¥\128\24Êç¥\129\8Vç¥\135\7\159ç¥\136\7\ \\134ç¥\137\10\3ç¥\144\16\147ç¥\147\24Ðç¥\149\24Ïç¥\150\12#ç¥\151\24Ìç¥\ \\154\24Îç¥\157\10ªç¥\158\11_ç¥\159\24Í祠\24Ë祢\14I祥\11\11票\15\27ç¥\ \\173\9\149祷\13Øç¥º\24Ñ祿\24Òç¦\128\24èç¦\129\8\22ç¦\132\17\92ç¦\133\ \\12\20ç¦\138\24Óç¦\141\6\144ç¦\142\13uç¦\143\15_ç¦\157\24Ô禦\7Ú禧\24Õç\ \¦ª\24×禮\24Øç¦°\14H禳\24Ù禹\24Ú禺\24Û禽\8\23禾\6\145禿\14\3ç§\128\ \\10\135ç§\129\10\4ç§\137\24Üç§\139\10\136ç§\145\6\136ç§\146\15\34ç§\149\ \\24Ýç§\152\14éç§\159\12$ç§¡\24àç§£\24á秤\14\137秦\11`ç§§\24Þç§©\13\1ç§\ \¬\24ßç§°\11\12ç§»\5Úç¨\128\7\136ç¨\136\24âç¨\139\13vç¨\141\24ãç¨\142\11Å\ \ç¨\148\16+ç¨\151\15\2ç¨\152\24äç¨\153\24åç¨\154\12ôç¨\156\17\5ç¨\159\24ç\ \稠\24æç¨®\10m稱\24é稲\5î稷\24ì稻\24ê稼\6\146稽\8m稾\24ë稿\9%ç©\ \\128\9Rç©\130\15¤ç©\131\24íç©\134\15óç©\137\24ïç©\141\11Ïç©\142\6.ç©\143\ \\6xç©\144\5ªç©\151\24îç©¡\24ðç©¢\24ñç©£\115ç©©\24òç©«\6îç©°\24ôç©´\8\138\ \ç©¶\7Æç©¹\24õ空\83穽\24öç©¿\11úçª\129\14\11çª\131\11Þçª\132\9³çª\136\ \\24÷çª\146\13\2çª\147\12Kçª\149\24ùçª\150\24ûçª\151\24øçª\152\24úçª\159\ \\8A窩\24ü窪\8E窮\7Ç窯\16±çª°\24þ窶\25\0窺\6\13窿\25\3ç«\131\7\22ç\ \«\132\25\2ç«\133\25\1ç«\135\25\5ç«\136\24ýç«\138\25\6ç«\139\16çç«\141\25\ \\7ç«\143\25\8ç«\146\19rç«\147\25\10ç«\149\25\9ç«\153\25\11ç«\154\25\12ç«\ \\156\16óç«\157\25\13ç«\159\29íç« \11\13ç«¡\25\14ç«¢\25\15ç«£\10¶ç«¥\13öç\ \«¦\25\16竪\12Çç«\173\25\17端\12Ûç«°\25\18ç«¶\7ã竸\18\30竹\12ü竺\101\ \ç«¿\7Fç¬\130\25\19ç¬\132\25 ç¬\134\25\22ç¬\136\7Èç¬\138\25\21ç¬\139\25\ \\34ç¬\143\25\20ç¬\145\11\14ç¬\152\25\24ç¬\153\25\25ç¬\155\13\138ç¬\158\ \\25\26笠\6ý笥\11y符\15D笨\25\28第\12¦ç¬³\25\23笵\25\27笶\25\29笹\ \\9¹ç\173\133\25$ç\173\134\15\13ç\173\136\14¤ç\173\137\13Ùç\173\139\8\24ç\ \\173\140\25#ç\173\141\25!ç\173\143\14³ç\173\144\25\30ç\173\145\12ýç\173\ \\146\13Ûç\173\148\13Úç\173\150\9´ç\173\157\256ç\173¥\25&ç\173§\25(ç\173¬\ \\25+ç\173®\25,ç\173°\25)ç\173±\25*ç\173´\25'ç\173µ\25%ç\173º\25\31ç®\134\ \\15\141ç®\135\6\147ç®\139\253ç®\141\250ç®\143\255ç®\146\254ç®\148\14\147\ \ç®\149\16%ç®\151\9Úç®\152\25.ç®\153\257ç®\154\252ç®\156\251ç®\157\25-ç®\ \\159\25/管\7G箪\12Üç®\173\11ûç®±\14 ç®´\25<箸\14¢ç¯\128\11ßç¯\129\259\ \ç¯\132\14Íç¯\134\25=ç¯\135\15\145ç¯\137\12úç¯\139\258ç¯\140\25:ç¯\143\25\ \;ç¯\157\25>篠\10B篤\14\4篥\25C篦\25B篩\25?ç¯\173\17U篳\25H篶\25Lç\ \¯·\25Iç°\128\25Eç°\135\25Fç°\141\25Kç°\145\25@ç°\146\18\147ç°\147\25Gç°\ \\148\25Aç°\151\25Jç°\159\25Pç°¡\7Hç°£\25Mç°§\25Nç°ª\25Oç°«\25Rç°·\25Qç°¸\ \\14ôç°½\25Sç°¾\17:ç°¿\15«ç±\128\25Xç±\131\25Uç±\140\25Tç±\141\11Ðç±\143\ \\25Wç±\144\25Yç±\148\25Vç±\150\25]ç±\152\25Zç±\159\25[ç± \25D籤\25\92ç±\ \¥\25^籬\25_ç±³\15\132ç±µ\25`ç±¾\16`ç²\129\8\12ç²\130\8Hç²\131\25aç²\137\ \\15rç²\139\11\136ç²\141\16.ç²\144\25bç²\146\16ñç²\149\14\148ç²\151\12%ç²\ \\152\14Sç²\155\10¬ç²\159\5¾ç²¡\25gç²¢\25e粤\25cç²¥\7\31ç²§\11\15粨\25h\ \粫\25fç²\173\25dç²®\25lç²±\25kç²²\25jç²³\25iç²¹\25mç²½\25nç²¾\11¸ç³\128\ \\25oç³\130\25qç³\133\25pç³\138\8Ðç³\142\12\23ç³\146\25sç³\150\13Üç³\152\ \\25rç³\156\25tç³\158\15sç³\159\12Lç³ \9&ç³¢\25uç³§\17\6糯\25wç³²\25xç³´\ \\25yç³¶\25z糸\10\5糺\25{ç³»\8nç³¾\7Êç´\128\7\137ç´\130\25\128ç´\132\16\ \qç´\133\9'ç´\134\25|ç´\138\25\131ç´\139\16dç´\141\14[ç´\144\15\18ç´\148\ \\10Ãç´\149\25\130ç´\151\10Qç´\152\9(ç´\153\10\6ç´\154\7Éç´\155\15tç´\156\ \\25\129ç´ \12&ç´¡\15áç´¢\9µç´«\10\7ç´¬\13[ç´®\25\134ç´¯\17\29ç´°\9\151ç´\ \²\25\135ç´³\11aç´µ\25\137ç´¹\11\16ç´º\9nç´¿\25\136çµ\130\10\137çµ\131\8¼\ \çµ\132\12'çµ\133\25\132çµ\134\25\138çµ\139\25\133çµ\140\8oçµ\142\25\141ç\ \µ\143\25\145çµ\144\8\139çµ\150\25\140çµ\155\25\149çµ\158\9)絡\16Íçµ¢\5º\ \çµ£\25\146給\7Ë絨\25\143çµ®\25\144çµ±\13Ýçµ²\25\142çµ³\25\139çµµ\6Ççµ¶\ \\11âçµ¹\8¦çµ½\25\151ç¶\137\25\148ç¶\143\25\150ç¶\147\25\147ç¶\153\8pç¶\ \\154\12qç¶\155\25\152ç¶\156\12Nç¶\159\25¥ç¶¢\25¡ç¶£\25\155ç¶«\25\159綬\ \\10xç¶\173\5Ûç¶®\25\154綯\25¢ç¶°\25¦ç¶±\9*ç¶²\16Tç¶´\13Tç¶µ\25\156綸\ \\25¤ç¶º\25\153ç¶»\12Ýç¶½\25\158ç¶¾\5»ç¶¿\16Hç·\135\25\157ç·\138\8\25ç·\ \\139\14êç·\143\12Mç·\145\17\14ç·\146\10Ïç·\149\25Îç·\152\25§ç·\154\11üç·\ \\156\25£ç·\157\25¨ç·\158\25ªç· \13wç·¡\25\173ç·¤\25©ç·¨\15\146ç·©\7Iç·¬\ \\16Iç·¯\5Üç·²\25¬ç·´\17;ç·»\25«ç¸\129\6Oç¸\132\14*ç¸\133\25®ç¸\137\25µç¸\ \\138\25¯ç¸\139\25¶ç¸\146\25²ç¸\155\14\155ç¸\158\10Hç¸\159\25´ç¸¡\25±ç¸¢\ \\25·ç¸£\25°ç¸¦\10£ç¸«\15Ä縮\10«ç¸±\25³ç¸²\25À縵\25»ç¸·\25¾ç¸¹\25¼ç¸º\ \\25Á縻\25ºç¸½\25 ç¸¾\11Ñç¹\129\14Éç¹\131\25½ç¹\134\25¸ç¹\138\12\0ç¹\139\ \\8qç¹\141\10\138ç¹\148\11Dç¹\149\12\21ç¹\150\25Äç¹\153\25Æç¹\154\25Çç¹\ \\157\25Ãç¹\158\25Å繦\25¹ç¹§\25Â繩\25Ê繪\25Éç¹\173\16\26ç¹°\8Jç¹¹\25Èç\ \¹»\25Ìç¹¼\25Ëç¹½\25Ï繿\25Ñçº\130\9Ûçº\131\25Íçº\136\25Òçº\137\25Óçº\140\ \\25Ôçº\142\25Úçº\143\13\154çº\144\25Öçº\146\25Õçº\147\25×çº\148\25Øçº\ \\150\25Ùçº\155\25Ûçº\156\25Üç¼¶\7J缸\25Ý缺\25Þç½\133\25ßç½\140\25àç½\ \\141\25áç½\142\25âç½\144\25ãç½\145\25äç½\148\25æç½\149\25åç½\152\25çç½\ \\159\25èç½ \25éç½§\25ì罨\25ê罩\25ë罪\9\159罫\8rç½®\12õç½°\14±ç½²\10Ð\ \ç½µ\14lç½·\14ë罸\25íç½¹\20ëç¾\130\25îç¾\131\25ðç¾\133\16Åç¾\134\25ïç¾\ \\135\25òç¾\136\25ñç¾\138\16²ç¾\140\25óç¾\142\14üç¾\148\25ôç¾\154\25÷ç¾\ \\157\25öç¾\158\25õç¾£\25øç¾¤\8Q羨\12\1義\7 ç¾®\25ü羯\25ùç¾²\25úç¾¶\25\ \ý羸\25þç¾¹\25ûç¾½\6\8ç¿\129\6eç¿\133\26\0ç¿\134\26\1ç¿\138\26\2ç¿\140\ \\16Âç¿\146\10\139ç¿\148\26\4ç¿\149\26\3ç¿ \11\137ç¿¡\26\5翦\26\6ç¿©\26\ \\7ç¿«\7cç¿°\7K翳\26\8翹\26\9ç¿»\15ü翼\16Ãè\128\128\16³è\128\129\17Vè\ \\128\131\9,è\128\132\26\12è\128\133\10Rè\128\134\26\11è\128\139\26\13è\ \\128\140\10'è\128\144\12\143è\128\146\26\14è\128\149\9+è\128\151\16Uè\ \\128\152\26\15è\128\153\26\16è\128\156\26\17è\128¡\26\18è\128¨\26\19è\ \\128³\10(è\128¶\16kè\128»\26\21è\128½\12Þè\128¿\26\20è\129\134\26\23è\ \\129\138\26\22è\129\146\26\24è\129\150\11¹è\129\152\26\25è\129\154\26\26\ \è\129\158\15wè\129\159\26\27è\129¡\12Oè\129¢\26\28è\129¨\26\29è\129¯\17<\ \è\129°\26 è\129²\26\31è\129³\26\30è\129´\13.è\129¶\26!è\129·\11Eè\129¹\ \\26\34è\129½\26#è\129¾\17Wè\129¿\26$è\130\132\26%è\130\133\26'è\130\134\ \\26&è\130\135\14£è\130\137\147è\130\139\17]è\130\140\14§è\130\147\26)è\ \\130\150\11\17è\130\152\15\9è\130\154\26*è\130\155\26(è\130\157\7Lè\130¡\ \\8Òè\130¢\10\8è\130¥\14ìè\130©\8¨è\130ª\15âè\130¬\26-è\130\173\26+è\130¯\ \\9-è\130±\9.è\130²\5çè\130´\9¦è\130º\14xè\131\131\5Ýè\131\132\262è\131\ \\134\12ßè\131\140\14wè\131\142\12\153è\131\150\264è\131\153\260è\131\154\ \\263è\131\155\26.è\131\157\261è\131\158\15Åè\131¡\8Óè\131¤\5ûè\131¥\26/è\ \\131¯\266è\131±\267è\131´\13÷è\131¸\7ùè\131¼\26Eè\131½\14\92è\132\130\10\ \\9è\132\133\7úè\132\134\11Æè\132\135\17eè\132\136\16,è\132\137\265è\132\ \\138\11Òè\132\154\7²è\132\155\268è\132£\26:è\132©\269è\132¯\26;è\132±\12\ \Åè\132³\14]è\132¹\13/è\132¾\26Bè\133\134\26Aè\133\139\26<è\133\142\11tè\ \\133\144\15Eè\133\145\26Dè\133\147\26Cè\133\148\9/è\133\149\17rè\133\159\ \\26Tè\133¥\26Hè\133¦\26Iè\133«\10nè\133®\26Gè\133°\9Xè\133±\26Fè\133´\26\ \Jè\133¸\130è\133¹\15`è\133º\12\2è\133¿\12\154è\134\128\26Nè\134\130\26Oè\ \\134\131\26Kè\134\136\26Lè\134\138\26Mè\134\143\90è\134\147\26Uè\134\149\ \\26Qè\134\154\15Fè\134\156\16\12è\134\157\15\7è\134 \26Pè\134£\26Sè\134¤\ \\26Rè\134¨\15ãè\134©\26Vè\134°\26Wè\134³\12\22è\134µ\26Xè\134¸\26Zè\134º\ \\26^è\134½\26[è\134¾\26Yè\134¿\14^è\135\128\26\92è\135\130\26]è\135\134\ \\6pè\135\136\26dè\135\137\26_è\135\141\26`è\135\145\26aè\135\147\12_è\ \\135\152\26cè\135\153\26bè\135\154\26eè\135\159\26fè\135 \26gè\135£\11bè\ \\135¥\6§è\135§\26hè\135¨\17\21è\135ª\10)è\135\173\10\140è\135³\10\10è\ \\135´\12öè\135º\26iè\135»\26jè\135¼\6\16è\135¾\26kè\136\129\26lè\136\130\ \\26mè\136\133\26nè\136\135\26oè\136\136\7ûè\136\137\21hè\136\138\26pè\ \\136\140\11ãè\136\141\26qè\136\142\10Iè\136\144\26rè\136\146\17®è\136\ \\150\26sè\136\151\15\156è\136\152\7Zè\136\155\12\3è\136\156\10·è\136\158\ \\15Qè\136\159\10\141è\136©\26tè\136ª\91è\136«\26uè\136¬\14Êè\136®\26\132\ \è\136³\26wè\136µ\12\135è\136¶\14\149è\136·\8½è\136¸\26vè\136¹\12\4è\137\ \\128\26xè\137\135\13xè\137\152\26zè\137\153\26yè\137\154\26|è\137\157\26\ \{è\137\159\26}è\137¢\26\128è\137¤\26~è\137¦\7Mè\137¨\26\129è\137ª\26\130\ \è\137«\26\131è\137®\9oè\137¯\17\7è\137±\26\133è\137²\11Fè\137¶\6Pè\137·\ \\26\134è\137¸\26\135è\137¾\26\136è\138\139\5ðè\138\141\26\137è\138\146\ \\26\138è\138\153\15Gè\138\157\10Eè\138\159\26\140è\138¥\6Èè\138¦\5°è\138\ \«\26\139è\138¬\26\142è\138\173\14mè\138¯\11cè\138±\6\148è\138³\15Æè\138¸\ \\8|è\138¹\8\26è\138»\26\141è\138½\6¨è\139\133\7!è\139\145\6Qè\139\146\26\ \\146è\139\147\17(è\139\148\12\155è\139\151\15#è\139\153\26\158è\139\155\ \\6\149è\139\156\26\156è\139\158\26\154è\139\159\26\145è\139¡\26\143è\139\ \£\26\144è\139¥\10aè\139¦\8*è\139§\13\23è\139«\14\15è\139±\60è\139³\26\ \\148è\139´\26\147è\139¹\26\153è\139º\26\149è\139»\26\152è\140\130\16Nè\ \\140\131\26\151è\140\132\6\150è\140\133\7\29è\140\134\26\155è\140\137\26\ \\157è\140\142\8sè\140\150\26¡è\140\151\26ªè\140\152\26«è\140\156\5©è\140\ \£\26²è\140¨\5ïè\140«\26©è\140¯\26¨è\140±\26£è\140²\26¢è\140´\26 è\140µ\ \\26\159è\140¶\13\3è\140¸\12¹è\140¹\26¥è\141\128\26¤è\141\133\26§è\141\ \\137\12Pè\141\138\8tè\141\143\6 è\141\144\26¦è\141\146\92è\141\152\12Qè\ \\141³\26¸è\141µ\26¹è\141·\6\151è\141»\6lè\141¼\26¶è\142\133\26¬è\142\135\ \\26´è\142\137\26»è\142\138\26µè\142\142\26³è\142\147\26\150è\142\150\26±\ \è\142\154\26\173è\142\158\7Nè\142\159\26¯è\142 \26ºè\142¢\26°è\142¨\26¼è\ \\142ª\26®è\142«\14\156è\142±\16Éè\142µ\26·è\142½\26Íè\143\129\26Åè\143\ \\133\11\155è\143\138\7¥è\143\140\8\27è\143\142\26Àè\143\147\6\153è\143\ \\150\11\18è\143\152\26Ãè\143\156\9\152è\143\159\13°è\143 \26Èè\143©\15¬è\ \\143«\26¿è\143¯\6\152è\143°\8Ôè\143±\15\8è\143²\26Éè\143´\26½è\143·\26Æè\ \\143»\26Ðè\143½\26Áè\144\131\26Âè\144\132\13øè\144\135\26Çè\144\139\26Äè\ \\144\140\15Çè\144\141\26Êè\144\142\5Þè\144\147\26¾è\144 \26Ìè\144¢\26Ëè\ \\144©\14\139è\144ª\26Òè\144¬\26Ýè\144±\7\30è\144µ\26àè\144¸\26Îè\144¼\26\ \Óè\144½\16Îè\145\134\26Üè\145\137\16´è\145\142\16èè\145\151\13\24è\145\ \\155\7\11è\145¡\15Rè\145¢\26âè\145£\13ßè\145¦\5¯è\145©\26Ûè\145«\26×è\ \\145¬\12Rè\145\173\26Ñè\145®\26Ùè\145¯\26Þè\145±\14Kè\145µ\5¨è\145·\26Öè\ \\145¹\26ßè\145º\15Xè\146\130\26Úè\146\132\26Õè\146\139\11\19è\146\144\10\ \\142è\146\148\10*è\146\153\16Vè\146\156\15&è\146\159\26åè\146¡\26îè\146\ \\173\26Øè\146²\7\23è\146¸\116è\146¹\26ãè\146»\26èè\146¼\12Sè\146¿\26äè\ \\147\129\26ëè\147\132\12þè\147\134\26ìè\147\137\16µè\147\138\26áè\147\ \\139\6×è\147\141\26çè\147\144\26êè\147\145\16*è\147\150\26íè\147\153\26æ\ \è\147\154\26éè\147¬\15Èè\147®\17@è\147´\26ñè\147¼\26øè\147¿\26ðè\148\128\ \\10Aè\148\134\26Ïè\148\145\15\140è\148\147\16 è\148\148\26÷è\148\149\26ö\ \è\148\151\26òè\148\152\26óè\148\154\6\21è\148\159\26õè\148¡\26ïè\148¦\13\ \Sè\148¬\26ôè\148\173\5üè\148µ\12`è\148½\15\129è\149\128\26ùè\149\129\27\ \\0è\149\131\14×è\149\136\26üè\149\137\11\20è\149\138\10Gè\149\139\27\2è\ \\149\142\7üè\149\149\27\3è\149\151\15Yè\149\152\26ûè\149\154\26Ôè\149£\ \\26úè\149¨\17nè\149©\13àè\149ª\15Sè\149\173\27\10è\149·\27\16è\149¾\27\ \\17è\150\128\27\4è\150\132\14\150è\150\135\27\14è\150\136\27\6è\150\138\ \\27\8è\150\144\27\18è\150\145\27\7è\150\148\27\11è\150\151\6Rè\150\153\ \\14#è\150\155\27\12è\150\156\27\15è\150¤\27\5è\150¦\12\5è\150¨\27\9è\150\ \©\9Æè\150ª\11dè\150«\8Oè\150¬\16rè\150®\16wè\150¯\10Òè\150¹\27\22è\150º\ \\27\20è\151\129\17mè\151\137\27\19è\151\141\16Õè\151\143\27\21è\151\144\ \\27\23è\151\149\27\24è\151\156\27\27è\151\157\27\25è\151¤\13áè\151¥\27\ \\26è\151©\14Ëè\151ª\27\13è\151·\10Óè\151¹\27\28è\151º\27!è\151»\12Tè\151\ \¾\27 è\152\130\27\1è\152\134\27\34è\152\135\12(è\152\138\27\29è\152\139\ \\27\31è\152\147\27\30è\152\150\22\144è\152\151\22\129è\152\154\27$è\152¢\ \\27#è\152\173\16Öè\152¯\24zè\152°\27%è\152¿\27&è\153\141\27'è\153\142\8Õ\ \è\153\144\7³è\153\148\27)è\153\149\18<è\153\154\7Õè\153\156\16øè\153\158\ \\81è\153\159\27*è\153§\27+è\153«\13\14è\153±\27,è\153¹\148è\153»\5¸è\154\ \\138\6¡è\154\139\271è\154\140\272è\154\147\27-è\154\149\9Üè\154£\27.è\ \\154¤\14aè\154©\27/è\154ª\270è\154«\27:è\154¯\274è\154°\277è\154¶\273è\ \\155\132\275è\155\134\276è\155\135\10Vè\155\137\278è\155\139\12àè\155\ \\141\8uè\155\142\6áè\155\148\27;è\155\153\6Þè\155\155\27Aè\155\158\27<è\ \\155\159\27@è\155¤\14¸è\155©\27=è\155¬\27>è\155\173\15'è\155®\14Øè\155¯\ \\27Bè\155¸\12»è\155¹\27Lè\155»\27Hè\155¾\6©è\156\128\27Fè\156\130\15Éè\ \\156\131\27Gè\156\134\27Dè\156\136\27Eè\156\137\27Jè\156\138\27Mè\156\ \\141\27Kè\156\145\27Iè\156\146\27Cè\156\152\12÷è\156\154\27Tè\156\156\16\ \(è\156¥\27Rè\156©\27Sè\156´\27Nè\156·\27Pè\156»\27Qè\156¿\27Oè\157\137\ \\11äè\157\139\17Xè\157\140\27Xè\157\142\27Yè\157\147\27_è\157\149\11Iè\ \\157\151\27[è\157\153\27^è\157\159\27Vè\157 \27Uè\157£\27`è\157¦\6\154è\ \\157¨\27\92è\157ª\27aè\157®\27]è\157´\27Zè\157¶\131è\157¸\27Wè\157¿\14\ \\136è\158\130\27eè\158\141\16\154è\158\159\27dè\158¢\27cè\158«\27lè\158¯\ \\27fè\158³\27nè\158º\16Æè\158»\27qè\158½\27hè\159\128\27iè\159\132\27mè\ \\159\134\27pè\159\135\27oè\159\139\27gè\159\144\27jè\159\146\27{è\159 \ \\27tè\159¯\27rè\159²\27sè\159¶\27xè\159·\27yè\159¹\6Éè\159»\7¡è\159¾\27w\ \è \133\27bè \141\27vè \142\27zè \143\27uè \145\27|è \149\27~è \150\27}è \ \¡\27\128è ¢\27\127è £\279è §\27\132è ±\27\129è ¶\27\130è ¹\27\131è »\27\ \\133è¡\128\8\140è¡\130\27\135è¡\132\27\134è¡\134\10\143è¡\140\93è¡\141\ \\22åè¡\146\27\136è¡\147\10°è¡\151\6Øè¡\153\27\137è¡\155\61è¡\157\11\21è¡\ \\158\27\138è¡¡\94è¡¢\27\139è¡£\5ß表\15\28è¡«\27\140è¡°\11\138衲\27\147\ \衵\27\144è¡·\13\15衽\27\145衾\27\142è¡¿\8\28è¢\129\27\141è¢\130\27\ \\148è¢\136\8Uè¢\139\12\156è¢\141\27\154è¢\146\27\150è¢\150\12sè¢\151\27\ \\149è¢\153\27\152è¢\158\27\143袢\27\153袤\27\155被\14í袮\27\151袰\ \\27\156袱\27\158袴\8Ñ袵\27\146袷\5¿è¢¿\27\157è£\129\9\153è£\130\174è\ \£\131\27\159è£\132\27 è£\133\12Uè£\143\16àè£\148\27¡è£\149\16\148è£\152\ \\27¢è£\153\27£è£\156\15¢è£\157\27¤è£\159\9~裡\16á裨\27©è£²\27ªè£³\11\ \\22裴\27¨è£¸\16Ç裹\27¥è£¼\27§è£½\11»è£¾\11\158è¤\130\27¦è¤\132\27«è¤\ \\135\15aè¤\138\27\173è¤\140\27¬è¤\144\7\12è¤\146\15Êè¤\147\27®è¤\157\27º\ \è¤\158\27°è¤¥\27±è¤ª\27²è¤«\27³è¤¶\27·è¤¸\27¸è¤»\27¶è¥\129\27´è¥\131\27¯\ \è¥\132\27µè¥\140\27¹è¥\141\29µè¥\150\6fè¥\158\27¼è¥\159\8\29襠\27»è¥¤\ \\27Á襦\27À襪\27Ãè¥\173\27Â襯\27Ä襲\10\144襴\27Å襷\27Æè¥¾\27Ç西\11\ \¼è¦\129\16¶è¦\131\27Èè¦\134\15bè¦\135\14eè¦\136\27Éè¦\138\27Êè¦\139\8©è¦\ \\143\7\139è¦\147\27Ëè¦\150\10\11è¦\151\14`è¦\152\27Ìè¦\154\6ï覡\27Í覦\ \\27Ï覧\16×覩\27Î親\11e覬\27Ð覯\27Ñ覲\27Ò観\7O覺\27Ó覽\27Ô覿\27\ \Õè§\128\27Öè§\146\6ðè§\154\27×è§\156\27Øè§\157\27Ùè§£\6°è§¦\11Gè§§\27Úè§\ \´\27Û觸\27Üè¨\128\8¾è¨\130\13yè¨\131\27Ýè¨\136\8vè¨\138\11uè¨\140\27àè¨\ \\142\13âè¨\144\27ßè¨\147\8Pè¨\150\27Þè¨\151\12µè¨\152\7\140è¨\155\27áè¨\ \\157\27âè¨\159\11\23訣\8\141訥\27ã訪\15Ëè¨\173\11Ý許\7Ö訳\16s訴\12\ \)訶\27ä診\11f註\13\16証\11\24è©\129\27åè©\134\27èè©\136\27éè©\144\9|\ \è©\145\12\128è©\146\27çè©\148\11\25è©\149\15\29è©\155\27æè©\158\10\12è© \ \\62è©¢\27íè©£\8w試\10\14è©©\10\13è©«\17l詬\27ìè©\173\27ëè©®\12\6è©°\7¬\ \話\17b該\6Ù詳\11\26詼\27êèª\130\27ïèª\132\27ðèª\133\27îèª\135\8Öèª\ \\137\16\159èª\140\10\15èª\141\14Fèª\145\27óèª\147\11¾èª\149\12áèª\152\16\ \\149èª\154\27öèª\158\8ê誠\11½èª¡\27ò誣\27÷誤\8ë誥\27ô誦\27õ誨\27ñè\ \ª¬\11àèª\173\14\7誰\12Î課\6\155誹\14î誼\7¢èª¿\132è«\130\27úè«\132\27\ \øè«\135\12ëè«\139\11¿è«\140\7Pè«\141\27ùè«\143\11zè«\146\17\8è«\150\17_è\ \«\154\27ûè«\155\28\7è«\156\133è«\158\28\6è« \28\3è«¡\28\11è«¢\28\4諤\28\ \\0諦\13zè«§\27þè««\27üè«\173\16\128è«®\10\16諱\28\1諳\27ýè«·\28\5諸\ \\10Ô諺\8¿è«¾\12¸è¬\128\15äè¬\129\69è¬\130\5àè¬\132\13ãè¬\135\28\9è¬\140\ \\28\8è¬\142\14$è¬\144\28\13è¬\148\28\2è¬\150\28\12è¬\151\28\14è¬\153\8ªè\ \¬\154\28\10è¬\155\95è¬\157\10S謠\28\15謡\16·è¬¦\28\18謨\28\21謫\28\ \\19謬\15\20謳\28\16謹\8\30謾\28\20è\173\129\28\22è\173\137\28\26è\ \\173\140\28\23è\173\142\28\25è\173\143\28\24è\173\150\28\27è\173\152\10/\ \è\173\154\28\29è\173\155\28\28è\173\156\15Hè\173\159\28\31è\173¦\8xè\173\ \«\28\30è\173¬\28 è\173¯\28!è\173°\7£è\173±\25ÿè\173²\117è\173´\28\34è\ \\173·\8ìè\173½\28#è®\128\28$è®\131\9Ýè®\138\21\140è®\140\28%è®\142\28&è®\ \\144\10\145è®\146\28'è®\147\28(è®\150\28)è®\153\28*è®\154\28+è°·\12Êè°º\ \\28,è°¿\28.è±\129\28-è±\134\13äè±\136\28/è±\138\15Ìè±\140\280è±\142\281è\ \±\144\282è±\149\283è±\154\14\24象\11\27è±¢\284豪\9K豫\17¬è±¬\285豸\ \\286è±¹\15\30豺\287è±¼\28?è²\130\288è²\133\28:è²\137\289è²\138\28;è²\ \\140\15åè²\141\28<è²\142\28=è²\148\28>è²\152\28@è²\157\6Ìè²\158\13eè² \ \\15I財\9 è²¢\96è²§\15.貨\6\157販\14Ì貪\28C貫\7Q責\11Óè²\173\28Bè²®\ \\28G貯\13\25è²°\16aè²²\28Eè²³\28Fè²´\7\141è²¶\28Hè²·\14\131貸\12\157è²\ \»\14ïè²¼\13\156è²½\28D貿\15æè³\128\6ªè³\129\28Jè³\130\17Gè³\131\13@è³\ \\132\17dè³\135\10\17è³\136\28Iè³\138\12oè³\141\28Zè³\142\12\7è³\145\146è\ \³\147\15/è³\154\28Mè³\155\9Þè³\156\10\18è³\158\11\28è³ \14\133è³¢\8«è³£\ \\28L賤\28K賦\15J質\10?è³\173\13±è³º\28Oè³»\28Pè³¼\97è³½\28Nè´\132\28Q\ \è´\133\28Rè´\135\28Tè´\136\12aè´\138\28Sè´\139\7dè´\141\28Vè´\143\28Uè´\ \\144\28Wè´\147\28Yè´\148\28[è´\150\28\92赤\11Ô赦\10Mèµ§\28]赫\6ñèµ\ \\173\28^èµ°\12Vèµ±\28_èµ³\28`èµ´\15Kèµ·\7\142è¶\129\28aè¶\133\134è¶\138\ \\6:è¶\153\28bè¶£\10o趨\11\150è¶³\12k趺\28eè¶¾\28dè·\130\28cè·\139\28kè\ \·\140\28iè·\143\28fè·\150\28hè·\154\28gè·\155\28jè·\157\7×è·\159\28nè·¡\ \\11Õè·£\28oè·¨\8×è·ª\28lè·«\28mè·¯\17Hè·³\135è·µ\12\8è·¼\28pè·¿\28sè¸\ \\136\28qè¸\137\28rè¸\138\16¸è¸\143\13åè¸\144\28vè¸\157\28tè¸\158\28uè¸\ \\159\28w踪\28\136踰\28z踴\28{踵\28yè¹\130\28xè¹\132\13{è¹\135\28\128\ \è¹\136\28\132è¹\137\28\129è¹\138\28|è¹\140\28\130è¹\144\28\131è¹\149\28\ \\138è¹\153\28\133è¹\159\11Öè¹ \28\135è¹£\28\137蹤\28\134è¹²\28\140è¹´\ \\10\146è¹¶\28\139è¹¼\28\141èº\129\28\142èº\132\28\145èº\133\28\144èº\135\ \\28\143èº\138\28\147èº\139\28\146èº\141\16tèº\145\28\149èº\147\28\148èº\ \\148\28\150èº\153\28\151躡\28\153躪\28\152身\11g躬\28\154躯\8+躰\ \\28\155躱\28\157躾\28\158è»\133\28\159è»\134\28\156è»\136\28 è»\138\10\ \Tè»\139\28¡è»\140\7\143è»\141\8Rè»\146\8¬è»\155\28¢è»\159\14.転\13\157è\ \»£\28£è»«\28¦è»¸\102è»»\28¥è»¼\28¤è»½\8y軾\28§è¼\131\6òè¼\133\28©è¼\137\ \\9\154è¼\138\28¨è¼\140\28±è¼\146\28«è¼\147\28\173è¼\148\15£è¼\149\28ªè¼\ \\153\28¬è¼\155\28°è¼\156\28®è¼\157\7\144è¼\159\28¯è¼¦\28²è¼©\14y輪\17\ \\22輯\10\147è¼³\28³è¼¸\16\129è¼¹\28µè¼»\28´è¼¾\28¸è¼¿\16 è½\130\28·è½\ \\132\7\13è½\133\28¶è½\134\28»è½\137\28ºè½\140\28¹è½\141\13\145è½\142\28¼\ \è½\151\28½è½\156\28¾è½\159\9L轡\8Dè½¢\28Àè½£\28Á轤\28Âè¾\155\11hè¾\156\ \\28Ãè¾\158\10+è¾\159\28Äè¾£\28Åè¾§\18_辨\18^è¾\173\28Æè¾®\25Ð辯\28Çè¾°\ \\12Ãè¾±\11Jè¾²\14_è¾·\28È辺\15\147è¾»\13Rè¾¼\9^辿\12Èè¿\130\6\9è¿\132\ \\16\24è¿\133\11vè¿\142\8}è¿\145\8\31è¿\148\15\148è¿\154\28Éè¿¢\28Ëè¿¥\28\ \Ê迦\6\158è¿©\144迪\28Ìè¿«\14\151è¿\173\13\146迯\28Íè¿°\10±è¿´\28Ïè¿·\ \\16@迸\28Þ迹\28Ñ迺\28Ò追\13Gé\128\128\12\158é\128\129\12Wé\128\131\ \\13æé\128\133\28Ðé\128\134\7´é\128\139\28Ùé\128\141\28Öé\128\142\28ãé\ \\128\143\13çé\128\144\13\0é\128\145\28Óé\128\147\13|é\128\148\13²é\128\ \\149\28Ôé\128\150\28Øé\128\151\11\128é\128\153\14\135é\128\154\13Jé\128\ \\157\11Àé\128\158\28×é\128\159\12lé\128 \12bé\128¡\28Õé\128¢\5§é\128£\17\ \Aé\128§\28Úé\128®\12\159é\128±\10\148é\128²\11ié\128µ\28Üé\128¶\28Ûé\128\ \¸\5íé\128¹\28Ýé\128¼\15\14é\128¾\28åé\129\129\14\25é\129\130\11\139é\129\ \\133\12øé\129\135\86é\129\137\28äé\129\138\16\150é\129\139\6\30é\129\141\ \\15\149é\129\142\6\159é\129\143\28ßé\129\144\28àé\129\145\28áé\129\146\ \\28âé\129\147\13ùé\129\148\12Âé\129\149\5áé\129\150\28æé\129\152\28çé\ \\129\153\31!é\129\156\12{é\129\158\28èé\129 \6Sé\129¡\12+é\129£\8\173é\ \\129¥\16¹é\129¨\28éé\129©\13\139é\129\173\12Xé\129®\10Ué\129¯\28êé\129²\ \\28íé\129µ\10Åé\129¶\28ëé\129·\12\10é\129¸\12\9é\129º\5âé\129¼\17\9é\129\ \½\28ïé\129¿\14ðé\130\128\28ñé\130\129\28ðé\130\130\28îé\130\131\25\4é\ \\130\132\7Ré\130\135\28Îé\130\137\28óé\130\138\28òé\130\143\28ôé\130\145\ \\16\151é\130£\14\31é\130¦\15Íé\130¨\28õé\130ª\10Wé\130¯\28öé\130±\28÷é\ \\130µ\28øé\130¸\13\128é\131\129\5èé\131\138\98é\131\142\17Yé\131\155\28ü\ \é\131¡\8Sé\131¢\28ùé\131¤\28úé\131¨\15Té\131\173\6óé\131µ\16\152é\131·\7\ \ýé\131½\13³é\132\130\28ýé\132\146\28þé\132\153\28ÿé\132\173\13\129é\132°\ \\29\1é\132²\29\0é\133\137\14\17é\133\138\29\2é\133\139\10\149é\133\140\ \\10^é\133\141\14zé\133\142\13\17é\133\146\10pé\133\148\11\140é\133\150\ \\29\3é\133\152\29\4é\133¢\11|é\133£\29\5é\133¥\29\6é\133©\29\7é\133ª\16Ï\ \é\133¬\10\150é\133²\29\9é\133³\29\8é\133µ\99é\133·\9Sé\133¸\9ßé\134\130\ \\29\12é\134\135\10Æé\134\137\29\11é\134\139\29\10é\134\141\12§é\134\144\ \\8íé\134\146\11Áé\134\151\14®é\134\156\10\152é\134¢\29\13é\134¤\11\29é\ \\134ª\29\16é\134«\29\14é\134¯\29\15é\134´\29\18é\134µ\29\17é\134¸\118é\ \\134º\29\19é\135\128\29\20é\135\129\29\21é\135\134\14Îé\135\135\9\145é\ \\135\136\10_é\135\137\29\22é\135\139\29\23é\135\140\16âé\135\141\10¤é\ \\135\142\16lé\135\143\17\10é\135\144\29\24é\135\145\8 é\135\150\29\25é\ \\135\152\13\130é\135\155\29\28é\135\156\7\24é\135\157\11jé\135\159\29\26\ \é\135¡\29\27é\135£\13^é\135¦\15ôé\135§\8:é\135µ\29\30é\135¶\29\31é\135¼\ \\29\29é\135¿\29!é\136\141\14\29é\136\142\6âé\136\145\29%é\136\148\29\34é\ \\136\149\29$é\136\158\29 é\136©\29né\136¬\29#é\136´\17)é\136·\8Øé\136¿\ \\29-é\137\132\13\147é\137\133\29(é\137\136\29+é\137\137\29)é\137\139\29.\ \é\137\144\29/é\137\151\29'é\137\154\294é\137\155\6Té\137\158\29&é\137¢\ \\14«é\137¤\29*é\137¦\11\30é\137±\9:é\137¾\15çé\138\128\8\34é\138\131\10¥\ \é\138\133\13úé\138\145\12\12é\138\147\292é\138\149\29,é\138\150\291é\138\ \\152\16Aé\138\154\136é\138\155\293é\138\156\290é\138\173\12\11é\138·\297\ \é\138¹\296é\139\143\295é\139\146\15Îé\139¤\10Ûé\139©\298é\139ª\15\157é\ \\139\173\63é\139²\15%é\139³\13\18é\139¸\7Øé\139º\29:é\139¼\9<é\140\134\9\ \Ëé\140\143\299é\140\144\11\141é\140\152\11\142é\140\153\29@é\140\154\29B\ \é\140 \119é\140¢\29Aé\140£\29Cé\140¦\8\17é\140¨\15$é\140«\10`é\140¬\17Bé\ \\140®\29<é\140¯\9¶é\140²\17^é\140µ\29Eé\140º\29Dé\140»\29Fé\141\132\29;é\ \\141\139\14'é\141\141\13´é\141\148\13Ué\141\150\29Ké\141\155\12âé\141\ \\156\29Gé\141 \29Hé\141¬\8Lé\141®\29Jé\141µ\8®é\141¼\29Ié\141¾\11\31é\ \\142\140\7\25é\142\148\29Oé\142\150\9}é\142\151\12Yé\142\154\13Hé\142§\6\ \Úé\142¬\29Mé\142\173\29Né\142®\13Aé\142°\29Lé\142¹\29Pé\143\131\29Vé\143\ \\136\29Yé\143\144\29Xé\143\145\13\140é\143\150\29Qé\143\151\29Ré\143\152\ \\29Ué\143\157\29Wé\143¡\7þé\143¤\29Zé\143¥\29Té\143¨\29Sé\144\131\29^é\ \\144\135\29_é\144\144\29`é\144\147\29]é\144\148\29\92é\144\152\11 é\144\ \\153\13èé\144\154\29[é\144¡\29dé\144«\29bé\144µ\29cé\144¶\29aé\144¸\12¶é\ \\144º\29eé\145\129\29fé\145\132\29hé\145\145\7Sé\145\146\29gé\145\147\16\ \xé\145\154\29sé\145\155\29ié\145\158\29lé\145 \29jé\145¢\29ké\145ª\29mé\ \\145°\29oé\145µ\29pé\145·\29qé\145¼\29té\145½\29ré\145¾\29ué\145¿\29wé\ \\146\129\29vé\149·\137é\150\128\16eé\150\130\29xé\150\131\12\13é\150\135\ \\29yé\150\137\15\130é\150\138\29zé\150\139\6Êé\150\143\6\27é\150\145\7Ué\ \\150\147\7Té\150\148\29{é\150\150\29|é\150\152\29}é\150\153\29~é\150 \29\ \\128é\150¢\7Vé\150£\6ôé\150¤\9=é\150¥\14´é\150§\29\130é\150¨\29\129é\150\ \\173\29\131é\150²\6;é\150¹\29\134é\150»\29\133é\150¼\29\132é\150¾\29\135\ \é\151\131\29\138é\151\135\5Åé\151\138\29\136é\151\140\29\140é\151\141\29\ \\139é\151\148\29\142é\151\149\29\141é\151\150\29\143é\151\152\13ìé\151\ \\156\29\144é\151¡\29\145é\151¢\29\147é\151¥\29\146é\152\156\15Lé\152¡\29\ \\148é\152¨\29\149é\152ª\9£é\152®\29\150é\152¯\29\151é\152²\15èé\152»\12*\ \é\152¿\5¢é\153\128\12\137é\153\130\29\152é\153\132\15Mé\153\139\29\155é\ \\153\140\29\153é\153\141\9>é\153\143\29\154é\153\144\8Àé\153\155\15\131é\ \\153\156\29\157é\153\157\29\159é\153\158\29\158é\153\159\29 é\153¢\6\0é\ \\153£\11wé\153¤\10Üé\153¥\7Wé\153¦\29¡é\153ª\14\134é\153¬\29£é\153°\6\1é\ \\153²\29¢é\153³\13Bé\153µ\17\11é\153¶\13éé\153·\29\156é\153¸\16äé\153º\8\ \¯é\153½\16ºé\154\133\87é\154\134\16òé\154\136\8Gé\154\138\12 é\154\139\ \\26@é\154\141\29¤é\154\142\6Ëé\154\143\11\143é\154\148\6õé\154\149\29¦é\ \\154\151\29§é\154\152\29¥é\154\153\8\132é\154\155\9\155é\154\156\11!é\ \\154 \6\2é\154£\17\23é\154§\29©é\154¨\28ìé\154ª\29¨é\154°\29¬é\154±\29ªé\ \\154²\29«é\154´\29\173é\154¶\29®é\154·\17*é\154¸\29¯é\154¹\29°é\154»\11Ç\ \é\154¼\14¹é\155\128\11\157é\155\129\7eé\155\132\16\153é\155\133\6«é\155\ \\134\10\151é\155\135\8Ùé\155\137\29³é\155\139\29²é\155\140\10\19é\155\ \\141\29´é\155\142\29±é\155\145\9Çé\155\149\29¸é\155\150\27ké\155\153\18\ \\148é\155\155\11\151é\155\156\29¶é\155¢\16ãé\155£\14/é\155¨\6\10é\155ª\ \\11áé\155«\104é\155°\15ué\155²\6\31é\155¶\17+é\155·\16Ëé\155¹\29¹é\155»\ \\13¤é\156\128\10yé\156\132\29ºé\156\134\29»é\156\135\11ké\156\136\29¼é\ \\156\138\17,é\156\141\29·é\156\142\29¾é\156\143\29Àé\156\145\29¿é\156\ \\147\29½é\156\150\29Áé\156\153\29Âé\156\156\12Zé\156\158\6 é\156¤\29Ãé\ \\156§\166é\156ª\29Äé\156°\29Åé\156²\17Ié\156¸\21Ðé\156¹\29Æé\156½\29Çé\ \\156¾\29Èé\157\130\29Ìé\157\132\29Éé\157\134\29Êé\157\136\29Ëé\157\137\ \\29Íé\157\146\11Âé\157\150\16ué\157\153\11Ãé\157\156\29Îé\157\158\14ñé\ \\157 \29Ïé\157¡\30òé\157¢\16Jé\157¤\29Ðé\157¦\29Ñé\157¨\29Òé\157©\6öé\ \\157«\29Ôé\157\173\11xé\157±\29Õé\157´\8Cé\157¹\29Öé\157º\29Úé\157¼\29Øé\ \\158\129\29Ùé\158\132\7\19é\158\133\29×é\158\134\29Ûé\158\139\29Üé\158\ \\141\5Æé\158\143\29Ýé\158\144\29Þé\158\152\11\34é\158\156\29ßé\158 \7¦é\ \\158£\29âé\158¦\29áé\158¨\29àé\158«\28\17é\158\173\15\154é\158³\29ãé\158\ \´\29äé\159\131\29åé\159\134\29æé\159\136\29çé\159\139\29èé\159\147\7Xé\ \\159\156\29éé\159\173\29êé\159®\14Bé\159²\29ìé\159³\6yé\159µ\29ïé\159¶\ \\29îé\159»\6\3é\159¿\7ÿé \129\15\133é \130\138é \131\9`é \133\9@é \134\ \\10Çé \136\11{é \140\29ñé \143\29ðé \144\16¡é \145\7fé \146\14Ðé \147\14\ \\26é \151\11\156é \152\17\12é \154\8zé ¡\29ôé ¤\29óé ¬\15êé \173\13êé ´\ \\6/é ·\29õé ¸\29òé »\150é ¼\16Êé ½\29öé¡\134\29÷é¡\139\29ùé¡\140\12¨é¡\ \\141\6úé¡\142\6ûé¡\143\29øé¡\148\7gé¡\149\8°é¡\152\7hé¡\155\13\158é¡\158\ \\17\30é¡§\8Úé¡«\29ú顯\29ûé¡°\29ü顱\30\0顳\30\2é¡´\30\1風\15W颪\30\3\ \颯\30\4颱\30\5颶\30\6é£\131\30\8é£\132\30\7é£\134\30\9é£\155\14òé£\ \\156\26\10é£\159\11H飢\7\145飩\30\10飫\30\11é£\173\18j飮\22\154飯\ \\14Ñ飲\5ù飴\5¹é£¼\10\20飽\15Ï飾\11<é¤\131\30\12é¤\133\16]é¤\137\30\ \\13é¤\138\16»é¤\140\6!é¤\144\9àé¤\146\30\14é¤\147\6¬é¤\148\30\15é¤\152\ \\30\16é¤\157\30\18é¤\158\30\19餠\30\21餡\30\17餤\30\20館\7Y餬\30\22\ \餮\30\23餽\30\24餾\30\25é¥\130\30\26é¥\133\30\28é¥\137\30\27é¥\139\30\ \\30é¥\140\30!é¥\144\30\29é¥\145\30\31é¥\146\30 é¥\149\30\34é¥\151\8\0é¦\ \\150\10qé¦\151\30#é¦\152\30$é¦\153\9A馥\30%馨\6Ý馬\14né¦\173\30&馮\ \\30'馳\12ù馴\14)馼\30(é§\129\14\157é§\132\12\138é§\133\67é§\134\8,é§\ \\136\8-é§\144\13\19é§\145\30-é§\146\8.é§\149\6\173é§\152\30,é§\155\30*é§\ \\157\30+é§\159\30)é§¢\307é§\173\30.é§®\30/é§±\300é§²\301駸\303é§»\302é§\ \¿\10¸é¨\129\304é¨\133\306é¨\142\7\146é¨\143\305é¨\146\12[é¨\147\8±é¨\153\ \\308騨\12\139騫\309騰\13ë騷\30:騾\30@é©\128\30=é©\130\30<é©\131\30>\ \é©\133\30;é©\141\30Bé©\149\30Aé©\151\30Dé©\154\8\1é©\155\30Cé©\159\30Eé©\ \¢\30F驤\30Hé©¥\30Gé©©\30I驪\30Ké©«\30J骨\9\92éª\173\30L骰\30M骸\6Ûé\ \ª¼\30Né«\128\30Oé«\132\11\145é«\143\30Pé«\145\30Qé«\147\30Ré«\148\30Sé«\ \\152\9Bé«\158\30Té«\159\30Ué«¢\30Vé«£\30W髦\30X髪\14¯é««\30Zé«\173\15\ \\5é«®\30[髯\30Y髱\30]é«´\30\92é«·\30^é«»\30_é¬\134\30`é¬\152\30aé¬\154\ \\30bé¬\159\30c鬢\30d鬣\30e鬥\30f鬧\30g鬨\30h鬩\30i鬪\30j鬮\30ké¬\ \¯\30l鬱\22\148鬲\30m鬻\25v鬼\7\147é\173\129\6Àé\173\130\9pé\173\131\ \\30oé\173\132\30né\173\133\16#é\173\141\30qé\173\142\30ré\173\143\30pé\ \\173\145\30sé\173\148\16\2é\173\152\30té\173\154\7Ûé\173¯\17Dé\173´\30ué\ \®\131\30wé®\142\5¼é®\145\30xé®\146\15ié®\147\30vé®\150\30yé®\151\30zé®\ \\159\30{é® \30|鮨\30}鮪\16\14鮫\9Ìé®\173\9¸é®®\12\14é®´\30~鮹\30\129\ \é¯\128\30\127é¯\134\30\130é¯\137\8ïé¯\138\30\128é¯\143\30\131é¯\145\30\ \\132é¯\146\30\133é¯\148\30\137é¯\150\9Éé¯\155\12¢é¯¡\30\138鯢\30\135鯣\ \\30\134鯤\30\136鯨\8~鯰\30\142鯱\30\141鯲\30\140鯵\5±é°\132\30\152\ \é°\134\30\148é°\136\30\149é°\137\30\145é°\138\30\151é°\140\30\147é°\141\ \\7\2é°\144\17ké°\146\30\150é°\147\30\146é°\148\30\144é°\149\30\143é°\155\ \\30\154é°¡\30\157é°¤\30\156é°¥\30\155é°\173\15(é°®\30\153é°¯\5ñé°°\30\ \\158é°²\30 é°¹\7\15é°º\30\139é°»\6\22é°¾\30¢é±\134\30¡é±\135\30\159é±\ \\136\12Ìé±\146\16\16é±\151\17\24é±\154\30£é± \30¤é±§\30¥é±¶\30¦é±¸\30§é³\ \¥\139é³§\30¨é³©\14µé³«\30\173鳬\30©é³°\30ªé³³\15Ðé³´\16Bé³¶\14\14é´\131\ \\30®é´\134\30¯é´\135\13üé´\136\30¬é´\137\30«é´\142\6hé´\146\30·é´\149\30\ \¶é´\155\6Ué´\159\30´é´£\30³é´¦\30±é´¨\7\27é´ª\30°é´«\100é´¬\6gé´»\9Cé´¾\ \\30ºé´¿\30¹éµ\129\30¸éµ\132\30µéµ\134\30»éµ\136\30¼éµ\144\30Äéµ\145\30Ãé\ \µ\153\30Åéµ\156\6\12éµ\157\30Àéµ\158\30Áéµ \9T鵡\167鵤\30Â鵬\15Ñ鵯\ \\30Êéµ²\30Æéµº\30Ëé¶\135\30Èé¶\137\30Çé¶\143\8{é¶\154\30Ì鶤\30Íé¶©\30Îé\ \¶«\30É鶯\30²é¶²\30Ïé¶´\13_鶸\30Ó鶺\30Ôé¶»\30Òé·\129\30Ñé·\130\30×é·\ \\132\30Ðé·\134\30Õé·\143\30Öé·\147\30Ùé·\153\30Øé·¦\30Ûé·\173\30Üé·¯\30Ý\ \é·²\17hé·¸\30Úé·¹\12©é·º\9«é·½\30Þé¸\154\30ßé¸\155\30àé¸\158\30áé¹µ\30âé\ \¹¸\8²é¹¹\30ãé¹½\30ä鹿\10-éº\129\30åéº\136\30æéº\139\30çéº\140\30èéº\145\ \\30ëéº\146\30ééº\147\17[éº\149\30êéº\151\17-éº\157\30ìéº\159\17\25麥\30\ \í麦\14\158麩\30î麪\30ðéº\173\30ñ麸\30ï麹\9M麺\16K麻\16\3麼\205éº\ \¾\22À麿\16\27é»\132\6ié»\140\30óé»\141\7¯é»\142\30ôé»\143\30õé»\144\30ö\ \é»\146\9Ué»\148\30÷é»\152\23Òé»\153\16Yé»\155\12¡é»\156\30øé»\157\30úé»\ \\158\30ùé» \30û黥\30ü黨\30ý黯\30þé»´\31\0é»¶\31\1é»·\31\2黹\31\3é»»\ \\31\4黼\31\5黽\31\6é¼\135\31\7é¼\136\31\8é¼\142\13\131é¼\147\8Ûé¼\149\ \\31\10é¼ \12,鼡\31\11鼬\31\12é¼»\15\0é¼¾\31\13é½\138\31\14é½\139\24Öé½\ \\142\28Xé½\143\29ëé½\146\31\15é½\148\31\16é½\159\31\18é½ \31\19齡\31\20\ \é½¢\17.é½£\31\17齦\31\21é½§\31\22齪\31\24齬\31\23é½²\31\26é½¶\31\27é½\ \·\31\25é¾\141\16ôé¾\149\31\28é¾\156\31\29é¾\157\24óé¾ \31\30ï¼\129\0\9ï¼\ \\131\0Tï¼\132\0Pï¼\133\0Sï¼\134\0Uï¼\136\0)ï¼\137\0*ï¼\138\0Vï¼\139\0;ï¼\ \\140\0\3ï¼\142\0\4ï¼\143\0\30ï¼\144\0Ïï¼\145\0Ðï¼\146\0Ñï¼\147\0Òï¼\148\ \\0Óï¼\149\0Ôï¼\150\0Õï¼\151\0Öï¼\152\0×ï¼\153\0Øï¼\154\0\6ï¼\155\0\7ï¼\ \\156\0Cï¼\157\0Aï¼\158\0Dï¼\159\0\8ï¼ \0WA\0àï¼¢\0áï¼£\0âD\0ãï¼¥\0äï\ \¼¦\0åï¼§\0æï¼¨\0çI\0èJ\0éK\0êL\0ëï¼\173\0ìï¼®\0íO\0îï¼°\0ïï¼±\ \\0ðï¼²\0ñï¼³\0òï¼´\0óï¼µ\0ôï¼¶\0õï¼·\0öX\0÷ï¼¹\0øï¼º\0ùï¼»\0-ï¼¼\0\31ï\ \¼½\0.ï¼¾\0\15_\0\17ï½\128\0\13ï½\129\1\1ï½\130\1\2ï½\131\1\3ï½\132\1\4\ \ï½\133\1\5ï½\134\1\6ï½\135\1\7ï½\136\1\8ï½\137\1\9ï½\138\1\10ï½\139\1\11\ \ï½\140\1\12ï½\141\1\13ï½\142\1\14ï½\143\1\15ï½\144\1\16ï½\145\1\17ï½\146\ \\1\18ï½\147\1\19ï½\148\1\20ï½\149\1\21ï½\150\1\22ï½\151\1\23ï½\152\1\24ï\ \½\153\1\25ï½\154\1\26ï½\155\0/ï½\156\0\34ï½\157\00ï¿£\0\16ï¿¥\0O" module where import Codec . Text . IConv ( convertStrictly ) import Data . Binary ( encode ) import Data . Bits ( shiftL , shiftR , ( . & . ) ) import qualified Data . ByteString . Lazy as BL import Data . ( chr , isDigit ) import Data . List ( intercalate ) import qualified Data . Map as M import Data . Maybe ( mapMaybe ) import Data . Word ( , , Word8 ) unicodeToKanji : : Word32 - > Maybe ( , ) unicodeToKanji cw = case convertStrictly " UTF-32BE " " Shift_JIS " cb of Left kc | BL.length kc = = 2 - > case fromIntegral ( kc ` BL.index ` 0 ) ` shiftL ` 8 + fromIntegral ( kc ` BL.index ` 1 ) of k | k > = 0x8140 & & k < = 0x9ffc - > Just ( cc , go ( k - 0x8140 ) ) | k > = 0xe040 & & k < = 0xebbf - > Just ( cc , go ( k - 0xc140 ) ) | otherwise - > Nothing _ - > Nothing where go : : Word16 go k = ( k ` shiftR ` 8) * 0xc0 + ( k . & . 0xff ) cc : : = chr ( fromIntegral cw ) cb : : [ fromIntegral ( cw ` shiftR ` 24 ) , fromIntegral ( cw ` shiftR ` 16 ) , fromIntegral ( cw ` shiftR ` 8) , fromIntegral cw ] showB : : Word8 - > String showB c | c < 0x20 || c = = 0x22 || c = = 0x5c || ( c > = 0x7f & & c < 0xa0 ) || c = = 0xad = ' \\ ' : show c | otherwise = [ chr ( fromIntegral c ) ] addEmptyString : : [ String ] - > [ String ] addEmptyString ( x@('\\ ' : _ ) : y@(y1 : _ ) : zs ) | isDigit y1 = x : " \ & " : y : addEmptyString zs addEmptyString ( x : xs ) = x : addEmptyString xs addEmptyString [ ] = [ ] chunksOf : : Int - > [ [ a ] ] - > [ [ a ] ] chunksOf = go [ ] where go : : [ a ] - > Int - > [ [ a ] ] - > [ [ a ] ] go p _ [ ] = [ p ] go p n ( x : xs ) = let n ' = n - length x in case n ' ` compare ` 0 of LT - > p : go [ ] n0 ( x : xs ) EQ - > ( p++x ) : go [ ] n0 xs GT - > go ( p++x ) n ' xs main : : IO ( ) main = do let kanjiMap : : M.Map kanjiMap = M.fromList ( mapMaybe unicodeToKanji [ 0 .. 0x10ffff ] ) stream : : [ String ] stream = addEmptyString ( map showB ( ( encode kanjiMap ) ) ) putStrLn " kanjiMap : : M.Map " putStrLn " kanjiMap = decode " putStrLn ( " \ " " + + intercalate " \\\n \\ " ( chunksOf 72 stream ) + + " \ " " ) module Main where import Codec.Text.IConv (convertStrictly) import Data.Binary (encode) import Data.Bits (shiftL, shiftR, (.&.)) import qualified Data.ByteString.Lazy as BL import Data.Char (chr, isDigit) import Data.List (intercalate) import qualified Data.Map as M import Data.Maybe (mapMaybe) import Data.Word (Word16, Word32, Word8) unicodeToKanji :: Word32 -> Maybe (Char, Word16) unicodeToKanji cw = case convertStrictly "UTF-32BE" "Shift_JIS" cb of Left kc | BL.length kc == 2 -> case fromIntegral (kc `BL.index` 0) `shiftL` 8 + fromIntegral (kc `BL.index` 1) of k | k >= 0x8140 && k <= 0x9ffc -> Just (cc, go (k - 0x8140)) | k >= 0xe040 && k <= 0xebbf -> Just (cc, go (k - 0xc140)) | otherwise -> Nothing _ -> Nothing where go :: Word16 -> Word16 go k = (k `shiftR` 8) * 0xc0 + (k .&. 0xff) cc :: Char cc = chr (fromIntegral cw) cb :: BL.ByteString cb = BL.pack [ fromIntegral (cw `shiftR` 24) , fromIntegral (cw `shiftR` 16) , fromIntegral (cw `shiftR` 8) , fromIntegral cw ] showB :: Word8 -> String showB c | c < 0x20 || c == 0x22 || c == 0x5c || (c >= 0x7f && c < 0xa0) || c == 0xad = '\\' : show c | otherwise = [chr (fromIntegral c)] addEmptyString :: [String] -> [String] addEmptyString (x@('\\':_) : y@(y1:_) : zs) | isDigit y1 = x : "\&" : y : addEmptyString zs addEmptyString (x:xs) = x : addEmptyString xs addEmptyString [] = [] chunksOf :: Int -> [[a]] -> [[a]] chunksOf n0 x0 = go [] n0 x0 where go :: [a] -> Int -> [[a]] -> [[a]] go p _ [] = [p] go p n (x:xs) = let n' = n - length x in case n' `compare` 0 of LT -> p : go [] n0 (x:xs) EQ -> (p++x) : go [] n0 xs GT -> go (p++x) n' xs main :: IO () main = do let kanjiMap :: M.Map Char Word16 kanjiMap = M.fromList (mapMaybe unicodeToKanji [0 .. 0x10ffff]) stream :: [String] stream = addEmptyString (map showB (BL.unpack (encode kanjiMap))) putStrLn "kanjiMap :: M.Map Char Word16" putStrLn "kanjiMap = decode" putStrLn (" \"" ++ intercalate "\\\n \\" (chunksOf 72 stream) ++ "\"") -}
3f53e1ded14896378469a94c58604ba82c86b180fbbaa105fdc1796479c2bca8
janestreet/hardcaml_of_verilog
with_interface.mli
open Base module Make (I : Hardcaml.Interface.S) (O : Hardcaml.Interface.S) : sig val create : ?verbose:bool -> ?passes:Pass.t list -> Verilog_design.t -> (Hardcaml.Signal.t I.t -> Hardcaml.Signal.t O.t Or_error.t) Or_error.t end
null
https://raw.githubusercontent.com/janestreet/hardcaml_of_verilog/c1d4e5abe18a1b15e8858151a43aa69efcbbe07b/src/with_interface.mli
ocaml
open Base module Make (I : Hardcaml.Interface.S) (O : Hardcaml.Interface.S) : sig val create : ?verbose:bool -> ?passes:Pass.t list -> Verilog_design.t -> (Hardcaml.Signal.t I.t -> Hardcaml.Signal.t O.t Or_error.t) Or_error.t end
9641062073c199e80b6bd71d9f56136b331c8922c5d8da43bf7eb2aa4e3a2633
lichenscript/lichenscript
transform.ml
* Copyright 2022 * * Licensed under the Apache License , Version 2.0 ( the " License " ) ; * you may not use this file except in compliance with the License . * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing , software * distributed under the License is distributed on an " AS IS " BASIS , * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . * See the License for the specific language governing permissions and * limitations under the License . * Copyright 2022 Vincent Chan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) open Core_kernel open Lichenscript_parsing.Asttypes open Lichenscript_parsing.Ast open Lichenscript_typing open Lichenscript_typing.Scope open Lichenscript_typing.Typedtree (* * Convert TypedTree to C-op *) module TScope = struct Why name_map ? * 1 . The same variable(type_id ) has different meaning in different scope , * In a lambda expression , a captured value represents a value to this , * but int outer scope , it 's a local variable . * 1. The same variable(type_id) has different meaning in different scope, * In a lambda expression, a captured value represents a value to this, * but int outer scope, it's a local variable. *) type t = { name_map: (string, Ir.symbol) Hashtbl.t; local_vars_to_release: Ir.symbol list ref; raw: scope option; prev: t option; } let create scope = let name_map = Hashtbl.create (module String) in { name_map; local_vars_to_release = ref []; raw = scope; prev = None; } let rec find_variable scope name = let find_in_prev () = match scope.prev with | Some prev_scope -> find_variable prev_scope name | None -> failwith (Format.sprintf "can not find variable %s" name) in match Hashtbl.find scope.name_map name with | Some v -> v | None -> find_in_prev () let distribute_name current_scope name = let fun_name = "LCC_" ^ name in Hashtbl.set current_scope.name_map ~key:name ~data:(SymLocal fun_name); fun_name let set_name scope = Hashtbl.set scope.name_map let add_vars_to_release scope (name: Ir.symbol) = scope.local_vars_to_release := name::!(scope.local_vars_to_release) let[@warning "-unused-value-declaration"] remove_release_var scope name = scope.local_vars_to_release := List.filter ~f:(fun sym -> match (sym, name) with | (Ir.SymLocal local_name, Ir.SymLocal name) -> not (String.equal local_name name) | _ -> true ) !(scope.local_vars_to_release) let rec get_symbols_to_release_til_function acc scope = let acc = List.append acc !(scope.local_vars_to_release) in let raw = Option.value_exn scope.raw in match raw#scope_type with | Scope.ST_Lambda | Scope.ST_Function -> acc | _ -> ( let prev_scope = Option.value_exn scope.prev in get_symbols_to_release_til_function acc prev_scope ) let rec get_symbols_to_release_til_while acc scope = let acc = List.append acc !(scope.local_vars_to_release) in let raw = Option.value_exn scope.raw in match raw#scope_type with | Scope.ST_While -> acc | _ -> ( let prev_scope = Option.value_exn scope.prev in get_symbols_to_release_til_while acc prev_scope ) let rec is_in_class scope = match scope.raw with | Some raw -> ( if Option.is_some raw#test_in_class then true else ( match scope.prev with | Some prev -> is_in_class prev | None -> false ) ) | None -> false let rec is_in_lambda scope = match scope.raw with | Some raw -> ( match raw#scope_type with | Scope.ST_Lambda -> true | _ -> ( match scope.prev with | Some prev -> is_in_lambda prev | None -> false ) ) | None -> false end (* * It's a monad, represent the `continuation` of pattern test * if (test) { * (* continuation here *) * } *) module PMMeta = struct type generateor = (finalizers:Ir.Stmt.t list -> unit -> Ir.Stmt.t list) type t = (generateor -> Ir.Stmt.t list) let (>>=) (left: t) (right: t) = (fun generateor -> left (fun ~finalizers:left_finalizers () -> right (fun ~finalizers:right_finalizers () -> let merged_finalizers = List.append left_finalizers right_finalizers in generateor ~finalizers:merged_finalizers () ) ) ) end type cls_meta = { cls_id: int; cls_gen_name: string; (* * logical name -> realname * * only this class, does NOT includes ancester's *) cls_fields_map: (string, string) Hashtbl.t; all generating fields , including 's cls_fields: (string * int) list; } let create_cls_meta cls_id cls_gen_name cls_fields : cls_meta = { cls_id; cls_gen_name; cls_fields_map = Hashtbl.create (module String); cls_fields; } type current_fun_meta = { fun_name: string; used_name: string Hash_set.t; mutable def_local_names: string list; } let preserved_name = [ "ret"; "rt"; "this"; "argc"; "argv"; "t"; "null"; "function"; "undefined"; "window" ] let create_current_fun_meta fun_name = { fun_name; used_name = Hash_set.of_list (module String) preserved_name; def_local_names = []; } type config = { (* automatic reference counting *) arc: bool; prepend_lambda: bool; ptr_size: Ir.ptr_size option; } type t = { prog: Program.t; config: config; mutable scope: TScope.t; mutable tmp_vars_count: int; mutable main_function_name: string option; mutable class_inits: Ir.Decl.init list; mutable prepends_decls: Ir.Decl.t list; (* * Some variables are local, but some are global, * such as a method of a class, the contructor of enum, etc *) global_name_map: (int, Ir.symbol) Hashtbl.t; cls_meta_map: (int, cls_meta) Hashtbl.t; (* for lambda generation *) mutable current_fun_meta: current_fun_meta option; mutable lambdas: Ir.Decl.t list; } let type_should_not_release (env: t) = Transform_helper.type_should_not_release ~ptr_size:(env.config.ptr_size) env.prog let type_is_not_gc env = Transform_helper.type_is_not_gc env.prog let[@warning "-unused-value-declaration"] is_identifier expr = let open Typedtree.Expression in match expr.spec with | Typedtree.Expression.Identifier _ -> true | _ -> false let[@warning "-unused-value-declaration"] is_this expr = let open Typedtree.Expression in match expr.spec with | Typedtree.Expression.This -> true | _ -> false let push_scope env (scope: TScope.t) = let scope = { scope with prev = Some env.scope; } in env.scope <- scope let pop_scope env = env.scope <- Option.value_exn env.scope.prev let with_scope env scope cb = push_scope env scope; let result = cb env in pop_scope env; result let find_variable env = TScope.find_variable env.scope let should_var_captured variable = if !(variable.var_captured) then ( match variable.var_kind with | Pvar_let -> true | _ -> false ) else false type expr_result = { prepend_stmts: Ir.Stmt.t list; expr: Ir.Expr.t; append_stmts: Ir.Stmt.t list; } let find_static_field_id_of_class (cls: Core_type.TypeDef.class_type) name = let static_props = List.filter_map ~f:(fun (name, elm) -> match elm with | Cls_elm_prop (_, prop_ty_int, _) -> Some (name, prop_ty_int) | _ -> None ) cls.tcls_static_elements in let field_id = List.find_mapi_exn ~f:(fun idx (field_name, _) -> if String.equal field_name name then Some idx else None ) static_props in field_id let create ~config prog = let scope = TScope.create None in let global_name_map = Hashtbl.create (module Int) in let cls_meta_map = Hashtbl.create (module Int) in { config; prog; scope; tmp_vars_count = 0; main_function_name = None; class_inits = []; prepends_decls = []; global_name_map; cls_meta_map; current_fun_meta = None; lambdas = []; } let get_local_var_name fun_meta realname ty_int = let name = if Hash_set.mem fun_meta.used_name realname then realname ^ "_" ^ (Int.to_string ty_int) else realname in Hash_set.add fun_meta.used_name name; name let rec transform_declaration env decl = let open Declaration in let { spec; loc; attributes } = decl in match spec with | Class cls -> ( transform_class env cls loc ) | Function_ _fun -> ( let specs = transform_function env _fun in let lambdas = env.lambdas in env.lambdas <- []; let bodys = List.map ~f:(fun spec -> { Ir.Decl. spec; loc }) specs in List.append lambdas bodys ) | Enum enum -> transform_enum env ~attributes enum loc | Interface _ -> [] | Declare declare -> ( let external_attribute = List.find_map ~f:(fun attr -> if String.equal attr.attr_name.txt "external" then Some attr.attr_payload else None ) attributes in match external_attribute with | Some (external_name::_) -> ( match declare.decl_spec with | DeclFunction fun_header -> ( let _, declare_id = fun_header.name in Hashtbl.set env.global_name_map ~key:declare_id ~data:(Ir.SymLocal external_name); [] ) ) | _ -> ( match declare.decl_spec with | DeclFunction fun_header -> ( let phys_name, _ = fun_header.name in let name = find_or_distribute_name env declare.decl_ty_var phys_name in let decl = { Ir.Decl. spec = FuncDecl name; loc = Loc.none; } in [decl] ) ) ) | Import _ -> [] and distribute_name env = TScope.distribute_name env.scope and find_or_distribute_name env id name = match Hashtbl.find env.global_name_map id with | Some name -> name | None -> ( let new_name = Ir.SymLocal (distribute_name env name) in Hashtbl.set env.global_name_map ~key:id ~data:new_name; new_name ) * 1 . Scan the function firstly , find out all the lambda expression * and captured variables * 2 . Transform body * 1. Scan the function firstly, find out all the lambda expression * and captured variables * 2. Transform body *) and transform_function env _fun = let open Function in let { body; comments; header; scope; _ } = _fun in let original_name, original_name_id = header.name in env.current_fun_meta <- Some (create_current_fun_meta original_name); let node = Program.get_node env.prog original_name_id in let fun_name = match find_or_distribute_name env original_name_id original_name with | Ir.SymLocal l -> l | _ -> failwith "unreachable" in if String.equal original_name "main" then ( env.main_function_name <- Some fun_name ); let result = transform_function_impl env ~name:(fun_name, node.loc) ~params:header.params ~scope ~body ~comments in env.current_fun_meta <- None; [ result ] and distribute_name_to_scope scope fun_meta local_vars : unit = let local_names = local_vars |> List.map ~f:(fun (var_name, variable) -> let gen_name = get_local_var_name fun_meta var_name variable.var_id in TScope.set_name scope ~key:var_name ~data:(SymLocal gen_name); gen_name ) in fun_meta.def_local_names <- List.append fun_meta.def_local_names local_names and transform_function_impl env ~name ~params ~body ~scope ~comments = let open Function in let fun_meta = Option.value_exn env.current_fun_meta in let fun_scope = TScope.create (Some scope) in push_scope env fun_scope; let params_set = Hash_set.create (module String) in List.iteri ~f:(fun index { param_name; _ } -> let param_name, _ = param_name in Hash_set.add params_set param_name; Hashtbl.set env.name_map ~key : param_ty ~data:(get_local_var_name param_name param_ty ) TScope.set_name fun_scope ~key:param_name ~data:(SymParam index) ) params.params_content; let capturing_variables = scope#capturing_variables in Scope.CapturingVarMap.iteri ~f:(fun ~key:name ~data:idx -> TScope.set_name fun_scope ~key:name ~data:(SymLambda(idx, name)); Hash_set.add params_set name; ) capturing_variables; (* filter all the params, get the "pure" local vars *) let local_vars = scope#vars |> List.filter ~f:(fun (name, _) -> not (Hash_set.mem params_set name)) in distribute_name_to_scope fun_scope fun_meta local_vars; let max_tmp_value = ref 0 in (* let before_stmts = env.tmp_vars_count in *) let stmts = List.map ~f:(fun stmt -> env.tmp_vars_count <- 0; let result = transform_statement env stmt in if env.tmp_vars_count > !max_tmp_value then ( max_tmp_value := env.tmp_vars_count ); result ) body.body |> List.concat in let generate_name_def () = let names = fun_meta.def_local_names in let open Ir.Stmt in [ VarDecl names; ] in let ending_parts = match List.last body.body with | Some { Typedtree.Statement. spec = Return _; _ } -> [] | Some { Typedtree.Statement. spec = Expr _; _ } -> let cleanup = generate_finalize_stmts fun_scope in let return_stmt = Ir.Stmt.Return (Some (Ir.Expr.Ident (Ir.SymLocal "ret"))) in List.append cleanup [return_stmt] | _ -> ( let cleanup = generate_finalize_stmts fun_scope in let return_stmt = Ir.Stmt.Return (Some Ir.Expr.Null) in List.append cleanup [return_stmt] ) in let def = if (List.length fun_meta.def_local_names) > 0 then ( generate_name_def () ) else [] in let new_body = { Ir.Block. body = List.concat [ def; stmts; ending_parts ]; loc = body.loc; } in let t_fun = { Ir.Func. name; body = new_body; tmp_vars_count = !max_tmp_value; comments; } in pop_scope env; env.tmp_vars_count <- !max_tmp_value; Ir.Decl.Func t_fun; and create_scope_and_distribute_vars env raw_scope = let scope = TScope.create (Some raw_scope) in let local_vars = raw_scope#vars in distribute_name_to_scope scope (Option.value_exn env.current_fun_meta) local_vars; scope and transform_statement ?ret env stmt = let open Statement in let { spec; _ } = stmt in let transform_return_expr ?ret expr = let tmp = transform_expression ~is_move:true env expr in let ret = Option.value ~default:(Ir.SymRet) ret in let assign = Ir.Expr.Assign(Ident ret, tmp.expr) in * It 's returning the function directly , it 's not need to retain , * because it 's directly assining to " ret " variable . * * But it should retain if it 's a normal block . * It's returning the function directly, it's not need to retain, * because it's directly assining to "ret" variable. * * But it should retain if it's a normal block. *) let expr = Ir.Stmt.Expr assign in List.concat [ tmp.prepend_stmts; [ expr ]; tmp.append_stmts ] in match spec with | Expr expr -> transform_return_expr ?ret expr | Semi expr -> ( let tmp = transform_expression env expr in let expr = Ir.Stmt.Expr tmp.expr in List.concat [ tmp.prepend_stmts; [ expr ]; tmp.append_stmts ] ) | While { while_test; while_block; _ } -> ( let while_test' = transform_expression env while_test in let bodys = transform_block ?ret env while_block in let body = { Ir.Block. body = List.append while_test'.append_stmts bodys; loc = while_block.loc; } in List.concat [ while_test'.prepend_stmts; [ Ir.Stmt.While(while_test'.expr, body); ]; while_test'.append_stmts; ] ) | ForIn for_in -> transform_for_in env ?ret for_in | Binding binding -> ( let original_name, name_id = match binding.binding_pat with | { spec = Pattern.Symbol sym; _ } -> sym | _ -> failwith "unrechable" in let scope = env.scope in let variable = Option.value_exn ~message:(Format.sprintf "%d:%d can not find %s" binding.binding_loc.start.line binding.binding_loc.start.column original_name) ((Option.value_exn scope.raw)#find_var_symbol original_name) in let name = TScope.find_variable scope original_name in let init_expr = transform_expression ~is_move:true env binding.binding_init in let node_type = Program.deref_node_type env.prog name_id in let need_release = env.config.arc && not (type_should_not_release env node_type) in * if a variable is captured , it will be upgraded into a RefCell . * type it is , it should be released . * if a variable is captured, it will be upgraded into a RefCell. * Whatevet type it is, it should be released. *) if need_release || !(variable.var_captured) then ( TScope.add_vars_to_release scope name ); let assign_expr = if should_var_captured variable then ( let init_expr = Ir.Expr.NewRef init_expr.expr in Ir.Expr.Assign((Ident name), init_expr) ) else Ir.Expr.Assign((Ident name), init_expr.expr); in List.concat [ init_expr.prepend_stmts; [ Ir.Stmt.Expr assign_expr; ]; init_expr.append_stmts; ] ) | Break _ -> let stmts = generate_finalize_stmts_while env.scope in List.append stmts [ Ir.Stmt.Break ] | Continue _ -> let stmts = generate_finalize_stmts_while env.scope in List.append stmts [ Ir.Stmt.Continue ] | Debugger -> [] | Return ret_opt -> ( let cleanup = generate_finalize_stmts_function env.scope in match ret_opt with | Some ret -> let ret = transform_return_expr ~ret:(Ir.SymRet) ret in let ret_stmt = Ir.Stmt.Return (Some (Ir.Expr.Ident Ir.SymRet)) in List.concat [ ret; cleanup; [ret_stmt]; ] | None -> let ret_stmt = Ir.Stmt.Return (Some Ir.Expr.Null) in List.append cleanup [ret_stmt] ) | Empty -> [] and transform_destructing_pattern env (pattern: Typedtree.Pattern.t) expr = let open Typedtree.Pattern in match pattern.spec with | Underscore -> [] | Symbol (sym_name, _) -> [ Ir.(Stmt.Expr( Expr.Assign( Expr.Ident (SymLocal sym_name), expr ) )) ] | EnumCtor _ | Literal _ -> failwith "unrechable" | Tuple tuple_list -> ( let stmts = tuple_list |> List.mapi ~f:(fun index item -> let tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign = Ir.(Stmt.Expr(Expr.Assign(Expr.Ident (SymTemp tmp), Expr.TupleGetValue(expr, index)))) in let child_stmts = transform_destructing_pattern env item (Ir.Expr.Ident (Ir.SymTemp tmp)) in List.concat [ [assign]; child_stmts; [Ir.Stmt.Release(Ir.Expr.Ident (Ir.SymTemp tmp))]; ] ) |> List.concat in stmts ) | Array _ -> failwith "unimplemented" and transform_for_in env ?ret for_in = let iterator_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let next_item_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let transformed_for_expr = transform_expression ~is_borrow:true env for_in.for_expr in let get_iterator_stmt = Ir.( Stmt.Expr( Expr.Assign( Expr.Ident (SymTemp iterator_id), Expr.Invoke(transformed_for_expr.expr, "getIterator", []) ) ) ) in let get_next_stmt = Ir.( Stmt.Expr( Expr.Assign( Expr.Ident(SymTemp next_item_id), Expr.Invoke(Expr.Ident(SymTemp iterator_id), "next", []) ) ) ) in let transformed_block = transform_block env ?ret ~map_scope:(fun scope -> TScope.add_vars_to_release scope (Ir.SymTemp next_item_id); scope ) for_in.for_block in let exit_if = Ir.( Stmt.If { if_test = Expr.TagEqual(Expr.Ident (SymTemp next_item_id), 1); if_consequent = [ Stmt.Release (Expr.Ident(SymTemp next_item_id)); Stmt.Break; ]; if_alternate = None; } ) in let expr_value_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let get_value_expr = Ir.(Expr.UnionGet(Expr.Ident (SymTemp next_item_id), 0)) in let assign_value = Ir.(Expr.Assign(Expr.Ident (SymTemp expr_value_tmp), get_value_expr)) in let destructing_assignments = transform_destructing_pattern env for_in.for_pat Ir.(Expr.Ident (SymTemp expr_value_tmp)) in let while_loop = Ir.Stmt.While (Ir.Expr.NewBoolean true, { Ir.Block. loc = for_in.for_loc; body = List.concat [ [ get_next_stmt; exit_if; Ir.Stmt.Expr assign_value; ]; destructing_assignments; transformed_block; [ Ir.(Stmt.Release (Ident (SymTemp expr_value_tmp))); (* optimize: don't need release if primitive *) ] ] }) in List.concat [ transformed_for_expr.prepend_stmts; [ get_iterator_stmt; while_loop; Ir.(Stmt.Release (Ident (SymTemp iterator_id))); ]; transformed_for_expr.append_stmts ] and gen_release_temp id = Ir.Stmt.Release (Ir.Expr.Temp id) and auto_release_expr env ?(is_move=false) ~append_stmts ty_var expr = let node_type = Program.deref_node_type env.prog ty_var in if (not env.config.arc) || is_move || type_should_not_release env node_type then ( expr ) else ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_expr = Ir.Expr.Assign( (Ident (Ir.SymTemp tmp_id)), expr) in append_stmts := (gen_release_temp tmp_id)::!append_stmts; assign_expr ) and prepend_expr env ~prepend_stmts ~append_stmts (expr: expr_result) = let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_expr = Ir.Expr.Assign( (Ident (Ir.SymTemp tmp_id)), expr.expr ) in let prepend_stmt = Ir.Stmt.Expr assign_expr in prepend_stmts := List.append !prepend_stmts [prepend_stmt]; let result = Ir.Expr.Temp tmp_id in append_stmts := (gen_release_temp tmp_id)::!append_stmts; result and try_folding_literals op left right original_expr = let open Expression in let do_integer_folding_i32 int_op left_int right_int = let new_int = let open Int32 in match int_op with | BinaryOp.Minus -> left_int - right_int | BinaryOp.Plus -> left_int + right_int | BinaryOp.Div -> left_int / right_int | BinaryOp.Mult -> left_int * right_int | _ -> failwith "unsupported binary op between integer" in Constant(Literal.I32(new_int)) in let do_integer_folding_i64 int_op left_int right_int = let new_int = let open Int64 in match int_op with | BinaryOp.Minus -> left_int - right_int | BinaryOp.Plus -> left_int + right_int | BinaryOp.Div -> left_int / right_int | BinaryOp.Mult -> left_int * right_int | _ -> failwith "unsupported binary op between integer" in Constant(Literal.I64(new_int)) in let do_f64_folding float_op left_str right_str = let new_float = let open Float in let left_f = Float.of_string left_str in let right_f = Float.of_string right_str in match float_op with | BinaryOp.Minus -> left_f - right_f | BinaryOp.Plus -> left_f + right_f | BinaryOp.Div -> left_f / right_f | BinaryOp.Mult -> left_f * right_f | _ -> failwith "unsupported binary op between float" in Constant(Literal.Float(Float.to_string new_float, false)) in match (left.spec, right.spec) with | (Constant(I32 left_int), Constant(I32 right_int)) -> ( match op with | BinaryOp.Plus | BinaryOp.Minus | BinaryOp.Div | BinaryOp.Mult -> ( let new_spec = do_integer_folding_i32 op left_int right_int in Some { left with spec = new_spec } ) | _ -> None ) | (Constant(I64 left_int), Constant(I64 right_int)) -> ( match op with | BinaryOp.Plus | BinaryOp.Minus | BinaryOp.Div | BinaryOp.Mult -> ( let new_spec = do_integer_folding_i64 op left_int right_int in Some { left with spec = new_spec } ) | _ -> None ) | (Constant(Float(left_f_str, false)), Constant(Float(right_f_str, false))) -> ( match op with | BinaryOp.Plus | BinaryOp.Minus | BinaryOp.Div | BinaryOp.Mult -> ( let new_spec = do_f64_folding op left_f_str right_f_str in Some { left with spec = new_spec } ) | _ -> None ) | (Constant(String(left_str, _, _)), Constant(String(right_str, _, _))) -> ( match op with | BinaryOp.Plus -> ( let concated = String.concat [left_str; right_str] in let new_spec = Constant(Literal.String(concated, left.loc, None)) in Some { left with spec = new_spec } ) | _ -> None ) | (Binary(_, _, _), _) -> ( let open Option in let res = try_folding_binary_expression left in res >>= fun left' -> (* if left being folded, try rec folding left' with right *) try_folding_literals op left' right { original_expr with spec = Binary(op, left', right) } ) | (_, Binary(_, _, _)) -> ( let open Option in let res = try_folding_binary_expression right in res >>= fun right' -> (* if right being folded, try rec folding left with right' *) try_folding_literals op left right' { original_expr with spec = Binary(op, left, right) } ) | _ -> None and try_folding_binary_expression expr: Expression.t option = let open Expression in match expr.spec with | Binary (op, left, right) -> ( here , we try fold binary expression to constant expression like : input : Expression { spec : BinaryAdd(Constant(Literal . Integer(1 ) ) , Constant(Literal . Integer(2 ) ) ) } ) output : Some(Expression { spec : Constant(Literal . Integer(3 ) ) } ) if ca n't be folded , None will be returned input: Expression { spec: BinaryAdd(Constant(Literal.Integer(1)), Constant(Literal.Integer(2))) }) output: Some(Expression { spec: Constant(Literal.Integer(3)) }) if can't be folded, None will be returned *) try_folding_literals op left right expr ) | _ -> None and transform_expression ?(is_move=false) ?(is_borrow=false) env expr = let open Expression in let { spec; loc; ty_var; _ } = expr in let prepend_stmts = ref [] in let append_stmts = ref [] in let expr_spec = match spec with | Constant literal -> ( let open Literal in match literal with | Unit -> Ir.Expr.Null | String(content, _, _) -> auto_release_expr env ~is_move ~append_stmts ty_var (Ir.Expr.NewString content) | I32 content -> let int_str = Int32.to_string content in Ir.Expr.NewI32 int_str | I64 content -> ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let int_str = Int64.to_string content in let result = Ir.Expr.NewI64 int_str in auto_release_expr env ~is_move ~append_stmts ty_var result ) | _ -> let int_str = Int64.to_string content in Ir.Expr.NewI64 int_str ) | Boolean bl -> Ir.Expr.NewBoolean bl | Float (fl, is_f32) -> if is_f32 then Ir.Expr.NewF32 fl else ( match env.config.ptr_size with | Some Ir.Ptr32 -> let result = Ir.Expr.NewF64 fl in auto_release_expr env ~is_move ~append_stmts ty_var result | _ -> Ir.Expr.NewF64 fl ) | Char ch -> Ir.Expr.NewChar ch ) * 1 . local variable * 2 . enum constructor * 1. local variable * 2. enum constructor *) | Identifier (name, name_id) -> ( let first_char = String.get name 0 in if Char.is_uppercase first_char then ( let node_type = Program.deref_node_type env.prog name_id in let ctor = Check_helper.find_construct_of env.prog node_type in let open Core_type in match ctor with | Some({ TypeDef. id = ctor_id; spec = EnumCtor _; _ }, _) -> let generate_name = Hashtbl.find_exn env.global_name_map ctor_id in let = find_variable env name in Ir.Expr.Call(generate_name, None, []) | _ -> let id_ty = Program.print_type_value env.prog node_type in failwith (Format.sprintf "unknown identifier: %s" id_ty) ) else ( let variable_opt = (Option.value_exn env.scope.raw)#find_var_symbol name in let variable = Option.value_exn variable_opt in let sym = find_variable env name in let id_expr = if should_var_captured variable then Ir.Expr.GetRef (sym, name) else Ir.Expr.Ident sym in let node_type = Program.deref_node_type env.prog variable.var_id in let need_release = env.config.arc && not (type_should_not_release env node_type) in if is_move && need_release then ( TScope.remove_release_var env.scope ; id_expr id_expr *) let id_expr = id_expr in Ir.Expr.Retaining id_expr ) else if (not is_borrow) && (not is_move) && need_release then ( let id_expr = id_expr in Ir.Expr.Retaining id_expr ) else id_expr ) ) | Lambda lambda_content -> ( let parent_scope = env.scope in let fun_meta = Option.value_exn ~message:"current function name not found" env.current_fun_meta in let lambda_name = fun_meta.fun_name ^ "_lambda_" ^ (Int.to_string ty_var) in let lambda_fun_name = "LCC_" ^ lambda_name in let capturing_variables = lambda_content.lambda_scope#capturing_variables in let capturing_names = Array.create ~len:(Scope.CapturingVarMap.length capturing_variables) (Ir.SymLocal "<unexpected>") in (* pass the capturing values into the deeper scope *) Scope.CapturingVarMap.iteri ~f:(fun ~key ~data -> let name = TScope.find_variable parent_scope key in Array.set capturing_names data name ) capturing_variables; let lambda = transform_lambda env ~lambda_name lambda_content ty_var in if env.config.prepend_lambda then ( env.lambdas <- lambda::env.lambdas ); let this_expr = if TScope.is_in_class env.scope then Ir.Expr.Ident(Ir.SymThis) else Null in let expr = Ir.Expr.NewLambda { lambda_name = lambda_fun_name; lambda_this = this_expr; lambda_capture_symbols = capturing_names; lambda_decl = lambda; } in auto_release_expr env ~is_move ~append_stmts ty_var expr ) | If if_desc -> let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let tmp_var = Ir.SymTemp tmp_id in if Check_helper.is_unit (Program.deref_node_type env.prog ty_var) then ( let init_stmt = Ir.Stmt.Expr(Ir.Expr.Assign(Ident tmp_var, Null)) in prepend_stmts := List.append !prepend_stmts [init_stmt]; ); let spec = transform_expression_if env ~ret:tmp_var ~prepend_stmts ~append_stmts loc if_desc in let tmp_stmt = Ir.Stmt.If spec in prepend_stmts := List.append !prepend_stmts [tmp_stmt]; Ir.Expr.Temp tmp_id | Tuple children -> let children_expr = List.map ~f:(fun expr -> let tmp = transform_expression ~is_borrow:true env expr in prepend_stmts := List.append !prepend_stmts tmp.prepend_stmts; append_stmts := List.append tmp.append_stmts !append_stmts; tmp.expr ) children in Ir.Expr.NewTuple children_expr | Array arr_list -> ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let arr_len = List.length arr_list in let tmp_sym = Ir.SymTemp tmp_id in let init_stmt = Ir.Stmt.Expr ( Ir.Expr.Assign( (Ident tmp_sym), (Ir.Expr.NewArray arr_len) ) ) in let max_tmp = ref env.tmp_vars_count in let init_stmts = arr_list |> List.mapi ~f:(fun index expr -> let saved_tmp = env.tmp_vars_count in let transformed_expr = transform_expression env expr in if env.tmp_vars_count > !max_tmp then ( max_tmp := env.tmp_vars_count; ); env.tmp_vars_count <- saved_tmp; let open Ir in let assign_stmt = Stmt.Expr ( Expr.ArraySetValue( (Ident tmp_sym), (NewI32 (Int.to_string index)), transformed_expr.expr ) ) in List.concat [ transformed_expr.prepend_stmts; [assign_stmt]; transformed_expr.append_stmts; ] ) |> List.concat in env.tmp_vars_count <- !max_tmp; prepend_stmts := List.concat [ !prepend_stmts; [init_stmt]; init_stmts; ]; append_stmts := List.concat [ if not is_move then [ gen_release_temp tmp_id ] else []; !append_stmts; ]; Ir.Expr.Temp tmp_id ) | Map entries -> ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let init_size = List.length entries in let init_stmt = Ir.( Stmt.Expr( Expr.Assign( Expr.Temp tmp_id, Expr.NewMap init_size) ) ) in let pre, set_stmts, app = entries |> List.map ~f:(fun entry -> let open Literal in let key_expr = match entry.map_entry_key with | String(content, _, _) -> auto_release_expr env ~is_move:false ~append_stmts ty_var (Ir.Expr.NewString content) | I32 content -> let int_str = Int32.to_string content in Ir.Expr.NewI32 int_str | _ -> failwith "unimplemented" in let expr = transform_expression env entry.map_entry_value in let set_expr = Ir.Expr.Call( Ir.SymLocal "lc_std_map_set", Some (Ir.Expr.Temp tmp_id), [key_expr; expr.expr] ) in ( expr.prepend_stmts, Ir.Stmt.Expr set_expr, expr.append_stmts ) ) |> List.unzip3 in prepend_stmts := List.concat [ !prepend_stmts; List.concat pre; [init_stmt]; set_stmts ]; append_stmts := List.concat [ List.concat app; !append_stmts; ]; Ir.Expr.Temp tmp_id ) | Call call -> ( let open Expression in (* let current_scope = env.scope in *) let { callee; call_params; _ } = call in let params_struct = List.map ~f:(transform_expression ~is_borrow:true env) call_params in let prepend, params, append = List.map ~f:(fun expr -> expr.prepend_stmts, expr.expr, expr.append_stmts) params_struct |> List.unzip3 in prepend_stmts := List.append !prepend_stmts (List.concat prepend); append_stmts := List.append !append_stmts (List.concat append); let test_namespace expr = match expr with | { spec = Identifier (_, id); _ } -> ( let expr_type = Program.deref_node_type env.prog id in match expr_type with | TypeDef { Core_type.TypeDef. spec = Namespace _; _ } -> true | _ -> false ) | _ -> false in let call_expr = match callee with | { spec = Identifier (_, id); _ } -> ( match Program.find_external_symbol env.prog id with | Some ext_name -> ( (* external method *) Ir.Expr.Call((Ir.SymLocal ext_name), None, params) ) (* it's a local function *) | None -> ( let deref_type = Program.deref_node_type env.prog callee.ty_var in match deref_type with | Core_type.TypeExpr.Lambda _ -> ( let transformed_callee = transform_expression ~is_borrow:true env callee in prepend_stmts := List.append !prepend_stmts (List.append !prepend_stmts transformed_callee.prepend_stmts); append_stmts := List.append !append_stmts (List.append !append_stmts transformed_callee.append_stmts); Ir.Expr.CallLambda(transformed_callee.expr, params) ) (* it's a contructor *) | _ -> let node = Program.get_node env.prog id in let ctor_opt = Check_helper.find_typedef_of env.prog node.value in let ctor_name = Option.value_exn ctor_opt in let name = find_variable env ctor_name.name in Ir.Expr.Call(name, None, params) ) ) | { spec = Member(_expr, None); _ } -> failwith "unrechable" | { spec = Member(expr, Some id); _ } -> begin if test_namespace expr then ( let callee_node = Program.get_node env.prog ty_var in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ctor_opt in let ctor_ty_id = ctor.id in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ctor_opt in let ctor_ty_id = ctor.id in *) let global_name = Hashtbl.find_exn env.global_name_map callee.ty_var in Ir.Expr.Call(global_name, None, params) ) else ( let expr_type = Program.deref_node_type env.prog expr.ty_var in let member = Check_helper.find_member_of_type env.prog ~scope:(Option.value_exn env.scope.raw) expr_type id.pident_name in match member with | Some ((Method ({ spec = ClassMethod { method_is_virtual = true; _ }; _ }, _, _)), _, _) -> ( let this_expr = transform_expression ~is_borrow:true env expr in prepend_stmts := List.append !prepend_stmts this_expr.prepend_stmts; append_stmts := List.append !append_stmts this_expr.append_stmts; Ir.Expr.Invoke(this_expr.expr, id.pident_name, params) ) | Some ((Method ({ id = method_id; spec = ClassMethod { method_get_set = None; _ }; _ }, _, _)), _, _) -> ( (* only class method needs a this_expr, this is useless for a static function *) let this_expr = transform_expression ~is_borrow:true env expr in prepend_stmts := List.append !prepend_stmts this_expr.prepend_stmts; append_stmts := List.append !append_stmts this_expr.append_stmts; match Program.find_external_symbol env.prog method_id with | Some ext_name -> ( (* external method *) Ir.Expr.Call((Ir.SymLocal ext_name), Some this_expr.expr, params) ) | _ -> let callee_node = Program.get_node env.prog method_id in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ~message:"Cannot find typedef of class" ctor_opt in let ctor_ty_id = ctor.id in let global_name = Hashtbl.find_exn env.global_name_map ctor_ty_id in Ir.Expr.Call(global_name, Some this_expr.expr, params) ) (* it's a static function *) | Some (TypeDef { id = fun_id; spec = Function _; _ }, _, _) -> ( let callee_node = Program.get_node env.prog fun_id in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ctor_opt in let ctor_ty_id = ctor.id in let ext_sym_opt = Program.find_external_symbol env.prog fun_id in match ext_sym_opt with | Some ext_sym -> Ir.Expr.Call(SymLocal ext_sym, None, params) | _ -> let global_name = Hashtbl.find_exn env.global_name_map ctor_ty_id in Ir.Expr.Call(global_name, None, params) ) | _ -> failwith "unrechable" ) end | _ -> ( let callee_node = Program.get_node env.prog callee.ty_var in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ctor_opt in let ctor_ty_id = ctor.id in let global_name = Hashtbl.find_exn env.global_name_map ctor_ty_id in Ir.Expr.Call(global_name, None, params) ) in auto_release_expr ~is_move env ~append_stmts ty_var call_expr ) | Member(_main_expr, None) -> failwith "unrechable" | Member(main_expr, Some id) -> ( let node_type = Program.deref_node_type env.prog main_expr.ty_var in let open Core_type.TypeDef in match node_type with | Core_type.TypeExpr.TypeDef { spec = Namespace _; _ } -> ( let expr_node_type = Program.deref_node_type env.prog expr.ty_var in let open Core_type in match expr_node_type with | TypeExpr.TypeDef { TypeDef. id = ctor_id; spec = EnumCtor _; _ } -> let generate_name = Hashtbl.find_exn env.global_name_map ctor_id in let = find_variable env name in Ir.Expr.Call(generate_name, None, []) | _ -> let id_ty = Program.print_type_value env.prog expr_node_type in failwith (Format.sprintf "unknown identifier: %s" id_ty) ) | Core_type.TypeExpr.TypeDef { spec = Class cls ; id = cls_id; _ } -> ( let field_id = find_static_field_id_of_class cls id.pident_name in let cls_meta = Hashtbl.find_exn env.cls_meta_map cls_id in let t = Ir.Expr.GetStaticValue(cls_meta.cls_gen_name, id.pident_name, field_id) in auto_release_expr env ~is_move ~append_stmts ty_var t ) | _ -> let expr_result = transform_expression ~is_borrow:true env main_expr in prepend_stmts := List.append !prepend_stmts expr_result.prepend_stmts; append_stmts := List.append expr_result.append_stmts !append_stmts; let member = Check_helper.find_member_of_type env.prog ~scope:(Option.value_exn env.scope.raw) node_type id.pident_name in (* could be a property of a getter *) match member with | Some (Method ({ Core_type.TypeDef. id = def_int; spec = ClassMethod { method_get_set = Some _; _ }; _ }, _params, _rt), _, _) -> ( let ext_sym_opt = Program.find_external_symbol env.prog def_int in let ext_sym = Option.value_exn ext_sym_opt in Ir.Expr.Call(SymLocal ext_sym, Some expr_result.expr, []) ) | Some (Core_type.TypeExpr.TypeDef { id = method_id; spec = ClassMethod { method_get_set = Some Getter; _ }; _ }, _, _) -> ( let ext_sym_opt = Program.find_external_symbol env.prog method_id in let ext_sym = Option.value_exn ext_sym_opt in Ir.Expr.Call(SymLocal ext_sym, Some expr_result.expr, []) ) (* it's a property *) | Some _ -> ( let expr_ctor_opt = Check_helper.find_construct_of env.prog node_type in match expr_ctor_opt with | Some({ id = expr_id; _ }, _) -> ( let cls_meta = Hashtbl.find_exn env.cls_meta_map expr_id in let prop_name = Hashtbl.find_exn cls_meta.cls_fields_map id.pident_name in let get_field_expr = Ir.Expr.GetField(expr_result.expr, cls_meta.cls_gen_name, prop_name) in if is_borrow then get_field_expr else Ir.Expr.( Retaining(get_field_expr) ) ) | _ -> Format.eprintf "%s expr_type: %a\n" id.pident_name Core_type.TypeExpr.pp node_type; failwith "can not find ctor of expr, maybe it's a property" ) | _ -> failwith (Format.sprintf "unexpected: can not find member %s of id %d" id.pident_name expr.ty_var) ) | Unary(op, expr) -> ( let expr' = transform_expression ~is_borrow:true env expr in let node_type = Program.deref_node_type env.prog expr.ty_var in prepend_stmts := List.append !prepend_stmts expr'.prepend_stmts; append_stmts := List.append expr'.append_stmts !append_stmts; match op with | UnaryOp.Not -> Ir.Expr.Not expr'.expr | UnaryOp.Plus -> expr'.expr | UnaryOp.Minus -> if Check_helper.is_i64 env.prog node_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let n1 = Ir.Expr.NewI64 "-1" in let n1 = auto_release_expr env ~is_move ~append_stmts expr.ty_var n1 in let tmp = Ir.Expr.I64Binary(BinaryOp.Mult, expr'.expr, n1) in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.I64Binary(BinaryOp.Mult, expr'.expr, Ir.Expr.NewI64 "-1") ) else if Check_helper.is_f64 env.prog node_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let n1 = Ir.Expr.NewF64 "-1" in let n1 = auto_release_expr env ~is_move ~append_stmts expr.ty_var n1 in let tmp = Ir.Expr.F64Binary(BinaryOp.Mult, expr'.expr, n1) in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.F64Binary(BinaryOp.Mult, expr'.expr, Ir.Expr.NewF64 "-1") ) else if Check_helper.is_f32 env.prog node_type then Ir.Expr.F32Binary(BinaryOp.Mult, expr'.expr, Ir.Expr.NewF32 "-1") else Ir.Expr.I32Binary(BinaryOp.Mult, expr'.expr, Ir.Expr.NewI32 "-1") | UnaryOp.BitNot -> if Check_helper.is_i64 env.prog node_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let tmp = Ir.Expr.I64BitNot expr'.expr in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.I64BitNot expr'.expr ) else Ir.Expr.I32BitNot expr'.expr ) | Binary (op, left, right) -> transform_binary_expr env ~is_move ~append_stmts ~prepend_stmts expr op left right * There are a lot of cases of assignment . * * 1 . Assign to an identifier : a = < expr > * - local variable * - local RefCel * - captured const * - captured refcell * 2 . Assign to a member : < expr>.xxx = < expr > * - property of a class * - setter of a class * - Assign to this property : this.xxx = expr * There are a lot of cases of assignment. * * 1. Assign to an identifier: a = <expr> * - local variable * - local RefCel * - captured const * - captured refcell * 2. Assign to a member: <expr>.xxx = <expr> * - property of a class * - setter of a class * - Assign to this property: this.xxx = expr *) | Assign (op_opt, left_expr, right_expr) -> ( let assign_or_update main_expr ty_id = let node_type = Program.deref_node_type env.prog ty_id in let need_release = env.config.arc && not (type_should_not_release env node_type) in (* save the previous value *) if need_release then ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- tmp_id + 1; let open Ir in let assign_stmt = Stmt.Expr ( Expr.Assign( Expr.Ident (SymTemp tmp_id), main_expr ) ) in let release_stmt = Stmt.Release( Expr.Ident( SymTemp tmp_id ) ) in prepend_stmts := List.append !prepend_stmts [assign_stmt]; append_stmts := List.append [release_stmt] !append_stmts ); match op_opt with | None -> ( let expr' = transform_expression ~is_move:true env right_expr in prepend_stmts := List.concat [ !prepend_stmts; expr'.prepend_stmts ]; append_stmts := List.concat [ !append_stmts; expr'.append_stmts ]; Ir.Expr.Assign(main_expr, expr'.expr) ) | Some op -> ( let binary_op = AssignOp.to_binary op in let binary_ir = transform_binary_expr env ~is_move:true ~append_stmts ~prepend_stmts expr binary_op left_expr right_expr in Ir.Expr.Assign(main_expr, binary_ir) ) in match (left_expr, op_opt) with (* transform_expression env left_expr *) | ({ spec = Typedtree.Expression.Identifier (name, name_id); _ }, _) -> ( let name = find_variable env name in assign_or_update (Ir.Expr.Ident name) name_id ) | ({ spec = Typedtree.Expression.Member (_main_expr, None); _ }, _) -> failwith "unrechable" (* TODO: maybe it's a setter? *) | ({ spec = Typedtree.Expression.Member (main_expr, Some id); _ }, _) -> ( let main_expr_ty = Program.deref_node_type env.prog main_expr.ty_var in match main_expr_ty with | Core_type.TypeExpr.TypeDef { spec = Class cls ; id = cls_id; _ } -> ( match op_opt with | None -> ( let field_id = find_static_field_id_of_class cls id.pident_name in let cls_meta = Hashtbl.find_exn env.cls_meta_map cls_id in let expr' = transform_expression ~is_move:false env right_expr in prepend_stmts := List.concat [ !prepend_stmts; expr'.prepend_stmts ]; append_stmts := List.concat [ !append_stmts; expr'.append_stmts ]; Ir.Expr.SetStaticValue(cls_meta.cls_gen_name, id.pident_name, field_id, expr'.expr) ) | _ -> failwith "unimplemented: update static value" ) | _ -> let transform_main_expr = transform_expression ~is_borrow:true env main_expr in prepend_stmts := List.concat [ !prepend_stmts; transform_main_expr.prepend_stmts ]; append_stmts := List.concat [ !append_stmts; transform_main_expr.append_stmts ]; let boxed_main_expr = prepend_expr ~is_borrow env ~prepend_stmts ~append_stmts transform_main_expr.expr in let classname_opt = Check_helper.find_classname_of_type env.prog main_expr_ty in let classname = Option.value_exn ~message:"can not find member of class" classname_opt in let gen_classname = find_variable env classname in let unwrap_name = match gen_classname with | Ir.SymLocal name -> name | _ -> failwith "unrechable" in assign_or_update (Ir.Expr.GetField( transform_main_expr.expr, unwrap_name, id.pident_name) ) main_expr.ty_var ) | ({ spec = Typedtree.Expression.Index (main_expr, value); _ }, None) -> ( let expr' = transform_expression ~is_move:true env right_expr in prepend_stmts := List.concat [ !prepend_stmts; expr'.prepend_stmts ]; append_stmts := List.concat [ !append_stmts; expr'.append_stmts ]; let transform_main_expr = transform_expression ~is_borrow:true env main_expr in let boxed_main_expr = prepend_expr env ~prepend_stmts ~append_stmts transform_main_expr.expr in let value_expr = transform_expression env value in prepend_stmts := List.concat [ !prepend_stmts; value_expr.prepend_stmts; transform_main_expr.prepend_stmts ]; append_stmts := List.concat [ transform_main_expr.append_stmts; value_expr.append_stmts; !append_stmts; ]; Ir.Expr.ArraySetValue(transform_main_expr.expr, value_expr.expr, expr'.expr) ) | _ -> Format.eprintf "Unexpected left: %a" Typedtree.Expression.pp left_expr; failwith "unreachable" ) | Init { init_name; init_elements; _ } -> ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let init_name, init_name_id = init_name in let cls_meta = Hashtbl.find_exn env.cls_meta_map init_name_id in (* logical name -> real name *) let fun_name = find_variable env init_name in let init_call_name = Ir.map_symbol ~f:(fun fun_name -> fun_name ^ "_init") fun_name in let init_call = Ir.Expr.InitCall(init_call_name, fun_name) in let init_cls_stmt = Ir.( Stmt.Expr ( Expr.Assign( (Temp tmp_id), init_call ) ) ) in let init_stmts = init_elements |> List.map ~f:(fun elm -> match elm with | InitEntry { init_entry_key; init_entry_value; _ } -> let actual_name = Hashtbl.find_exn cls_meta.cls_fields_map init_entry_key.pident_name in let transformed_value = transform_expression ~is_move:true env init_entry_value in let unwrap_name = match fun_name with | Ir.SymLocal name -> name | _ -> failwith "unrechable" in let left_value = ( Ir.Expr.GetField( (Temp tmp_id), unwrap_name, actual_name ) ) in [Ir.Stmt.Expr( Assign( left_value, transformed_value.expr ) )] | InitSpread spread_expr -> ( let transformed_spread = transform_expression ~is_move:true env spread_expr in let spread_expr' = if is_identifier spread_expr then transformed_spread.expr else prepend_expr env ~prepend_stmts ~append_stmts transformed_spread in transform_spreading_init env tmp_id spread_expr.ty_var spread_expr' ) ) |> List.concat in prepend_stmts := List.append !prepend_stmts (init_cls_stmt::init_stmts); if not is_move then ( let release_stmt = Ir.Stmt.Release(Ir.Expr.Temp tmp_id) in append_stmts := List.append !append_stmts [release_stmt]; ); Ir.Expr.Temp tmp_id ) | Block block -> let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let tmp_var = Ir.SymTemp tmp_id in let init = Ir.( Stmt.Expr ( Expr.Assign ( (Ident tmp_var), Null ) ) ) in let stmts = transform_block ~ret:tmp_var env block in prepend_stmts := List.concat [!prepend_stmts; [init]; stmts]; Ir.Expr.Temp tmp_id | Match _match -> transform_pattern_matching env ~prepend_stmts ~append_stmts ~loc ~ty_var _match | This -> ( let this_symbol = if TScope.is_in_lambda env.scope then Ir.Expr.Ident SymLambdaThis else Ir.Expr.Ident SymThis in if is_move then Ir.Expr.Retaining this_symbol else if (not is_borrow) && (not is_move) then Ir.Expr.Retaining this_symbol else this_symbol ) | TypeCast(expr, _type) ->( if Check_helper.check_castable_primitive env.prog _type then ( let expr_type = Program.deref_node_type env.prog expr.ty_var in let expr_result = transform_expression ~is_move:true env expr in let expr_type = Primitives.PrimType.from_type ~ctx:env.prog expr_type in let cast_type = Primitives.PrimType.from_type ~ctx:env.prog _type in Ir.Expr.TypeCast(expr_result.expr, expr_type, cast_type) ) else ( let tmp = transform_expression ~is_move ~is_borrow env expr in append_stmts := tmp.append_stmts; prepend_stmts := tmp.prepend_stmts; tmp.expr ) ) | Try try_expr -> ( let expr_result = transform_expression ~is_move:true env try_expr in let expr' = prepend_expr env ~prepend_stmts ~append_stmts expr_result in let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let tmp_var = "t[" ^ (Int.to_string tmp_id) ^ "]" in let cleanup = generate_finalize_stmts_function env.scope in let open Ir in let stmt = Stmt.If { 1 represent error if_consequent = List.concat [ expr_result.append_stmts; cleanup; [ Stmt.Return (Some expr') ] ]; if_alternate = None; } in let union_get_expr = Expr.UnionGet(expr', 0) in let assign_stmt = Stmt.Expr( Expr.Assign( Expr.Ident (SymLocal tmp_var), union_get_expr ) ) in prepend_stmts := List.concat [ !prepend_stmts; expr_result.prepend_stmts; [stmt; assign_stmt] ]; append_stmts := List.append expr_result.append_stmts !append_stmts; Temp tmp_id ) | Super -> failwith "unrechable" | Index(expr, index) -> ( let expr' = transform_expression ~is_borrow:true env expr in let node_type = Program.deref_node_type env.prog expr.ty_var in let index = transform_expression env index in prepend_stmts := List.concat [ !prepend_stmts; index.prepend_stmts; expr'.prepend_stmts ]; append_stmts := List.concat [ expr'.append_stmts; index.append_stmts; !append_stmts ]; match node_type with | String -> Ir.Expr.Call(Ir.SymLocal "lc_std_string_get_char", Some expr'.expr, [index.expr]) | _ -> ( let result = Ir.Expr.ArrayGetValue(expr'.expr, (Ir.Expr.IntValue index.expr)) in auto_release_expr env ~is_move ~append_stmts expr.ty_var result ) ) in { prepend_stmts = !prepend_stmts; expr = expr_spec; append_stmts = !append_stmts; } and transform_pattern_matching env ~prepend_stmts:out_prepend_stmts ~append_stmts:out_append_stmts ~loc:_ ~ty_var _match = let open Typedtree.Expression in let { match_expr; match_clauses; _ } = _match in let transformed_expr = transform_expression ~is_move:true env match_expr in let match_expr = let t = prepend_expr env ~prepend_stmts:out_prepend_stmts ~append_stmts:out_append_stmts transformed_expr in out_append_stmts := List.concat [ !out_append_stmts; transformed_expr.append_stmts; ]; t in let result_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; out_prepend_stmts := List.append !out_prepend_stmts [Ir.Stmt.Expr ( Ir.Expr.Assign ( (Ident (Ir.SymTemp result_tmp)), Null ); )]; let tmp_counter = ref [] in let label_name = "done_" ^ (Int.to_string ty_var) in let prepend_stmts = ref [] in let is_last_goto stmts = let last_opt = List.last stmts in match last_opt with | Some (Ir.Stmt.Goto _) -> true | _ -> false in let rec transform_pattern_to_test match_expr pat : PMMeta.t = let open Pattern in let { spec; _ } = pat in match spec with | Underscore -> (fun genereator -> genereator ~finalizers:[] ()) | Literal (Literal.I32 i) -> ( let i_str = Int32.to_string i in let if_test = Ir.Expr.IntValue(I32Binary(BinaryOp.Equal, match_expr, NewI32 i_str)) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) | Literal (Literal.String(str, _, _)) -> ( let if_test = Ir.Expr.StringEqUtf8(match_expr, str) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) | Literal (Literal.Boolean bl) -> ( let if_test = if bl then Ir.Expr.IntValue match_expr else Ir.Expr.IntValue(Not match_expr) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) | Literal (Literal.Char ch) -> ( let if_test = Ir.Expr.IntValue(I32Binary(BinaryOp.Equal, match_expr, Ir.Expr.NewChar ch)) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) | Literal _ -> failwith "unimplemented" | Symbol (name, name_id) -> ( let first_char = String.get name 0 in if Char.is_uppercase first_char then ( let name_node = Program.get_node env.prog name_id in let ctor_opt = Check_helper.find_typedef_of env.prog name_node.value in let ctor = Option.value_exn ~message:(Format.sprintf "find enum ctor failed: %s %d" name name_id) ctor_opt in let enum_ctor = Core_type.TypeDef.( match ctor.spec with | EnumCtor v -> v | _ -> failwith "unrechable" ) in let if_test = Ir.Expr.TagEqual(match_expr, enum_ctor.enum_ctor_tag_id) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) else ( (* binding local var *) let sym = find_variable env name in let assign_stmt = Ir.Stmt.Expr( Assign( Ident sym, match_expr ) ) in (fun genereator -> let acc = genereator ~finalizers:[] () in assign_stmt::acc ) ) ) | EnumCtor ((_name, name_id), child) -> ( let name_node = Program.get_node env.prog name_id in let ctor_opt = Check_helper.find_typedef_of env.prog name_node.value in let ctor = Option.value_exn ctor_opt in let enum_ctor = Core_type.TypeDef.( match ctor.spec with | EnumCtor v -> v | _ -> failwith "n" ) in let if_test = Ir.Expr.TagEqual(match_expr, enum_ctor.enum_ctor_tag_id) in let match_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let open Ir in let assign_stmt = Stmt.Expr( Expr.Assign( Expr.Temp match_tmp, Expr.UnionGet(match_expr, 0) ) ) in let release_stmt = Stmt.Release(Ir.Expr.Temp match_tmp) in let open PMMeta in let this_pm: t = fun generator -> let acc = generator ~finalizers:[release_stmt] () in let if_consequent= if is_last_goto acc then List.concat [ [assign_stmt]; acc; ] else List.concat [ [assign_stmt]; acc; [release_stmt]; ] in let if_stmt = Ir.Stmt.If { if_test; if_consequent; if_alternate = None; } in [if_stmt] in let child_pm = transform_pattern_to_test (Temp match_tmp) child in this_pm >>= child_pm ) | Tuple children -> ( let open Ir in let assign_stmts, release_stmts, child_pms = children |> List.mapi ~f:(fun index elm -> let match_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_stmt = Stmt.Expr( Assign( Temp match_tmp, TupleGetValue(match_expr, index) ) ) in let release_stmt = Stmt.Release(Expr.Temp match_tmp) in let child_pm = transform_pattern_to_test (Temp match_tmp) elm in assign_stmt, release_stmt, child_pm ) |> List.unzip3 in let open PMMeta in let this_pm: t = fun generator -> let acc = generator ~finalizers:release_stmts () in if is_last_goto acc then List.concat [ assign_stmts; acc; ] else List.concat [ assign_stmts; acc; release_stmts; ] in List.fold ~init:this_pm ~f:(fun acc elm -> acc >>= elm) child_pms ) | Array { elements; rest; } -> ( let elm_len = List.length elements in let open Ir in let need_test = Expr.IntValue ( match rest with | Some _ -> Expr.I32Binary( BinaryOp.GreaterThanEqual, Expr.Call(SymLocal "lc_std_array_get_length", Some match_expr, []), Expr.NewI32 (Int.to_string elm_len)) | None -> Expr.I32Binary( BinaryOp.Equal, Expr.Call(SymLocal "lc_std_array_get_length", Some match_expr, []), Expr.NewI32 (Int.to_string elm_len)) ) in let assign_stmts, release_stmts, child_pms = elements |> List.mapi ~f:(fun index elm -> let match_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_stmt = Ir.Stmt.Expr( Assign( Temp match_tmp, ArrayGetValue(match_expr, Expr.IntValue(Expr.NewI32 (Int.to_string index))) ) ) in let release_stmt = Ir.Stmt.Release(Expr.Temp match_tmp) in let child_pm = transform_pattern_to_test (Temp match_tmp) elm in assign_stmt, release_stmt, child_pm ) |> List.unzip3 in let rest_assigns, rest_releases, rest_pms = match rest with | Some { spec = Underscore; _ } -> [], [], [] | Some rest_pat -> ( let match_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_stmt = Ir.Stmt.Expr( Assign( Temp match_tmp, Call( SymLocal "lc_std_array_slice", Some match_expr, [ Expr.NewI32 (Int.to_string elm_len); Expr.Call(SymLocal "lc_std_array_get_length", Some match_expr, []) ] ) ) ) in let release_stmt = Ir.Stmt.Release(Expr.Temp match_tmp) in let rest_pm = transform_pattern_to_test (Temp match_tmp) rest_pat in [assign_stmt], [release_stmt], [rest_pm] ) | None -> [], [], [] in let open PMMeta in let this_pm: t = fun generator -> let acc = generator ~finalizers:(List.append rest_releases release_stmts) () in let if_consequent = if is_last_goto acc then List.concat [ assign_stmts; rest_assigns; acc; ] else List.concat [ assign_stmts; rest_assigns; acc; rest_releases; release_stmts; ] in let if_stmt = Ir.Stmt.If { if_test = need_test; if_consequent; if_alternate = None; } in [if_stmt] in List.fold ~init:this_pm ~f:(fun acc elm -> acc >>= elm) (List.append child_pms rest_pms) ) in let transform_clause clause = let scope = create_scope_and_distribute_vars env clause.clause_scope in with_scope env scope (fun env -> let saved_tmp_count = env.tmp_vars_count in let body = transform_expression ~is_move:true env clause.clause_consequent in let done_stmt = Ir.Stmt.Goto label_name in let consequent ~finalizers () : Ir.Stmt.t list = List.concat [ body.prepend_stmts; [Ir.Stmt.Expr ( Assign( (Ident (Ir.SymTemp result_tmp)), body.expr ) )]; body.append_stmts; finalizers; [done_stmt]; ] in let pm_meta = transform_pattern_to_test match_expr clause.clause_pat in let pm_stmts = pm_meta consequent in prepend_stmts := List.append !prepend_stmts pm_stmts; tmp_counter := env.tmp_vars_count::(!tmp_counter); env.tmp_vars_count <- saved_tmp_count; ) in List.iter ~f:transform_clause match_clauses; let end_label = Ir.Stmt.WithLabel(label_name, !prepend_stmts) in out_prepend_stmts := List.append !out_prepend_stmts [end_label]; use the max tmp vars env.tmp_vars_count <- List.fold ~init:0 ~f:(fun acc item -> if item > acc then item else acc) !tmp_counter; Ir.Expr.Temp result_tmp and transform_spreading_init env tmp_id spread_ty_var spread_expr = let expr_node_type = Program.deref_node_type env.prog spread_ty_var in let ctor_opt = Check_helper.find_construct_of env.prog expr_node_type in let ctor, _ = Option.value_exn ~message:(Format.asprintf "Can not find ctor of spreading init: %d %a" spread_ty_var Core_type.TypeExpr.pp expr_node_type) ctor_opt in let cls_id = ctor.id in let cls_meta = Hashtbl.find_exn env.cls_meta_map cls_id in cls_meta.cls_fields |> List.map ~f:(fun (field_name, _) -> let open Ir in let left_value = ( Expr.GetField( (Temp tmp_id), cls_meta.cls_gen_name, field_name ) ) in let get_field = Expr.GetField(spread_expr, cls_meta.cls_gen_name, field_name) in [ Stmt.Retain get_field; Stmt.Expr( Assign( left_value, get_field ) ); ] ) |> List.concat and transform_binary_expr env ~is_move ~append_stmts ~prepend_stmts expr op left right = let open Expression in let { ty_var; _ } = expr in let gen_c_op left right = let left' = transform_expression ~is_borrow:true env left in let right' = transform_expression ~is_borrow:true env right in prepend_stmts := List.concat [!prepend_stmts; left'.prepend_stmts; right'.prepend_stmts]; append_stmts := List.concat [!append_stmts; left'.append_stmts; right'.append_stmts]; let left_type = Program.deref_node_type env.prog left.ty_var in let open Core_type in match (left_type, op) with | (TypeExpr.String, BinaryOp.Plus) -> let spec = auto_release_expr ~is_move env ~append_stmts ty_var (Ir.Expr. Call(SymLocal "lc_std_string_concat", None, [left'.expr; right'.expr])) in spec | (TypeExpr.String, BinaryOp.Equal) | (TypeExpr.String, BinaryOp.NotEqual) | (TypeExpr.String, BinaryOp.LessThan) | (TypeExpr.String, BinaryOp.LessThanEqual) | (TypeExpr.String, BinaryOp.GreaterThan) | (TypeExpr.String, BinaryOp.GreaterThanEqual) -> let spec = auto_release_expr ~is_move env ~append_stmts ty_var (Ir.Expr.StringCmp(op, left'.expr, right'.expr)) in spec | _ -> ( (* let node_type = Program.deref_node_type env.prog ty_var in *) if Check_helper.is_i64 env.prog left_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let tmp = Ir.Expr.I64Binary(op, left'.expr, right'.expr) in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.I64Binary(op, left'.expr, right'.expr) ) else if Check_helper.is_f64 env.prog left_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let tmp = Ir.Expr.F64Binary(op, left'.expr, right'.expr) in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.F64Binary(op, left'.expr, right'.expr) ) else if Check_helper.is_f32 env.prog left_type then Ir.Expr.F32Binary(op, left'.expr, right'.expr) else Ir.Expr.I32Binary(op, left'.expr, right'.expr) ) in let is_constant expression = match expression.spec with | Constant _ -> true | _ -> false in if is_constant left && is_constant right then if left and right are constants , try folding . if expr does not transformed by folding then generate c op directly by current left and right else try recursive transform new_expr if expr does not transformed by folding then generate c op directly by current left and right else try recursive transform new_expr *) let new_expr = try_folding_literals op left right expr in match new_expr with | Some(folded_expr) -> ( let result = transform_expression ~is_borrow:true env folded_expr in result.expr ) | None -> gen_c_op left right else ( let left_res = try_folding_binary_expression left in let right_res = try_folding_binary_expression right in match (left_res, right_res) with | (None, None) -> if both left and right ca n't be fold , gen c op here gen_c_op left right | _ -> ( (* if `left` or `right` or both of them being transformed, we should do literal folding with updated expr too. *) let left_expr = match left_res with | Some(left') -> left' | None -> left in let right_expr = match right_res with | Some(right') -> right' | None -> right in let temp_expr = { expr with spec = Binary(op, left_expr, right_expr) } in let maybe_folded_expr = try_folding_literals op left_expr right_expr temp_expr in let expr = match maybe_folded_expr with | None -> temp_expr | Some(folded_expr) -> folded_expr in let result = transform_expression ~is_move env expr in append_stmts := List.append !append_stmts result.append_stmts; result.expr ) ) and transform_expression_if env ?ret ~prepend_stmts ~append_stmts loc if_desc = let open Typedtree.Expression in let test = transform_expression env if_desc.if_test in let if_test = Ir.Expr.IntValue test.expr in let consequent = transform_block ?ret env if_desc.if_consequent in let if_alternate = Option.map ~f:(fun alt -> match alt with | If_alt_if if_spec -> Ir.Stmt.If_alt_if (transform_expression_if env ?ret ~prepend_stmts ~append_stmts loc if_spec) | If_alt_block blk -> let consequent = transform_block ?ret env blk in Ir.Stmt.If_alt_block consequent ) if_desc.if_alternative in let spec = { Ir.Stmt. if_test; if_consequent = consequent; if_alternate; } in prepend_stmts := List.concat [!prepend_stmts; test.prepend_stmts]; append_stmts := List.append test.append_stmts !append_stmts; spec and transform_block env ?ret ?map_scope (block: Typedtree.Block.t): Ir.Stmt.t list = let block_scope = create_scope_and_distribute_vars env block.scope in let block_scope = match map_scope with | Some map -> map block_scope | None -> block_scope in with_scope env block_scope (fun env -> let stmts = List.map ~f:(transform_statement ?ret env) block.body |> List.concat in let cleanup = generate_finalize_stmts env.scope in List.append stmts cleanup ) (* * for normal blocks, * only the vars in the current blocks should be released *) and generate_finalize_stmts scope = let open TScope in !(scope.local_vars_to_release) |> List.rev |> List.filter_map ~f:(fun sym -> Some (Ir.Stmt.Release(Ident sym)) ) (* * for return statements, * all the variables in the function should be released *) and generate_finalize_stmts_function scope = TScope.get_symbols_to_release_til_function [] scope |> List.rev |> List.filter_map ~f:(fun sym -> Some (Ir.Stmt.Release (Ident sym)) ) and generate_finalize_stmts_while scope = TScope.get_symbols_to_release_til_while [] scope |> List.rev |> List.filter_map ~f:(fun sym -> Some (Ir.Stmt.Release (Ident sym)) ) and generate_cls_meta env cls_id gen_name = let node = Program.get_node env.prog cls_id in let ctor_opt = Check_helper.find_typedef_of env.prog node.value in let ctor = Option.value_exn ctor_opt in let rec generate_properties_including_ancester child (cls_def: Core_type.TypeDef.t) = let cls_def = match cls_def with | { spec = Class cls; _ } -> cls | _ -> failwith "unexpected: not a class" in let properties = List.filter_map ~f:(fun (elm_name, elm) -> match elm with | Cls_elm_prop (_, ty_var, _) -> Some (elm_name, ty_var) | _ -> None ) cls_def.tcls_elements; in let result = List.append properties child in match cls_def.tcls_extends with | Some ancester -> ( let ctor_opt = Check_helper.find_construct_of env.prog ancester in let ctor, _ = Option.value_exn ctor_opt in generate_properties_including_ancester result ctor ) | _ -> result in let prop_names = generate_properties_including_ancester [] ctor in let result = create_cls_meta cls_id gen_name prop_names in List.iter ~f:(fun (field_name, _) -> Hashtbl.set result.cls_fields_map ~key:field_name ~data:field_name) result.cls_fields; result and transform_class_method env _method : (Ir.Decl.t list * Ir.Decl.class_method_tuple option) = let open Declaration in let { cls_method_name; cls_method_params; cls_method_body; cls_method_scope; _ } = _method in env.tmp_vars_count <- 0; let origin_method_name, method_id = cls_method_name in let new_name = match Hashtbl.find_exn env.global_name_map method_id with | Ir.SymLocal name -> name | _ -> failwith "unrechable" in let open Core_type in let node = Program.get_node env.prog method_id in let node_type = Program.deref_type env.prog node.value in let is_virtual = match node_type with | TypeExpr.TypeDef { spec = TypeDef.ClassMethod { method_is_virtual = true; _ }; _ } -> true | _ -> false in let tuple = if is_virtual then Some { Ir.Decl. class_method_name = origin_method_name; class_method_gen_name = new_name; } else None in let _fun = { Ir.Decl. spec = (transform_function_impl env ~name:(new_name, node.loc) ~params:cls_method_params ~scope:(Option.value_exn cls_method_scope) ~body:cls_method_body ~comments:[]); loc = _method.cls_method_loc; } in let lambdas = env.lambdas in env.lambdas <- []; (* will be reversed in the future *) (_fun::lambdas), tuple and distribute_name_to_class_method env cls_original_name _method = let open Declaration in let { cls_method_name; _ } = _method in let origin_method_name, method_id = cls_method_name in let new_name = cls_original_name ^ "_" ^ origin_method_name in let new_name = distribute_name env new_name in let pre_declare = { Ir.Decl. spec = FuncDecl (SymLocal new_name); loc = Loc.none; } in env.prepends_decls <- pre_declare::(env.prepends_decls); Hashtbl.set env.global_name_map ~key:method_id ~data:(SymLocal new_name) and transform_class env cls loc: Ir.Decl.t list = let open Declaration in let { cls_id; cls_body; _ } = cls in let original_name, cls_name_id = cls_id in let fun_name = distribute_name env original_name in let finalizer_name = fun_name ^ "_finalizer" in let gc_marker_name = fun_name ^ "_marker" in env.current_fun_meta <- Some (create_current_fun_meta original_name); Hashtbl.set env.global_name_map ~key:cls_name_id ~data:(SymLocal fun_name); let _, cls_id' = cls_id in let cls_meta = generate_cls_meta env cls_id' fun_name in Hashtbl.set env.cls_meta_map ~key:cls_meta.cls_id ~data:cls_meta; (* * Prescan: * * Distributes names to all methods, * because the body of all methods will call the method of class itself * *) List.iter ~f:(fun elm-> match elm with | Cls_method _method -> distribute_name_to_class_method env original_name _method | _ -> () ) cls_body.cls_body_elements; let class_methods = ref [] in let class_static_fields = ref [] in let methods: Ir.Decl.t list = List.fold ~init:[] ~f:(fun acc elm -> match elm with | Cls_method _method -> ( let stmts, tuple_opt = transform_class_method env _method in (match tuple_opt with | Some tuple -> class_methods := tuple::!class_methods | None -> () ); (* will be reversed in the future *) List.append stmts acc ) | Cls_static_property prop -> ( let name, _ = prop.cls_static_prop_name in let init_expr = transform_expression ~is_move:true env prop.cls_static_prop_init in class_static_fields := (name, init_expr.expr)::(!class_static_fields); acc ) | Cls_property _ | Cls_declare _ -> acc ) cls_body.cls_body_elements; in let _, cls_id' = cls_id in let cls_type = Program.deref_node_type env.prog cls_id' in let cls_typedef = Check_helper.find_typedef_of env.prog cls_type in let unwrap_class = match cls_typedef with | Some { Core_type.TypeDef. spec = Class cls; _ } -> cls | _ -> failwith "unrechable" in let class_ancester = Option.( unwrap_class.tcls_extends >>= fun ancester -> let typedef, _ = Option.value_exn (Check_helper.find_construct_of env.prog ancester) in let ancester_id = typedef.id in let prog = env.prog in let open Program in match prog.root_class with | Some root_class' -> ( (* the ancester is Object *) if root_class'.root_class_id = ancester_id then None else ( let name = Hashtbl.find_exn env.global_name_map ancester_id in Some name ) ) | None -> ( let name = Hashtbl.find_exn env.global_name_map ancester_id in Some name ) ) in let class_init = { Ir.Decl. class_ancester; class_name = fun_name; class_id_name = fun_name ^ "_class_id"; class_def_name = fun_name ^ "_def"; class_methods = List.rev !class_methods; class_static_fields = List.rev !class_static_fields; } in env.class_inits <- (Ir.Decl.InitClass class_init)::env.class_inits; let finalizer = generate_finalizer env finalizer_name (Option.value_exn cls_typedef) in let gc_marker = generate_gc_marker env gc_marker_name (Option.value_exn cls_typedef) in let cls = { Ir.Decl. name = fun_name; original_name; finalizer; gc_marker; properties = cls_meta.cls_fields; init = class_init; } in List.append [ { Ir.Decl. spec = Ir.Decl.Class cls; loc; } ] (List.rev methods) * Generate finalizer statements for a class : * If a class has ancesters , generate the ancesters 's statements first . * Generate finalizer statements for a class: * If a class has ancesters, generate the ancesters's statements first. *) and generate_finalizer env name (type_def: Core_type.TypeDef.t) : Ir.Decl.class_finalizer option = let generate_release_statements_by_cls_meta type_def = let open Core_type.TypeDef in let open Ir in let cls_meta = Hashtbl.find_exn env.cls_meta_map type_def.id in List.filter_map ~f:(fun (field_name, ty_var) -> let field_type = Program.deref_node_type env.prog ty_var in if type_should_not_release env field_type then None else Some ( Stmt.Release (Expr.RawGetField("ptr", field_name)) ) ) cls_meta.cls_fields in let finalizer_content = generate_release_statements_by_cls_meta type_def in if List.is_empty finalizer_content then None else Some { finalizer_name = name; finalizer_content; } and generate_gc_marker env name (type_def: Core_type.TypeDef.t) : Ir.Decl.gc_marker option = let generate_marker_fields type_def = let open Core_type.TypeDef in let cls_meta = Hashtbl.find_exn env.cls_meta_map type_def.id in List.filter_map ~f:(fun (field_name, ty_var) -> let field_type = Program.deref_node_type env.prog ty_var in if type_is_not_gc env field_type then None else Some field_name ) cls_meta.cls_fields in let fields = generate_marker_fields type_def in if List.is_empty fields then None else Some { gc_marker_name = name; gc_marker_field_names = fields; } and transform_enum env ~attributes enum loc : Ir.Decl.t list = let open Enum in let { elements; name = (enum_original_name, _); _ } = enum in env.current_fun_meta <- Some (create_current_fun_meta enum_original_name); let meta_id' = List.find_map ~f:(fun attr -> let open Lichenscript_parsing.Ast in if String.equal attr.attr_name.txt "meta_id" then ( match attr.attr_payload with | name::_ -> Some name | _ -> None ) else None ) attributes in let enum_name = "LCC_" ^ enum_original_name in let meta_id = match meta_id' with | Some v -> v | None -> enum_name ^ "_id" in let enum_members = ref [] in let result = elements |> List.mapi ~f:(fun index elm -> match elm with | Typedtree.Enum.Case case -> ( let case_name, case_name_id = case.case_name in let new_name = distribute_name env case_name in Hashtbl.set env.global_name_map ~key:case_name_id ~data:(SymLocal new_name); let enum_ctor_params_size = List.length case.case_fields in let spec = Ir.Decl.EnumCtor { enum_ctor_name = new_name; enum_ctor_meta_id = meta_id; enum_ctor_meta_name = enum_name; enum_ctor_tag_id = index; enum_ctor_params_size; } in enum_members := (case_name, enum_ctor_params_size)::(!enum_members); [{ Ir.Decl. spec; loc }] ) | Typedtree.Enum.Method _method -> distribute_name_to_class_method env enum_original_name _method; let stmts, _ = transform_class_method env _method in stmts ) |> List.concat in let enum_def = { Ir.Decl. enum_has_meta_id = Option.is_some meta_id'; enum_name; enum_original_name; enum_members = List.rev !enum_members; } in if Option.is_none meta_id' then ( env.class_inits <- (Ir.Decl.InitEnum enum_def)::env.class_inits ); env.current_fun_meta <- None; List.append [{ Ir.Decl. spec = Enum enum_def; loc = Loc.none; }] result and transform_lambda env ~lambda_name content _ty_var = let prev_fun_meta = env.current_fun_meta in env.current_fun_meta <- Some (create_current_fun_meta lambda_name); let lambda_gen_name = "LCC_" ^ lambda_name in let fake_block = { Block. body = [ { Statement. spec = Expr content.lambda_body; loc = Loc.none; attributes = []; } ]; scope = content.lambda_scope; loc = Loc.none; return_ty = content.lambda_body.ty_var; } in let _fun = transform_function_impl env ~name:(lambda_gen_name, Loc.none) ~params:content.lambda_params ~scope:content.lambda_scope ~body:fake_block ~comments:[] in let result = { Ir.Decl. spec = _fun; loc = Loc.none; } in env.current_fun_meta <- prev_fun_meta; result; type result = { main_function_name: string option; declarations: Ir.Decl.t list; global_class_init: string option; } let transform_declarations ~config ctx declarations = let env = create ~config ctx in let declarations = List.map ~f:(transform_declaration env) declarations |> List.concat in let declarations, global_class_init = if List.is_empty env.class_inits then declarations, None else ( let name = "LC_class_init" in (List.append declarations [{ Ir.Decl. spec = GlobalClassInit(name, List.rev env.class_inits); loc = Loc.none; }]), Some name ) in let prepends_decls = List.rev env.prepends_decls in env.prepends_decls <- []; { main_function_name = env.main_function_name; declarations = List.append prepends_decls declarations; global_class_init; }
null
https://raw.githubusercontent.com/lichenscript/lichenscript/d159486f178972d01ac6ed5cf060e972267f097b/lib/ir/transform.ml
ocaml
* Convert TypedTree to C-op * It's a monad, represent the `continuation` of pattern test * if (test) { * (* continuation here * logical name -> realname * * only this class, does NOT includes ancester's automatic reference counting * Some variables are local, but some are global, * such as a method of a class, the contructor of enum, etc for lambda generation filter all the params, get the "pure" local vars let before_stmts = env.tmp_vars_count in optimize: don't need release if primitive if left being folded, try rec folding left' with right if right being folded, try rec folding left with right' pass the capturing values into the deeper scope let current_scope = env.scope in external method it's a local function it's a contructor only class method needs a this_expr, this is useless for a static function external method it's a static function could be a property of a getter it's a property save the previous value transform_expression env left_expr TODO: maybe it's a setter? logical name -> real name binding local var let node_type = Program.deref_node_type env.prog ty_var in if `left` or `right` or both of them being transformed, we should do literal folding with updated expr too. * for normal blocks, * only the vars in the current blocks should be released * for return statements, * all the variables in the function should be released will be reversed in the future * Prescan: * * Distributes names to all methods, * because the body of all methods will call the method of class itself * will be reversed in the future the ancester is Object
* Copyright 2022 * * Licensed under the Apache License , Version 2.0 ( the " License " ) ; * you may not use this file except in compliance with the License . * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing , software * distributed under the License is distributed on an " AS IS " BASIS , * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . * See the License for the specific language governing permissions and * limitations under the License . * Copyright 2022 Vincent Chan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * -2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) open Core_kernel open Lichenscript_parsing.Asttypes open Lichenscript_parsing.Ast open Lichenscript_typing open Lichenscript_typing.Scope open Lichenscript_typing.Typedtree module TScope = struct Why name_map ? * 1 . The same variable(type_id ) has different meaning in different scope , * In a lambda expression , a captured value represents a value to this , * but int outer scope , it 's a local variable . * 1. The same variable(type_id) has different meaning in different scope, * In a lambda expression, a captured value represents a value to this, * but int outer scope, it's a local variable. *) type t = { name_map: (string, Ir.symbol) Hashtbl.t; local_vars_to_release: Ir.symbol list ref; raw: scope option; prev: t option; } let create scope = let name_map = Hashtbl.create (module String) in { name_map; local_vars_to_release = ref []; raw = scope; prev = None; } let rec find_variable scope name = let find_in_prev () = match scope.prev with | Some prev_scope -> find_variable prev_scope name | None -> failwith (Format.sprintf "can not find variable %s" name) in match Hashtbl.find scope.name_map name with | Some v -> v | None -> find_in_prev () let distribute_name current_scope name = let fun_name = "LCC_" ^ name in Hashtbl.set current_scope.name_map ~key:name ~data:(SymLocal fun_name); fun_name let set_name scope = Hashtbl.set scope.name_map let add_vars_to_release scope (name: Ir.symbol) = scope.local_vars_to_release := name::!(scope.local_vars_to_release) let[@warning "-unused-value-declaration"] remove_release_var scope name = scope.local_vars_to_release := List.filter ~f:(fun sym -> match (sym, name) with | (Ir.SymLocal local_name, Ir.SymLocal name) -> not (String.equal local_name name) | _ -> true ) !(scope.local_vars_to_release) let rec get_symbols_to_release_til_function acc scope = let acc = List.append acc !(scope.local_vars_to_release) in let raw = Option.value_exn scope.raw in match raw#scope_type with | Scope.ST_Lambda | Scope.ST_Function -> acc | _ -> ( let prev_scope = Option.value_exn scope.prev in get_symbols_to_release_til_function acc prev_scope ) let rec get_symbols_to_release_til_while acc scope = let acc = List.append acc !(scope.local_vars_to_release) in let raw = Option.value_exn scope.raw in match raw#scope_type with | Scope.ST_While -> acc | _ -> ( let prev_scope = Option.value_exn scope.prev in get_symbols_to_release_til_while acc prev_scope ) let rec is_in_class scope = match scope.raw with | Some raw -> ( if Option.is_some raw#test_in_class then true else ( match scope.prev with | Some prev -> is_in_class prev | None -> false ) ) | None -> false let rec is_in_lambda scope = match scope.raw with | Some raw -> ( match raw#scope_type with | Scope.ST_Lambda -> true | _ -> ( match scope.prev with | Some prev -> is_in_lambda prev | None -> false ) ) | None -> false end * } *) module PMMeta = struct type generateor = (finalizers:Ir.Stmt.t list -> unit -> Ir.Stmt.t list) type t = (generateor -> Ir.Stmt.t list) let (>>=) (left: t) (right: t) = (fun generateor -> left (fun ~finalizers:left_finalizers () -> right (fun ~finalizers:right_finalizers () -> let merged_finalizers = List.append left_finalizers right_finalizers in generateor ~finalizers:merged_finalizers () ) ) ) end type cls_meta = { cls_id: int; cls_gen_name: string; cls_fields_map: (string, string) Hashtbl.t; all generating fields , including 's cls_fields: (string * int) list; } let create_cls_meta cls_id cls_gen_name cls_fields : cls_meta = { cls_id; cls_gen_name; cls_fields_map = Hashtbl.create (module String); cls_fields; } type current_fun_meta = { fun_name: string; used_name: string Hash_set.t; mutable def_local_names: string list; } let preserved_name = [ "ret"; "rt"; "this"; "argc"; "argv"; "t"; "null"; "function"; "undefined"; "window" ] let create_current_fun_meta fun_name = { fun_name; used_name = Hash_set.of_list (module String) preserved_name; def_local_names = []; } type config = { arc: bool; prepend_lambda: bool; ptr_size: Ir.ptr_size option; } type t = { prog: Program.t; config: config; mutable scope: TScope.t; mutable tmp_vars_count: int; mutable main_function_name: string option; mutable class_inits: Ir.Decl.init list; mutable prepends_decls: Ir.Decl.t list; global_name_map: (int, Ir.symbol) Hashtbl.t; cls_meta_map: (int, cls_meta) Hashtbl.t; mutable current_fun_meta: current_fun_meta option; mutable lambdas: Ir.Decl.t list; } let type_should_not_release (env: t) = Transform_helper.type_should_not_release ~ptr_size:(env.config.ptr_size) env.prog let type_is_not_gc env = Transform_helper.type_is_not_gc env.prog let[@warning "-unused-value-declaration"] is_identifier expr = let open Typedtree.Expression in match expr.spec with | Typedtree.Expression.Identifier _ -> true | _ -> false let[@warning "-unused-value-declaration"] is_this expr = let open Typedtree.Expression in match expr.spec with | Typedtree.Expression.This -> true | _ -> false let push_scope env (scope: TScope.t) = let scope = { scope with prev = Some env.scope; } in env.scope <- scope let pop_scope env = env.scope <- Option.value_exn env.scope.prev let with_scope env scope cb = push_scope env scope; let result = cb env in pop_scope env; result let find_variable env = TScope.find_variable env.scope let should_var_captured variable = if !(variable.var_captured) then ( match variable.var_kind with | Pvar_let -> true | _ -> false ) else false type expr_result = { prepend_stmts: Ir.Stmt.t list; expr: Ir.Expr.t; append_stmts: Ir.Stmt.t list; } let find_static_field_id_of_class (cls: Core_type.TypeDef.class_type) name = let static_props = List.filter_map ~f:(fun (name, elm) -> match elm with | Cls_elm_prop (_, prop_ty_int, _) -> Some (name, prop_ty_int) | _ -> None ) cls.tcls_static_elements in let field_id = List.find_mapi_exn ~f:(fun idx (field_name, _) -> if String.equal field_name name then Some idx else None ) static_props in field_id let create ~config prog = let scope = TScope.create None in let global_name_map = Hashtbl.create (module Int) in let cls_meta_map = Hashtbl.create (module Int) in { config; prog; scope; tmp_vars_count = 0; main_function_name = None; class_inits = []; prepends_decls = []; global_name_map; cls_meta_map; current_fun_meta = None; lambdas = []; } let get_local_var_name fun_meta realname ty_int = let name = if Hash_set.mem fun_meta.used_name realname then realname ^ "_" ^ (Int.to_string ty_int) else realname in Hash_set.add fun_meta.used_name name; name let rec transform_declaration env decl = let open Declaration in let { spec; loc; attributes } = decl in match spec with | Class cls -> ( transform_class env cls loc ) | Function_ _fun -> ( let specs = transform_function env _fun in let lambdas = env.lambdas in env.lambdas <- []; let bodys = List.map ~f:(fun spec -> { Ir.Decl. spec; loc }) specs in List.append lambdas bodys ) | Enum enum -> transform_enum env ~attributes enum loc | Interface _ -> [] | Declare declare -> ( let external_attribute = List.find_map ~f:(fun attr -> if String.equal attr.attr_name.txt "external" then Some attr.attr_payload else None ) attributes in match external_attribute with | Some (external_name::_) -> ( match declare.decl_spec with | DeclFunction fun_header -> ( let _, declare_id = fun_header.name in Hashtbl.set env.global_name_map ~key:declare_id ~data:(Ir.SymLocal external_name); [] ) ) | _ -> ( match declare.decl_spec with | DeclFunction fun_header -> ( let phys_name, _ = fun_header.name in let name = find_or_distribute_name env declare.decl_ty_var phys_name in let decl = { Ir.Decl. spec = FuncDecl name; loc = Loc.none; } in [decl] ) ) ) | Import _ -> [] and distribute_name env = TScope.distribute_name env.scope and find_or_distribute_name env id name = match Hashtbl.find env.global_name_map id with | Some name -> name | None -> ( let new_name = Ir.SymLocal (distribute_name env name) in Hashtbl.set env.global_name_map ~key:id ~data:new_name; new_name ) * 1 . Scan the function firstly , find out all the lambda expression * and captured variables * 2 . Transform body * 1. Scan the function firstly, find out all the lambda expression * and captured variables * 2. Transform body *) and transform_function env _fun = let open Function in let { body; comments; header; scope; _ } = _fun in let original_name, original_name_id = header.name in env.current_fun_meta <- Some (create_current_fun_meta original_name); let node = Program.get_node env.prog original_name_id in let fun_name = match find_or_distribute_name env original_name_id original_name with | Ir.SymLocal l -> l | _ -> failwith "unreachable" in if String.equal original_name "main" then ( env.main_function_name <- Some fun_name ); let result = transform_function_impl env ~name:(fun_name, node.loc) ~params:header.params ~scope ~body ~comments in env.current_fun_meta <- None; [ result ] and distribute_name_to_scope scope fun_meta local_vars : unit = let local_names = local_vars |> List.map ~f:(fun (var_name, variable) -> let gen_name = get_local_var_name fun_meta var_name variable.var_id in TScope.set_name scope ~key:var_name ~data:(SymLocal gen_name); gen_name ) in fun_meta.def_local_names <- List.append fun_meta.def_local_names local_names and transform_function_impl env ~name ~params ~body ~scope ~comments = let open Function in let fun_meta = Option.value_exn env.current_fun_meta in let fun_scope = TScope.create (Some scope) in push_scope env fun_scope; let params_set = Hash_set.create (module String) in List.iteri ~f:(fun index { param_name; _ } -> let param_name, _ = param_name in Hash_set.add params_set param_name; Hashtbl.set env.name_map ~key : param_ty ~data:(get_local_var_name param_name param_ty ) TScope.set_name fun_scope ~key:param_name ~data:(SymParam index) ) params.params_content; let capturing_variables = scope#capturing_variables in Scope.CapturingVarMap.iteri ~f:(fun ~key:name ~data:idx -> TScope.set_name fun_scope ~key:name ~data:(SymLambda(idx, name)); Hash_set.add params_set name; ) capturing_variables; let local_vars = scope#vars |> List.filter ~f:(fun (name, _) -> not (Hash_set.mem params_set name)) in distribute_name_to_scope fun_scope fun_meta local_vars; let max_tmp_value = ref 0 in let stmts = List.map ~f:(fun stmt -> env.tmp_vars_count <- 0; let result = transform_statement env stmt in if env.tmp_vars_count > !max_tmp_value then ( max_tmp_value := env.tmp_vars_count ); result ) body.body |> List.concat in let generate_name_def () = let names = fun_meta.def_local_names in let open Ir.Stmt in [ VarDecl names; ] in let ending_parts = match List.last body.body with | Some { Typedtree.Statement. spec = Return _; _ } -> [] | Some { Typedtree.Statement. spec = Expr _; _ } -> let cleanup = generate_finalize_stmts fun_scope in let return_stmt = Ir.Stmt.Return (Some (Ir.Expr.Ident (Ir.SymLocal "ret"))) in List.append cleanup [return_stmt] | _ -> ( let cleanup = generate_finalize_stmts fun_scope in let return_stmt = Ir.Stmt.Return (Some Ir.Expr.Null) in List.append cleanup [return_stmt] ) in let def = if (List.length fun_meta.def_local_names) > 0 then ( generate_name_def () ) else [] in let new_body = { Ir.Block. body = List.concat [ def; stmts; ending_parts ]; loc = body.loc; } in let t_fun = { Ir.Func. name; body = new_body; tmp_vars_count = !max_tmp_value; comments; } in pop_scope env; env.tmp_vars_count <- !max_tmp_value; Ir.Decl.Func t_fun; and create_scope_and_distribute_vars env raw_scope = let scope = TScope.create (Some raw_scope) in let local_vars = raw_scope#vars in distribute_name_to_scope scope (Option.value_exn env.current_fun_meta) local_vars; scope and transform_statement ?ret env stmt = let open Statement in let { spec; _ } = stmt in let transform_return_expr ?ret expr = let tmp = transform_expression ~is_move:true env expr in let ret = Option.value ~default:(Ir.SymRet) ret in let assign = Ir.Expr.Assign(Ident ret, tmp.expr) in * It 's returning the function directly , it 's not need to retain , * because it 's directly assining to " ret " variable . * * But it should retain if it 's a normal block . * It's returning the function directly, it's not need to retain, * because it's directly assining to "ret" variable. * * But it should retain if it's a normal block. *) let expr = Ir.Stmt.Expr assign in List.concat [ tmp.prepend_stmts; [ expr ]; tmp.append_stmts ] in match spec with | Expr expr -> transform_return_expr ?ret expr | Semi expr -> ( let tmp = transform_expression env expr in let expr = Ir.Stmt.Expr tmp.expr in List.concat [ tmp.prepend_stmts; [ expr ]; tmp.append_stmts ] ) | While { while_test; while_block; _ } -> ( let while_test' = transform_expression env while_test in let bodys = transform_block ?ret env while_block in let body = { Ir.Block. body = List.append while_test'.append_stmts bodys; loc = while_block.loc; } in List.concat [ while_test'.prepend_stmts; [ Ir.Stmt.While(while_test'.expr, body); ]; while_test'.append_stmts; ] ) | ForIn for_in -> transform_for_in env ?ret for_in | Binding binding -> ( let original_name, name_id = match binding.binding_pat with | { spec = Pattern.Symbol sym; _ } -> sym | _ -> failwith "unrechable" in let scope = env.scope in let variable = Option.value_exn ~message:(Format.sprintf "%d:%d can not find %s" binding.binding_loc.start.line binding.binding_loc.start.column original_name) ((Option.value_exn scope.raw)#find_var_symbol original_name) in let name = TScope.find_variable scope original_name in let init_expr = transform_expression ~is_move:true env binding.binding_init in let node_type = Program.deref_node_type env.prog name_id in let need_release = env.config.arc && not (type_should_not_release env node_type) in * if a variable is captured , it will be upgraded into a RefCell . * type it is , it should be released . * if a variable is captured, it will be upgraded into a RefCell. * Whatevet type it is, it should be released. *) if need_release || !(variable.var_captured) then ( TScope.add_vars_to_release scope name ); let assign_expr = if should_var_captured variable then ( let init_expr = Ir.Expr.NewRef init_expr.expr in Ir.Expr.Assign((Ident name), init_expr) ) else Ir.Expr.Assign((Ident name), init_expr.expr); in List.concat [ init_expr.prepend_stmts; [ Ir.Stmt.Expr assign_expr; ]; init_expr.append_stmts; ] ) | Break _ -> let stmts = generate_finalize_stmts_while env.scope in List.append stmts [ Ir.Stmt.Break ] | Continue _ -> let stmts = generate_finalize_stmts_while env.scope in List.append stmts [ Ir.Stmt.Continue ] | Debugger -> [] | Return ret_opt -> ( let cleanup = generate_finalize_stmts_function env.scope in match ret_opt with | Some ret -> let ret = transform_return_expr ~ret:(Ir.SymRet) ret in let ret_stmt = Ir.Stmt.Return (Some (Ir.Expr.Ident Ir.SymRet)) in List.concat [ ret; cleanup; [ret_stmt]; ] | None -> let ret_stmt = Ir.Stmt.Return (Some Ir.Expr.Null) in List.append cleanup [ret_stmt] ) | Empty -> [] and transform_destructing_pattern env (pattern: Typedtree.Pattern.t) expr = let open Typedtree.Pattern in match pattern.spec with | Underscore -> [] | Symbol (sym_name, _) -> [ Ir.(Stmt.Expr( Expr.Assign( Expr.Ident (SymLocal sym_name), expr ) )) ] | EnumCtor _ | Literal _ -> failwith "unrechable" | Tuple tuple_list -> ( let stmts = tuple_list |> List.mapi ~f:(fun index item -> let tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign = Ir.(Stmt.Expr(Expr.Assign(Expr.Ident (SymTemp tmp), Expr.TupleGetValue(expr, index)))) in let child_stmts = transform_destructing_pattern env item (Ir.Expr.Ident (Ir.SymTemp tmp)) in List.concat [ [assign]; child_stmts; [Ir.Stmt.Release(Ir.Expr.Ident (Ir.SymTemp tmp))]; ] ) |> List.concat in stmts ) | Array _ -> failwith "unimplemented" and transform_for_in env ?ret for_in = let iterator_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let next_item_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let transformed_for_expr = transform_expression ~is_borrow:true env for_in.for_expr in let get_iterator_stmt = Ir.( Stmt.Expr( Expr.Assign( Expr.Ident (SymTemp iterator_id), Expr.Invoke(transformed_for_expr.expr, "getIterator", []) ) ) ) in let get_next_stmt = Ir.( Stmt.Expr( Expr.Assign( Expr.Ident(SymTemp next_item_id), Expr.Invoke(Expr.Ident(SymTemp iterator_id), "next", []) ) ) ) in let transformed_block = transform_block env ?ret ~map_scope:(fun scope -> TScope.add_vars_to_release scope (Ir.SymTemp next_item_id); scope ) for_in.for_block in let exit_if = Ir.( Stmt.If { if_test = Expr.TagEqual(Expr.Ident (SymTemp next_item_id), 1); if_consequent = [ Stmt.Release (Expr.Ident(SymTemp next_item_id)); Stmt.Break; ]; if_alternate = None; } ) in let expr_value_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let get_value_expr = Ir.(Expr.UnionGet(Expr.Ident (SymTemp next_item_id), 0)) in let assign_value = Ir.(Expr.Assign(Expr.Ident (SymTemp expr_value_tmp), get_value_expr)) in let destructing_assignments = transform_destructing_pattern env for_in.for_pat Ir.(Expr.Ident (SymTemp expr_value_tmp)) in let while_loop = Ir.Stmt.While (Ir.Expr.NewBoolean true, { Ir.Block. loc = for_in.for_loc; body = List.concat [ [ get_next_stmt; exit_if; Ir.Stmt.Expr assign_value; ]; destructing_assignments; transformed_block; [ ] ] }) in List.concat [ transformed_for_expr.prepend_stmts; [ get_iterator_stmt; while_loop; Ir.(Stmt.Release (Ident (SymTemp iterator_id))); ]; transformed_for_expr.append_stmts ] and gen_release_temp id = Ir.Stmt.Release (Ir.Expr.Temp id) and auto_release_expr env ?(is_move=false) ~append_stmts ty_var expr = let node_type = Program.deref_node_type env.prog ty_var in if (not env.config.arc) || is_move || type_should_not_release env node_type then ( expr ) else ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_expr = Ir.Expr.Assign( (Ident (Ir.SymTemp tmp_id)), expr) in append_stmts := (gen_release_temp tmp_id)::!append_stmts; assign_expr ) and prepend_expr env ~prepend_stmts ~append_stmts (expr: expr_result) = let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_expr = Ir.Expr.Assign( (Ident (Ir.SymTemp tmp_id)), expr.expr ) in let prepend_stmt = Ir.Stmt.Expr assign_expr in prepend_stmts := List.append !prepend_stmts [prepend_stmt]; let result = Ir.Expr.Temp tmp_id in append_stmts := (gen_release_temp tmp_id)::!append_stmts; result and try_folding_literals op left right original_expr = let open Expression in let do_integer_folding_i32 int_op left_int right_int = let new_int = let open Int32 in match int_op with | BinaryOp.Minus -> left_int - right_int | BinaryOp.Plus -> left_int + right_int | BinaryOp.Div -> left_int / right_int | BinaryOp.Mult -> left_int * right_int | _ -> failwith "unsupported binary op between integer" in Constant(Literal.I32(new_int)) in let do_integer_folding_i64 int_op left_int right_int = let new_int = let open Int64 in match int_op with | BinaryOp.Minus -> left_int - right_int | BinaryOp.Plus -> left_int + right_int | BinaryOp.Div -> left_int / right_int | BinaryOp.Mult -> left_int * right_int | _ -> failwith "unsupported binary op between integer" in Constant(Literal.I64(new_int)) in let do_f64_folding float_op left_str right_str = let new_float = let open Float in let left_f = Float.of_string left_str in let right_f = Float.of_string right_str in match float_op with | BinaryOp.Minus -> left_f - right_f | BinaryOp.Plus -> left_f + right_f | BinaryOp.Div -> left_f / right_f | BinaryOp.Mult -> left_f * right_f | _ -> failwith "unsupported binary op between float" in Constant(Literal.Float(Float.to_string new_float, false)) in match (left.spec, right.spec) with | (Constant(I32 left_int), Constant(I32 right_int)) -> ( match op with | BinaryOp.Plus | BinaryOp.Minus | BinaryOp.Div | BinaryOp.Mult -> ( let new_spec = do_integer_folding_i32 op left_int right_int in Some { left with spec = new_spec } ) | _ -> None ) | (Constant(I64 left_int), Constant(I64 right_int)) -> ( match op with | BinaryOp.Plus | BinaryOp.Minus | BinaryOp.Div | BinaryOp.Mult -> ( let new_spec = do_integer_folding_i64 op left_int right_int in Some { left with spec = new_spec } ) | _ -> None ) | (Constant(Float(left_f_str, false)), Constant(Float(right_f_str, false))) -> ( match op with | BinaryOp.Plus | BinaryOp.Minus | BinaryOp.Div | BinaryOp.Mult -> ( let new_spec = do_f64_folding op left_f_str right_f_str in Some { left with spec = new_spec } ) | _ -> None ) | (Constant(String(left_str, _, _)), Constant(String(right_str, _, _))) -> ( match op with | BinaryOp.Plus -> ( let concated = String.concat [left_str; right_str] in let new_spec = Constant(Literal.String(concated, left.loc, None)) in Some { left with spec = new_spec } ) | _ -> None ) | (Binary(_, _, _), _) -> ( let open Option in let res = try_folding_binary_expression left in res >>= fun left' -> try_folding_literals op left' right { original_expr with spec = Binary(op, left', right) } ) | (_, Binary(_, _, _)) -> ( let open Option in let res = try_folding_binary_expression right in res >>= fun right' -> try_folding_literals op left right' { original_expr with spec = Binary(op, left, right) } ) | _ -> None and try_folding_binary_expression expr: Expression.t option = let open Expression in match expr.spec with | Binary (op, left, right) -> ( here , we try fold binary expression to constant expression like : input : Expression { spec : BinaryAdd(Constant(Literal . Integer(1 ) ) , Constant(Literal . Integer(2 ) ) ) } ) output : Some(Expression { spec : Constant(Literal . Integer(3 ) ) } ) if ca n't be folded , None will be returned input: Expression { spec: BinaryAdd(Constant(Literal.Integer(1)), Constant(Literal.Integer(2))) }) output: Some(Expression { spec: Constant(Literal.Integer(3)) }) if can't be folded, None will be returned *) try_folding_literals op left right expr ) | _ -> None and transform_expression ?(is_move=false) ?(is_borrow=false) env expr = let open Expression in let { spec; loc; ty_var; _ } = expr in let prepend_stmts = ref [] in let append_stmts = ref [] in let expr_spec = match spec with | Constant literal -> ( let open Literal in match literal with | Unit -> Ir.Expr.Null | String(content, _, _) -> auto_release_expr env ~is_move ~append_stmts ty_var (Ir.Expr.NewString content) | I32 content -> let int_str = Int32.to_string content in Ir.Expr.NewI32 int_str | I64 content -> ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let int_str = Int64.to_string content in let result = Ir.Expr.NewI64 int_str in auto_release_expr env ~is_move ~append_stmts ty_var result ) | _ -> let int_str = Int64.to_string content in Ir.Expr.NewI64 int_str ) | Boolean bl -> Ir.Expr.NewBoolean bl | Float (fl, is_f32) -> if is_f32 then Ir.Expr.NewF32 fl else ( match env.config.ptr_size with | Some Ir.Ptr32 -> let result = Ir.Expr.NewF64 fl in auto_release_expr env ~is_move ~append_stmts ty_var result | _ -> Ir.Expr.NewF64 fl ) | Char ch -> Ir.Expr.NewChar ch ) * 1 . local variable * 2 . enum constructor * 1. local variable * 2. enum constructor *) | Identifier (name, name_id) -> ( let first_char = String.get name 0 in if Char.is_uppercase first_char then ( let node_type = Program.deref_node_type env.prog name_id in let ctor = Check_helper.find_construct_of env.prog node_type in let open Core_type in match ctor with | Some({ TypeDef. id = ctor_id; spec = EnumCtor _; _ }, _) -> let generate_name = Hashtbl.find_exn env.global_name_map ctor_id in let = find_variable env name in Ir.Expr.Call(generate_name, None, []) | _ -> let id_ty = Program.print_type_value env.prog node_type in failwith (Format.sprintf "unknown identifier: %s" id_ty) ) else ( let variable_opt = (Option.value_exn env.scope.raw)#find_var_symbol name in let variable = Option.value_exn variable_opt in let sym = find_variable env name in let id_expr = if should_var_captured variable then Ir.Expr.GetRef (sym, name) else Ir.Expr.Ident sym in let node_type = Program.deref_node_type env.prog variable.var_id in let need_release = env.config.arc && not (type_should_not_release env node_type) in if is_move && need_release then ( TScope.remove_release_var env.scope ; id_expr id_expr *) let id_expr = id_expr in Ir.Expr.Retaining id_expr ) else if (not is_borrow) && (not is_move) && need_release then ( let id_expr = id_expr in Ir.Expr.Retaining id_expr ) else id_expr ) ) | Lambda lambda_content -> ( let parent_scope = env.scope in let fun_meta = Option.value_exn ~message:"current function name not found" env.current_fun_meta in let lambda_name = fun_meta.fun_name ^ "_lambda_" ^ (Int.to_string ty_var) in let lambda_fun_name = "LCC_" ^ lambda_name in let capturing_variables = lambda_content.lambda_scope#capturing_variables in let capturing_names = Array.create ~len:(Scope.CapturingVarMap.length capturing_variables) (Ir.SymLocal "<unexpected>") in Scope.CapturingVarMap.iteri ~f:(fun ~key ~data -> let name = TScope.find_variable parent_scope key in Array.set capturing_names data name ) capturing_variables; let lambda = transform_lambda env ~lambda_name lambda_content ty_var in if env.config.prepend_lambda then ( env.lambdas <- lambda::env.lambdas ); let this_expr = if TScope.is_in_class env.scope then Ir.Expr.Ident(Ir.SymThis) else Null in let expr = Ir.Expr.NewLambda { lambda_name = lambda_fun_name; lambda_this = this_expr; lambda_capture_symbols = capturing_names; lambda_decl = lambda; } in auto_release_expr env ~is_move ~append_stmts ty_var expr ) | If if_desc -> let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let tmp_var = Ir.SymTemp tmp_id in if Check_helper.is_unit (Program.deref_node_type env.prog ty_var) then ( let init_stmt = Ir.Stmt.Expr(Ir.Expr.Assign(Ident tmp_var, Null)) in prepend_stmts := List.append !prepend_stmts [init_stmt]; ); let spec = transform_expression_if env ~ret:tmp_var ~prepend_stmts ~append_stmts loc if_desc in let tmp_stmt = Ir.Stmt.If spec in prepend_stmts := List.append !prepend_stmts [tmp_stmt]; Ir.Expr.Temp tmp_id | Tuple children -> let children_expr = List.map ~f:(fun expr -> let tmp = transform_expression ~is_borrow:true env expr in prepend_stmts := List.append !prepend_stmts tmp.prepend_stmts; append_stmts := List.append tmp.append_stmts !append_stmts; tmp.expr ) children in Ir.Expr.NewTuple children_expr | Array arr_list -> ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let arr_len = List.length arr_list in let tmp_sym = Ir.SymTemp tmp_id in let init_stmt = Ir.Stmt.Expr ( Ir.Expr.Assign( (Ident tmp_sym), (Ir.Expr.NewArray arr_len) ) ) in let max_tmp = ref env.tmp_vars_count in let init_stmts = arr_list |> List.mapi ~f:(fun index expr -> let saved_tmp = env.tmp_vars_count in let transformed_expr = transform_expression env expr in if env.tmp_vars_count > !max_tmp then ( max_tmp := env.tmp_vars_count; ); env.tmp_vars_count <- saved_tmp; let open Ir in let assign_stmt = Stmt.Expr ( Expr.ArraySetValue( (Ident tmp_sym), (NewI32 (Int.to_string index)), transformed_expr.expr ) ) in List.concat [ transformed_expr.prepend_stmts; [assign_stmt]; transformed_expr.append_stmts; ] ) |> List.concat in env.tmp_vars_count <- !max_tmp; prepend_stmts := List.concat [ !prepend_stmts; [init_stmt]; init_stmts; ]; append_stmts := List.concat [ if not is_move then [ gen_release_temp tmp_id ] else []; !append_stmts; ]; Ir.Expr.Temp tmp_id ) | Map entries -> ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let init_size = List.length entries in let init_stmt = Ir.( Stmt.Expr( Expr.Assign( Expr.Temp tmp_id, Expr.NewMap init_size) ) ) in let pre, set_stmts, app = entries |> List.map ~f:(fun entry -> let open Literal in let key_expr = match entry.map_entry_key with | String(content, _, _) -> auto_release_expr env ~is_move:false ~append_stmts ty_var (Ir.Expr.NewString content) | I32 content -> let int_str = Int32.to_string content in Ir.Expr.NewI32 int_str | _ -> failwith "unimplemented" in let expr = transform_expression env entry.map_entry_value in let set_expr = Ir.Expr.Call( Ir.SymLocal "lc_std_map_set", Some (Ir.Expr.Temp tmp_id), [key_expr; expr.expr] ) in ( expr.prepend_stmts, Ir.Stmt.Expr set_expr, expr.append_stmts ) ) |> List.unzip3 in prepend_stmts := List.concat [ !prepend_stmts; List.concat pre; [init_stmt]; set_stmts ]; append_stmts := List.concat [ List.concat app; !append_stmts; ]; Ir.Expr.Temp tmp_id ) | Call call -> ( let open Expression in let { callee; call_params; _ } = call in let params_struct = List.map ~f:(transform_expression ~is_borrow:true env) call_params in let prepend, params, append = List.map ~f:(fun expr -> expr.prepend_stmts, expr.expr, expr.append_stmts) params_struct |> List.unzip3 in prepend_stmts := List.append !prepend_stmts (List.concat prepend); append_stmts := List.append !append_stmts (List.concat append); let test_namespace expr = match expr with | { spec = Identifier (_, id); _ } -> ( let expr_type = Program.deref_node_type env.prog id in match expr_type with | TypeDef { Core_type.TypeDef. spec = Namespace _; _ } -> true | _ -> false ) | _ -> false in let call_expr = match callee with | { spec = Identifier (_, id); _ } -> ( match Program.find_external_symbol env.prog id with | Some ext_name -> ( Ir.Expr.Call((Ir.SymLocal ext_name), None, params) ) | None -> ( let deref_type = Program.deref_node_type env.prog callee.ty_var in match deref_type with | Core_type.TypeExpr.Lambda _ -> ( let transformed_callee = transform_expression ~is_borrow:true env callee in prepend_stmts := List.append !prepend_stmts (List.append !prepend_stmts transformed_callee.prepend_stmts); append_stmts := List.append !append_stmts (List.append !append_stmts transformed_callee.append_stmts); Ir.Expr.CallLambda(transformed_callee.expr, params) ) | _ -> let node = Program.get_node env.prog id in let ctor_opt = Check_helper.find_typedef_of env.prog node.value in let ctor_name = Option.value_exn ctor_opt in let name = find_variable env ctor_name.name in Ir.Expr.Call(name, None, params) ) ) | { spec = Member(_expr, None); _ } -> failwith "unrechable" | { spec = Member(expr, Some id); _ } -> begin if test_namespace expr then ( let callee_node = Program.get_node env.prog ty_var in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ctor_opt in let ctor_ty_id = ctor.id in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ctor_opt in let ctor_ty_id = ctor.id in *) let global_name = Hashtbl.find_exn env.global_name_map callee.ty_var in Ir.Expr.Call(global_name, None, params) ) else ( let expr_type = Program.deref_node_type env.prog expr.ty_var in let member = Check_helper.find_member_of_type env.prog ~scope:(Option.value_exn env.scope.raw) expr_type id.pident_name in match member with | Some ((Method ({ spec = ClassMethod { method_is_virtual = true; _ }; _ }, _, _)), _, _) -> ( let this_expr = transform_expression ~is_borrow:true env expr in prepend_stmts := List.append !prepend_stmts this_expr.prepend_stmts; append_stmts := List.append !append_stmts this_expr.append_stmts; Ir.Expr.Invoke(this_expr.expr, id.pident_name, params) ) | Some ((Method ({ id = method_id; spec = ClassMethod { method_get_set = None; _ }; _ }, _, _)), _, _) -> ( let this_expr = transform_expression ~is_borrow:true env expr in prepend_stmts := List.append !prepend_stmts this_expr.prepend_stmts; append_stmts := List.append !append_stmts this_expr.append_stmts; match Program.find_external_symbol env.prog method_id with | Some ext_name -> ( Ir.Expr.Call((Ir.SymLocal ext_name), Some this_expr.expr, params) ) | _ -> let callee_node = Program.get_node env.prog method_id in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ~message:"Cannot find typedef of class" ctor_opt in let ctor_ty_id = ctor.id in let global_name = Hashtbl.find_exn env.global_name_map ctor_ty_id in Ir.Expr.Call(global_name, Some this_expr.expr, params) ) | Some (TypeDef { id = fun_id; spec = Function _; _ }, _, _) -> ( let callee_node = Program.get_node env.prog fun_id in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ctor_opt in let ctor_ty_id = ctor.id in let ext_sym_opt = Program.find_external_symbol env.prog fun_id in match ext_sym_opt with | Some ext_sym -> Ir.Expr.Call(SymLocal ext_sym, None, params) | _ -> let global_name = Hashtbl.find_exn env.global_name_map ctor_ty_id in Ir.Expr.Call(global_name, None, params) ) | _ -> failwith "unrechable" ) end | _ -> ( let callee_node = Program.get_node env.prog callee.ty_var in let ctor_opt = Check_helper.find_typedef_of env.prog callee_node.value in let ctor = Option.value_exn ctor_opt in let ctor_ty_id = ctor.id in let global_name = Hashtbl.find_exn env.global_name_map ctor_ty_id in Ir.Expr.Call(global_name, None, params) ) in auto_release_expr ~is_move env ~append_stmts ty_var call_expr ) | Member(_main_expr, None) -> failwith "unrechable" | Member(main_expr, Some id) -> ( let node_type = Program.deref_node_type env.prog main_expr.ty_var in let open Core_type.TypeDef in match node_type with | Core_type.TypeExpr.TypeDef { spec = Namespace _; _ } -> ( let expr_node_type = Program.deref_node_type env.prog expr.ty_var in let open Core_type in match expr_node_type with | TypeExpr.TypeDef { TypeDef. id = ctor_id; spec = EnumCtor _; _ } -> let generate_name = Hashtbl.find_exn env.global_name_map ctor_id in let = find_variable env name in Ir.Expr.Call(generate_name, None, []) | _ -> let id_ty = Program.print_type_value env.prog expr_node_type in failwith (Format.sprintf "unknown identifier: %s" id_ty) ) | Core_type.TypeExpr.TypeDef { spec = Class cls ; id = cls_id; _ } -> ( let field_id = find_static_field_id_of_class cls id.pident_name in let cls_meta = Hashtbl.find_exn env.cls_meta_map cls_id in let t = Ir.Expr.GetStaticValue(cls_meta.cls_gen_name, id.pident_name, field_id) in auto_release_expr env ~is_move ~append_stmts ty_var t ) | _ -> let expr_result = transform_expression ~is_borrow:true env main_expr in prepend_stmts := List.append !prepend_stmts expr_result.prepend_stmts; append_stmts := List.append expr_result.append_stmts !append_stmts; let member = Check_helper.find_member_of_type env.prog ~scope:(Option.value_exn env.scope.raw) node_type id.pident_name in match member with | Some (Method ({ Core_type.TypeDef. id = def_int; spec = ClassMethod { method_get_set = Some _; _ }; _ }, _params, _rt), _, _) -> ( let ext_sym_opt = Program.find_external_symbol env.prog def_int in let ext_sym = Option.value_exn ext_sym_opt in Ir.Expr.Call(SymLocal ext_sym, Some expr_result.expr, []) ) | Some (Core_type.TypeExpr.TypeDef { id = method_id; spec = ClassMethod { method_get_set = Some Getter; _ }; _ }, _, _) -> ( let ext_sym_opt = Program.find_external_symbol env.prog method_id in let ext_sym = Option.value_exn ext_sym_opt in Ir.Expr.Call(SymLocal ext_sym, Some expr_result.expr, []) ) | Some _ -> ( let expr_ctor_opt = Check_helper.find_construct_of env.prog node_type in match expr_ctor_opt with | Some({ id = expr_id; _ }, _) -> ( let cls_meta = Hashtbl.find_exn env.cls_meta_map expr_id in let prop_name = Hashtbl.find_exn cls_meta.cls_fields_map id.pident_name in let get_field_expr = Ir.Expr.GetField(expr_result.expr, cls_meta.cls_gen_name, prop_name) in if is_borrow then get_field_expr else Ir.Expr.( Retaining(get_field_expr) ) ) | _ -> Format.eprintf "%s expr_type: %a\n" id.pident_name Core_type.TypeExpr.pp node_type; failwith "can not find ctor of expr, maybe it's a property" ) | _ -> failwith (Format.sprintf "unexpected: can not find member %s of id %d" id.pident_name expr.ty_var) ) | Unary(op, expr) -> ( let expr' = transform_expression ~is_borrow:true env expr in let node_type = Program.deref_node_type env.prog expr.ty_var in prepend_stmts := List.append !prepend_stmts expr'.prepend_stmts; append_stmts := List.append expr'.append_stmts !append_stmts; match op with | UnaryOp.Not -> Ir.Expr.Not expr'.expr | UnaryOp.Plus -> expr'.expr | UnaryOp.Minus -> if Check_helper.is_i64 env.prog node_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let n1 = Ir.Expr.NewI64 "-1" in let n1 = auto_release_expr env ~is_move ~append_stmts expr.ty_var n1 in let tmp = Ir.Expr.I64Binary(BinaryOp.Mult, expr'.expr, n1) in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.I64Binary(BinaryOp.Mult, expr'.expr, Ir.Expr.NewI64 "-1") ) else if Check_helper.is_f64 env.prog node_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let n1 = Ir.Expr.NewF64 "-1" in let n1 = auto_release_expr env ~is_move ~append_stmts expr.ty_var n1 in let tmp = Ir.Expr.F64Binary(BinaryOp.Mult, expr'.expr, n1) in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.F64Binary(BinaryOp.Mult, expr'.expr, Ir.Expr.NewF64 "-1") ) else if Check_helper.is_f32 env.prog node_type then Ir.Expr.F32Binary(BinaryOp.Mult, expr'.expr, Ir.Expr.NewF32 "-1") else Ir.Expr.I32Binary(BinaryOp.Mult, expr'.expr, Ir.Expr.NewI32 "-1") | UnaryOp.BitNot -> if Check_helper.is_i64 env.prog node_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let tmp = Ir.Expr.I64BitNot expr'.expr in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.I64BitNot expr'.expr ) else Ir.Expr.I32BitNot expr'.expr ) | Binary (op, left, right) -> transform_binary_expr env ~is_move ~append_stmts ~prepend_stmts expr op left right * There are a lot of cases of assignment . * * 1 . Assign to an identifier : a = < expr > * - local variable * - local RefCel * - captured const * - captured refcell * 2 . Assign to a member : < expr>.xxx = < expr > * - property of a class * - setter of a class * - Assign to this property : this.xxx = expr * There are a lot of cases of assignment. * * 1. Assign to an identifier: a = <expr> * - local variable * - local RefCel * - captured const * - captured refcell * 2. Assign to a member: <expr>.xxx = <expr> * - property of a class * - setter of a class * - Assign to this property: this.xxx = expr *) | Assign (op_opt, left_expr, right_expr) -> ( let assign_or_update main_expr ty_id = let node_type = Program.deref_node_type env.prog ty_id in let need_release = env.config.arc && not (type_should_not_release env node_type) in if need_release then ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- tmp_id + 1; let open Ir in let assign_stmt = Stmt.Expr ( Expr.Assign( Expr.Ident (SymTemp tmp_id), main_expr ) ) in let release_stmt = Stmt.Release( Expr.Ident( SymTemp tmp_id ) ) in prepend_stmts := List.append !prepend_stmts [assign_stmt]; append_stmts := List.append [release_stmt] !append_stmts ); match op_opt with | None -> ( let expr' = transform_expression ~is_move:true env right_expr in prepend_stmts := List.concat [ !prepend_stmts; expr'.prepend_stmts ]; append_stmts := List.concat [ !append_stmts; expr'.append_stmts ]; Ir.Expr.Assign(main_expr, expr'.expr) ) | Some op -> ( let binary_op = AssignOp.to_binary op in let binary_ir = transform_binary_expr env ~is_move:true ~append_stmts ~prepend_stmts expr binary_op left_expr right_expr in Ir.Expr.Assign(main_expr, binary_ir) ) in match (left_expr, op_opt) with | ({ spec = Typedtree.Expression.Identifier (name, name_id); _ }, _) -> ( let name = find_variable env name in assign_or_update (Ir.Expr.Ident name) name_id ) | ({ spec = Typedtree.Expression.Member (_main_expr, None); _ }, _) -> failwith "unrechable" | ({ spec = Typedtree.Expression.Member (main_expr, Some id); _ }, _) -> ( let main_expr_ty = Program.deref_node_type env.prog main_expr.ty_var in match main_expr_ty with | Core_type.TypeExpr.TypeDef { spec = Class cls ; id = cls_id; _ } -> ( match op_opt with | None -> ( let field_id = find_static_field_id_of_class cls id.pident_name in let cls_meta = Hashtbl.find_exn env.cls_meta_map cls_id in let expr' = transform_expression ~is_move:false env right_expr in prepend_stmts := List.concat [ !prepend_stmts; expr'.prepend_stmts ]; append_stmts := List.concat [ !append_stmts; expr'.append_stmts ]; Ir.Expr.SetStaticValue(cls_meta.cls_gen_name, id.pident_name, field_id, expr'.expr) ) | _ -> failwith "unimplemented: update static value" ) | _ -> let transform_main_expr = transform_expression ~is_borrow:true env main_expr in prepend_stmts := List.concat [ !prepend_stmts; transform_main_expr.prepend_stmts ]; append_stmts := List.concat [ !append_stmts; transform_main_expr.append_stmts ]; let boxed_main_expr = prepend_expr ~is_borrow env ~prepend_stmts ~append_stmts transform_main_expr.expr in let classname_opt = Check_helper.find_classname_of_type env.prog main_expr_ty in let classname = Option.value_exn ~message:"can not find member of class" classname_opt in let gen_classname = find_variable env classname in let unwrap_name = match gen_classname with | Ir.SymLocal name -> name | _ -> failwith "unrechable" in assign_or_update (Ir.Expr.GetField( transform_main_expr.expr, unwrap_name, id.pident_name) ) main_expr.ty_var ) | ({ spec = Typedtree.Expression.Index (main_expr, value); _ }, None) -> ( let expr' = transform_expression ~is_move:true env right_expr in prepend_stmts := List.concat [ !prepend_stmts; expr'.prepend_stmts ]; append_stmts := List.concat [ !append_stmts; expr'.append_stmts ]; let transform_main_expr = transform_expression ~is_borrow:true env main_expr in let boxed_main_expr = prepend_expr env ~prepend_stmts ~append_stmts transform_main_expr.expr in let value_expr = transform_expression env value in prepend_stmts := List.concat [ !prepend_stmts; value_expr.prepend_stmts; transform_main_expr.prepend_stmts ]; append_stmts := List.concat [ transform_main_expr.append_stmts; value_expr.append_stmts; !append_stmts; ]; Ir.Expr.ArraySetValue(transform_main_expr.expr, value_expr.expr, expr'.expr) ) | _ -> Format.eprintf "Unexpected left: %a" Typedtree.Expression.pp left_expr; failwith "unreachable" ) | Init { init_name; init_elements; _ } -> ( let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let init_name, init_name_id = init_name in let cls_meta = Hashtbl.find_exn env.cls_meta_map init_name_id in let fun_name = find_variable env init_name in let init_call_name = Ir.map_symbol ~f:(fun fun_name -> fun_name ^ "_init") fun_name in let init_call = Ir.Expr.InitCall(init_call_name, fun_name) in let init_cls_stmt = Ir.( Stmt.Expr ( Expr.Assign( (Temp tmp_id), init_call ) ) ) in let init_stmts = init_elements |> List.map ~f:(fun elm -> match elm with | InitEntry { init_entry_key; init_entry_value; _ } -> let actual_name = Hashtbl.find_exn cls_meta.cls_fields_map init_entry_key.pident_name in let transformed_value = transform_expression ~is_move:true env init_entry_value in let unwrap_name = match fun_name with | Ir.SymLocal name -> name | _ -> failwith "unrechable" in let left_value = ( Ir.Expr.GetField( (Temp tmp_id), unwrap_name, actual_name ) ) in [Ir.Stmt.Expr( Assign( left_value, transformed_value.expr ) )] | InitSpread spread_expr -> ( let transformed_spread = transform_expression ~is_move:true env spread_expr in let spread_expr' = if is_identifier spread_expr then transformed_spread.expr else prepend_expr env ~prepend_stmts ~append_stmts transformed_spread in transform_spreading_init env tmp_id spread_expr.ty_var spread_expr' ) ) |> List.concat in prepend_stmts := List.append !prepend_stmts (init_cls_stmt::init_stmts); if not is_move then ( let release_stmt = Ir.Stmt.Release(Ir.Expr.Temp tmp_id) in append_stmts := List.append !append_stmts [release_stmt]; ); Ir.Expr.Temp tmp_id ) | Block block -> let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let tmp_var = Ir.SymTemp tmp_id in let init = Ir.( Stmt.Expr ( Expr.Assign ( (Ident tmp_var), Null ) ) ) in let stmts = transform_block ~ret:tmp_var env block in prepend_stmts := List.concat [!prepend_stmts; [init]; stmts]; Ir.Expr.Temp tmp_id | Match _match -> transform_pattern_matching env ~prepend_stmts ~append_stmts ~loc ~ty_var _match | This -> ( let this_symbol = if TScope.is_in_lambda env.scope then Ir.Expr.Ident SymLambdaThis else Ir.Expr.Ident SymThis in if is_move then Ir.Expr.Retaining this_symbol else if (not is_borrow) && (not is_move) then Ir.Expr.Retaining this_symbol else this_symbol ) | TypeCast(expr, _type) ->( if Check_helper.check_castable_primitive env.prog _type then ( let expr_type = Program.deref_node_type env.prog expr.ty_var in let expr_result = transform_expression ~is_move:true env expr in let expr_type = Primitives.PrimType.from_type ~ctx:env.prog expr_type in let cast_type = Primitives.PrimType.from_type ~ctx:env.prog _type in Ir.Expr.TypeCast(expr_result.expr, expr_type, cast_type) ) else ( let tmp = transform_expression ~is_move ~is_borrow env expr in append_stmts := tmp.append_stmts; prepend_stmts := tmp.prepend_stmts; tmp.expr ) ) | Try try_expr -> ( let expr_result = transform_expression ~is_move:true env try_expr in let expr' = prepend_expr env ~prepend_stmts ~append_stmts expr_result in let tmp_id = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let tmp_var = "t[" ^ (Int.to_string tmp_id) ^ "]" in let cleanup = generate_finalize_stmts_function env.scope in let open Ir in let stmt = Stmt.If { 1 represent error if_consequent = List.concat [ expr_result.append_stmts; cleanup; [ Stmt.Return (Some expr') ] ]; if_alternate = None; } in let union_get_expr = Expr.UnionGet(expr', 0) in let assign_stmt = Stmt.Expr( Expr.Assign( Expr.Ident (SymLocal tmp_var), union_get_expr ) ) in prepend_stmts := List.concat [ !prepend_stmts; expr_result.prepend_stmts; [stmt; assign_stmt] ]; append_stmts := List.append expr_result.append_stmts !append_stmts; Temp tmp_id ) | Super -> failwith "unrechable" | Index(expr, index) -> ( let expr' = transform_expression ~is_borrow:true env expr in let node_type = Program.deref_node_type env.prog expr.ty_var in let index = transform_expression env index in prepend_stmts := List.concat [ !prepend_stmts; index.prepend_stmts; expr'.prepend_stmts ]; append_stmts := List.concat [ expr'.append_stmts; index.append_stmts; !append_stmts ]; match node_type with | String -> Ir.Expr.Call(Ir.SymLocal "lc_std_string_get_char", Some expr'.expr, [index.expr]) | _ -> ( let result = Ir.Expr.ArrayGetValue(expr'.expr, (Ir.Expr.IntValue index.expr)) in auto_release_expr env ~is_move ~append_stmts expr.ty_var result ) ) in { prepend_stmts = !prepend_stmts; expr = expr_spec; append_stmts = !append_stmts; } and transform_pattern_matching env ~prepend_stmts:out_prepend_stmts ~append_stmts:out_append_stmts ~loc:_ ~ty_var _match = let open Typedtree.Expression in let { match_expr; match_clauses; _ } = _match in let transformed_expr = transform_expression ~is_move:true env match_expr in let match_expr = let t = prepend_expr env ~prepend_stmts:out_prepend_stmts ~append_stmts:out_append_stmts transformed_expr in out_append_stmts := List.concat [ !out_append_stmts; transformed_expr.append_stmts; ]; t in let result_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; out_prepend_stmts := List.append !out_prepend_stmts [Ir.Stmt.Expr ( Ir.Expr.Assign ( (Ident (Ir.SymTemp result_tmp)), Null ); )]; let tmp_counter = ref [] in let label_name = "done_" ^ (Int.to_string ty_var) in let prepend_stmts = ref [] in let is_last_goto stmts = let last_opt = List.last stmts in match last_opt with | Some (Ir.Stmt.Goto _) -> true | _ -> false in let rec transform_pattern_to_test match_expr pat : PMMeta.t = let open Pattern in let { spec; _ } = pat in match spec with | Underscore -> (fun genereator -> genereator ~finalizers:[] ()) | Literal (Literal.I32 i) -> ( let i_str = Int32.to_string i in let if_test = Ir.Expr.IntValue(I32Binary(BinaryOp.Equal, match_expr, NewI32 i_str)) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) | Literal (Literal.String(str, _, _)) -> ( let if_test = Ir.Expr.StringEqUtf8(match_expr, str) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) | Literal (Literal.Boolean bl) -> ( let if_test = if bl then Ir.Expr.IntValue match_expr else Ir.Expr.IntValue(Not match_expr) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) | Literal (Literal.Char ch) -> ( let if_test = Ir.Expr.IntValue(I32Binary(BinaryOp.Equal, match_expr, Ir.Expr.NewChar ch)) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) ) | Literal _ -> failwith "unimplemented" | Symbol (name, name_id) -> ( let first_char = String.get name 0 in if Char.is_uppercase first_char then ( let name_node = Program.get_node env.prog name_id in let ctor_opt = Check_helper.find_typedef_of env.prog name_node.value in let ctor = Option.value_exn ~message:(Format.sprintf "find enum ctor failed: %s %d" name name_id) ctor_opt in let enum_ctor = Core_type.TypeDef.( match ctor.spec with | EnumCtor v -> v | _ -> failwith "unrechable" ) in let if_test = Ir.Expr.TagEqual(match_expr, enum_ctor.enum_ctor_tag_id) in (fun genereator -> let if_stmt = Ir.Stmt.If { if_test; if_consequent= genereator ~finalizers:[] (); if_alternate = None; } in [if_stmt] ) let sym = find_variable env name in let assign_stmt = Ir.Stmt.Expr( Assign( Ident sym, match_expr ) ) in (fun genereator -> let acc = genereator ~finalizers:[] () in assign_stmt::acc ) ) ) | EnumCtor ((_name, name_id), child) -> ( let name_node = Program.get_node env.prog name_id in let ctor_opt = Check_helper.find_typedef_of env.prog name_node.value in let ctor = Option.value_exn ctor_opt in let enum_ctor = Core_type.TypeDef.( match ctor.spec with | EnumCtor v -> v | _ -> failwith "n" ) in let if_test = Ir.Expr.TagEqual(match_expr, enum_ctor.enum_ctor_tag_id) in let match_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let open Ir in let assign_stmt = Stmt.Expr( Expr.Assign( Expr.Temp match_tmp, Expr.UnionGet(match_expr, 0) ) ) in let release_stmt = Stmt.Release(Ir.Expr.Temp match_tmp) in let open PMMeta in let this_pm: t = fun generator -> let acc = generator ~finalizers:[release_stmt] () in let if_consequent= if is_last_goto acc then List.concat [ [assign_stmt]; acc; ] else List.concat [ [assign_stmt]; acc; [release_stmt]; ] in let if_stmt = Ir.Stmt.If { if_test; if_consequent; if_alternate = None; } in [if_stmt] in let child_pm = transform_pattern_to_test (Temp match_tmp) child in this_pm >>= child_pm ) | Tuple children -> ( let open Ir in let assign_stmts, release_stmts, child_pms = children |> List.mapi ~f:(fun index elm -> let match_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_stmt = Stmt.Expr( Assign( Temp match_tmp, TupleGetValue(match_expr, index) ) ) in let release_stmt = Stmt.Release(Expr.Temp match_tmp) in let child_pm = transform_pattern_to_test (Temp match_tmp) elm in assign_stmt, release_stmt, child_pm ) |> List.unzip3 in let open PMMeta in let this_pm: t = fun generator -> let acc = generator ~finalizers:release_stmts () in if is_last_goto acc then List.concat [ assign_stmts; acc; ] else List.concat [ assign_stmts; acc; release_stmts; ] in List.fold ~init:this_pm ~f:(fun acc elm -> acc >>= elm) child_pms ) | Array { elements; rest; } -> ( let elm_len = List.length elements in let open Ir in let need_test = Expr.IntValue ( match rest with | Some _ -> Expr.I32Binary( BinaryOp.GreaterThanEqual, Expr.Call(SymLocal "lc_std_array_get_length", Some match_expr, []), Expr.NewI32 (Int.to_string elm_len)) | None -> Expr.I32Binary( BinaryOp.Equal, Expr.Call(SymLocal "lc_std_array_get_length", Some match_expr, []), Expr.NewI32 (Int.to_string elm_len)) ) in let assign_stmts, release_stmts, child_pms = elements |> List.mapi ~f:(fun index elm -> let match_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_stmt = Ir.Stmt.Expr( Assign( Temp match_tmp, ArrayGetValue(match_expr, Expr.IntValue(Expr.NewI32 (Int.to_string index))) ) ) in let release_stmt = Ir.Stmt.Release(Expr.Temp match_tmp) in let child_pm = transform_pattern_to_test (Temp match_tmp) elm in assign_stmt, release_stmt, child_pm ) |> List.unzip3 in let rest_assigns, rest_releases, rest_pms = match rest with | Some { spec = Underscore; _ } -> [], [], [] | Some rest_pat -> ( let match_tmp = env.tmp_vars_count in env.tmp_vars_count <- env.tmp_vars_count + 1; let assign_stmt = Ir.Stmt.Expr( Assign( Temp match_tmp, Call( SymLocal "lc_std_array_slice", Some match_expr, [ Expr.NewI32 (Int.to_string elm_len); Expr.Call(SymLocal "lc_std_array_get_length", Some match_expr, []) ] ) ) ) in let release_stmt = Ir.Stmt.Release(Expr.Temp match_tmp) in let rest_pm = transform_pattern_to_test (Temp match_tmp) rest_pat in [assign_stmt], [release_stmt], [rest_pm] ) | None -> [], [], [] in let open PMMeta in let this_pm: t = fun generator -> let acc = generator ~finalizers:(List.append rest_releases release_stmts) () in let if_consequent = if is_last_goto acc then List.concat [ assign_stmts; rest_assigns; acc; ] else List.concat [ assign_stmts; rest_assigns; acc; rest_releases; release_stmts; ] in let if_stmt = Ir.Stmt.If { if_test = need_test; if_consequent; if_alternate = None; } in [if_stmt] in List.fold ~init:this_pm ~f:(fun acc elm -> acc >>= elm) (List.append child_pms rest_pms) ) in let transform_clause clause = let scope = create_scope_and_distribute_vars env clause.clause_scope in with_scope env scope (fun env -> let saved_tmp_count = env.tmp_vars_count in let body = transform_expression ~is_move:true env clause.clause_consequent in let done_stmt = Ir.Stmt.Goto label_name in let consequent ~finalizers () : Ir.Stmt.t list = List.concat [ body.prepend_stmts; [Ir.Stmt.Expr ( Assign( (Ident (Ir.SymTemp result_tmp)), body.expr ) )]; body.append_stmts; finalizers; [done_stmt]; ] in let pm_meta = transform_pattern_to_test match_expr clause.clause_pat in let pm_stmts = pm_meta consequent in prepend_stmts := List.append !prepend_stmts pm_stmts; tmp_counter := env.tmp_vars_count::(!tmp_counter); env.tmp_vars_count <- saved_tmp_count; ) in List.iter ~f:transform_clause match_clauses; let end_label = Ir.Stmt.WithLabel(label_name, !prepend_stmts) in out_prepend_stmts := List.append !out_prepend_stmts [end_label]; use the max tmp vars env.tmp_vars_count <- List.fold ~init:0 ~f:(fun acc item -> if item > acc then item else acc) !tmp_counter; Ir.Expr.Temp result_tmp and transform_spreading_init env tmp_id spread_ty_var spread_expr = let expr_node_type = Program.deref_node_type env.prog spread_ty_var in let ctor_opt = Check_helper.find_construct_of env.prog expr_node_type in let ctor, _ = Option.value_exn ~message:(Format.asprintf "Can not find ctor of spreading init: %d %a" spread_ty_var Core_type.TypeExpr.pp expr_node_type) ctor_opt in let cls_id = ctor.id in let cls_meta = Hashtbl.find_exn env.cls_meta_map cls_id in cls_meta.cls_fields |> List.map ~f:(fun (field_name, _) -> let open Ir in let left_value = ( Expr.GetField( (Temp tmp_id), cls_meta.cls_gen_name, field_name ) ) in let get_field = Expr.GetField(spread_expr, cls_meta.cls_gen_name, field_name) in [ Stmt.Retain get_field; Stmt.Expr( Assign( left_value, get_field ) ); ] ) |> List.concat and transform_binary_expr env ~is_move ~append_stmts ~prepend_stmts expr op left right = let open Expression in let { ty_var; _ } = expr in let gen_c_op left right = let left' = transform_expression ~is_borrow:true env left in let right' = transform_expression ~is_borrow:true env right in prepend_stmts := List.concat [!prepend_stmts; left'.prepend_stmts; right'.prepend_stmts]; append_stmts := List.concat [!append_stmts; left'.append_stmts; right'.append_stmts]; let left_type = Program.deref_node_type env.prog left.ty_var in let open Core_type in match (left_type, op) with | (TypeExpr.String, BinaryOp.Plus) -> let spec = auto_release_expr ~is_move env ~append_stmts ty_var (Ir.Expr. Call(SymLocal "lc_std_string_concat", None, [left'.expr; right'.expr])) in spec | (TypeExpr.String, BinaryOp.Equal) | (TypeExpr.String, BinaryOp.NotEqual) | (TypeExpr.String, BinaryOp.LessThan) | (TypeExpr.String, BinaryOp.LessThanEqual) | (TypeExpr.String, BinaryOp.GreaterThan) | (TypeExpr.String, BinaryOp.GreaterThanEqual) -> let spec = auto_release_expr ~is_move env ~append_stmts ty_var (Ir.Expr.StringCmp(op, left'.expr, right'.expr)) in spec | _ -> ( if Check_helper.is_i64 env.prog left_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let tmp = Ir.Expr.I64Binary(op, left'.expr, right'.expr) in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.I64Binary(op, left'.expr, right'.expr) ) else if Check_helper.is_f64 env.prog left_type then ( match env.config.ptr_size with | Some Ir.Ptr32 -> ( let tmp = Ir.Expr.F64Binary(op, left'.expr, right'.expr) in auto_release_expr env ~is_move ~append_stmts expr.ty_var tmp ) | _ -> Ir.Expr.F64Binary(op, left'.expr, right'.expr) ) else if Check_helper.is_f32 env.prog left_type then Ir.Expr.F32Binary(op, left'.expr, right'.expr) else Ir.Expr.I32Binary(op, left'.expr, right'.expr) ) in let is_constant expression = match expression.spec with | Constant _ -> true | _ -> false in if is_constant left && is_constant right then if left and right are constants , try folding . if expr does not transformed by folding then generate c op directly by current left and right else try recursive transform new_expr if expr does not transformed by folding then generate c op directly by current left and right else try recursive transform new_expr *) let new_expr = try_folding_literals op left right expr in match new_expr with | Some(folded_expr) -> ( let result = transform_expression ~is_borrow:true env folded_expr in result.expr ) | None -> gen_c_op left right else ( let left_res = try_folding_binary_expression left in let right_res = try_folding_binary_expression right in match (left_res, right_res) with | (None, None) -> if both left and right ca n't be fold , gen c op here gen_c_op left right | _ -> ( let left_expr = match left_res with | Some(left') -> left' | None -> left in let right_expr = match right_res with | Some(right') -> right' | None -> right in let temp_expr = { expr with spec = Binary(op, left_expr, right_expr) } in let maybe_folded_expr = try_folding_literals op left_expr right_expr temp_expr in let expr = match maybe_folded_expr with | None -> temp_expr | Some(folded_expr) -> folded_expr in let result = transform_expression ~is_move env expr in append_stmts := List.append !append_stmts result.append_stmts; result.expr ) ) and transform_expression_if env ?ret ~prepend_stmts ~append_stmts loc if_desc = let open Typedtree.Expression in let test = transform_expression env if_desc.if_test in let if_test = Ir.Expr.IntValue test.expr in let consequent = transform_block ?ret env if_desc.if_consequent in let if_alternate = Option.map ~f:(fun alt -> match alt with | If_alt_if if_spec -> Ir.Stmt.If_alt_if (transform_expression_if env ?ret ~prepend_stmts ~append_stmts loc if_spec) | If_alt_block blk -> let consequent = transform_block ?ret env blk in Ir.Stmt.If_alt_block consequent ) if_desc.if_alternative in let spec = { Ir.Stmt. if_test; if_consequent = consequent; if_alternate; } in prepend_stmts := List.concat [!prepend_stmts; test.prepend_stmts]; append_stmts := List.append test.append_stmts !append_stmts; spec and transform_block env ?ret ?map_scope (block: Typedtree.Block.t): Ir.Stmt.t list = let block_scope = create_scope_and_distribute_vars env block.scope in let block_scope = match map_scope with | Some map -> map block_scope | None -> block_scope in with_scope env block_scope (fun env -> let stmts = List.map ~f:(transform_statement ?ret env) block.body |> List.concat in let cleanup = generate_finalize_stmts env.scope in List.append stmts cleanup ) and generate_finalize_stmts scope = let open TScope in !(scope.local_vars_to_release) |> List.rev |> List.filter_map ~f:(fun sym -> Some (Ir.Stmt.Release(Ident sym)) ) and generate_finalize_stmts_function scope = TScope.get_symbols_to_release_til_function [] scope |> List.rev |> List.filter_map ~f:(fun sym -> Some (Ir.Stmt.Release (Ident sym)) ) and generate_finalize_stmts_while scope = TScope.get_symbols_to_release_til_while [] scope |> List.rev |> List.filter_map ~f:(fun sym -> Some (Ir.Stmt.Release (Ident sym)) ) and generate_cls_meta env cls_id gen_name = let node = Program.get_node env.prog cls_id in let ctor_opt = Check_helper.find_typedef_of env.prog node.value in let ctor = Option.value_exn ctor_opt in let rec generate_properties_including_ancester child (cls_def: Core_type.TypeDef.t) = let cls_def = match cls_def with | { spec = Class cls; _ } -> cls | _ -> failwith "unexpected: not a class" in let properties = List.filter_map ~f:(fun (elm_name, elm) -> match elm with | Cls_elm_prop (_, ty_var, _) -> Some (elm_name, ty_var) | _ -> None ) cls_def.tcls_elements; in let result = List.append properties child in match cls_def.tcls_extends with | Some ancester -> ( let ctor_opt = Check_helper.find_construct_of env.prog ancester in let ctor, _ = Option.value_exn ctor_opt in generate_properties_including_ancester result ctor ) | _ -> result in let prop_names = generate_properties_including_ancester [] ctor in let result = create_cls_meta cls_id gen_name prop_names in List.iter ~f:(fun (field_name, _) -> Hashtbl.set result.cls_fields_map ~key:field_name ~data:field_name) result.cls_fields; result and transform_class_method env _method : (Ir.Decl.t list * Ir.Decl.class_method_tuple option) = let open Declaration in let { cls_method_name; cls_method_params; cls_method_body; cls_method_scope; _ } = _method in env.tmp_vars_count <- 0; let origin_method_name, method_id = cls_method_name in let new_name = match Hashtbl.find_exn env.global_name_map method_id with | Ir.SymLocal name -> name | _ -> failwith "unrechable" in let open Core_type in let node = Program.get_node env.prog method_id in let node_type = Program.deref_type env.prog node.value in let is_virtual = match node_type with | TypeExpr.TypeDef { spec = TypeDef.ClassMethod { method_is_virtual = true; _ }; _ } -> true | _ -> false in let tuple = if is_virtual then Some { Ir.Decl. class_method_name = origin_method_name; class_method_gen_name = new_name; } else None in let _fun = { Ir.Decl. spec = (transform_function_impl env ~name:(new_name, node.loc) ~params:cls_method_params ~scope:(Option.value_exn cls_method_scope) ~body:cls_method_body ~comments:[]); loc = _method.cls_method_loc; } in let lambdas = env.lambdas in env.lambdas <- []; (_fun::lambdas), tuple and distribute_name_to_class_method env cls_original_name _method = let open Declaration in let { cls_method_name; _ } = _method in let origin_method_name, method_id = cls_method_name in let new_name = cls_original_name ^ "_" ^ origin_method_name in let new_name = distribute_name env new_name in let pre_declare = { Ir.Decl. spec = FuncDecl (SymLocal new_name); loc = Loc.none; } in env.prepends_decls <- pre_declare::(env.prepends_decls); Hashtbl.set env.global_name_map ~key:method_id ~data:(SymLocal new_name) and transform_class env cls loc: Ir.Decl.t list = let open Declaration in let { cls_id; cls_body; _ } = cls in let original_name, cls_name_id = cls_id in let fun_name = distribute_name env original_name in let finalizer_name = fun_name ^ "_finalizer" in let gc_marker_name = fun_name ^ "_marker" in env.current_fun_meta <- Some (create_current_fun_meta original_name); Hashtbl.set env.global_name_map ~key:cls_name_id ~data:(SymLocal fun_name); let _, cls_id' = cls_id in let cls_meta = generate_cls_meta env cls_id' fun_name in Hashtbl.set env.cls_meta_map ~key:cls_meta.cls_id ~data:cls_meta; List.iter ~f:(fun elm-> match elm with | Cls_method _method -> distribute_name_to_class_method env original_name _method | _ -> () ) cls_body.cls_body_elements; let class_methods = ref [] in let class_static_fields = ref [] in let methods: Ir.Decl.t list = List.fold ~init:[] ~f:(fun acc elm -> match elm with | Cls_method _method -> ( let stmts, tuple_opt = transform_class_method env _method in (match tuple_opt with | Some tuple -> class_methods := tuple::!class_methods | None -> () ); List.append stmts acc ) | Cls_static_property prop -> ( let name, _ = prop.cls_static_prop_name in let init_expr = transform_expression ~is_move:true env prop.cls_static_prop_init in class_static_fields := (name, init_expr.expr)::(!class_static_fields); acc ) | Cls_property _ | Cls_declare _ -> acc ) cls_body.cls_body_elements; in let _, cls_id' = cls_id in let cls_type = Program.deref_node_type env.prog cls_id' in let cls_typedef = Check_helper.find_typedef_of env.prog cls_type in let unwrap_class = match cls_typedef with | Some { Core_type.TypeDef. spec = Class cls; _ } -> cls | _ -> failwith "unrechable" in let class_ancester = Option.( unwrap_class.tcls_extends >>= fun ancester -> let typedef, _ = Option.value_exn (Check_helper.find_construct_of env.prog ancester) in let ancester_id = typedef.id in let prog = env.prog in let open Program in match prog.root_class with | Some root_class' -> ( if root_class'.root_class_id = ancester_id then None else ( let name = Hashtbl.find_exn env.global_name_map ancester_id in Some name ) ) | None -> ( let name = Hashtbl.find_exn env.global_name_map ancester_id in Some name ) ) in let class_init = { Ir.Decl. class_ancester; class_name = fun_name; class_id_name = fun_name ^ "_class_id"; class_def_name = fun_name ^ "_def"; class_methods = List.rev !class_methods; class_static_fields = List.rev !class_static_fields; } in env.class_inits <- (Ir.Decl.InitClass class_init)::env.class_inits; let finalizer = generate_finalizer env finalizer_name (Option.value_exn cls_typedef) in let gc_marker = generate_gc_marker env gc_marker_name (Option.value_exn cls_typedef) in let cls = { Ir.Decl. name = fun_name; original_name; finalizer; gc_marker; properties = cls_meta.cls_fields; init = class_init; } in List.append [ { Ir.Decl. spec = Ir.Decl.Class cls; loc; } ] (List.rev methods) * Generate finalizer statements for a class : * If a class has ancesters , generate the ancesters 's statements first . * Generate finalizer statements for a class: * If a class has ancesters, generate the ancesters's statements first. *) and generate_finalizer env name (type_def: Core_type.TypeDef.t) : Ir.Decl.class_finalizer option = let generate_release_statements_by_cls_meta type_def = let open Core_type.TypeDef in let open Ir in let cls_meta = Hashtbl.find_exn env.cls_meta_map type_def.id in List.filter_map ~f:(fun (field_name, ty_var) -> let field_type = Program.deref_node_type env.prog ty_var in if type_should_not_release env field_type then None else Some ( Stmt.Release (Expr.RawGetField("ptr", field_name)) ) ) cls_meta.cls_fields in let finalizer_content = generate_release_statements_by_cls_meta type_def in if List.is_empty finalizer_content then None else Some { finalizer_name = name; finalizer_content; } and generate_gc_marker env name (type_def: Core_type.TypeDef.t) : Ir.Decl.gc_marker option = let generate_marker_fields type_def = let open Core_type.TypeDef in let cls_meta = Hashtbl.find_exn env.cls_meta_map type_def.id in List.filter_map ~f:(fun (field_name, ty_var) -> let field_type = Program.deref_node_type env.prog ty_var in if type_is_not_gc env field_type then None else Some field_name ) cls_meta.cls_fields in let fields = generate_marker_fields type_def in if List.is_empty fields then None else Some { gc_marker_name = name; gc_marker_field_names = fields; } and transform_enum env ~attributes enum loc : Ir.Decl.t list = let open Enum in let { elements; name = (enum_original_name, _); _ } = enum in env.current_fun_meta <- Some (create_current_fun_meta enum_original_name); let meta_id' = List.find_map ~f:(fun attr -> let open Lichenscript_parsing.Ast in if String.equal attr.attr_name.txt "meta_id" then ( match attr.attr_payload with | name::_ -> Some name | _ -> None ) else None ) attributes in let enum_name = "LCC_" ^ enum_original_name in let meta_id = match meta_id' with | Some v -> v | None -> enum_name ^ "_id" in let enum_members = ref [] in let result = elements |> List.mapi ~f:(fun index elm -> match elm with | Typedtree.Enum.Case case -> ( let case_name, case_name_id = case.case_name in let new_name = distribute_name env case_name in Hashtbl.set env.global_name_map ~key:case_name_id ~data:(SymLocal new_name); let enum_ctor_params_size = List.length case.case_fields in let spec = Ir.Decl.EnumCtor { enum_ctor_name = new_name; enum_ctor_meta_id = meta_id; enum_ctor_meta_name = enum_name; enum_ctor_tag_id = index; enum_ctor_params_size; } in enum_members := (case_name, enum_ctor_params_size)::(!enum_members); [{ Ir.Decl. spec; loc }] ) | Typedtree.Enum.Method _method -> distribute_name_to_class_method env enum_original_name _method; let stmts, _ = transform_class_method env _method in stmts ) |> List.concat in let enum_def = { Ir.Decl. enum_has_meta_id = Option.is_some meta_id'; enum_name; enum_original_name; enum_members = List.rev !enum_members; } in if Option.is_none meta_id' then ( env.class_inits <- (Ir.Decl.InitEnum enum_def)::env.class_inits ); env.current_fun_meta <- None; List.append [{ Ir.Decl. spec = Enum enum_def; loc = Loc.none; }] result and transform_lambda env ~lambda_name content _ty_var = let prev_fun_meta = env.current_fun_meta in env.current_fun_meta <- Some (create_current_fun_meta lambda_name); let lambda_gen_name = "LCC_" ^ lambda_name in let fake_block = { Block. body = [ { Statement. spec = Expr content.lambda_body; loc = Loc.none; attributes = []; } ]; scope = content.lambda_scope; loc = Loc.none; return_ty = content.lambda_body.ty_var; } in let _fun = transform_function_impl env ~name:(lambda_gen_name, Loc.none) ~params:content.lambda_params ~scope:content.lambda_scope ~body:fake_block ~comments:[] in let result = { Ir.Decl. spec = _fun; loc = Loc.none; } in env.current_fun_meta <- prev_fun_meta; result; type result = { main_function_name: string option; declarations: Ir.Decl.t list; global_class_init: string option; } let transform_declarations ~config ctx declarations = let env = create ~config ctx in let declarations = List.map ~f:(transform_declaration env) declarations |> List.concat in let declarations, global_class_init = if List.is_empty env.class_inits then declarations, None else ( let name = "LC_class_init" in (List.append declarations [{ Ir.Decl. spec = GlobalClassInit(name, List.rev env.class_inits); loc = Loc.none; }]), Some name ) in let prepends_decls = List.rev env.prepends_decls in env.prepends_decls <- []; { main_function_name = env.main_function_name; declarations = List.append prepends_decls declarations; global_class_init; }
8f38a7e2e21b0dd27597e50b53917bdc92992bfd812f50ec4a717c23a0701372
barrel-db/barrel
barrel_replicate_remote_SUITE.erl
%%%------------------------------------------------------------------- @author benoitc ( C ) 2017 , < COMPANY > %%% @doc %%% %%% @end Created : 29 . Jun 2017 15:46 %%%------------------------------------------------------------------- -module(barrel_replicate_remote_SUITE). -author("benoitc"). %% API %% API -export([ all/0, init_per_suite/1, end_per_suite/1, init_per_testcase/2, end_per_testcase/2 ]). -export([ one_doc/1 ]). all() -> [ one_doc ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(barrel), {ok, RemoteNode} = start_slave(barrel_test1), [{remote, RemoteNode} | Config]. end_per_suite(Config) -> ok = stop_slave(barrel_test1), Config. init_per_testcase(_, Config) -> {ok, _} = barrel:create_database(#{ <<"database_id">> => <<"sourcedb">> }), ok = create_remote_db(Config), Config. end_per_testcase(_, Config) -> ok = barrel:delete_database(<<"sourcedb">>), ok = delete_remote_db(Config), ok. one_doc(Config) -> TargetDb = target(Config), RepConfig = #{ source => <<"sourcedb">>, target => TargetDb, options => #{ metrics_freq => 100 } }, {ok, #{ id := RepId }} = barrel_replicate:start_replication(RepConfig), Doc = #{ <<"id">> => <<"a">>, <<"v">> => 1}, {ok, <<"a">>, _RevId} = barrel:post(<<"sourcedb">>, Doc, #{}), timer:sleep(200), {ok, Doc2, _} = barrel:get(<<"sourcedb">>, <<"a">>, #{}), {ok, Doc2, _} = barrel_replicate_api_wrapper:get(TargetDb, <<"a">>, #{}), ok = barrel_replicate:stop_replication(RepId), {ok, <<"a">>, _RevId_1} = delete_doc(<<"sourcedb">>, <<"a">>), {error, not_found} = delete_doc(TargetDb, <<"b">>), ok. %% ============================== %% internal helpers remote(Config) -> Remote = proplists:get_value(remote, Config), Remote. target(Config) -> Remote = proplists:get_value(remote, Config), {Remote, <<"targetdb">>}. start_slave(Node) -> {ok, HostNode} = ct_slave:start(Node, [{kill_if_fail, true}, {monitor_master, true}, {init_timeout, 3000}, {startup_timeout, 3000}]), pong = net_adm:ping(HostNode), CodePath = filter_rebar_path(code:get_path()), true = rpc:call(HostNode, code, set_path, [CodePath]), {ok,_} = rpc:call(HostNode, application, ensure_all_started, [barrel]), ct:print("\e[32m ---> Node ~p [OK] \e[0m", [HostNode]), {ok, HostNode}. stop_slave(Node) -> {ok, _} = ct_slave:stop(Node), ok. create_remote_db(Config) -> {ok, _} = rpc:call( remote(Config), barrel, create_database, [#{ <<"database_id">> => <<"targetdb">>}] ), ok. delete_remote_db(Config) -> rpc:call(remote(Config), barrel, delete_database, [<<"targetdb">>] ). %% a hack to filter rebar path %% see filter_rebar_path(CodePath) -> lists:filter( fun(P) -> case string:str(P, "rebar3") of 0 -> true; _ -> false end end, CodePath ). delete_doc({Node, DbName}, DocId) -> [Res] = barrel_rpc:update_docs(Node, DbName, [{delete, DocId}], #{}), Res; delete_doc(Db, DocId) -> barrel:delete(Db, DocId, #{}).
null
https://raw.githubusercontent.com/barrel-db/barrel/1695ca4cfe821808526f9ecb2e019bc1b8eff48e/test/barrel_replicate_remote_SUITE.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API API ============================== internal helpers a hack to filter rebar path see
@author benoitc ( C ) 2017 , < COMPANY > Created : 29 . Jun 2017 15:46 -module(barrel_replicate_remote_SUITE). -author("benoitc"). -export([ all/0, init_per_suite/1, end_per_suite/1, init_per_testcase/2, end_per_testcase/2 ]). -export([ one_doc/1 ]). all() -> [ one_doc ]. init_per_suite(Config) -> {ok, _} = application:ensure_all_started(barrel), {ok, RemoteNode} = start_slave(barrel_test1), [{remote, RemoteNode} | Config]. end_per_suite(Config) -> ok = stop_slave(barrel_test1), Config. init_per_testcase(_, Config) -> {ok, _} = barrel:create_database(#{ <<"database_id">> => <<"sourcedb">> }), ok = create_remote_db(Config), Config. end_per_testcase(_, Config) -> ok = barrel:delete_database(<<"sourcedb">>), ok = delete_remote_db(Config), ok. one_doc(Config) -> TargetDb = target(Config), RepConfig = #{ source => <<"sourcedb">>, target => TargetDb, options => #{ metrics_freq => 100 } }, {ok, #{ id := RepId }} = barrel_replicate:start_replication(RepConfig), Doc = #{ <<"id">> => <<"a">>, <<"v">> => 1}, {ok, <<"a">>, _RevId} = barrel:post(<<"sourcedb">>, Doc, #{}), timer:sleep(200), {ok, Doc2, _} = barrel:get(<<"sourcedb">>, <<"a">>, #{}), {ok, Doc2, _} = barrel_replicate_api_wrapper:get(TargetDb, <<"a">>, #{}), ok = barrel_replicate:stop_replication(RepId), {ok, <<"a">>, _RevId_1} = delete_doc(<<"sourcedb">>, <<"a">>), {error, not_found} = delete_doc(TargetDb, <<"b">>), ok. remote(Config) -> Remote = proplists:get_value(remote, Config), Remote. target(Config) -> Remote = proplists:get_value(remote, Config), {Remote, <<"targetdb">>}. start_slave(Node) -> {ok, HostNode} = ct_slave:start(Node, [{kill_if_fail, true}, {monitor_master, true}, {init_timeout, 3000}, {startup_timeout, 3000}]), pong = net_adm:ping(HostNode), CodePath = filter_rebar_path(code:get_path()), true = rpc:call(HostNode, code, set_path, [CodePath]), {ok,_} = rpc:call(HostNode, application, ensure_all_started, [barrel]), ct:print("\e[32m ---> Node ~p [OK] \e[0m", [HostNode]), {ok, HostNode}. stop_slave(Node) -> {ok, _} = ct_slave:stop(Node), ok. create_remote_db(Config) -> {ok, _} = rpc:call( remote(Config), barrel, create_database, [#{ <<"database_id">> => <<"targetdb">>}] ), ok. delete_remote_db(Config) -> rpc:call(remote(Config), barrel, delete_database, [<<"targetdb">>] ). filter_rebar_path(CodePath) -> lists:filter( fun(P) -> case string:str(P, "rebar3") of 0 -> true; _ -> false end end, CodePath ). delete_doc({Node, DbName}, DocId) -> [Res] = barrel_rpc:update_docs(Node, DbName, [{delete, DocId}], #{}), Res; delete_doc(Db, DocId) -> barrel:delete(Db, DocId, #{}).
4ae7dda30f9f415b00b91d0a3e86b647f5001d12b3014557ce2c70eb710c68d2
PacktWorkshops/The-Clojure-Workshop
repl.clj
;;; In REPL from Exercise 4.06 (def game-users [{:id 9342 :username "speedy" :current-points 45 :remaining-lives 2 :experience-level 5 :status :active} {:id 9854 :username "stealthy" :current-points 1201 :remaining-lives 1 :experience-level 8 :status :speed-boost} {:id 3014 :username "sneaky" :current-points 725 :remaining-lives 7 :experience-level 3 :status :active} {:id 2051 :username "forgetful" :current-points 89 :remaining-lives 4 :experience-level 5 :status :imprisoned} {:id 1032 :username "wandering" :current-points 2043 :remaining-lives 12 :experience-level 7 :status :speed-boost} {:id 7213 :username "slowish" :current-points 143 :remaining-lives 0 :experience-level 1 :status :speed-boost} {:id 5633 :username "smarter" :current-points 99 :remaining-lives 4 :experience-level 4 :status :terminated} {:id 3954 :username "crafty" :current-points 21 :remaining-lives 2 :experience-level 8 :status :active} {:id 7213 :username "smarty" :current-points 290 :remaining-lives 5 :experience-level 12 :status :terminated} {:id 3002 :username "clever" :current-points 681 :remaining-lives 1 :experience-level 8 :status :active}]) ;;; In REPL (def keep-statuses #{:active :imprisoned :speed-boost}) (filter (fn [player] (keep-statuses (:status player))) game-users) (->> game-users (filter (comp #{:active :imprisoned :speed-boost} :status)) (map :current-points))
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter04/Exercise4.07/repl.clj
clojure
In REPL In REPL
from Exercise 4.06 (def game-users [{:id 9342 :username "speedy" :current-points 45 :remaining-lives 2 :experience-level 5 :status :active} {:id 9854 :username "stealthy" :current-points 1201 :remaining-lives 1 :experience-level 8 :status :speed-boost} {:id 3014 :username "sneaky" :current-points 725 :remaining-lives 7 :experience-level 3 :status :active} {:id 2051 :username "forgetful" :current-points 89 :remaining-lives 4 :experience-level 5 :status :imprisoned} {:id 1032 :username "wandering" :current-points 2043 :remaining-lives 12 :experience-level 7 :status :speed-boost} {:id 7213 :username "slowish" :current-points 143 :remaining-lives 0 :experience-level 1 :status :speed-boost} {:id 5633 :username "smarter" :current-points 99 :remaining-lives 4 :experience-level 4 :status :terminated} {:id 3954 :username "crafty" :current-points 21 :remaining-lives 2 :experience-level 8 :status :active} {:id 7213 :username "smarty" :current-points 290 :remaining-lives 5 :experience-level 12 :status :terminated} {:id 3002 :username "clever" :current-points 681 :remaining-lives 1 :experience-level 8 :status :active}]) (def keep-statuses #{:active :imprisoned :speed-boost}) (filter (fn [player] (keep-statuses (:status player))) game-users) (->> game-users (filter (comp #{:active :imprisoned :speed-boost} :status)) (map :current-points))
497e584ef79936b3cd4738412c9811aa1c50752b89f9292da5e442dcd133f53a
TorXakis/TorXakis
TExprLinearization.hs
TorXakis - Model Based Testing Copyright ( c ) 2015 - 2017 TNO and University of Twente See LICENSE at root directory of this repository . TorXakis - Model Based Testing Copyright (c) 2015-2017 TNO and University of Twente See LICENSE at root directory of this repository. -} ----------------------------------------------------------------------------- -- | -- Module : TExprLinearization Copyright : TNO and University of Twente -- License : BSD3 -- Maintainer : -- Stability : experimental -- ----------------------------------------------------------------------------- # LANGUAGE ViewPatterns # module TExprLinearization ( linearizeTExprs ) where import qualified Data.Map as Map import qualified Data.Set as Set import qualified Control.Monad as Monad import qualified EnvCore as IOC import qualified TxsDefs import qualified TxsShow import qualified ProcId import qualified ProcDef import qualified SortOf import BehExprDefs import ProcIdFactory import ProcDepTree import qualified ProcInstUpdates import HideElim import BranchLinearityUtils import PrefixResolution import ProcSearch import qualified LinearizeParallel import qualified LinearizeEnable import qualified LinearizeDisable import qualified LinearizeInterrupt linearizeTExprs :: TxsDefs.BExpr -> IOC.IOC TxsDefs.BExpr linearizeTExprs bexpr = do procDepTree <- getProcDepTree bexpr let orderedProcs = getProcsOrderedByMaxDepth procDepTree procInstUpdateMap <- Monad.foldM linearizeTExprsInProc Map.empty orderedProcs return (ProcInstUpdates.applyMapToProcInst procInstUpdateMap bexpr) -- linearizeTExprs linearizeTExprsInProc :: ProcInstUpdates.ProcInstUpdateMap -> ProcId.ProcId -> IOC.IOC ProcInstUpdates.ProcInstUpdateMap linearizeTExprsInProc procInstUpdateMap pid = do IOC.putInfo [ "Linearizing " ++ showProcId pid ++ "..." ] -- printProcsInBody ("Current form of " ++ showProcId pid ++ " ====>") pid r <- getProcById pid case r of Just (ProcDef.ProcDef cidDecls vidDecls body) -> do -- Function to be used for the instantiation of the linearized process: let createProcInst = procInst pid cidDecls Distinguish linear branches in the body that are finished from non - linear branches (= branches with thread expressions ): let (nlbranches, lbranches) = Set.partition isNonLinearBranch (getBranches body) Linearize non - linear branches : let tempProcInstUpdateMap = ProcInstUpdates.addToMap procInstUpdateMap pid (ProcInstUpdates.createIdentical pid) rs <- Monad.mapM (linearizeTExpr createProcInst tempProcInstUpdateMap) (Set.toList nlbranches) -- Check if the result is linear. IT SHOULD BE LINEAR! checkLinearBExprs pid (Set.toList nlbranches) (Set.toList (Set.unions (map lrBranches rs))) let newVids = concatMap lrParams rs let newVidDecls = vidDecls ++ newVids let newPredefInits = Map.unions (map lrPredefInits rs) -- Replace process instantiations in branches that were just linearized. -- (Currently, they probably are incorrect because they only set newly introduced variables.) newProcId <- createFreshProcIdWithDifferentVars pid (map SortOf.sortOf newVidDecls) newPBranches <- Set.unions <$> Monad.mapM (ProcInstUpdates.createAndApply pid newProcId newVidDecls) rs -- Replace instantiations of the current process in branches that were already finished. -- Remember how such instantiations should be updated, for later use. newProcInstUpdate <- ProcInstUpdates.create newProcId vidDecls newVidDecls newPredefInits let newProcInstUpdateMap = ProcInstUpdates.addToMap procInstUpdateMap pid newProcInstUpdate let newNPBranches = Set.map (ProcInstUpdates.applyMapToBExpr newProcInstUpdateMap) lbranches -- Newly produced branches may not have an action prefix. -- Therefore, do another round of prefix resolution, and -- register the process with a new body constructed from the new branches. let newBranches = Set.union newNPBranches newPBranches newBody <- resolveProcPrefixesInBody newProcId cidDecls newVidDecls (choice newBranches) registerProc newProcId (ProcDef.ProcDef cidDecls newVidDecls newBody) -- Check if the result is linear. IT SHOULD BE LINEAR! checkLinearBExprs newProcId (Set.toList newBranches) (Set.toList (getBranches newBody)) (_newProcId', newProcInstUpdateMap') <- eliminateHide (newProcId, newProcInstUpdateMap) -- printProcsInBody "AFTER HIDE ------> " newProcId' return newProcInstUpdateMap' Nothing -> error ("Unknown process (\"" ++ TxsShow.fshow pid ++ "\")!") -- linearizeTExprsInProc linearizeTExpr :: ([TxsDefs.VExpr] -> TxsDefs.BExpr) -> ProcInstUpdates.ProcInstUpdateMap -> TxsDefs.BExpr -> IOC.IOC TExprLinResult linearizeTExpr createProcInst procInstUpdateMap currentBExpr = let remappedBExpr = ProcInstUpdates.applyMapToBExpr procInstUpdateMap currentBExpr in case remappedBExpr of (TxsDefs.view -> Hide cidSet bexpr) -> do linResult <- linearizeNonHideTExpr createProcInst bexpr return (linResult { lrBranches = Set.map (applyHide cidSet) (lrBranches linResult) }) _ -> linearizeNonHideTExpr createProcInst remappedBExpr -- linearizeTExpr linearizeNonHideTExpr :: ([TxsDefs.VExpr] -> TxsDefs.BExpr) -> TxsDefs.BExpr -> IOC.IOC TExprLinResult linearizeNonHideTExpr createProcInst currentBExpr = case currentBExpr of (TxsDefs.view -> Guard g bexpr) -> case bexpr of (TxsDefs.view -> Parallel {}) -> LinearizeParallel.linearize createProcInst g bexpr (TxsDefs.view -> Enable {}) -> LinearizeEnable.linearize createProcInst g bexpr (TxsDefs.view -> Disable {}) -> LinearizeDisable.linearize createProcInst g bexpr (TxsDefs.view -> Interrupt {}) -> LinearizeInterrupt.linearize createProcInst g bexpr _ -> error ("No implementation yet for \"" ++ show currentBExpr ++ "\"!") _ -> error ("Behavioral expression not accounted for (\"" ++ TxsShow.fshow currentBExpr ++ "\")!")
null
https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/sys/lpeq/src/preparation/TExprLinearization.hs
haskell
--------------------------------------------------------------------------- | Module : TExprLinearization License : BSD3 Maintainer : Stability : experimental --------------------------------------------------------------------------- linearizeTExprs printProcsInBody ("Current form of " ++ showProcId pid ++ " ====>") pid Function to be used for the instantiation of the linearized process: Check if the result is linear. IT SHOULD BE LINEAR! Replace process instantiations in branches that were just linearized. (Currently, they probably are incorrect because they only set newly introduced variables.) Replace instantiations of the current process in branches that were already finished. Remember how such instantiations should be updated, for later use. Newly produced branches may not have an action prefix. Therefore, do another round of prefix resolution, and register the process with a new body constructed from the new branches. Check if the result is linear. IT SHOULD BE LINEAR! printProcsInBody "AFTER HIDE ------> " newProcId' linearizeTExprsInProc linearizeTExpr
TorXakis - Model Based Testing Copyright ( c ) 2015 - 2017 TNO and University of Twente See LICENSE at root directory of this repository . TorXakis - Model Based Testing Copyright (c) 2015-2017 TNO and University of Twente See LICENSE at root directory of this repository. -} Copyright : TNO and University of Twente # LANGUAGE ViewPatterns # module TExprLinearization ( linearizeTExprs ) where import qualified Data.Map as Map import qualified Data.Set as Set import qualified Control.Monad as Monad import qualified EnvCore as IOC import qualified TxsDefs import qualified TxsShow import qualified ProcId import qualified ProcDef import qualified SortOf import BehExprDefs import ProcIdFactory import ProcDepTree import qualified ProcInstUpdates import HideElim import BranchLinearityUtils import PrefixResolution import ProcSearch import qualified LinearizeParallel import qualified LinearizeEnable import qualified LinearizeDisable import qualified LinearizeInterrupt linearizeTExprs :: TxsDefs.BExpr -> IOC.IOC TxsDefs.BExpr linearizeTExprs bexpr = do procDepTree <- getProcDepTree bexpr let orderedProcs = getProcsOrderedByMaxDepth procDepTree procInstUpdateMap <- Monad.foldM linearizeTExprsInProc Map.empty orderedProcs return (ProcInstUpdates.applyMapToProcInst procInstUpdateMap bexpr) linearizeTExprsInProc :: ProcInstUpdates.ProcInstUpdateMap -> ProcId.ProcId -> IOC.IOC ProcInstUpdates.ProcInstUpdateMap linearizeTExprsInProc procInstUpdateMap pid = do IOC.putInfo [ "Linearizing " ++ showProcId pid ++ "..." ] r <- getProcById pid case r of Just (ProcDef.ProcDef cidDecls vidDecls body) -> do let createProcInst = procInst pid cidDecls Distinguish linear branches in the body that are finished from non - linear branches (= branches with thread expressions ): let (nlbranches, lbranches) = Set.partition isNonLinearBranch (getBranches body) Linearize non - linear branches : let tempProcInstUpdateMap = ProcInstUpdates.addToMap procInstUpdateMap pid (ProcInstUpdates.createIdentical pid) rs <- Monad.mapM (linearizeTExpr createProcInst tempProcInstUpdateMap) (Set.toList nlbranches) checkLinearBExprs pid (Set.toList nlbranches) (Set.toList (Set.unions (map lrBranches rs))) let newVids = concatMap lrParams rs let newVidDecls = vidDecls ++ newVids let newPredefInits = Map.unions (map lrPredefInits rs) newProcId <- createFreshProcIdWithDifferentVars pid (map SortOf.sortOf newVidDecls) newPBranches <- Set.unions <$> Monad.mapM (ProcInstUpdates.createAndApply pid newProcId newVidDecls) rs newProcInstUpdate <- ProcInstUpdates.create newProcId vidDecls newVidDecls newPredefInits let newProcInstUpdateMap = ProcInstUpdates.addToMap procInstUpdateMap pid newProcInstUpdate let newNPBranches = Set.map (ProcInstUpdates.applyMapToBExpr newProcInstUpdateMap) lbranches let newBranches = Set.union newNPBranches newPBranches newBody <- resolveProcPrefixesInBody newProcId cidDecls newVidDecls (choice newBranches) registerProc newProcId (ProcDef.ProcDef cidDecls newVidDecls newBody) checkLinearBExprs newProcId (Set.toList newBranches) (Set.toList (getBranches newBody)) (_newProcId', newProcInstUpdateMap') <- eliminateHide (newProcId, newProcInstUpdateMap) return newProcInstUpdateMap' Nothing -> error ("Unknown process (\"" ++ TxsShow.fshow pid ++ "\")!") linearizeTExpr :: ([TxsDefs.VExpr] -> TxsDefs.BExpr) -> ProcInstUpdates.ProcInstUpdateMap -> TxsDefs.BExpr -> IOC.IOC TExprLinResult linearizeTExpr createProcInst procInstUpdateMap currentBExpr = let remappedBExpr = ProcInstUpdates.applyMapToBExpr procInstUpdateMap currentBExpr in case remappedBExpr of (TxsDefs.view -> Hide cidSet bexpr) -> do linResult <- linearizeNonHideTExpr createProcInst bexpr return (linResult { lrBranches = Set.map (applyHide cidSet) (lrBranches linResult) }) _ -> linearizeNonHideTExpr createProcInst remappedBExpr linearizeNonHideTExpr :: ([TxsDefs.VExpr] -> TxsDefs.BExpr) -> TxsDefs.BExpr -> IOC.IOC TExprLinResult linearizeNonHideTExpr createProcInst currentBExpr = case currentBExpr of (TxsDefs.view -> Guard g bexpr) -> case bexpr of (TxsDefs.view -> Parallel {}) -> LinearizeParallel.linearize createProcInst g bexpr (TxsDefs.view -> Enable {}) -> LinearizeEnable.linearize createProcInst g bexpr (TxsDefs.view -> Disable {}) -> LinearizeDisable.linearize createProcInst g bexpr (TxsDefs.view -> Interrupt {}) -> LinearizeInterrupt.linearize createProcInst g bexpr _ -> error ("No implementation yet for \"" ++ show currentBExpr ++ "\"!") _ -> error ("Behavioral expression not accounted for (\"" ++ TxsShow.fshow currentBExpr ++ "\")!")
18a08e6e6ab9553d169e9aa84254c25d062fe94fd698ca5b6247e0f34e389ff5
escherize/defrag
specs.clj
(ns defrag.specs (:require [clojure.spec.alpha :as s])) ;;; This ns coppied from clojure.core.specs.alpha 0.2.44, with slight modifications ;;;; destructure (s/def ::local-name (s/and simple-symbol? #(not= '& %))) (s/def ::binding-form (s/or :local-symbol ::local-name :seq-destructure ::seq-binding-form :map-destructure ::map-binding-form)) ;; sequential destructuring (s/def ::seq-binding-form (s/and vector? (s/conformer identity vec) (s/cat :elems (s/* ::binding-form) :rest (s/? (s/cat :amp #{'&} :form ::binding-form)) :as (s/? (s/cat :as #{:as} :sym ::local-name))))) ;; map destructuring (s/def ::keys (s/coll-of ident? :kind vector?)) (s/def ::syms (s/coll-of symbol? :kind vector?)) (s/def ::strs (s/coll-of simple-symbol? :kind vector?)) (s/def ::or (s/map-of simple-symbol? any?)) (s/def ::as ::local-name) (s/def ::map-special-binding (s/keys :opt-un [::as ::or ::keys ::syms ::strs])) (s/def ::map-binding (s/tuple ::binding-form any?)) (s/def ::ns-keys (s/tuple (s/and qualified-keyword? #(-> % name #{"keys" "syms"})) (s/coll-of simple-symbol? :kind vector?))) (s/def ::map-bindings (s/every (s/or :map-binding ::map-binding :qualified-keys-or-syms ::ns-keys :special-binding (s/tuple #{:as :or :keys :syms :strs} any?)) :kind map?)) (s/def ::map-binding-form (s/merge ::map-bindings ::map-special-binding)) ;; bindings (defn even-number-of-forms? "Returns true if there are an even number of forms in a binding vector" [forms] (even? (count forms))) (s/def ::binding (s/cat :form ::binding-form :init-expr any?)) (s/def ::bindings (s/and vector? even-number-of-forms? (s/* ::binding))) ;; defn, defn-, fn (defn arg-list-unformer [a] (vec (if (and (coll? (last a)) (= '& (first (last a)))) (concat (drop-last a) (last a)) a))) (s/def ::param-list (s/and vector? (s/conformer identity arg-list-unformer) (s/cat :args (s/* ::binding-form) :varargs (s/? (s/cat :amp #{'&} :form ::binding-form))))) (s/def ::params+body (s/cat :params ::param-list :body (s/alt :prepost+body (s/cat :prepost map? :body (s/+ any?)) :body (s/* any?)))) (s/def ::defn-args (s/cat :fn-name simple-symbol? :docstring (s/? string?) :meta (s/? map?) :fn-tail (s/alt :arity-1 ::params+body :arity-n (s/cat :bodies (s/+ (s/spec ::params+body)) :attr-map (s/? map?))))) ;; (s/fdef clojure.core/defn ;; :args ::defn-args : ret any ? ) ;; (s/fdef clojure.core/defn- ;; :args ::defn-args : ret any ? ) ;; (s/fdef clojure.core/fn : args ( s / cat : fn - name ( s/ ? simple - symbol ? ) : fn - tail ( s / alt : arity-1 : : : arity - n ( s/+ ( s / spec : : ) ) ) ) : ret any ? )
null
https://raw.githubusercontent.com/escherize/defrag/385158007ea9af19db6e6f4edc936a1816bbec7d/src/defrag/specs.clj
clojure
This ns coppied from clojure.core.specs.alpha 0.2.44, with slight modifications destructure sequential destructuring map destructuring bindings defn, defn-, fn (s/fdef clojure.core/defn :args ::defn-args (s/fdef clojure.core/defn- :args ::defn-args (s/fdef clojure.core/fn
(ns defrag.specs (:require [clojure.spec.alpha :as s])) (s/def ::local-name (s/and simple-symbol? #(not= '& %))) (s/def ::binding-form (s/or :local-symbol ::local-name :seq-destructure ::seq-binding-form :map-destructure ::map-binding-form)) (s/def ::seq-binding-form (s/and vector? (s/conformer identity vec) (s/cat :elems (s/* ::binding-form) :rest (s/? (s/cat :amp #{'&} :form ::binding-form)) :as (s/? (s/cat :as #{:as} :sym ::local-name))))) (s/def ::keys (s/coll-of ident? :kind vector?)) (s/def ::syms (s/coll-of symbol? :kind vector?)) (s/def ::strs (s/coll-of simple-symbol? :kind vector?)) (s/def ::or (s/map-of simple-symbol? any?)) (s/def ::as ::local-name) (s/def ::map-special-binding (s/keys :opt-un [::as ::or ::keys ::syms ::strs])) (s/def ::map-binding (s/tuple ::binding-form any?)) (s/def ::ns-keys (s/tuple (s/and qualified-keyword? #(-> % name #{"keys" "syms"})) (s/coll-of simple-symbol? :kind vector?))) (s/def ::map-bindings (s/every (s/or :map-binding ::map-binding :qualified-keys-or-syms ::ns-keys :special-binding (s/tuple #{:as :or :keys :syms :strs} any?)) :kind map?)) (s/def ::map-binding-form (s/merge ::map-bindings ::map-special-binding)) (defn even-number-of-forms? "Returns true if there are an even number of forms in a binding vector" [forms] (even? (count forms))) (s/def ::binding (s/cat :form ::binding-form :init-expr any?)) (s/def ::bindings (s/and vector? even-number-of-forms? (s/* ::binding))) (defn arg-list-unformer [a] (vec (if (and (coll? (last a)) (= '& (first (last a)))) (concat (drop-last a) (last a)) a))) (s/def ::param-list (s/and vector? (s/conformer identity arg-list-unformer) (s/cat :args (s/* ::binding-form) :varargs (s/? (s/cat :amp #{'&} :form ::binding-form))))) (s/def ::params+body (s/cat :params ::param-list :body (s/alt :prepost+body (s/cat :prepost map? :body (s/+ any?)) :body (s/* any?)))) (s/def ::defn-args (s/cat :fn-name simple-symbol? :docstring (s/? string?) :meta (s/? map?) :fn-tail (s/alt :arity-1 ::params+body :arity-n (s/cat :bodies (s/+ (s/spec ::params+body)) :attr-map (s/? map?))))) : ret any ? ) : ret any ? ) : args ( s / cat : fn - name ( s/ ? simple - symbol ? ) : fn - tail ( s / alt : arity-1 : : : arity - n ( s/+ ( s / spec : : ) ) ) ) : ret any ? )
d1f3b2b73fb4d4fb1a4ffd10590b3a85729edaf79c18d666f69d4004d077e3ff
vlstill/hsExprTest
Union.hs
# LANGUAGE DataKinds , ScopedTypeVariables , TypeFamilies , MultiParamTypeClasses , FlexibleInstances , UndecidableInstances , ConstraintKinds , PolyKinds , FlexibleContexts , TypeOperators , UnicodeSyntax # ScopedTypeVariables, TypeFamilies, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, ConstraintKinds, PolyKinds, FlexibleContexts, TypeOperators, UnicodeSyntax #-} module Test.QuickCheck.Union ( Union ( Union ) ) where import Data.Coerce ( Coercible, coerce ) import Data.Proxy import Data.Kind ( Type, Constraint ) import Test.QuickCheck ( Arbitrary, Gen, arbitrary, shrink, frequency ) import GHC.TypeLits newtype Union (target :: Type) (alternatives :: [Type]) = Union target class AllConstraint (cs :: Type -> Constraint) (alt :: [Type]) where instance ∀ (cs :: Type -> Constraint). AllConstraint cs '[] instance ∀ (cs :: Type -> Constraint) (a :: Type) (as :: [Type]). (cs a, AllConstraint cs as) => AllConstraint cs (a ': as) class TypeListLenght (xs :: [κ]) where type ListLenght (xs :: [κ]) :: Nat typeListLength :: ∀ κ (xs :: [κ]) proxy. (TypeListLenght xs, KnownNat (ListLenght xs)) => proxy xs -> Int typeListLength _ = fromInteger (natVal (Proxy :: Proxy (ListLenght xs))) instance TypeListLenght '[] where type ListLenght '[] = 0 instance ∀ κ (x :: κ) (xs :: [κ]). TypeListLenght xs => TypeListLenght (x ': xs) where type ListLenght (x ': xs) = 1 + ListLenght xs instance (Show target, AllConstraint (Coercible target) alternatives) => Show (Union target alternatives) where show (Union x) = show x instance {-# OVERLAPPING #-} ∀ target alt. (Coercible target alt, Arbitrary alt) => Arbitrary (Union target '[alt]) where arbitrary = coerce <$> (arbitrary :: Gen alt) shrink x = coerce <$> shrink (coerce x :: alt) instance {-# OVERLAPPING #-} ∀ target alt (as :: [Type]). (TypeListLenght as, KnownNat (ListLenght as), 1 <= ListLenght as, Coercible target alt, Arbitrary alt, Arbitrary (Union target as)) => Arbitrary (Union target (alt ': as)) where arbitrary = frequency [(1, coerce <$> (arbitrary :: Gen alt)), (typeListLength (Proxy :: Proxy as), coerce <$> (arbitrary :: Gen (Union target as)))] shrink _ = []
null
https://raw.githubusercontent.com/vlstill/hsExprTest/0c7754979cf837d48f5740674639e2decb96e547/testlib/Test/QuickCheck/Union.hs
haskell
# OVERLAPPING # # OVERLAPPING #
# LANGUAGE DataKinds , ScopedTypeVariables , TypeFamilies , MultiParamTypeClasses , FlexibleInstances , UndecidableInstances , ConstraintKinds , PolyKinds , FlexibleContexts , TypeOperators , UnicodeSyntax # ScopedTypeVariables, TypeFamilies, MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, ConstraintKinds, PolyKinds, FlexibleContexts, TypeOperators, UnicodeSyntax #-} module Test.QuickCheck.Union ( Union ( Union ) ) where import Data.Coerce ( Coercible, coerce ) import Data.Proxy import Data.Kind ( Type, Constraint ) import Test.QuickCheck ( Arbitrary, Gen, arbitrary, shrink, frequency ) import GHC.TypeLits newtype Union (target :: Type) (alternatives :: [Type]) = Union target class AllConstraint (cs :: Type -> Constraint) (alt :: [Type]) where instance ∀ (cs :: Type -> Constraint). AllConstraint cs '[] instance ∀ (cs :: Type -> Constraint) (a :: Type) (as :: [Type]). (cs a, AllConstraint cs as) => AllConstraint cs (a ': as) class TypeListLenght (xs :: [κ]) where type ListLenght (xs :: [κ]) :: Nat typeListLength :: ∀ κ (xs :: [κ]) proxy. (TypeListLenght xs, KnownNat (ListLenght xs)) => proxy xs -> Int typeListLength _ = fromInteger (natVal (Proxy :: Proxy (ListLenght xs))) instance TypeListLenght '[] where type ListLenght '[] = 0 instance ∀ κ (x :: κ) (xs :: [κ]). TypeListLenght xs => TypeListLenght (x ': xs) where type ListLenght (x ': xs) = 1 + ListLenght xs instance (Show target, AllConstraint (Coercible target) alternatives) => Show (Union target alternatives) where show (Union x) = show x ∀ target alt. (Coercible target alt, Arbitrary alt) => Arbitrary (Union target '[alt]) where arbitrary = coerce <$> (arbitrary :: Gen alt) shrink x = coerce <$> shrink (coerce x :: alt) ∀ target alt (as :: [Type]). (TypeListLenght as, KnownNat (ListLenght as), 1 <= ListLenght as, Coercible target alt, Arbitrary alt, Arbitrary (Union target as)) => Arbitrary (Union target (alt ': as)) where arbitrary = frequency [(1, coerce <$> (arbitrary :: Gen alt)), (typeListLength (Proxy :: Proxy as), coerce <$> (arbitrary :: Gen (Union target as)))] shrink _ = []
78e513bc0a69bdd7dd9ecc72aab677ced1418d928e42c687670c7b0eb59821d5
adamwynne/twitter-api
creds.clj
(ns twitter.test.creds (:require [twitter.oauth :refer [make-oauth-creds]])) (defn assert-get "get a value from the environment, otherwise throw an exception detailing the problem" [key-name] (or (System/getenv key-name) (throw (Exception. (format "please define %s in the test environment" key-name))))) (def ^:dynamic *app-consumer-key* (assert-get "CONSUMER_KEY")) (def ^:dynamic *app-consumer-secret* (assert-get "CONSUMER_SECRET")) (def ^:dynamic *user-screen-name* (assert-get "SCREEN_NAME")) (def ^:dynamic *user-access-token* (assert-get "ACCESS_TOKEN")) (def ^:dynamic *user-access-token-secret* (assert-get "ACCESS_TOKEN_SECRET")) (defn make-test-creds "makes an Oauth structure that uses an app's credentials and a users's credentials" [] (make-oauth-creds *app-consumer-key* *app-consumer-secret* *user-access-token* *user-access-token-secret*)) (defn make-app-only-test-creds "makes an Oauth structure that uses only an app's credentials" [] (make-oauth-creds *app-consumer-key* *app-consumer-secret*))
null
https://raw.githubusercontent.com/adamwynne/twitter-api/6443d1c8ed7d6b6cc9f5efaa5fd9c7cc176e80f0/test/twitter/test/creds.clj
clojure
(ns twitter.test.creds (:require [twitter.oauth :refer [make-oauth-creds]])) (defn assert-get "get a value from the environment, otherwise throw an exception detailing the problem" [key-name] (or (System/getenv key-name) (throw (Exception. (format "please define %s in the test environment" key-name))))) (def ^:dynamic *app-consumer-key* (assert-get "CONSUMER_KEY")) (def ^:dynamic *app-consumer-secret* (assert-get "CONSUMER_SECRET")) (def ^:dynamic *user-screen-name* (assert-get "SCREEN_NAME")) (def ^:dynamic *user-access-token* (assert-get "ACCESS_TOKEN")) (def ^:dynamic *user-access-token-secret* (assert-get "ACCESS_TOKEN_SECRET")) (defn make-test-creds "makes an Oauth structure that uses an app's credentials and a users's credentials" [] (make-oauth-creds *app-consumer-key* *app-consumer-secret* *user-access-token* *user-access-token-secret*)) (defn make-app-only-test-creds "makes an Oauth structure that uses only an app's credentials" [] (make-oauth-creds *app-consumer-key* *app-consumer-secret*))
91648a20337ce0f500870eb4091868e358f3f6b78ca03fd0ce9ae67c4258d759
haskell/cabal
Dependency.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # module Distribution.Types.Dependency ( Dependency(..) , mkDependency , depPkgName , depVerRange , depLibraries , simplifyDependency , mainLibSet ) where import Distribution.Compat.Prelude import Prelude () import Distribution.Types.VersionRange (isAnyVersionLight) import Distribution.Version (VersionRange, anyVersion, simplifyVersionRange) import Distribution.CabalSpecVersion import Distribution.Compat.CharParsing (char, spaces) import Distribution.Compat.Parsing (between, option) import Distribution.Parsec import Distribution.Pretty import Distribution.Types.LibraryName import Distribution.Types.PackageName import Distribution.Types.UnqualComponentName import qualified Distribution.Compat.NonEmptySet as NES import qualified Text.PrettyPrint as PP -- | Describes a dependency on a source package (API) -- /Invariant:/ package name does not appear as ' ' in -- set of library names. -- /Note:/ ' Dependency ' is not an instance of ' ' , and so it can not be used -- in 'Set' or as the key to a 'Map'. For these and similar use cases see ' ' . -- data Dependency = Dependency PackageName VersionRange (NonEmptySet LibraryName) -- ^ The set of libraries required from the package. -- Only the selected libraries will be built. -- It does not affect the cabal-install solver yet. deriving (Generic, Read, Show, Eq, Ord, Typeable, Data) depPkgName :: Dependency -> PackageName depPkgName (Dependency pn _ _) = pn depVerRange :: Dependency -> VersionRange depVerRange (Dependency _ vr _) = vr depLibraries :: Dependency -> NonEmptySet LibraryName depLibraries (Dependency _ _ cs) = cs -- | Smart constructor of 'Dependency'. -- If ' PackageName ' is appears as ' ' in a set of sublibraries , -- it is automatically converted to 'LMainLibName'. -- -- @since 3.4.0.0 -- mkDependency :: PackageName -> VersionRange -> NonEmptySet LibraryName -> Dependency mkDependency pn vr lb = Dependency pn vr (NES.map conv lb) where pn' = packageNameToUnqualComponentName pn conv l@LMainLibName = l conv l@(LSubLibName ln) | ln == pn' = LMainLibName | otherwise = l instance Binary Dependency instance Structured Dependency instance NFData Dependency where rnf = genericRnf -- | -- -- >>> prettyShow $ Dependency "pkg" anyVersion mainLibSet -- "pkg" -- > > > prettyShow $ Dependency " pkg " anyVersion $ NES.insert ( " sublib " ) mainLibSet -- "pkg:{pkg, sublib}" -- > > > prettyShow $ Dependency " pkg " anyVersion $ NES.singleton ( " sublib " ) -- "pkg:sublib" -- > > > prettyShow $ Dependency " pkg " anyVersion $ NES.insert ( " sublib - b " ) $ NES.singleton ( " sublib - a " ) " pkg:{sublib - a , sublib - b } " -- instance Pretty Dependency where pretty (Dependency name ver sublibs) = withSubLibs (pretty name) <+> pver where TODO : change to isAnyVersion after # 6736 pver | isAnyVersionLight ver = PP.empty | otherwise = pretty ver withSubLibs doc = case NES.toList sublibs of [LMainLibName] -> doc [LSubLibName uq] -> doc <<>> PP.colon <<>> pretty uq _ -> doc <<>> PP.colon <<>> PP.braces prettySublibs prettySublibs = PP.hsep $ PP.punctuate PP.comma $ prettySublib <$> NES.toList sublibs prettySublib LMainLibName = PP.text $ unPackageName name prettySublib (LSubLibName un) = PP.text $ unUnqualComponentName un -- | -- > > > simpleParsec " : sub " : : Maybe Dependency Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub " ) :| [ ] ) ) ) -- > > > simpleParsec " mylib:{sub1,sub2 } " : : Maybe Dependency Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) ) -- > > > simpleParsec " : { sub1 , sub2 } " : : Maybe Dependency Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) ) -- > > > simpleParsec " : { sub1 , sub2 } ^>= 42 " : : Maybe Dependency Just ( Dependency ( PackageName " " ) ( MajorBoundVersion ( mkVersion [ 42 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) ) -- > > > simpleParsec " : { } ^>= 42 " : : Maybe Dependency -- Nothing -- > > > traverse _ print ( map simpleParsec [ " : " , " mylib:{mylib } " , " mylib:{mylib , sublib } " ] : : [ Maybe Dependency ] ) Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ] ) ) ) Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ] ) ) ) Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ( UnqualComponentName " sublib " ) ] ) ) ) -- -- Spaces around colon are not allowed: -- > > > map [ " : sub " , " : sub " , " : { sub1,sub2 } " , " : { sub1,sub2 } " ] : : [ Maybe Dependency ] -- [Nothing,Nothing,Nothing,Nothing] -- Sublibrary syntax is accepted since - version : 3.0@ -- > > > map ( ` simpleParsec ' ` " : sub " ) [ CabalSpecV2_4 , CabalSpecV3_0 ] : : [ Maybe Dependency ] [ Nothing , Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub " ) :| [ ] ) ) ) ] -- instance Parsec Dependency where parsec = do name <- parsec libs <- option mainLibSet $ do _ <- char ':' versionGuardMultilibs NES.singleton <$> parseLib <|> parseMultipleLibs spaces -- ver <- parsec <|> pure anyVersion return $ mkDependency name ver libs where parseLib = LSubLibName <$> parsec parseMultipleLibs = between (char '{' *> spaces) (spaces *> char '}') (NES.fromNonEmpty <$> parsecCommaNonEmpty parseLib) versionGuardMultilibs :: CabalParsing m => m () versionGuardMultilibs = do csv <- askCabalSpecVersion when (csv < CabalSpecV3_0) $ fail $ unwords [ "Sublibrary dependency syntax used." , "To use this syntax the package needs to specify at least 'cabal-version: 3.0'." , "Alternatively, if you are depending on an internal library, you can write" , "directly the library name as it were a package." ] -- | Library set with main library. -- -- @since 3.4.0.0 mainLibSet :: NonEmptySet LibraryName mainLibSet = NES.singleton LMainLibName | Simplify the ' VersionRange ' expression in a ' Dependency ' . -- See 'simplifyVersionRange'. -- simplifyDependency :: Dependency -> Dependency simplifyDependency (Dependency name range comps) = Dependency name (simplifyVersionRange range) comps
null
https://raw.githubusercontent.com/haskell/cabal/23536274bb7baabe5c33140620471e897cf34cf2/Cabal-syntax/src/Distribution/Types/Dependency.hs
haskell
# LANGUAGE DeriveDataTypeable # | Describes a dependency on a source package (API) set of library names. in 'Set' or as the key to a 'Map'. For these and similar use cases see ^ The set of libraries required from the package. Only the selected libraries will be built. It does not affect the cabal-install solver yet. | Smart constructor of 'Dependency'. it is automatically converted to 'LMainLibName'. @since 3.4.0.0 | >>> prettyShow $ Dependency "pkg" anyVersion mainLibSet "pkg" "pkg:{pkg, sublib}" "pkg:sublib" | Nothing Spaces around colon are not allowed: [Nothing,Nothing,Nothing,Nothing] | Library set with main library. @since 3.4.0.0 See 'simplifyVersionRange'.
# LANGUAGE DeriveGeneric # module Distribution.Types.Dependency ( Dependency(..) , mkDependency , depPkgName , depVerRange , depLibraries , simplifyDependency , mainLibSet ) where import Distribution.Compat.Prelude import Prelude () import Distribution.Types.VersionRange (isAnyVersionLight) import Distribution.Version (VersionRange, anyVersion, simplifyVersionRange) import Distribution.CabalSpecVersion import Distribution.Compat.CharParsing (char, spaces) import Distribution.Compat.Parsing (between, option) import Distribution.Parsec import Distribution.Pretty import Distribution.Types.LibraryName import Distribution.Types.PackageName import Distribution.Types.UnqualComponentName import qualified Distribution.Compat.NonEmptySet as NES import qualified Text.PrettyPrint as PP /Invariant:/ package name does not appear as ' ' in /Note:/ ' Dependency ' is not an instance of ' ' , and so it can not be used ' ' . data Dependency = Dependency PackageName VersionRange (NonEmptySet LibraryName) deriving (Generic, Read, Show, Eq, Ord, Typeable, Data) depPkgName :: Dependency -> PackageName depPkgName (Dependency pn _ _) = pn depVerRange :: Dependency -> VersionRange depVerRange (Dependency _ vr _) = vr depLibraries :: Dependency -> NonEmptySet LibraryName depLibraries (Dependency _ _ cs) = cs If ' PackageName ' is appears as ' ' in a set of sublibraries , mkDependency :: PackageName -> VersionRange -> NonEmptySet LibraryName -> Dependency mkDependency pn vr lb = Dependency pn vr (NES.map conv lb) where pn' = packageNameToUnqualComponentName pn conv l@LMainLibName = l conv l@(LSubLibName ln) | ln == pn' = LMainLibName | otherwise = l instance Binary Dependency instance Structured Dependency instance NFData Dependency where rnf = genericRnf > > > prettyShow $ Dependency " pkg " anyVersion $ NES.insert ( " sublib " ) mainLibSet > > > prettyShow $ Dependency " pkg " anyVersion $ NES.singleton ( " sublib " ) > > > prettyShow $ Dependency " pkg " anyVersion $ NES.insert ( " sublib - b " ) $ NES.singleton ( " sublib - a " ) " pkg:{sublib - a , sublib - b } " instance Pretty Dependency where pretty (Dependency name ver sublibs) = withSubLibs (pretty name) <+> pver where TODO : change to isAnyVersion after # 6736 pver | isAnyVersionLight ver = PP.empty | otherwise = pretty ver withSubLibs doc = case NES.toList sublibs of [LMainLibName] -> doc [LSubLibName uq] -> doc <<>> PP.colon <<>> pretty uq _ -> doc <<>> PP.colon <<>> PP.braces prettySublibs prettySublibs = PP.hsep $ PP.punctuate PP.comma $ prettySublib <$> NES.toList sublibs prettySublib LMainLibName = PP.text $ unPackageName name prettySublib (LSubLibName un) = PP.text $ unUnqualComponentName un > > > simpleParsec " : sub " : : Maybe Dependency Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub " ) :| [ ] ) ) ) > > > simpleParsec " mylib:{sub1,sub2 } " : : Maybe Dependency Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) ) > > > simpleParsec " : { sub1 , sub2 } " : : Maybe Dependency Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) ) > > > simpleParsec " : { sub1 , sub2 } ^>= 42 " : : Maybe Dependency Just ( Dependency ( PackageName " " ) ( MajorBoundVersion ( mkVersion [ 42 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) ) > > > simpleParsec " : { } ^>= 42 " : : Maybe Dependency > > > traverse _ print ( map simpleParsec [ " : " , " mylib:{mylib } " , " mylib:{mylib , sublib } " ] : : [ Maybe Dependency ] ) Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ] ) ) ) Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ] ) ) ) Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ( UnqualComponentName " sublib " ) ] ) ) ) > > > map [ " : sub " , " : sub " , " : { sub1,sub2 } " , " : { sub1,sub2 } " ] : : [ Maybe Dependency ] Sublibrary syntax is accepted since - version : 3.0@ > > > map ( ` simpleParsec ' ` " : sub " ) [ CabalSpecV2_4 , CabalSpecV3_0 ] : : [ Maybe Dependency ] [ Nothing , Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub " ) :| [ ] ) ) ) ] instance Parsec Dependency where parsec = do name <- parsec libs <- option mainLibSet $ do _ <- char ':' versionGuardMultilibs NES.singleton <$> parseLib <|> parseMultipleLibs ver <- parsec <|> pure anyVersion return $ mkDependency name ver libs where parseLib = LSubLibName <$> parsec parseMultipleLibs = between (char '{' *> spaces) (spaces *> char '}') (NES.fromNonEmpty <$> parsecCommaNonEmpty parseLib) versionGuardMultilibs :: CabalParsing m => m () versionGuardMultilibs = do csv <- askCabalSpecVersion when (csv < CabalSpecV3_0) $ fail $ unwords [ "Sublibrary dependency syntax used." , "To use this syntax the package needs to specify at least 'cabal-version: 3.0'." , "Alternatively, if you are depending on an internal library, you can write" , "directly the library name as it were a package." ] mainLibSet :: NonEmptySet LibraryName mainLibSet = NES.singleton LMainLibName | Simplify the ' VersionRange ' expression in a ' Dependency ' . simplifyDependency :: Dependency -> Dependency simplifyDependency (Dependency name range comps) = Dependency name (simplifyVersionRange range) comps
7ffdd3da6b6d169be98ab6fc1cbd8decf1706a619943d5a6ccfd0a84b15bd22b
nuprl/gradual-typing-performance
run.rkt
#lang racket/base (date-display-format 'iso-8601) TODO ;; - add option to change governor, default to something reasonable ;; Benchmark driver ;; ;; Usage: run.rkt ;; This will: ;; - Create directories `BENCHMARK/benchmark` and `BENCHMARK/benchmark/base` - Spawn jobs for each of the 2**n configurations ;; Each job will create a new directory & save results to a file ;; - Aggregate the results from all sub-jobs (provide run-benchmark ;; Same as calling from the command line, just pass argv vector ) (require benchmark-util/data-lattice gtp-summarize/stats-helpers (only-in glob in-glob) (only-in racket/file file->value) (only-in racket/format ~a ~r) math/statistics mzlib/os glob pkg/lib racket/class racket/cmdline racket/date racket/draw (only-in racket/format ~a ~r) (only-in racket/file file->value) racket/future racket/match racket/list racket/port racket/string racket/system racket/vector unstable/sequence) ;; Flag to set compilation-only mode. If #f it will compile and ;; run, otherwise only compiles. (define only-compile? (make-parameter #f)) ;; Number of iterations to run the benchmark ;; - If `num-iterations` is given, run EXACTLY that ;; - By default, run `min-iterations` then check for non-normality. ;; If non-normal, run more--until `max-iterations` (define num-iterations (make-parameter #f)) (define min-iterations (make-parameter 10)) (define max-iterations (make-parameter 30)) ;; # warmup iterations to run. Throw these numbers away (define *NUM-WARMUP* (make-parameter 1)) ;; Processes that finish quicker than *MIN-MILLISECONDS* ;; are very likely to be affected by OS effects (define *MIN-MILLISECONDS* (make-parameter (* 1.3 1000))) ;; Apply transformation to the list of configurations before running TODO should be a sequence (define *PERMUTE* (make-parameter values)) ;; The number of jobs to spawn for the configurations. When jobs is ;; greater than 1, the configuration space is split evenly and allocated ;; to the various jobs. (define num-jobs (make-parameter "1")) ;; Paths to write results/diagrams (define output-path (make-parameter #f)) (define entry-point-param (make-parameter #f)) (define exclusive-config (make-parameter #f)) (define min-max-config (make-parameter #f)) (define *racket-bin* (make-parameter "")) ;; Path-String Boolean ( ) (define *DATA-TMPFILE* (make-parameter #f)) (define *TIME-TMPFILE* (make-parameter "time.tmp")) (define *TEMPERATURE-FREQUENCY* (make-parameter 1)) (define-syntax-rule (compile-error path) (let ([message (format "Compilation failed in '~a/~a'" (current-directory) path)]) (*ERROR-MESSAGES* (cons message (*ERROR-MESSAGES*))) (error 'run:compile message))) (define-syntax-rule (runtime-error var var-idx) (let ([message (format "Error running configuration ~a in '~a'" var-idx var)]) (*ERROR-MESSAGES* (cons message (*ERROR-MESSAGES*))) (error 'run:runtime message))) (define (timestamp) (date->string (current-date) #t)) (define (time? t) (or (unixtime? t) (real? t))) (define (time*->min t*) (if (unixtime? (car t*)) (unixtime*->min t*) (apply min t*))) (define (time->real t) (if (unixtime? t) (unixtime-real t) t)) ;; Get paths for all configuration directories Path Path - > (define (mk-configurations basepath entry-point) (define num-modules (for/sum ([fname (in-list (directory-list (build-path basepath "untyped")))] #:when (regexp-match? "\\.rkt$" (path->string fname))) 1)) (for/list ([i (in-range (expt 2 num-modules))]) (define bits (if (zero? i) (make-string num-modules #\0) (~r i #:base 2 #:min-width num-modules #:pad-string "0"))) (define var-str (format "configuration~a" bits)) (build-path basepath "benchmark" var-str entry-point))) ;; Start a thread to monitor CPU temperature ;; Delay before returning (define (make-temperature-monitor) (define t-file (string-append (output-path) ".heat")) (and (check-system-command "sensors") (printf "### Monitoring temperature at '~a'\n" t-file) (let ([p (process (string-append (format "echo '(~a ' > " (timestamp)) t-file "; " "sensors -u >> " t-file "; " "echo ')' >> " t-file "; " "while true; do " (format "sleep ~a; " (*TEMPERATURE-FREQUENCY*)) (format "echo '(~a ' >> " (timestamp)) t-file "; " "sensors -u >> " t-file "; " "echo ') ' >> " t-file "; " "done"))]) (sleep 2) ;; For temperature readings to stabilize p))) (define (system-command-exists? cmd-str) (if (system (format "hash ~a &> /dev/null" cmd-str)) #t #f)) (define (check-system-command cmd-str) (unless (system-command-exists? cmd-str) (printf "WARNING: `sensors` command not found, cannot monitor temperature\n") #f)) (define (system-command-fallback . cmd-str*) (or (for/or ([cmd (in-list cmd-str*)] #:when (system-command-exists? cmd)) cmd) (raise-user-error 'run "sys command fallback failed ~a" cmd-str*))) (define (kill-temperature-monitor TM) (when TM (match-define (list out in pid err control) TM) (control 'kill) (control 'wait) (for-each displayln (port->lines err)) (close-output-port in) (close-input-port out) (close-input-port err)) (void)) (define ((make-run-command/racket job#) stub #:iters [iters 1] #:stat? [stat? #f]) (define cmd (string-append (if (*AFFINITY?*) (format "taskset -c ~a " job#) "") " " stub)) (for/list ([i (in-range iters)]) (match-define (list out in pid err control) (process cmd #:set-pwd? #t)) (control 'wait) (for-each displayln (port->lines err)) (define t 2016 - 05 - 10 : can also use for / first (for/last ([line (in-list (port->lines out))]) (regexp-match #rx"cpu time: (.*) real time: (.*) gc time: (.*)" line))]) (match time-info [(list full (app string->number cpu) (app string->number real) (app string->number gc)) (printf "job#~a, iteration#~a - cpu: ~a real: ~a gc: ~a~n" job# i cpu real gc) real] [#f (when (regexp-match? "racket " stub) (runtime-error 'run stub))]))) (close-input-port out) (close-input-port err) (close-output-port in) t)) ( - > Natural ( - > String # : iters Natural # : stat ? Boolean ( unixtime ) ) ) (define ((make-run-command/gnutime job#) stub #:iters [iters 1] #:stat? [stat? #f]) (define time-cmd (system-command-fallback "gtime" "/usr/bin/time")) (define time-tmpfile (*TIME-TMPFILE*)) (when (file-exists? time-tmpfile) (delete-file time-tmpfile)) (define cmd (string-append (format " for i in `seq 1 ~a`; do " iters) (if (*AFFINITY?*) (format "taskset -c ~a " job#) "") time-cmd " -o " time-tmpfile " --append " " -f " TIME-FMT " " stub "; done;")) (printf "#### exec `~a` in `~a`\n" stub (current-directory)) (match-define (list out in pid err control) (process cmd #:set-pwd? #t)) (control 'wait) (for-each displayln (port->lines err)) (define ut* (with-input-from-file time-tmpfile (lambda () (for/fold ([acc '()]) ([ln (in-lines)]) (cond [(string->unixtime ln) => (lambda (ut) (if (zero? (unixtime-exit ut)) (cons ut acc) (raise-user-error 'run-command "Process terminated with non-zero exit code '~a'. Full command was '~a'" (unixtime-exit ut) cmd)))] [(string->number ln) => (lambda (n) (cons n acc))] [else acc]))))) (close-input-port out) (close-input-port err) (close-output-port in) ut*) ;; Run the configurations for each configuration directory ;; Optional argument gives the exact configuration to run. ;; Default is to run all configurations ( ) Path Nat Nat [ ( U ( ) # f ) ] - > Void (define (run-benchmarks basepath entry-point jobs #:config [cfg #f] #:min/max [min/max #f]) (define benchmark-dir (build-path basepath "benchmark")) (unless (directory-exists? benchmark-dir) (raise-user-error 'run (format "Directory '~a' does not exist, please run `setup.rkt ~a` and try again." benchmark-dir basepath))) (define configurations (cond [cfg (list (build-path benchmark-dir (string-append "configuration" cfg) entry-point))] [min/max (match-define (list min max) min/max) (define all-vars (mk-configurations basepath entry-point)) (define (in-range? var) (match-define (list _ bits) (regexp-match "configuration([10]*)/" var)) (define n (string->number bits 2)) (and (>= n (string->number min)) (<= n (string->number max)))) (filter in-range? all-vars)] [else ((*PERMUTE*) (mk-configurations basepath entry-point))])) (define hot-proc (make-temperature-monitor)) ;; allocate a slice of the configurations per job (define slice-size (ceiling (/ (length configurations) jobs))) (define thread* (for/list ([var-slice (in-slice slice-size (in-values-sequence (in-indexed (in-list configurations))))] [job# (in-range 1 (add1 jobs))]) ;; Spawn a control thread for each job, which will in turn spawn an OS process. ;; Each job gets assigned to the CPU that is the same as the job# using ;; the `taskset` command. (thread (λ () (define run-command (make-run-command/racket job#)) (for ([var-in-slice var-slice]) (match-define (list var var-idx) var-in-slice) (define-values (new-cwd file _2) (split-path var)) (define file-str (path->string file)) (parameterize ([current-directory new-cwd]) ;; first compile the configuration (void (run-command (format "~araco make -v ~a" (*racket-bin*) file-str))) ;; run the iterations that will count for the data (define exact-iters (num-iterations)) (unless (or (only-compile?) (file-exists? (*DATA-TMPFILE*))) (define ut* (let* (;[rkt-command (format "~aracket ~a" (*racket-bin*) file-str)] [rkt-command (format "~aracket -e '~s'" (*racket-bin*) `(time (dynamic-require ,file-str #f)))] ;; -- throwaway builds (use to get baseline time) [time0 (time*->min (run-command #:iters (*NUM-WARMUP*) rkt-command))] [use-stat? (< time0 (*MIN-MILLISECONDS*))] [run (lambda (i) (run-command rkt-command #:iters i #:stat? use-stat?))] ;; -- real thing [ut0* (run (or exact-iters (min-iterations)))] [ut1* (if (or exact-iters (anderson-darling? (map time->real ut0*))) '() (run (- (+ 1 (max-iterations) (min-iterations)))))]) (append ut0* ut1*))) (write-results (reverse ut*))))))))) ;; synchronize on all jobs (for ([thd (in-list thread*)]) (thread-wait thd)) (kill-temperature-monitor hot-proc) #t) (define (write-results times [dir (current-directory)]) (with-output-to-file (build-path dir (*DATA-TMPFILE*)) #:exists 'append (lambda () (display "(") (writeln (timestamp)) (for-each writeln times) (displayln ")")))) ;; Get the most recent commit hash for the chosen Racket install (define (racket-checksum) (define rkt-dir (if (zero? (string-length (*racket-bin*))) ;; Hacks (string-append (with-output-to-string (lambda () (system "which racket"))) "/..") (*racket-bin*))) (define success? (box #f)) (define str (parameterize ([current-directory rkt-dir]) (with-output-to-string (lambda () (when (directory-exists? "./git") (and (system "git rev-parse HEAD") (set-box! success? #t))))))) ;; If we parsed the git version, print it. Otherwise, notify. (if (unbox success?) (~a str #:max-width 8) "<unknown-commit>")) ;; Use the current `raco` to get the most-recent commit hash for typed-racket (define (typed-racket-checksum) (define tbl (installed-pkg-table #:scope 'installation)) (if tbl (let ([pkg (hash-ref tbl "typed-racket")]) (if pkg (let ([chk (pkg-info-checksum pkg)]) (~a chk #:max-width 8)) (printf "Failed to find package 'typed-racket' in 'installation pkg-table\n"))) (printf "Failed to get 'installed-pkg-table'\n"))) ;; Read a string, return a permutation function on lists ( - > String ( All ( A ) ( - > ( A ) ( A ) ) ) ) (define (read-permutation str) (cond [(string=? str "reverse") reverse] [(string=? str "shuffle") shuffle] [(string->number str) => rotate] [else values])) ;; Rotate a list (define ((rotate i) x*) (let-values (((a b) (split-at x* (modulo i (length x*))))) (append b a))) Read a .rktd file which SHOULD contain 1 list of runtimes . Raise an error if there 's more than 1 list or the data is malformed . (define (result-file->time* fname) (with-handlers ([exn:fail? (lambda (e) (raise-user-error 'run "Error collecting data from file '~a', please inspect & try again.\n~a" fname (exn-message e)))]) (define v (file->value fname)) (unless (and (list? v) (not (null? (cdr v))) (for/and ([x (in-list (cdr v))]) (time? x))) (raise-user-error 'run "Malformed tmp data ~a" v)) (map time->real (cdr v)))) (define (run-benchmark vec) (define basepath (command-line #:program "benchmark-runner" #:argv vec #:once-any [("-x" "--exclusive") x-p "Run the given configuration and no others" (exclusive-config x-p)] [("-m" "--min-max") min max "Run the configurations between min and max inclusive" (min-max-config (list min max))] #:once-each [("-w" "--warmup") w "Set number of warmup iterations" (*NUM-WARMUP* (string->number w))] [("-p" "--permute") p "Change order of configurations" (*PERMUTE* (read-permutation p))] [("-n" "--no-affinity") "Do NOT set task affinity (runs all jobs on current core)" (*AFFINITY?* #f)] [("-c" "--only-compile") "Only compile and don't run" (only-compile? #t)] [("-o" "--output") o-p "A path to write data to" (output-path o-p)] [("-e" "--entry-point") e-p "The main file to execute. (Defaults to 'main.rkt'.)" (entry-point-param e-p)] [("-j" "--jobs") j "The number of processes to spawn" (num-jobs j)] [("-r" "--racket") r-p "Directory containing the preferred racket & raco executables" (*racket-bin* (string-append r-p "/"))] #:multi [("-i" "--iterations") n-i "The number of iterations to run" (let ([n (string->number n-i)]) (unless n (raise-user-error 'run (format "Expected natural number, got '~a'" n-i))) (num-iterations n))] #:args (basepath) basepath)) Validate given entry - point , or fall back to default (define entry-point (cond [(and (entry-point-param) (path-string? (entry-point-param)) (regexp-match? #rx"\\.rkt$" (entry-point-param))) (entry-point-param)] [(entry-point-param) ;; Optional argument given, but is not a .rkt file (raise-user-error (format "expected a Racket file, given ~a" (entry-point-param)))] [else ;; Default "main.rkt"])) ;; Assert that the parsed entry point exists in the project (unless (and (directory-exists? basepath) (file-exists? (build-path basepath "untyped" entry-point)) (file-exists? (build-path basepath "typed" entry-point))) (raise-user-error (format "entry point '~a' not found in project '~a', cannot run" entry-point basepath))) (unless (path-string? basepath) (raise-user-error (format "expected a path, given ~a" basepath))) (unless (and (path-string? entry-point) (regexp-match? #rx"\\.rkt$" entry-point)) (raise-user-error (format "expected a Racket file, given ~a" entry-point))) (define jobs (string->number (num-jobs))) (unless (number? jobs) (raise-user-error (format "expected a number, given ~a" (num-jobs)))) ;; Set a default output path based on the "basepath" if one is not provided ;; Also set *DATA-TMPFILE* (cond [(output-path) (*DATA-TMPFILE* (output-path))] [else (date-display-format 'iso-8601) (define tag (last (string-split basepath "/"))) (output-path (string-append tag "-" (timestamp) ".rktd")) (*DATA-TMPFILE* (string-append tag ".rktd"))]) Need at least 2 CPUs since our controller thread is pinned to core 0 and workers to cores 1 and above . (when (< (processor-count) 2) (raise-user-error (string-append "Detected less than 2 CPUs. Please run this " "script on a machine/VM with at least 2 CPUs."))) (when (< (processor-count) (add1 jobs)) (raise-user-error (string-append "Too many jobs specified. Need at least as many " "processors as #jobs+1"))) Set the CPU affinity for this script to CPU0 . Jobs spawned by this script run using CPU1 and above . (when (*AFFINITY?*) (system (format "taskset -pc 0 ~a" (getpid)))) (run-benchmarks basepath entry-point jobs #:config (exclusive-config) #:min/max (min-max-config)) (when (and (not (only-compile?)) (output-path)) (with-output-to-file (output-path) (λ () ;; first write a comment that encodes the commandline args / version (printf ";; ~a~n" (current-command-line-arguments)) (printf ";; ~a~n" (version)) (printf ";; base @ ~a~n" (racket-checksum)) (printf ";; typed-racket @ ~a~n" (typed-racket-checksum)) (printf ";; ~a~n" (timestamp)) (displayln "#(") (for ([result-file (in-glob (format "~a/benchmark/configuration*/~a" basepath (*DATA-TMPFILE*)))]) (writeln (file->value result-file))) (displayln ")")) #:mode 'text #:exists 'replace)) (printf "### saved results to '~a'\n" (output-path)) (void)) ;; ============================================================================= (module+ main (run-benchmark (current-command-line-arguments)))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/tools/run.rkt
racket
- add option to change governor, default to something reasonable Benchmark driver Usage: This will: - Create directories `BENCHMARK/benchmark` and `BENCHMARK/benchmark/base` Each job will create a new directory & save results to a file - Aggregate the results from all sub-jobs Same as calling from the command line, just pass argv vector Flag to set compilation-only mode. If #f it will compile and run, otherwise only compiles. Number of iterations to run the benchmark - If `num-iterations` is given, run EXACTLY that - By default, run `min-iterations` then check for non-normality. If non-normal, run more--until `max-iterations` # warmup iterations to run. Throw these numbers away Processes that finish quicker than *MIN-MILLISECONDS* are very likely to be affected by OS effects Apply transformation to the list of configurations before running The number of jobs to spawn for the configurations. When jobs is greater than 1, the configuration space is split evenly and allocated to the various jobs. Paths to write results/diagrams Path-String Get paths for all configuration directories Start a thread to monitor CPU temperature Delay before returning For temperature readings to stabilize Run the configurations for each configuration directory Optional argument gives the exact configuration to run. Default is to run all configurations allocate a slice of the configurations per job Spawn a control thread for each job, which will in turn spawn an OS process. Each job gets assigned to the CPU that is the same as the job# using the `taskset` command. first compile the configuration run the iterations that will count for the data [rkt-command (format "~aracket ~a" (*racket-bin*) file-str)] -- throwaway builds (use to get baseline time) -- real thing synchronize on all jobs Get the most recent commit hash for the chosen Racket install Hacks If we parsed the git version, print it. Otherwise, notify. Use the current `raco` to get the most-recent commit hash for typed-racket Read a string, return a permutation function on lists Rotate a list Optional argument given, but is not a .rkt file Default Assert that the parsed entry point exists in the project Set a default output path based on the "basepath" if one is not provided Also set *DATA-TMPFILE* first write a comment that encodes the commandline args / version =============================================================================
#lang racket/base (date-display-format 'iso-8601) TODO run.rkt - Spawn jobs for each of the 2**n configurations (provide run-benchmark ) (require benchmark-util/data-lattice gtp-summarize/stats-helpers (only-in glob in-glob) (only-in racket/file file->value) (only-in racket/format ~a ~r) math/statistics mzlib/os glob pkg/lib racket/class racket/cmdline racket/date racket/draw (only-in racket/format ~a ~r) (only-in racket/file file->value) racket/future racket/match racket/list racket/port racket/string racket/system racket/vector unstable/sequence) (define only-compile? (make-parameter #f)) (define num-iterations (make-parameter #f)) (define min-iterations (make-parameter 10)) (define max-iterations (make-parameter 30)) (define *NUM-WARMUP* (make-parameter 1)) (define *MIN-MILLISECONDS* (make-parameter (* 1.3 1000))) TODO should be a sequence (define *PERMUTE* (make-parameter values)) (define num-jobs (make-parameter "1")) (define output-path (make-parameter #f)) (define entry-point-param (make-parameter #f)) (define exclusive-config (make-parameter #f)) (define min-max-config (make-parameter #f)) Boolean ( ) (define *DATA-TMPFILE* (make-parameter #f)) (define *TIME-TMPFILE* (make-parameter "time.tmp")) (define *TEMPERATURE-FREQUENCY* (make-parameter 1)) (define-syntax-rule (compile-error path) (let ([message (format "Compilation failed in '~a/~a'" (current-directory) path)]) (*ERROR-MESSAGES* (cons message (*ERROR-MESSAGES*))) (error 'run:compile message))) (define-syntax-rule (runtime-error var var-idx) (let ([message (format "Error running configuration ~a in '~a'" var-idx var)]) (*ERROR-MESSAGES* (cons message (*ERROR-MESSAGES*))) (error 'run:runtime message))) (define (timestamp) (date->string (current-date) #t)) (define (time? t) (or (unixtime? t) (real? t))) (define (time*->min t*) (if (unixtime? (car t*)) (unixtime*->min t*) (apply min t*))) (define (time->real t) (if (unixtime? t) (unixtime-real t) t)) Path Path - > (define (mk-configurations basepath entry-point) (define num-modules (for/sum ([fname (in-list (directory-list (build-path basepath "untyped")))] #:when (regexp-match? "\\.rkt$" (path->string fname))) 1)) (for/list ([i (in-range (expt 2 num-modules))]) (define bits (if (zero? i) (make-string num-modules #\0) (~r i #:base 2 #:min-width num-modules #:pad-string "0"))) (define var-str (format "configuration~a" bits)) (build-path basepath "benchmark" var-str entry-point))) (define (make-temperature-monitor) (define t-file (string-append (output-path) ".heat")) (and (check-system-command "sensors") (printf "### Monitoring temperature at '~a'\n" t-file) (let ([p (process (string-append (format "echo '(~a ' > " (timestamp)) t-file "; " "sensors -u >> " t-file "; " "echo ')' >> " t-file "; " "while true; do " (format "sleep ~a; " (*TEMPERATURE-FREQUENCY*)) (format "echo '(~a ' >> " (timestamp)) t-file "; " "sensors -u >> " t-file "; " "echo ') ' >> " t-file "; " "done"))]) p))) (define (system-command-exists? cmd-str) (if (system (format "hash ~a &> /dev/null" cmd-str)) #t #f)) (define (check-system-command cmd-str) (unless (system-command-exists? cmd-str) (printf "WARNING: `sensors` command not found, cannot monitor temperature\n") #f)) (define (system-command-fallback . cmd-str*) (or (for/or ([cmd (in-list cmd-str*)] #:when (system-command-exists? cmd)) cmd) (raise-user-error 'run "sys command fallback failed ~a" cmd-str*))) (define (kill-temperature-monitor TM) (when TM (match-define (list out in pid err control) TM) (control 'kill) (control 'wait) (for-each displayln (port->lines err)) (close-output-port in) (close-input-port out) (close-input-port err)) (void)) (define ((make-run-command/racket job#) stub #:iters [iters 1] #:stat? [stat? #f]) (define cmd (string-append (if (*AFFINITY?*) (format "taskset -c ~a " job#) "") " " stub)) (for/list ([i (in-range iters)]) (match-define (list out in pid err control) (process cmd #:set-pwd? #t)) (control 'wait) (for-each displayln (port->lines err)) (define t 2016 - 05 - 10 : can also use for / first (for/last ([line (in-list (port->lines out))]) (regexp-match #rx"cpu time: (.*) real time: (.*) gc time: (.*)" line))]) (match time-info [(list full (app string->number cpu) (app string->number real) (app string->number gc)) (printf "job#~a, iteration#~a - cpu: ~a real: ~a gc: ~a~n" job# i cpu real gc) real] [#f (when (regexp-match? "racket " stub) (runtime-error 'run stub))]))) (close-input-port out) (close-input-port err) (close-output-port in) t)) ( - > Natural ( - > String # : iters Natural # : stat ? Boolean ( unixtime ) ) ) (define ((make-run-command/gnutime job#) stub #:iters [iters 1] #:stat? [stat? #f]) (define time-cmd (system-command-fallback "gtime" "/usr/bin/time")) (define time-tmpfile (*TIME-TMPFILE*)) (when (file-exists? time-tmpfile) (delete-file time-tmpfile)) (define cmd (string-append (format " for i in `seq 1 ~a`; do " iters) (if (*AFFINITY?*) (format "taskset -c ~a " job#) "") time-cmd " -o " time-tmpfile " --append " " -f " TIME-FMT " " stub "; done;")) (printf "#### exec `~a` in `~a`\n" stub (current-directory)) (match-define (list out in pid err control) (process cmd #:set-pwd? #t)) (control 'wait) (for-each displayln (port->lines err)) (define ut* (with-input-from-file time-tmpfile (lambda () (for/fold ([acc '()]) ([ln (in-lines)]) (cond [(string->unixtime ln) => (lambda (ut) (if (zero? (unixtime-exit ut)) (cons ut acc) (raise-user-error 'run-command "Process terminated with non-zero exit code '~a'. Full command was '~a'" (unixtime-exit ut) cmd)))] [(string->number ln) => (lambda (n) (cons n acc))] [else acc]))))) (close-input-port out) (close-input-port err) (close-output-port in) ut*) ( ) Path Nat Nat [ ( U ( ) # f ) ] - > Void (define (run-benchmarks basepath entry-point jobs #:config [cfg #f] #:min/max [min/max #f]) (define benchmark-dir (build-path basepath "benchmark")) (unless (directory-exists? benchmark-dir) (raise-user-error 'run (format "Directory '~a' does not exist, please run `setup.rkt ~a` and try again." benchmark-dir basepath))) (define configurations (cond [cfg (list (build-path benchmark-dir (string-append "configuration" cfg) entry-point))] [min/max (match-define (list min max) min/max) (define all-vars (mk-configurations basepath entry-point)) (define (in-range? var) (match-define (list _ bits) (regexp-match "configuration([10]*)/" var)) (define n (string->number bits 2)) (and (>= n (string->number min)) (<= n (string->number max)))) (filter in-range? all-vars)] [else ((*PERMUTE*) (mk-configurations basepath entry-point))])) (define hot-proc (make-temperature-monitor)) (define slice-size (ceiling (/ (length configurations) jobs))) (define thread* (for/list ([var-slice (in-slice slice-size (in-values-sequence (in-indexed (in-list configurations))))] [job# (in-range 1 (add1 jobs))]) (thread (λ () (define run-command (make-run-command/racket job#)) (for ([var-in-slice var-slice]) (match-define (list var var-idx) var-in-slice) (define-values (new-cwd file _2) (split-path var)) (define file-str (path->string file)) (parameterize ([current-directory new-cwd]) (void (run-command (format "~araco make -v ~a" (*racket-bin*) file-str))) (define exact-iters (num-iterations)) (unless (or (only-compile?) (file-exists? (*DATA-TMPFILE*))) (define ut* [rkt-command (format "~aracket -e '~s'" (*racket-bin*) `(time (dynamic-require ,file-str #f)))] [time0 (time*->min (run-command #:iters (*NUM-WARMUP*) rkt-command))] [use-stat? (< time0 (*MIN-MILLISECONDS*))] [run (lambda (i) (run-command rkt-command #:iters i #:stat? use-stat?))] [ut0* (run (or exact-iters (min-iterations)))] [ut1* (if (or exact-iters (anderson-darling? (map time->real ut0*))) '() (run (- (+ 1 (max-iterations) (min-iterations)))))]) (append ut0* ut1*))) (write-results (reverse ut*))))))))) (for ([thd (in-list thread*)]) (thread-wait thd)) (kill-temperature-monitor hot-proc) #t) (define (write-results times [dir (current-directory)]) (with-output-to-file (build-path dir (*DATA-TMPFILE*)) #:exists 'append (lambda () (display "(") (writeln (timestamp)) (for-each writeln times) (displayln ")")))) (define (racket-checksum) (define rkt-dir (if (zero? (string-length (*racket-bin*))) (string-append (with-output-to-string (lambda () (system "which racket"))) "/..") (*racket-bin*))) (define success? (box #f)) (define str (parameterize ([current-directory rkt-dir]) (with-output-to-string (lambda () (when (directory-exists? "./git") (and (system "git rev-parse HEAD") (set-box! success? #t))))))) (if (unbox success?) (~a str #:max-width 8) "<unknown-commit>")) (define (typed-racket-checksum) (define tbl (installed-pkg-table #:scope 'installation)) (if tbl (let ([pkg (hash-ref tbl "typed-racket")]) (if pkg (let ([chk (pkg-info-checksum pkg)]) (~a chk #:max-width 8)) (printf "Failed to find package 'typed-racket' in 'installation pkg-table\n"))) (printf "Failed to get 'installed-pkg-table'\n"))) ( - > String ( All ( A ) ( - > ( A ) ( A ) ) ) ) (define (read-permutation str) (cond [(string=? str "reverse") reverse] [(string=? str "shuffle") shuffle] [(string->number str) => rotate] [else values])) (define ((rotate i) x*) (let-values (((a b) (split-at x* (modulo i (length x*))))) (append b a))) Read a .rktd file which SHOULD contain 1 list of runtimes . Raise an error if there 's more than 1 list or the data is malformed . (define (result-file->time* fname) (with-handlers ([exn:fail? (lambda (e) (raise-user-error 'run "Error collecting data from file '~a', please inspect & try again.\n~a" fname (exn-message e)))]) (define v (file->value fname)) (unless (and (list? v) (not (null? (cdr v))) (for/and ([x (in-list (cdr v))]) (time? x))) (raise-user-error 'run "Malformed tmp data ~a" v)) (map time->real (cdr v)))) (define (run-benchmark vec) (define basepath (command-line #:program "benchmark-runner" #:argv vec #:once-any [("-x" "--exclusive") x-p "Run the given configuration and no others" (exclusive-config x-p)] [("-m" "--min-max") min max "Run the configurations between min and max inclusive" (min-max-config (list min max))] #:once-each [("-w" "--warmup") w "Set number of warmup iterations" (*NUM-WARMUP* (string->number w))] [("-p" "--permute") p "Change order of configurations" (*PERMUTE* (read-permutation p))] [("-n" "--no-affinity") "Do NOT set task affinity (runs all jobs on current core)" (*AFFINITY?* #f)] [("-c" "--only-compile") "Only compile and don't run" (only-compile? #t)] [("-o" "--output") o-p "A path to write data to" (output-path o-p)] [("-e" "--entry-point") e-p "The main file to execute. (Defaults to 'main.rkt'.)" (entry-point-param e-p)] [("-j" "--jobs") j "The number of processes to spawn" (num-jobs j)] [("-r" "--racket") r-p "Directory containing the preferred racket & raco executables" (*racket-bin* (string-append r-p "/"))] #:multi [("-i" "--iterations") n-i "The number of iterations to run" (let ([n (string->number n-i)]) (unless n (raise-user-error 'run (format "Expected natural number, got '~a'" n-i))) (num-iterations n))] #:args (basepath) basepath)) Validate given entry - point , or fall back to default (define entry-point (cond [(and (entry-point-param) (path-string? (entry-point-param)) (regexp-match? #rx"\\.rkt$" (entry-point-param))) (entry-point-param)] (raise-user-error (format "expected a Racket file, given ~a" (entry-point-param)))] "main.rkt"])) (unless (and (directory-exists? basepath) (file-exists? (build-path basepath "untyped" entry-point)) (file-exists? (build-path basepath "typed" entry-point))) (raise-user-error (format "entry point '~a' not found in project '~a', cannot run" entry-point basepath))) (unless (path-string? basepath) (raise-user-error (format "expected a path, given ~a" basepath))) (unless (and (path-string? entry-point) (regexp-match? #rx"\\.rkt$" entry-point)) (raise-user-error (format "expected a Racket file, given ~a" entry-point))) (define jobs (string->number (num-jobs))) (unless (number? jobs) (raise-user-error (format "expected a number, given ~a" (num-jobs)))) (cond [(output-path) (*DATA-TMPFILE* (output-path))] [else (date-display-format 'iso-8601) (define tag (last (string-split basepath "/"))) (output-path (string-append tag "-" (timestamp) ".rktd")) (*DATA-TMPFILE* (string-append tag ".rktd"))]) Need at least 2 CPUs since our controller thread is pinned to core 0 and workers to cores 1 and above . (when (< (processor-count) 2) (raise-user-error (string-append "Detected less than 2 CPUs. Please run this " "script on a machine/VM with at least 2 CPUs."))) (when (< (processor-count) (add1 jobs)) (raise-user-error (string-append "Too many jobs specified. Need at least as many " "processors as #jobs+1"))) Set the CPU affinity for this script to CPU0 . Jobs spawned by this script run using CPU1 and above . (when (*AFFINITY?*) (system (format "taskset -pc 0 ~a" (getpid)))) (run-benchmarks basepath entry-point jobs #:config (exclusive-config) #:min/max (min-max-config)) (when (and (not (only-compile?)) (output-path)) (with-output-to-file (output-path) (λ () (printf ";; ~a~n" (current-command-line-arguments)) (printf ";; ~a~n" (version)) (printf ";; base @ ~a~n" (racket-checksum)) (printf ";; typed-racket @ ~a~n" (typed-racket-checksum)) (printf ";; ~a~n" (timestamp)) (displayln "#(") (for ([result-file (in-glob (format "~a/benchmark/configuration*/~a" basepath (*DATA-TMPFILE*)))]) (writeln (file->value result-file))) (displayln ")")) #:mode 'text #:exists 'replace)) (printf "### saved results to '~a'\n" (output-path)) (void)) (module+ main (run-benchmark (current-command-line-arguments)))
a6514cc5e48ebdf747e19bf3130bbb3fb8678847fc5b739bca33f1331436f8de
dfinity/motoko
async_cap.ml
(* Async capabilities *) module T = Type type async_cap = | QueryCap of T.con (* can (query) async (i.e. in a shared query func) *) | ErrorCap (* can try, catch (i.e. in the async body of shared query func) *) | AsyncCap of T.con (* can async, send (i.e. in a func of async type or shared func) *) | AwaitCap of T.con (* can async, send, try, catch, await (i.e. in an async expression *) | NullCap (* none of the above *) let top_cap = Cons.fresh "$top-level" (T.Def([],T.Any)) let initial_cap () = AwaitCap top_cap
null
https://raw.githubusercontent.com/dfinity/motoko/d8e13023dfdc965907512432c0181c8d137d84ad/src/mo_types/async_cap.ml
ocaml
Async capabilities can (query) async (i.e. in a shared query func) can try, catch (i.e. in the async body of shared query func) can async, send (i.e. in a func of async type or shared func) can async, send, try, catch, await (i.e. in an async expression none of the above
module T = Type type async_cap = let top_cap = Cons.fresh "$top-level" (T.Def([],T.Any)) let initial_cap () = AwaitCap top_cap
bd35da8e607f54259f4722e5d0f0d7520980bf5d7c9da73c641f294b256b9927
xapi-project/xen-api
xapi_diagnostics.ml
Copyright ( C ) Citrix Systems Inc. This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; version 2.1 only . with the special exception on linking described in file LICENSE . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . Copyright (C) Citrix Systems Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; version 2.1 only. with the special exception on linking described in file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *) let gc_compact ~__context ~host:_ = Gc.compact () let gc_stats ~__context ~host:_ = let stat = Gc.stat () in [ ("minor_words", string_of_float stat.Gc.minor_words) ; ("promoted_words", string_of_float stat.Gc.promoted_words) ; ("major_words", string_of_float stat.Gc.major_words) ; ("minor_collections", string_of_int stat.Gc.minor_collections) ; ("major_collections", string_of_int stat.Gc.major_collections) ; ("heap_words", string_of_int stat.Gc.heap_words) ; ("heap_chunks", string_of_int stat.Gc.heap_chunks) ; ("live_words", string_of_int stat.Gc.live_words) ; ("live_blocks", string_of_int stat.Gc.live_blocks) ; ("free_words", string_of_int stat.Gc.free_words) ; ("free_blocks", string_of_int stat.Gc.free_blocks) ; ("largest_free", string_of_int stat.Gc.largest_free) ; ("fragments", string_of_int stat.Gc.fragments) ; ("compactions", string_of_int stat.Gc.compactions) ; ("top_heap_words", string_of_int stat.Gc.top_heap_words) ] let db_stats ~__context = (* Use Printf.sprintf to keep format *) let n, avgtime, min, max = Db_lock.report () in [ ("n", Printf.sprintf "%d" n) ; ("avgtime", Printf.sprintf "%f" avgtime) ; ("min", Printf.sprintf "%f" min) ; ("max", Printf.sprintf "%f" max) ] let network_stats ~__context ~host:_ ~params = let meth (m, _, _) = (not (List.mem_assoc "method" params)) || String.lowercase_ascii (Http.string_of_method_t m) = String.lowercase_ascii (List.assoc "method" params) in let uri (_, u, _) = (not (List.mem_assoc "uri" params)) || String.lowercase_ascii u = String.lowercase_ascii (List.assoc "uri" params) in let has_param x = (not (List.mem_assoc "params" params)) || List.mem x (String.split_on_char ',' (List.assoc "params" params)) in Http_svr.Server.all_stats Xapi_http.server |> List.filter meth |> List.filter uri |> List.map (fun (m, uri, stats) -> List.concat [ (if has_param "method" then [Http.string_of_method_t m] else []) ; (if has_param "uri" then [uri] else []) ; ( if has_param "requests" then [string_of_int stats.Http_svr.Stats.n_requests] else [] ) ; ( if has_param "connections" then [string_of_int stats.Http_svr.Stats.n_connections] else [] ) ; ( if has_param "framed" then [string_of_int stats.Http_svr.Stats.n_framed] else [] ) ] )
null
https://raw.githubusercontent.com/xapi-project/xen-api/fa6f118fb512a2c90159368a1a0bc1cc730c895b/ocaml/xapi/xapi_diagnostics.ml
ocaml
Use Printf.sprintf to keep format
Copyright ( C ) Citrix Systems Inc. This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; version 2.1 only . with the special exception on linking described in file LICENSE . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . Copyright (C) Citrix Systems Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; version 2.1 only. with the special exception on linking described in file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *) let gc_compact ~__context ~host:_ = Gc.compact () let gc_stats ~__context ~host:_ = let stat = Gc.stat () in [ ("minor_words", string_of_float stat.Gc.minor_words) ; ("promoted_words", string_of_float stat.Gc.promoted_words) ; ("major_words", string_of_float stat.Gc.major_words) ; ("minor_collections", string_of_int stat.Gc.minor_collections) ; ("major_collections", string_of_int stat.Gc.major_collections) ; ("heap_words", string_of_int stat.Gc.heap_words) ; ("heap_chunks", string_of_int stat.Gc.heap_chunks) ; ("live_words", string_of_int stat.Gc.live_words) ; ("live_blocks", string_of_int stat.Gc.live_blocks) ; ("free_words", string_of_int stat.Gc.free_words) ; ("free_blocks", string_of_int stat.Gc.free_blocks) ; ("largest_free", string_of_int stat.Gc.largest_free) ; ("fragments", string_of_int stat.Gc.fragments) ; ("compactions", string_of_int stat.Gc.compactions) ; ("top_heap_words", string_of_int stat.Gc.top_heap_words) ] let db_stats ~__context = let n, avgtime, min, max = Db_lock.report () in [ ("n", Printf.sprintf "%d" n) ; ("avgtime", Printf.sprintf "%f" avgtime) ; ("min", Printf.sprintf "%f" min) ; ("max", Printf.sprintf "%f" max) ] let network_stats ~__context ~host:_ ~params = let meth (m, _, _) = (not (List.mem_assoc "method" params)) || String.lowercase_ascii (Http.string_of_method_t m) = String.lowercase_ascii (List.assoc "method" params) in let uri (_, u, _) = (not (List.mem_assoc "uri" params)) || String.lowercase_ascii u = String.lowercase_ascii (List.assoc "uri" params) in let has_param x = (not (List.mem_assoc "params" params)) || List.mem x (String.split_on_char ',' (List.assoc "params" params)) in Http_svr.Server.all_stats Xapi_http.server |> List.filter meth |> List.filter uri |> List.map (fun (m, uri, stats) -> List.concat [ (if has_param "method" then [Http.string_of_method_t m] else []) ; (if has_param "uri" then [uri] else []) ; ( if has_param "requests" then [string_of_int stats.Http_svr.Stats.n_requests] else [] ) ; ( if has_param "connections" then [string_of_int stats.Http_svr.Stats.n_connections] else [] ) ; ( if has_param "framed" then [string_of_int stats.Http_svr.Stats.n_framed] else [] ) ] )
71cd63d53475a77d20274a2b4f2edbd2606db2d28314dafab899370f620bcdb1
TerrorJack/ghc-alter
T7787.hs
import Control.Concurrent.MVar import Control.Exception main = do mv <- newMVar 'x' e <- try (modifyMVar mv $ \_ -> return undefined) let _ = e :: Either SomeException () withMVar mv print -- should not hang
null
https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/tests/T7787.hs
haskell
should not hang
import Control.Concurrent.MVar import Control.Exception main = do mv <- newMVar 'x' e <- try (modifyMVar mv $ \_ -> return undefined) let _ = e :: Either SomeException ()
7b988e2162b41838291dab7e0c948060f425e947ab7be9ad97f32f8bbe939ec4
ssor/erlangDemos
my_module.erl
This is a simple Erlang module -module(my_module). -export([pie/0, print/1, either_or_both/2, area/1, sign/1, yesno/1, render/0, sum/1, do_sum/1, rev/1, tailrev/1]). pie() -> 3.14. print(Term) -> io:format("The value of Term is: ~w.~n", [Term]). either_or_both(true, B) when is_boolean(B) -> true; either_or_both(A, true) when is_boolean(A) -> true; either_or_both(false, false) -> false. area(Shape) -> case Shape of {circle, Radius} -> Radius * Radius * math:pi(); {square, Side} -> Side * Side; {rectangle, Height, Width} -> Height * Width end. sign(N) when is_number(N) -> if N > 0 -> positive; N < 0 -> negative; true -> zero end. yesno(F) -> case F(true, false) of true -> io:format("yes~n"); false -> io:format("no~n") end. to_html(Items, F) -> ["<dl>\n", [io_lib:format("<dt>~s:\n<dd>~s\n", [F(T),F(D)]) || {T, D} <- Items], "</dl>" ]. render(Items, Em) -> to_html(Items, fun (Text) -> "<" ++ Em ++ ">" ++ Text ++ "</" ++ Em ++ ">" end). render() -> render([{"D&D", "Dungeons and Dragons"}], "b"). sum(0) -> 0; sum(N) -> sum(N-1) + N. do_sum(N) -> do_sum(N, 0). do_sum(0, Total) -> Total; do_sum(N, Total) -> do_sum(N-1, Total+N). rev([X | TheRest]) -> rev(TheRest) ++ [X]; rev([]) -> []. tailrev(List) -> tailrev(List, []). tailrev([X | TheRest], Acc) -> tailrev(TheRest, [X | Acc]); tailrev([], Acc) -> Acc.
null
https://raw.githubusercontent.com/ssor/erlangDemos/632cd905be2c4f275f1c1ae15238e711d7bb9147/erlware-Erlang-and-OTP-in-Action-Source/chapter_02/my_module.erl
erlang
This is a simple Erlang module -module(my_module). -export([pie/0, print/1, either_or_both/2, area/1, sign/1, yesno/1, render/0, sum/1, do_sum/1, rev/1, tailrev/1]). pie() -> 3.14. print(Term) -> io:format("The value of Term is: ~w.~n", [Term]). either_or_both(true, B) when is_boolean(B) -> true; either_or_both(A, true) when is_boolean(A) -> true; either_or_both(false, false) -> false. area(Shape) -> case Shape of {circle, Radius} -> Radius * Radius * math:pi(); {square, Side} -> Side * Side; {rectangle, Height, Width} -> Height * Width end. sign(N) when is_number(N) -> if N > 0 -> positive; N < 0 -> negative; true -> zero end. yesno(F) -> case F(true, false) of true -> io:format("yes~n"); false -> io:format("no~n") end. to_html(Items, F) -> ["<dl>\n", [io_lib:format("<dt>~s:\n<dd>~s\n", [F(T),F(D)]) || {T, D} <- Items], "</dl>" ]. render(Items, Em) -> to_html(Items, fun (Text) -> "<" ++ Em ++ ">" ++ Text ++ "</" ++ Em ++ ">" end). render() -> render([{"D&D", "Dungeons and Dragons"}], "b"). sum(0) -> 0; sum(N) -> sum(N-1) + N. do_sum(N) -> do_sum(N, 0). do_sum(0, Total) -> Total; do_sum(N, Total) -> do_sum(N-1, Total+N). rev([X | TheRest]) -> rev(TheRest) ++ [X]; rev([]) -> []. tailrev(List) -> tailrev(List, []). tailrev([X | TheRest], Acc) -> tailrev(TheRest, [X | Acc]); tailrev([], Acc) -> Acc.
c7b5a3e48a15a4fddb2fabfb7c9f7783fc60444ca381e78bdfd9dc0b634ee465
kappelmann/engaging-large-scale-functional-programming
SubmissionList.hs
# LANGUAGE CPP # {-# LANGUAGE PackageImports #-} module Competition.SubmissionList (submissions) where import Competition.Game.StrategyWrapper (wrapStrategyEvaluation) import Competition.Types (Submission (..)) #include "SubmissionList.Imports.generated" submissions :: [Submission] submissions = tail [ undefined #include "SubmissionList.generated" ]
null
https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/80e8a732c38691ff4e602e0cf77ff2eefb486284/resources/game_tournament_framework/backend/tournament-runner/src/Competition/SubmissionList.hs
haskell
# LANGUAGE PackageImports #
# LANGUAGE CPP # module Competition.SubmissionList (submissions) where import Competition.Game.StrategyWrapper (wrapStrategyEvaluation) import Competition.Types (Submission (..)) #include "SubmissionList.Imports.generated" submissions :: [Submission] submissions = tail [ undefined #include "SubmissionList.generated" ]
9fda7e4d9c2943af4d92336647a40d9694614311db11d678425088b301b7b410
nionita/Barbarossa
TransTab.hs
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE EmptyDataDecls #-} # LANGUAGE MagicHash # # LANGUAGE CPP # module Hash.TransTab ( Cache, newCache, freeCache, retrieveEntry, readCache, writeCache, newGener, -- checkProp ) where import Control . Applicative ( ( < $ > ) ) import Data.Bits import Data.Int import Data.Word import Foreign.Marshal.Array import Foreign.Marshal.Alloc (free) import Foreign.Storable import Foreign.Ptr import Data.Text.Unsafe (inlinePerformIO) -- import Test.QuickCheck hiding ((.&.)) import GHC.Exts import Struct.Struct -- type Index = Int type Mask = Word64 cacheLineSize :: Int cacheLineSize = 64 -- this should be the size in bytes of a memory cache line on modern processors -- The data type Cell and its Storable instance is declared only for alignement purposes -- The operations in the cell are done on PCacheEn elements data Cell instance Storable Cell where sizeOf _ = cacheLineSize alignment _ = cacheLineSize peek _ = return undefined poke _ _ = return () data Cache = Cache { mem :: Ptr Cell, -- the cache line aligned byte array for the data lomask, mimask, zemask :: !Mask, -- masks depending on the size (in entries) of the table gener :: !Word64 -- the generation of the current search } a packed TT entry pCacheEnSize :: Int i.e. 16 bytes instance Storable PCacheEn where sizeOf _ = pCacheEnSize alignment _ = alignment (undefined :: Word64) # INLINE peek # peek p = let !q = castPtr p high ( with zkey ) first wl <- peek (q `plusPtr` 8) return PCacheEn { lo = wl, hi = wh } # INLINE poke # poke p (PCacheEn { lo = wl, hi = wh }) = let !q = castPtr p in do poke q wh poke (q `plusPtr` 8) wl - A packed cache entry consists of 2 Word64 parts ( the order of the bit fields is fixed ): - word 1 ( high ) contains ( ttbitlen is the number of bits to represent the table length in cells , i.e. for 2 ^ 18 cells , ttbitlen = 18 ): - part 1 of the ZKey : - the first ( 64 - ttbitlen - 2 ) higher bits of the ZKey - unused bits - variable length depending on number of tt entries (= ttbitlen - 16 ) - score - 16 bits - part 3 of the ZKey : the last 2 bits - word 2 ( low ) contains ( new ): - generation - 8 bits - node type - 2 bit : exact = 2 , lower = 1 , upper = 0 - depth - 6 bits - nodes - 32 bits - move - 16 bits It results that anyway the number of entries in the table must be at least 2 ^ 18 ( i.e. 2 ^ 16 cells with 4 entries each ) , in which case the " unused bits " part is empty ( 0 bits ) . Part 2 of the ZKey is the cell number where the entry resides . These are fields of the word 1 and the masks that we keep ( here for minimum of 2 ^ 18 entries ): |6 5 2 1 0| |32109 ... 1098765432109876543210| |<--part 1 - -><----score-----><>| | < -----lomask----->| lomask and mimask cover also the unused bits , if any | ... ... < -----mimask---> .. | zemask is the complement of mimask - A packed cache entry consists of 2 Word64 parts (the order of the bit fields is fixed): - word 1 (high) contains (ttbitlen is the number of bits to represent the table length in cells, i.e. for 2^18 cells, ttbitlen = 18): - part 1 of the ZKey: - the first (64 - ttbitlen - 2) higher bits of the ZKey - unused bits - variable length depending on number of tt entries (= ttbitlen - 16) - score - 16 bits - part 3 of the ZKey: the last 2 bits - word 2 (low) contains (new): - generation - 8 bits - node type - 2 bit: exact = 2, lower = 1, upper = 0 - depth - 6 bits - nodes - 32 bits - move - 16 bits It results that anyway the number of entries in the table must be at least 2^18 (i.e. 2^16 cells with 4 entries each), in which case the "unused bits" part is empty (0 bits). Part 2 of the ZKey is the cell number where the entry resides. These are fields of the word 1 and the masks that we keep (here for minimum of 2^18 entries): |6 5 2 1 0| |32109...1098765432109876543210| |<--part 1--><----score-----><>| | <-----lomask----->| lomask and mimask cover also the unused bits, if any |... ...<-----mimask--->..| zemask is the complement of mimask --} part3Mask :: Mask the cell has 4 entries ( other option : 8) minEntries :: Int 2 ^ 18 -- Create a new transposition table with a number of entries -- corresponding to the given (integral) number of MB The number of entries will be rounded up to the next power of 2 newCache :: Int -> IO Cache newCache mb = do let c = mb * 1024 * 1024 `div` pCacheEnSize nentries = max minEntries $ nextPowOf2 c 4 entries per cell lom = fromIntegral $ nentries - 1 mim = lom .&. cellMask memc <- mallocArray ncells return Cache { mem = memc, lomask = lom, mimask = mim, zemask = complement mim, gener = 0 } where cellMask = complement part3Mask -- for speed we keep both masks freeCache :: Cache -> IO () freeCache = free . mem generInc, generMsk :: Word64 1 in first byte generMsk = 0xFF00000000000000 -- to mask all except generation Increase the generation by 1 for a new search , it wraps automatically , beeing in higherst 8 bits newGener :: Cache -> Cache newGener c = c { gener = gener c + generInc } - -- This computes the adress of the first entry of the cell where an entry given by the key -- should be stored , and the ( ideal ) index of that entry -- The ( low ) mask of the transposition table is also used - this determines the size of the index zKeyToCellIndex : : Cache - > ZKey - > ( Ptr PCacheEn , Index ) zKeyToCellIndex tt zkey = ( base , idx ) where idx = fromIntegral $ zkey . & . tt -- This is the wanted calculation : -- cell = idx ` unsafeShiftR ` 2 -- 2 because we have 4 entries per cell -- base = mem tt ` plusPtr ` ( cell * sizeOf Cell ) -- NB : plusPtr advances Bytes ! -- And this is how it is done efficiently : -- idx is entry number , we want cell number : 4 entries per cell = = > shiftR 2 -- plusPtr needs bytes , 16 bytes / entry * 4 entries / cell = 64 bytes / cell = = > shiftL 6 ! base = mem tt ` plusPtr ` ( ( idx ` unsafeShiftR ` 2 ) ` unsafeShiftL ` 6 ) -- Retrieve the ZKey of a packed entry getZKey : : Cache - > Index - > PCacheEn - > ZKey getZKey tt ! idx ( PCacheEn { hi = w1 } ) = zkey where ! zkey = w1 . & . zemask tt -- the first part of the stored ZKey .| . widx . & . mimask tt -- the second part of the stored ZKey widx = fromIntegral idx - -- This computes the adress of the first entry of the cell where an entry given by the key -- should be stored, and the (ideal) index of that entry -- The (low) mask of the transposition table is also used - this determines the size of the index zKeyToCellIndex :: Cache -> ZKey -> (Ptr PCacheEn, Index) zKeyToCellIndex tt zkey = (base, idx) where idx = fromIntegral $ zkey .&. lomask tt -- This is the wanted calculation: -- cell = idx `unsafeShiftR` 2 -- 2 because we have 4 entries per cell -- base = mem tt `plusPtr` (cell * sizeOf Cell) -- NB: plusPtr advances Bytes! -- And this is how it is done efficiently: -- idx is entry number, we want cell number: 4 entries per cell ==> shiftR 2 -- plusPtr needs bytes, 16 bytes/entry * 4 entries/cell = 64 bytes/cell ==> shiftL 6 !base = mem tt `plusPtr` ((idx `unsafeShiftR` 2) `unsafeShiftL` 6) -- Retrieve the ZKey of a packed entry getZKey :: Cache -> Index -> PCacheEn -> ZKey getZKey tt !idx (PCacheEn {hi = w1}) = zkey where !zkey = w1 .&. zemask tt -- the first part of the stored ZKey .|. widx .&. mimask tt -- the second part of the stored ZKey widx = fromIntegral idx --} This computes the adress of the first entry of the cell where an entry given by the key -- should be stored - see the remarks from zKeyToCellIndex for the calculations zKeyToCell :: Cache -> ZKey -> Ptr Word64 zKeyToCell tt zkey = base where idx = fromIntegral $ zkey .&. lomask tt !base = mem tt `plusPtr` ((idx `unsafeShiftR` 2) `unsafeShiftL` 6) -- Faster check if we have the same key under the pointer When we come to check this , we went through zKeyToCell with the sought key -- Which means, we are already in the correct cell, so the mid part of the key ( which in TT is overwritten by the score ) will be all time the same ( zkey . & . ) -- In this case we can mask the mid part of the sought key once we start the search and in the search itself ( up to 4 times ) we have just to mask that part too , -- and compare the result with the precomputed sought key -- So we don't need to reconstruct the original key (which would be more expensive) isSameKey :: Word64 -> Word64 -> Ptr Word64 -> Bool isSameKey !mmask !mzkey !ptr = let w = inlinePerformIO $ peek ptr in w .&. mmask == mzkey Search a position in table based on ZKey The position ZKey determines the cell where the TT entry should be , and there we do a linear search ( i.e. 4 comparisons in case of a miss ) readCache :: Addr# -> IO (Maybe (Int, Int, Int, Move, Int64)) #if __GLASGOW_HASKELL__ >= 708 readCache addr = if isTrue# (eqAddr# addr nullAddr#) #else readCache addr = if (eqAddr# addr nullAddr#) #endif then return Nothing else Just . cacheEnToQuint <$> peek (castPtr (Ptr addr)) retrieveEntry :: Cache -> ZKey -> Addr# retrieveEntry tt zkey = let bas = zKeyToCell tt zkey mkey = zkey .&. zemask tt lasta = bas `plusPtr` lastaAmount in retrieve (zemask tt) mkey lasta bas where retrieve mmask mkey lasta = go where go !crt0@(Ptr a) = if isSameKey mmask mkey crt0 then a else if crt0 >= lasta then nullAddr# else go $ crt0 `plusPtr` pCacheEnSize -- Write the position in the table -- We want to keep table entries that: -- + are from the same generation, or -- + have more nodes behind (from a previous search), or -- + have been searched deeper, or + have a more precise score ( node type 2 before 1 and 0 ) That 's why we choose the order in second word like it is ( easy comparison ) Actually we always search in the whole cell in the hope to find the zkey and replace it -- but also keep track of the weakest entry in the cell, which will be replaced otherwise writeCache :: Cache -> ZKey -> Int -> Int -> Int -> Move -> Int64 -> IO () writeCache !tt !zkey !depth !tp !score !move !nodes = do let bas = zKeyToCell tt zkey gen = gener tt pCE = quintToCacheEn tt zkey depth tp score move nodes mkey = zkey .&. zemask tt lasta = bas `plusPtr` lastaAmount store gen (zemask tt) mkey pCE lasta bas bas maxBound where store !gen !mmask !mkey !pCE !lasta = go where go !crt0 !rep0 !sco0 = if isSameKey mmask mkey crt0 then poke (castPtr crt0) pCE -- here we found the same entry: just update (but depth?) else do lowc <- peek (crt0 `plusPtr` 8) -- take the low word scoreReplaceLow gen lowc crt0 rep0 sco0 (\r -> poke (castPtr r) pCE) (\r s -> if crt0 >= lasta then poke (castPtr r) pCE else go (crt0 `plusPtr` pCacheEnSize) r s) lastaAmount :: Int lastaAmount = 3 * pCacheEnSize -- for computation of the last address in the cell -- Here we implement the logic which decides which entry is weaker -- the low word is the score (when the move is masked away): generation ( when > curr gen : whole score is 0 ) type ( 2 - exact - only few entries , PV , 1 - lower bound : have good moves , 0 - upper bound ) -- depth -- nodes scoreReplaceLow :: Word64 -> Word64 -> Ptr Word64 -> Ptr Word64 -> Word64 -> (Ptr Word64 -> IO ()) -- terminating function -> (Ptr Word64 -> Word64 -> IO ()) -- continue function -> IO () scoreReplaceLow gen lowc crt rep sco term cont | generation > gen = term crt | lowm < sco = cont crt lowm | otherwise = cont rep sco where generation = lowc .&. generMsk lowm = lowc .&. 0xFFFF -- mask the move quintToCacheEn :: Cache -> ZKey -> Int -> Int -> Int -> Move -> Int64 -> PCacheEn quintToCacheEn !tt !zkey !depth !tp !score !(Move move) !nodes = pCE where w1 = (zkey .&. zemask tt) .|. fromIntegral ((score .&. 0xFFFF) `unsafeShiftL` 2) w2 = gener tt .|. (fromIntegral tp `unsafeShiftL` 54) .|. (fromIntegral depth `unsafeShiftL` 48) .|. (fromIntegral nodes `unsafeShiftL` 16) .|. (fromIntegral move) !pCE = PCacheEn { hi = w1, lo = w2 } cacheEnToQuint :: PCacheEn -> (Int, Int, Int, Move, Int64) cacheEnToQuint (PCacheEn { hi = w1, lo = w2 }) = (de, ty, sc, Move mv, no) where u32 = fromIntegral (w1 `unsafeShiftR` 2) :: Word32 s16 = fromIntegral (u32 .&. 0xFFFF) :: Int16 !sc = fromIntegral s16 !no = fromIntegral $ (w2 `unsafeShiftR` 16) .&. 0xFFFFFFFF w2lo = fromIntegral w2 :: Word32 !mv = fromIntegral $ w2lo .&. 0xFFFF w2hi = fromIntegral (w2 `unsafeShiftR` 32) :: Word32 !de = fromIntegral $ (w2hi `unsafeShiftR` 16) .&. 0x3F !ty = fromIntegral $ (w2hi `unsafeShiftR` 22) .&. 0x3 -- perhaps is not a good idea to make them dependent on each other -- this must be tested and optimised for speed nextPowOf2 :: Int -> Int nextPowOf2 x = bit (l - 1) where pow2s = iterate (* 2) 1 l = length $ takeWhile (<= x) pow2s - dumpTT : : Cache - > String - > IO ( ) dumpTT tt = withFile fname WriteMode $ \h - > do forM [ 0 .. lomask tt ] $ \idx - > do let adr = mem tt ` plusPtr ` idx * 16 ent < - peek adr let zk = getZKey tt idx ent ( de , ty , sc , mv , no ) = cacheEnToQuint ent putStrLn $ show idx + + " : ( " + + showHex ( hi ent ) . showHex ( lo ent ) ( show zk + + " " + + show de + + " " + + show ty + + " " + + show sc + + " " + + show mv + + " " + + show no ) - dumpTT :: Cache -> String -> IO () dumpTT tt fname = withFile fname WriteMode $ \h -> do forM [0 .. lomask tt] $ \idx -> do let adr = mem tt `plusPtr` idx * 16 ent <- peek adr let zk = getZKey tt idx ent (de, ty, sc, mv, no) = cacheEnToQuint ent putStrLn $ show idx ++ ": (" ++ showHex (hi ent) . showHex (lo ent) (show zk ++ " " ++ show de ++ " " ++ show ty ++ " " ++ show sc ++ " " ++ show mv ++ " " ++ show no) --} --------- Test in IO ------------- - testIt : : IO Cache testIt = do tt < - newCache 32 let z = 118896 putStrLn $ " tt = " + + show ( mem tt ) " z = " + + show z putStrLn " Write : 5 2 124 ( Move 364 ) 123456 " writeCache tt z 5 2 124 ( Move 364 ) 123456 putStrLn " Read : " let ptr = retrieveEntry tt z mr < - readCache ptr putStrLn $ show mr return tt ----------- QuickCheck ------------- newtype = Q ( Int , Int , Int , Move , Int ) deriving Show mvm : : = ( 1 ` shiftL ` 16 ) - 1 instance Arbitrary Quint where arbitrary = do sc < - choose ( -20000 , 20000 ) ty < - choose ( 0 , 2 ) de < - choose ( 0 , 63 ) mv < - arbitrary ` suchThat ` ( < = mvm ) no < - arbitrary ` suchThat ` ( > = 0 ) return $ Q ( de , ty , sc , Move mv , no ) prop_Inverse : : Cache - > ZKey - > Int - > Quint - > Bool prop_Inverse tt zkey _ ( Q q@(de , ty , sc , mv , no ) ) -- unused : gen = q = = cacheEnToQuint ( quintToCacheEn tt zkey de ty sc mv no ) checkProp : : IO ( ) checkProp = do tt < - newCache 128 let zkey = 0 gen = 0 : : Int putStrLn $ " Fix zkey & gen : " + + show zkey + + " , " + + show gen -- quickCheck $ prop_Inverse tt zkey gen verboseCheck $ prop_Inverse tt zkey gen putStrLn $ " Arbitrary zkey , fixed gen = " + + show gen -- quickCheck $ \z - > prop_Inverse tt z gen verboseCheck $ \z - > prop_Inverse tt z gen - testIt :: IO Cache testIt = do tt <- newCache 32 let z = 118896 putStrLn $ "tt = " ++ show (mem tt) putStrLn $ "z = " ++ show z putStrLn "Write: 5 2 124 (Move 364) 123456" writeCache tt z 5 2 124 (Move 364) 123456 putStrLn "Read:" let ptr = retrieveEntry tt z mr <- readCache ptr putStrLn $ show mr return tt ----------- QuickCheck ------------- newtype Quint = Q (Int, Int, Int, Move, Int) deriving Show mvm :: Word16 mvm = (1 `shiftL` 16) - 1 instance Arbitrary Quint where arbitrary = do sc <- choose (-20000, 20000) ty <- choose (0, 2) de <- choose (0, 63) mv <- arbitrary `suchThat` (<= mvm) no <- arbitrary `suchThat` (>= 0) return $ Q (de, ty, sc, Move mv, no) prop_Inverse :: Cache -> ZKey -> Int -> Quint -> Bool prop_Inverse tt zkey _ (Q q@(de, ty, sc, mv, no)) -- unused: gen = q == cacheEnToQuint (quintToCacheEn tt zkey de ty sc mv no) checkProp :: IO () checkProp = do tt <- newCache 128 let zkey = 0 gen = 0 :: Int putStrLn $ "Fix zkey & gen: " ++ show zkey ++ ", " ++ show gen -- quickCheck $ prop_Inverse tt zkey gen verboseCheck $ prop_Inverse tt zkey gen putStrLn $ "Arbitrary zkey, fixed gen = " ++ show gen -- quickCheck $ \z -> prop_Inverse tt z gen verboseCheck $ \z -> prop_Inverse tt z gen --}
null
https://raw.githubusercontent.com/nionita/Barbarossa/81032b17ac36dc01771cbcfaaae88c30e7661d7b/Hash/TransTab.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE EmptyDataDecls # checkProp import Test.QuickCheck hiding ((.&.)) type Index = Int this should be the size in bytes of a memory cache line on modern processors The data type Cell and its Storable instance is declared only for alignement purposes The operations in the cell are done on PCacheEn elements the cache line aligned byte array for the data masks depending on the size (in entries) of the table the generation of the current search part 1 - -><----score-----><>| ---lomask----->| lomask and mimask cover also the unused bits , if any ---mimask---> .. | zemask is the complement of mimask part 1--><----score-----><>| ---lomask----->| lomask and mimask cover also the unused bits, if any ---mimask--->..| zemask is the complement of mimask } Create a new transposition table with a number of entries corresponding to the given (integral) number of MB for speed we keep both masks to mask all except generation This computes the adress of the first entry of the cell where an entry given by the key should be stored , and the ( ideal ) index of that entry The ( low ) mask of the transposition table is also used - this determines the size of the index This is the wanted calculation : cell = idx ` unsafeShiftR ` 2 -- 2 because we have 4 entries per cell base = mem tt ` plusPtr ` ( cell * sizeOf Cell ) NB : plusPtr advances Bytes ! And this is how it is done efficiently : idx is entry number , we want cell number : 4 entries per cell = = > shiftR 2 plusPtr needs bytes , 16 bytes / entry * 4 entries / cell = 64 bytes / cell = = > shiftL 6 Retrieve the ZKey of a packed entry the first part of the stored ZKey the second part of the stored ZKey This computes the adress of the first entry of the cell where an entry given by the key should be stored, and the (ideal) index of that entry The (low) mask of the transposition table is also used - this determines the size of the index This is the wanted calculation: cell = idx `unsafeShiftR` 2 -- 2 because we have 4 entries per cell base = mem tt `plusPtr` (cell * sizeOf Cell) NB: plusPtr advances Bytes! And this is how it is done efficiently: idx is entry number, we want cell number: 4 entries per cell ==> shiftR 2 plusPtr needs bytes, 16 bytes/entry * 4 entries/cell = 64 bytes/cell ==> shiftL 6 Retrieve the ZKey of a packed entry the first part of the stored ZKey the second part of the stored ZKey } should be stored - see the remarks from zKeyToCellIndex for the calculations Faster check if we have the same key under the pointer Which means, we are already in the correct cell, so the mid part of the key In this case we can mask the mid part of the sought key once we start the search and compare the result with the precomputed sought key So we don't need to reconstruct the original key (which would be more expensive) Write the position in the table We want to keep table entries that: + are from the same generation, or + have more nodes behind (from a previous search), or + have been searched deeper, or but also keep track of the weakest entry in the cell, which will be replaced otherwise here we found the same entry: just update (but depth?) take the low word for computation of the last address in the cell Here we implement the logic which decides which entry is weaker the low word is the score (when the move is masked away): depth nodes terminating function continue function mask the move perhaps is not a good idea to make them dependent on each other this must be tested and optimised for speed } ------- Test in IO ------------- --------- QuickCheck ------------- unused : gen quickCheck $ prop_Inverse tt zkey gen quickCheck $ \z - > prop_Inverse tt z gen --------- QuickCheck ------------- unused: gen quickCheck $ prop_Inverse tt zkey gen quickCheck $ \z -> prop_Inverse tt z gen }
# LANGUAGE MagicHash # # LANGUAGE CPP # module Hash.TransTab ( Cache, newCache, freeCache, retrieveEntry, readCache, writeCache, newGener, ) where import Control . Applicative ( ( < $ > ) ) import Data.Bits import Data.Int import Data.Word import Foreign.Marshal.Array import Foreign.Marshal.Alloc (free) import Foreign.Storable import Foreign.Ptr import Data.Text.Unsafe (inlinePerformIO) import GHC.Exts import Struct.Struct type Mask = Word64 cacheLineSize :: Int data Cell instance Storable Cell where sizeOf _ = cacheLineSize alignment _ = cacheLineSize peek _ = return undefined poke _ _ = return () data Cache = Cache { lomask, mimask, } a packed TT entry pCacheEnSize :: Int i.e. 16 bytes instance Storable PCacheEn where sizeOf _ = pCacheEnSize alignment _ = alignment (undefined :: Word64) # INLINE peek # peek p = let !q = castPtr p high ( with zkey ) first wl <- peek (q `plusPtr` 8) return PCacheEn { lo = wl, hi = wh } # INLINE poke # poke p (PCacheEn { lo = wl, hi = wh }) = let !q = castPtr p in do poke q wh poke (q `plusPtr` 8) wl - A packed cache entry consists of 2 Word64 parts ( the order of the bit fields is fixed ): - word 1 ( high ) contains ( ttbitlen is the number of bits to represent the table length in cells , i.e. for 2 ^ 18 cells , ttbitlen = 18 ): - part 1 of the ZKey : - the first ( 64 - ttbitlen - 2 ) higher bits of the ZKey - unused bits - variable length depending on number of tt entries (= ttbitlen - 16 ) - score - 16 bits - part 3 of the ZKey : the last 2 bits - word 2 ( low ) contains ( new ): - generation - 8 bits - node type - 2 bit : exact = 2 , lower = 1 , upper = 0 - depth - 6 bits - nodes - 32 bits - move - 16 bits It results that anyway the number of entries in the table must be at least 2 ^ 18 ( i.e. 2 ^ 16 cells with 4 entries each ) , in which case the " unused bits " part is empty ( 0 bits ) . Part 2 of the ZKey is the cell number where the entry resides . These are fields of the word 1 and the masks that we keep ( here for minimum of 2 ^ 18 entries ): |6 5 2 1 0| |32109 ... 1098765432109876543210| - A packed cache entry consists of 2 Word64 parts (the order of the bit fields is fixed): - word 1 (high) contains (ttbitlen is the number of bits to represent the table length in cells, i.e. for 2^18 cells, ttbitlen = 18): - part 1 of the ZKey: - the first (64 - ttbitlen - 2) higher bits of the ZKey - unused bits - variable length depending on number of tt entries (= ttbitlen - 16) - score - 16 bits - part 3 of the ZKey: the last 2 bits - word 2 (low) contains (new): - generation - 8 bits - node type - 2 bit: exact = 2, lower = 1, upper = 0 - depth - 6 bits - nodes - 32 bits - move - 16 bits It results that anyway the number of entries in the table must be at least 2^18 (i.e. 2^16 cells with 4 entries each), in which case the "unused bits" part is empty (0 bits). Part 2 of the ZKey is the cell number where the entry resides. These are fields of the word 1 and the masks that we keep (here for minimum of 2^18 entries): |6 5 2 1 0| |32109...1098765432109876543210| part3Mask :: Mask the cell has 4 entries ( other option : 8) minEntries :: Int 2 ^ 18 The number of entries will be rounded up to the next power of 2 newCache :: Int -> IO Cache newCache mb = do let c = mb * 1024 * 1024 `div` pCacheEnSize nentries = max minEntries $ nextPowOf2 c 4 entries per cell lom = fromIntegral $ nentries - 1 mim = lom .&. cellMask memc <- mallocArray ncells return Cache { mem = memc, lomask = lom, mimask = mim, zemask = complement mim, gener = 0 } freeCache :: Cache -> IO () freeCache = free . mem generInc, generMsk :: Word64 1 in first byte Increase the generation by 1 for a new search , it wraps automatically , beeing in higherst 8 bits newGener :: Cache -> Cache newGener c = c { gener = gener c + generInc } - zKeyToCellIndex : : Cache - > ZKey - > ( Ptr PCacheEn , Index ) zKeyToCellIndex tt zkey = ( base , idx ) where idx = fromIntegral $ zkey . & . tt ! base = mem tt ` plusPtr ` ( ( idx ` unsafeShiftR ` 2 ) ` unsafeShiftL ` 6 ) getZKey : : Cache - > Index - > PCacheEn - > ZKey getZKey tt ! idx ( PCacheEn { hi = w1 } ) = zkey widx = fromIntegral idx - zKeyToCellIndex :: Cache -> ZKey -> (Ptr PCacheEn, Index) zKeyToCellIndex tt zkey = (base, idx) where idx = fromIntegral $ zkey .&. lomask tt !base = mem tt `plusPtr` ((idx `unsafeShiftR` 2) `unsafeShiftL` 6) getZKey :: Cache -> Index -> PCacheEn -> ZKey getZKey tt !idx (PCacheEn {hi = w1}) = zkey widx = fromIntegral idx This computes the adress of the first entry of the cell where an entry given by the key zKeyToCell :: Cache -> ZKey -> Ptr Word64 zKeyToCell tt zkey = base where idx = fromIntegral $ zkey .&. lomask tt !base = mem tt `plusPtr` ((idx `unsafeShiftR` 2) `unsafeShiftL` 6) When we come to check this , we went through zKeyToCell with the sought key ( which in TT is overwritten by the score ) will be all time the same ( zkey . & . ) and in the search itself ( up to 4 times ) we have just to mask that part too , isSameKey :: Word64 -> Word64 -> Ptr Word64 -> Bool isSameKey !mmask !mzkey !ptr = let w = inlinePerformIO $ peek ptr in w .&. mmask == mzkey Search a position in table based on ZKey The position ZKey determines the cell where the TT entry should be , and there we do a linear search ( i.e. 4 comparisons in case of a miss ) readCache :: Addr# -> IO (Maybe (Int, Int, Int, Move, Int64)) #if __GLASGOW_HASKELL__ >= 708 readCache addr = if isTrue# (eqAddr# addr nullAddr#) #else readCache addr = if (eqAddr# addr nullAddr#) #endif then return Nothing else Just . cacheEnToQuint <$> peek (castPtr (Ptr addr)) retrieveEntry :: Cache -> ZKey -> Addr# retrieveEntry tt zkey = let bas = zKeyToCell tt zkey mkey = zkey .&. zemask tt lasta = bas `plusPtr` lastaAmount in retrieve (zemask tt) mkey lasta bas where retrieve mmask mkey lasta = go where go !crt0@(Ptr a) = if isSameKey mmask mkey crt0 then a else if crt0 >= lasta then nullAddr# else go $ crt0 `plusPtr` pCacheEnSize + have a more precise score ( node type 2 before 1 and 0 ) That 's why we choose the order in second word like it is ( easy comparison ) Actually we always search in the whole cell in the hope to find the zkey and replace it writeCache :: Cache -> ZKey -> Int -> Int -> Int -> Move -> Int64 -> IO () writeCache !tt !zkey !depth !tp !score !move !nodes = do let bas = zKeyToCell tt zkey gen = gener tt pCE = quintToCacheEn tt zkey depth tp score move nodes mkey = zkey .&. zemask tt lasta = bas `plusPtr` lastaAmount store gen (zemask tt) mkey pCE lasta bas bas maxBound where store !gen !mmask !mkey !pCE !lasta = go where go !crt0 !rep0 !sco0 = if isSameKey mmask mkey crt0 else do scoreReplaceLow gen lowc crt0 rep0 sco0 (\r -> poke (castPtr r) pCE) (\r s -> if crt0 >= lasta then poke (castPtr r) pCE else go (crt0 `plusPtr` pCacheEnSize) r s) lastaAmount :: Int generation ( when > curr gen : whole score is 0 ) type ( 2 - exact - only few entries , PV , 1 - lower bound : have good moves , 0 - upper bound ) scoreReplaceLow :: Word64 -> Word64 -> Ptr Word64 -> Ptr Word64 -> Word64 -> IO () scoreReplaceLow gen lowc crt rep sco term cont | generation > gen = term crt | lowm < sco = cont crt lowm | otherwise = cont rep sco where generation = lowc .&. generMsk quintToCacheEn :: Cache -> ZKey -> Int -> Int -> Int -> Move -> Int64 -> PCacheEn quintToCacheEn !tt !zkey !depth !tp !score !(Move move) !nodes = pCE where w1 = (zkey .&. zemask tt) .|. fromIntegral ((score .&. 0xFFFF) `unsafeShiftL` 2) w2 = gener tt .|. (fromIntegral tp `unsafeShiftL` 54) .|. (fromIntegral depth `unsafeShiftL` 48) .|. (fromIntegral nodes `unsafeShiftL` 16) .|. (fromIntegral move) !pCE = PCacheEn { hi = w1, lo = w2 } cacheEnToQuint :: PCacheEn -> (Int, Int, Int, Move, Int64) cacheEnToQuint (PCacheEn { hi = w1, lo = w2 }) = (de, ty, sc, Move mv, no) where u32 = fromIntegral (w1 `unsafeShiftR` 2) :: Word32 s16 = fromIntegral (u32 .&. 0xFFFF) :: Int16 !sc = fromIntegral s16 !no = fromIntegral $ (w2 `unsafeShiftR` 16) .&. 0xFFFFFFFF w2lo = fromIntegral w2 :: Word32 !mv = fromIntegral $ w2lo .&. 0xFFFF w2hi = fromIntegral (w2 `unsafeShiftR` 32) :: Word32 !de = fromIntegral $ (w2hi `unsafeShiftR` 16) .&. 0x3F !ty = fromIntegral $ (w2hi `unsafeShiftR` 22) .&. 0x3 nextPowOf2 :: Int -> Int nextPowOf2 x = bit (l - 1) where pow2s = iterate (* 2) 1 l = length $ takeWhile (<= x) pow2s - dumpTT : : Cache - > String - > IO ( ) dumpTT tt = withFile fname WriteMode $ \h - > do forM [ 0 .. lomask tt ] $ \idx - > do let adr = mem tt ` plusPtr ` idx * 16 ent < - peek adr let zk = getZKey tt idx ent ( de , ty , sc , mv , no ) = cacheEnToQuint ent putStrLn $ show idx + + " : ( " + + showHex ( hi ent ) . showHex ( lo ent ) ( show zk + + " " + + show de + + " " + + show ty + + " " + + show sc + + " " + + show mv + + " " + + show no ) - dumpTT :: Cache -> String -> IO () dumpTT tt fname = withFile fname WriteMode $ \h -> do forM [0 .. lomask tt] $ \idx -> do let adr = mem tt `plusPtr` idx * 16 ent <- peek adr let zk = getZKey tt idx ent (de, ty, sc, mv, no) = cacheEnToQuint ent putStrLn $ show idx ++ ": (" ++ showHex (hi ent) . showHex (lo ent) (show zk ++ " " ++ show de ++ " " ++ show ty ++ " " ++ show sc ++ " " ++ show mv ++ " " ++ show no) - testIt : : IO Cache testIt = do tt < - newCache 32 let z = 118896 putStrLn $ " tt = " + + show ( mem tt ) " z = " + + show z putStrLn " Write : 5 2 124 ( Move 364 ) 123456 " writeCache tt z 5 2 124 ( Move 364 ) 123456 putStrLn " Read : " let ptr = retrieveEntry tt z mr < - readCache ptr putStrLn $ show mr return tt newtype = Q ( Int , Int , Int , Move , Int ) deriving Show mvm : : = ( 1 ` shiftL ` 16 ) - 1 instance Arbitrary Quint where arbitrary = do sc < - choose ( -20000 , 20000 ) ty < - choose ( 0 , 2 ) de < - choose ( 0 , 63 ) mv < - arbitrary ` suchThat ` ( < = mvm ) no < - arbitrary ` suchThat ` ( > = 0 ) return $ Q ( de , ty , sc , Move mv , no ) prop_Inverse : : Cache - > ZKey - > Int - > Quint - > Bool = q = = cacheEnToQuint ( quintToCacheEn tt zkey de ty sc mv no ) checkProp : : IO ( ) checkProp = do tt < - newCache 128 let zkey = 0 gen = 0 : : Int putStrLn $ " Fix zkey & gen : " + + show zkey + + " , " + + show gen verboseCheck $ prop_Inverse tt zkey gen putStrLn $ " Arbitrary zkey , fixed gen = " + + show gen verboseCheck $ \z - > prop_Inverse tt z gen - testIt :: IO Cache testIt = do tt <- newCache 32 let z = 118896 putStrLn $ "tt = " ++ show (mem tt) putStrLn $ "z = " ++ show z putStrLn "Write: 5 2 124 (Move 364) 123456" writeCache tt z 5 2 124 (Move 364) 123456 putStrLn "Read:" let ptr = retrieveEntry tt z mr <- readCache ptr putStrLn $ show mr return tt newtype Quint = Q (Int, Int, Int, Move, Int) deriving Show mvm :: Word16 mvm = (1 `shiftL` 16) - 1 instance Arbitrary Quint where arbitrary = do sc <- choose (-20000, 20000) ty <- choose (0, 2) de <- choose (0, 63) mv <- arbitrary `suchThat` (<= mvm) no <- arbitrary `suchThat` (>= 0) return $ Q (de, ty, sc, Move mv, no) prop_Inverse :: Cache -> ZKey -> Int -> Quint -> Bool = q == cacheEnToQuint (quintToCacheEn tt zkey de ty sc mv no) checkProp :: IO () checkProp = do tt <- newCache 128 let zkey = 0 gen = 0 :: Int putStrLn $ "Fix zkey & gen: " ++ show zkey ++ ", " ++ show gen verboseCheck $ prop_Inverse tt zkey gen putStrLn $ "Arbitrary zkey, fixed gen = " ++ show gen verboseCheck $ \z -> prop_Inverse tt z gen
142dbdd2561ae77ed317123f3c8d703665eab66dd7e9adea65cd40ef66cf2de0
mirage/ptt-deployer
logging.mli
val init : unit -> unit (** Initialise the Logs library with some sensible defaults. *) val run : unit Current.or_error Lwt.t -> unit Current.or_error (** [run x] is like [Lwt_main.run x], but logs the returned error, if any. *)
null
https://raw.githubusercontent.com/mirage/ptt-deployer/9a2bd4464c6dbc189ba1331adeaedc73defe01d2/src/logging.mli
ocaml
* Initialise the Logs library with some sensible defaults. * [run x] is like [Lwt_main.run x], but logs the returned error, if any.
val init : unit -> unit val run : unit Current.or_error Lwt.t -> unit Current.or_error
64c144b507db07555056ff271725cbb28dc2747b25b67c12fc8f2d4b69bb55b2
chetmurthy/ensemble
socksupp.mli
(**************************************************************) (* SOCKSUPP.MLI *) Ohad Rodeh : 10/2002 (**************************************************************) type buf = string type len = int type ofs = int type socket = Unix.file_descr type timeval = { mutable sec10 : int ; mutable usec : int } type mcast_send_recv = | Recv_only | Send_only | Both type win = Win_3_11 | Win_95_98 | Win_NT_3_5 | Win_NT_4 | Win_2000 type os_t_v = OS_Unix | OS_Win of win val print_line : string -> unit val is_unix : bool val max_msg_size : int val some_of : 'a option -> 'a exception Out_of_iovec_memory
null
https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/socket/socksupp.mli
ocaml
************************************************************ SOCKSUPP.MLI ************************************************************
Ohad Rodeh : 10/2002 type buf = string type len = int type ofs = int type socket = Unix.file_descr type timeval = { mutable sec10 : int ; mutable usec : int } type mcast_send_recv = | Recv_only | Send_only | Both type win = Win_3_11 | Win_95_98 | Win_NT_3_5 | Win_NT_4 | Win_2000 type os_t_v = OS_Unix | OS_Win of win val print_line : string -> unit val is_unix : bool val max_msg_size : int val some_of : 'a option -> 'a exception Out_of_iovec_memory
45997a57bff3bebb9c7b9b7a24c3d7ed87198dd585c31cb752214b96b52cfa16
tmfg/mmtis-national-access-point
error_landing.cljs
(ns ote.views.error.error-landing (:require [stylefy.core :as stylefy] [ote.style.buttons :as style-buttons] [ote.localization :refer [tr]])) (defn error-landing-vw [{:keys [error-landing]}] [:div [:h2 (or (:title error-landing) (tr [:error-landing :resource-not-found]))] [:div (:desc error-landing)] [:br] [:div [:a (merge {:href (str "#/") :id "btn-go-to-frontpage"} (stylefy/use-style style-buttons/primary-button)) (tr [:error-landing :go-to-frontpage])]]])
null
https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/src/cljs/ote/views/error/error_landing.cljs
clojure
(ns ote.views.error.error-landing (:require [stylefy.core :as stylefy] [ote.style.buttons :as style-buttons] [ote.localization :refer [tr]])) (defn error-landing-vw [{:keys [error-landing]}] [:div [:h2 (or (:title error-landing) (tr [:error-landing :resource-not-found]))] [:div (:desc error-landing)] [:br] [:div [:a (merge {:href (str "#/") :id "btn-go-to-frontpage"} (stylefy/use-style style-buttons/primary-button)) (tr [:error-landing :go-to-frontpage])]]])
b0277dbcb5e8d1ff505690db5466fc6ab39a755dce6bcc9596ae03ecedd47dbd
cyverse-archive/DiscoveryEnvironmentBackend
serve_test.clj
(ns user-preferences.serve-test (:use [midje.sweet] [kameleon.user-prefs-queries] [kameleon.misc-queries] [user-preferences.serve] [ring.util.response])) (fact "santize works" (sanitize {:foo "bar"}) => {:foo "bar"} (sanitize nil) => {} (sanitize {:preferences "{\"foo\":\"bar\"}"}) => {:preferences {:foo "bar"}} (sanitize {:preferences "{\"foo\":\"bar\"}" :id "foo" :user_id "bar"}) => {:preferences {:foo "bar"}}) (fact "not-a-user returns a sane map" (not-a-user "foo") => {:status 404 :body {:user "foo"}}) (fact "invalid content returns a sane map" (invalid-content "foo") {:status 415 :body {:content-type "foo"}}) (with-redefs [user? (fn [u] false)] (fact "validate macro is sane-ish with a bad user." (validate ["foo" {:content-type "poopy"} true]) => {:status 404 :body {:user "foo"}} (validate ["foo" {:content-type "poopy"} false]) => {:status 404 :body {:user "foo"}})) (with-redefs [user? (fn [u] true)] (fact "validate macro is sane-ish with a bad content-type." (validate ["foo" {:content-type "poopy"} true]) => {:status 415 :body {:content-type "poopy"}} (validate ["foo" {:content-type "poopy"} false] true) => true)) ;;; Testing the (get-req) function (with-redefs [user? (fn [u] true) user-prefs (fn [u] "{\"foo\":\"bar\"}")] (fact "get-req returns a sane value with a good user and content type" (get-req "foo" {:content-type "application-json"}) => (response {:foo "bar"})) (fact "get-req shouldn't care about the content-type" (get-req "foo" {:content-type "foo"}) => (response {:foo "bar"}))) (with-redefs [user? (fn [u] false) user-prefs (fn [u] "{\"foo\":\"bar\"}")] (fact "get-req returns an error map when the user is bad" (get-req "foo" {:content-type "application-json"}) => {:status 404 :body {:user "foo"}})) ;;; Testing the (post-req) function (with-redefs [user? (fn [u] true) save-user-prefs (fn [u b] {:user_id 50 :preferences "{\"foo\":\"bar\"}" :id "boo"})] (fact "post-req returns a sane value with a good user and content type" (post-req "foo" {:content-type "application/json" :body "{\"foo\":\"bar\"}"}) => (response {:preferences {:foo "bar"}})) (fact "post-req should care about the content type" (post-req "foo" {:content-type "foo" :body "{\"foo\":\"bar\"}"}) => (invalid-content "foo"))) (with-redefs [user? (fn [u] false) save-user-prefs (fn [u b] {:user_id 50 :preferences "{\"foo\":\"bar\"}" :id "boo"})] (fact "post-req should care about the user existing" (post-req "foo" {:content-type "foo" :body "{\"foo\":\"bar\"}"}) => (not-a-user "foo"))) ;;; testing the (delete-req) function (with-redefs [user? (fn [u] true) delete-user-prefs (fn [u] {:user_id 50 :preferences "{\"foo\":\"bar\"}" :id "boo"})] (fact "delete-req returns a sane value" (delete-req "foo" {:content-type "application/json" :body "{\"foo\":\"bar\"}"}) => "" (delete-req "foo" {:content-type "foo" :body "{\"foo\":\"bar\"}"}) => "")) (with-redefs [user? (fn [u] false) delete-user-prefs (fn [u] {:user_id 50 :preferences "{\"foo\":\"bar\"}" :id "boo"})] (fact "delete-req returns a sane value" (delete-req "foo" {:content-type "application/json" :body "{\"foo\":\"bar\"}"}) => ""))
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/user-preferences/test/user_preferences/serve_test.clj
clojure
Testing the (get-req) function Testing the (post-req) function testing the (delete-req) function
(ns user-preferences.serve-test (:use [midje.sweet] [kameleon.user-prefs-queries] [kameleon.misc-queries] [user-preferences.serve] [ring.util.response])) (fact "santize works" (sanitize {:foo "bar"}) => {:foo "bar"} (sanitize nil) => {} (sanitize {:preferences "{\"foo\":\"bar\"}"}) => {:preferences {:foo "bar"}} (sanitize {:preferences "{\"foo\":\"bar\"}" :id "foo" :user_id "bar"}) => {:preferences {:foo "bar"}}) (fact "not-a-user returns a sane map" (not-a-user "foo") => {:status 404 :body {:user "foo"}}) (fact "invalid content returns a sane map" (invalid-content "foo") {:status 415 :body {:content-type "foo"}}) (with-redefs [user? (fn [u] false)] (fact "validate macro is sane-ish with a bad user." (validate ["foo" {:content-type "poopy"} true]) => {:status 404 :body {:user "foo"}} (validate ["foo" {:content-type "poopy"} false]) => {:status 404 :body {:user "foo"}})) (with-redefs [user? (fn [u] true)] (fact "validate macro is sane-ish with a bad content-type." (validate ["foo" {:content-type "poopy"} true]) => {:status 415 :body {:content-type "poopy"}} (validate ["foo" {:content-type "poopy"} false] true) => true)) (with-redefs [user? (fn [u] true) user-prefs (fn [u] "{\"foo\":\"bar\"}")] (fact "get-req returns a sane value with a good user and content type" (get-req "foo" {:content-type "application-json"}) => (response {:foo "bar"})) (fact "get-req shouldn't care about the content-type" (get-req "foo" {:content-type "foo"}) => (response {:foo "bar"}))) (with-redefs [user? (fn [u] false) user-prefs (fn [u] "{\"foo\":\"bar\"}")] (fact "get-req returns an error map when the user is bad" (get-req "foo" {:content-type "application-json"}) => {:status 404 :body {:user "foo"}})) (with-redefs [user? (fn [u] true) save-user-prefs (fn [u b] {:user_id 50 :preferences "{\"foo\":\"bar\"}" :id "boo"})] (fact "post-req returns a sane value with a good user and content type" (post-req "foo" {:content-type "application/json" :body "{\"foo\":\"bar\"}"}) => (response {:preferences {:foo "bar"}})) (fact "post-req should care about the content type" (post-req "foo" {:content-type "foo" :body "{\"foo\":\"bar\"}"}) => (invalid-content "foo"))) (with-redefs [user? (fn [u] false) save-user-prefs (fn [u b] {:user_id 50 :preferences "{\"foo\":\"bar\"}" :id "boo"})] (fact "post-req should care about the user existing" (post-req "foo" {:content-type "foo" :body "{\"foo\":\"bar\"}"}) => (not-a-user "foo"))) (with-redefs [user? (fn [u] true) delete-user-prefs (fn [u] {:user_id 50 :preferences "{\"foo\":\"bar\"}" :id "boo"})] (fact "delete-req returns a sane value" (delete-req "foo" {:content-type "application/json" :body "{\"foo\":\"bar\"}"}) => "" (delete-req "foo" {:content-type "foo" :body "{\"foo\":\"bar\"}"}) => "")) (with-redefs [user? (fn [u] false) delete-user-prefs (fn [u] {:user_id 50 :preferences "{\"foo\":\"bar\"}" :id "boo"})] (fact "delete-req returns a sane value" (delete-req "foo" {:content-type "application/json" :body "{\"foo\":\"bar\"}"}) => ""))
30ab920bd2e995ff5e30283cd7be7f4a0a2fd12044102e243f1dccff8db99306
borkdude/advent-of-cljc
mrmcc3.cljc
(ns aoc.y2018.d08.mrmcc3 (:refer-clojure :exclude [read-string format]) (:require [aoc.utils :as u :refer [deftest read-string format]] [aoc.y2018.d08.data :refer [input answer-1 answer-2]] [clojure.test :refer [is testing]] [clojure.string :as str])) (def count-vals (map (comp count :vals))) (defn node-value [subs meta] (if (seq subs) (let [value-fn #(:value (nth subs (dec %) {:value 0}))] (transduce (map value-fn) + meta)) (reduce + meta))) (defn children [vals] (lazy-seq (let [c (nth vals 0) m (nth vals 1) subs (vec (take c (children (subvec vals 2)))) sub-l (transduce count-vals + subs) l (+ 2 sub-l m) meta (subvec vals (+ 2 sub-l) l)] (cons {:vals (subvec vals 0 l) :subs subs :meta meta :value (node-value subs meta)} (children (subvec vals l)))))) (def root (->> (str/split input #" ") (mapv u/parse-int) children first delay)) ;; delay (defn solve-1 [] (->> @root (tree-seq (comp seq :subs) :subs) (mapcat :meta) (reduce +))) (defn solve-2 [] (:value @root)) (deftest part-1 (is (= (str answer-1) (str (solve-1))))) (deftest part-2 (is (= (str answer-2) (str (solve-2)))))
null
https://raw.githubusercontent.com/borkdude/advent-of-cljc/17c8abb876b95ab01eee418f1da2e402e845c596/src/aoc/y2018/d08/mrmcc3.cljc
clojure
delay
(ns aoc.y2018.d08.mrmcc3 (:refer-clojure :exclude [read-string format]) (:require [aoc.utils :as u :refer [deftest read-string format]] [aoc.y2018.d08.data :refer [input answer-1 answer-2]] [clojure.test :refer [is testing]] [clojure.string :as str])) (def count-vals (map (comp count :vals))) (defn node-value [subs meta] (if (seq subs) (let [value-fn #(:value (nth subs (dec %) {:value 0}))] (transduce (map value-fn) + meta)) (reduce + meta))) (defn children [vals] (lazy-seq (let [c (nth vals 0) m (nth vals 1) subs (vec (take c (children (subvec vals 2)))) sub-l (transduce count-vals + subs) l (+ 2 sub-l m) meta (subvec vals (+ 2 sub-l) l)] (cons {:vals (subvec vals 0 l) :subs subs :meta meta :value (node-value subs meta)} (children (subvec vals l)))))) (def root (defn solve-1 [] (->> @root (tree-seq (comp seq :subs) :subs) (mapcat :meta) (reduce +))) (defn solve-2 [] (:value @root)) (deftest part-1 (is (= (str answer-1) (str (solve-1))))) (deftest part-2 (is (= (str answer-2) (str (solve-2)))))
1be234d8dc5eda417804f336b3d4c7542c15935adc937f2465d8027e3c203a35
manuel-serrano/bigloo
dsssl.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / recette / dsssl.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Tue Mar 31 09:21:59 1998 * / * Last change : Mon Nov 11 08:39:25 2013 ( serrano ) * / ;* ------------------------------------------------------------- */ * DSSSL funcall tests * / ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module dsssl (import (main "main.scm") (vararity "vararity.scm")) (include "test.sch") (export (test-dsssl) (foo ::int y #!optional z (zz 1) #!rest r #!key i (j 1)) (dsssl2 a #!optional b (c 'c) (d 'd)) (dsssl4 a #!key b (c 'c) (d 'd)) (dsssl6 #!optional (a 'a) b) (dsssl7 #!optional (dsssl7 2) (z dsssl7)) (dsssl8 #!key (y 2) (z y)) (dsssl9 ::input-port ::output-port #!optional (s 1) (o -1)) (dsssl11 x y #!optional z #!key i (j 1) #!rest r) (dsssl-lexical b c #!optional (=::procedure equal?)) (dt->sec a #!key (x #t))) (eval (export dsssl2) (export dsssl3) (export dsssl3b) (export dsssl4) (export dsssl6))) (define (foo x y #!optional z (zz 1) #!rest r #!key i (j 1)) (let ((f (lambda (z y #!key (i 8)) (list z y i)))) (labels ((g (a b #!rest l) (list a b l))) (list x y z zz i: i j: j)))) (define (test-dsssl-eval) (eval '(define (dsssl x y #!optional z (zz 1) #!rest r #!key i (j 1)) (let ((f (lambda (z y #!key (i 8)) (list z y i)))) (labels ((g (a b #!rest l) (list a b l))) (list x y z zz i: i j: j))))) #t) (define (dsssl-lexical b c #!optional (=::procedure equal?)) (= b c)) (define (connect #!optional environment #!key (hostname "localhost")) (cons environment hostname)) ;*---------------------------------------------------------------------*/ * * / ;*---------------------------------------------------------------------*/ (define (dsssl2 a #!optional b (c 'c) (d 'd)) (list a b c d)) (define (dsssl2-test1) (list (dsssl2 11 22 33 44) (dsssl2 11 22 33) (dsssl2 11 22) (dsssl2 11))) (define (dsssl2-test1-eval) (eval '(list (dsssl2 11 22 33 44) (dsssl2 11 22 33) (dsssl2 11 22) (dsssl2 11)))) (define (dsssl2-test2 f) (list (f 11 22 33 44) (f 11 22 33) (f 11 22) (f 11))) (define (dsssl2-test3 f) (list (apply f '(11 22 33 44)) (apply f '(11 22 33)) (apply f '(11 22)) (apply f '(11)))) (define (dsssl2-test4 f . args) (apply f args)) (define (dsssl3-test1) (list (dsssl3 11 22 33 44) (dsssl3 11 22 33) (dsssl3 11 22) (dsssl3 11))) (define (dsssl3-test2) (list ((car (list dsssl3)) 11 22 33 44) ((car (list dsssl3)) 11 22 33) ((car (list dsssl3)) 11 22) ((car (list dsssl3)) 11))) (define (dsssl3b-test1) (list (dsssl3b 11 c: 33 b: 22 d: 44) (dsssl3b 11 b: 22 c: 33) (dsssl3b 11 b: 22) (dsssl3b 11))) (define (dsssl3b-test2) (list ((car (list dsssl3b)) 11 d: 44 b: 22 c: 33) ((car (list dsssl3b)) 11 c: 33 b: 22) ((car (list dsssl3b)) 11 b: 22) ((car (list dsssl3b)) 11))) ;*---------------------------------------------------------------------*/ ;* dsssl4 ... */ ;*---------------------------------------------------------------------*/ (define (dsssl4 a #!key b (d 'd) (c 'c)) (list a b c d)) (define (dsssl4-test1) (list (dsssl4 11 c: 33 b: 22 d: 44) (dsssl4 11 b: 22 c: 33) (dsssl4 11 b: 22) (dsssl4 11))) (define (dsssl4-test1-eval) (eval '(list (dsssl4 11 c: 33 b: 22 d: 44) (dsssl4 11 b: 22 c: 33) (dsssl4 11 b: 22) (dsssl4 11)))) (define c c:) (define b b:) (define (dsssl4-test1b) (list (dsssl4 11 d: 44 b: 22 c 33) (dsssl4 11 c 33 b 22) (dsssl4 11 b 22) (dsssl4 11))) (define (dsssl4-test1b-eval) (eval '(let ((c c:) (b b:)) (list (dsssl4 11 d: 44 b: 22 c 33) (dsssl4 11 c 33 b 22) (dsssl4 11 b 22) (dsssl4 11))))) (define (dsssl4-test2 f) (list (f 11 c: 33 b: 22 d: 44) (f 11 c: 33 b: 22 ) (f 11 b: 22) (f 11))) (define (dsssl4-test3 f) (list (apply f (list 11 b: 22 d: 44 c: 33)) (apply f (list 11 c: 33 b: 22)) (apply f (list 11 b: 22)) (apply f (list 11)))) (define (dsssl4-test4 f . args) (apply f args)) ;*---------------------------------------------------------------------*/ * ... * / ;*---------------------------------------------------------------------*/ (define (dsssl5 ident #!key (version #unspecified) (format "raw") (filter #f) (delegate #f) (symbol-table '()) (custom '()) (info '())) (list ident version custom info format)) ;*---------------------------------------------------------------------*/ ;* dsssl6 */ ;*---------------------------------------------------------------------*/ (define (dsssl6 #!optional (a 'a) b) (list a b)) (define (dsssl6-test1) (list (dsssl6 11 22) (dsssl6 11) (dsssl6))) (define (dsssl6-test1-eval) (eval '(list (dsssl6 11 22) (dsssl6 11) (dsssl6)))) (define (dsssl6-test2 f) (list (f 11 22) (f 11) (f))) (define (dsssl6-test3 f) (list (apply f '(11 22)) (apply f '(11)) (apply f '()))) (define (dsssl6-test4 f . args) (apply f args)) ;*---------------------------------------------------------------------*/ ;* dsssl6b ... */ ;*---------------------------------------------------------------------*/ (define dsssl6b dsssl6) (define (dsssl6b-test1) (list (dsssl6b 11 22) (dsssl6b 11) (dsssl6b))) (define (dsssl6b-test2 f) (list (f 11 22) (f 11) (f))) (define (dsssl6b-test3 f) (list (apply f '(11 22)) (apply f '(11)) (apply f '()))) (define (dsssl6b-test4 f . args) (apply f args)) ;*---------------------------------------------------------------------*/ ;* dsssl7 ... */ ;*---------------------------------------------------------------------*/ (define (dsssl7 #!optional (dsssl7 2) (z dsssl7)) z) ;*---------------------------------------------------------------------*/ ;* dsssl8 ... */ ;*---------------------------------------------------------------------*/ (define (dsssl8 #!key (y 2) (z y)) z) ;*---------------------------------------------------------------------*/ ;* dsssl9 ... */ ;*---------------------------------------------------------------------*/ (define (dsssl9 ip::input-port op::output-port #!optional (s 1) (o -1)) (+fx s o)) ;*---------------------------------------------------------------------*/ ;* dsssl11 ... */ ;*---------------------------------------------------------------------*/ (define (dsssl11 x y #!optional z #!key i (j 1) #!rest r) (list x y z i: i j: j r)) ;*---------------------------------------------------------------------*/ ;* DSSSL-mac ... */ ;*---------------------------------------------------------------------*/ (define-macro (DSSSL-mac x) x) ;*---------------------------------------------------------------------*/ ;* dt->sec ... */ ;*---------------------------------------------------------------------*/ (define (dt->sec a #!key (x #t)) (date->seconds x)) ;*---------------------------------------------------------------------*/ * dsssl - bug ... * / ;*---------------------------------------------------------------------*/ (define (dsssl-bug #!key (foo::bool #t)) foo) ;*---------------------------------------------------------------------*/ ;* test-dsssl ... */ ;*---------------------------------------------------------------------*/ (define (test-dsssl) (test-module "dsssl" "dsssl.scm") (test "dsssl" (foo 1 2 3 4 i: 5) '(1 2 3 4 i: 5 j: 1)) (test "dsssl" (foo 1 2 3 4 i: 5 j: 3) '(1 2 3 4 i: 5 j: 3)) (test "dsssl" ((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7) '(3 4 5 i: 6 j: 1)) (test "dsssl-eps" ((lambda (x y #!optional z #!rest r #!key i (j (DSSSL-mac 1))) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7) '(3 4 5 i: 6 j: 1)) (test "eval" (test-dsssl-eval) #t) (test "eval" (eval '(dsssl 1 2 3 4 i: 5)) '(1 2 3 4 i: 5 j: 1)) (test "eval-eps" (eval '(begin (define-macro (DSSSL-mac x) x) ((lambda (x y #!optional z #!rest r #!key i (j (DSSSL-mac 1))) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7))) '(3 4 5 i: 6 j: 1)) (test "dsssl" (eval '((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7)) '(3 4 5 i: 6 j: 1)) (test "lexical" (dsssl-lexical '(1 2) (list 1 2)) #t) (test "lexical.2" (let ((equal? (lambda (a b) #f))) (dsssl-lexical '(1 2) (list 1 2))) #t) (test "lexical.3" (let ((equal? (lambda (a b) #f))) ((car (list dsssl-lexical)) '(1 2) (list 1 2))) #t) (test "optional+key" (connect 3) '(3 . "localhost")) (test "optional+key" (connect 3 hostname: "hueco") '(3 . "hueco")) (test "optional+rest+key" (eval '((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z r: r i: i j: j)) 3 4 5 6 i: 6)) '(3 4 5 r: (6 i: 6) i: 6 j: 1)) (test "optional+rest+key" (eval '((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z r: r i: i j: j)) 3 4 5 6 7 8 9 i: 6)) '(3 4 5 r: (6 7 8 9 i: 6) i: 6 j: 1)) (test "ucs2-char" (ucs2->integer (integer->ucs2 (char->integer #\a))) (char->integer #\a)) (test "dsssl2.1" (dsssl2-test1) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2-eval.1" (dsssl2-test1-eval) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2.2" (dsssl2-test2 dsssl2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2.2b" (dsssl2-test2 (car (list dsssl2))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2.3" (dsssl2-test3 dsssl2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2.3b" (dsssl2-test3 (car (list dsssl2))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.1" (dsssl3-test1) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.2" (dsssl2-test2 dsssl3) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.2b" (dsssl2-test2 (car (list dsssl3))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.3" (dsssl2-test3 dsssl3) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.3" (dsssl2-test4 dsssl3 11 22 33 44) '(11 22 33 44)) (test "dsssl3.3" ((car (list dsssl2-test4)) (car (list dsssl3)) 11 22 33 44) '(11 22 33 44)) (test "dsssl3.3b" (dsssl2-test3 (car (list dsssl3))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.4" (dsssl3-test2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.5" (dsssl3b-test1) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.6" (dsssl3b-test2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.5" (dsssl3b-test2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.1" (dsssl4-test1) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4-eval.1" (dsssl4-test1-eval) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.1b" (dsssl4-test1b) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4-eval.1b" (dsssl4-test1b-eval) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.2" (dsssl4-test2 dsssl4) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.2b" (dsssl4-test2 (car (list dsssl4))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.3" (dsssl4-test3 dsssl4) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.3" (dsssl4-test4 dsssl4 11 b: 22 d: 44 c: 33) '(11 22 33 44)) (test "dsssl4.3" ((car (list dsssl4-test4)) (car (list dsssl4)) 11 b: 22 d: 44 c: 33) '(11 22 33 44)) (test "dsssl4.3b" (dsssl4-test3 (car (list dsssl4))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4-error" (with-handler (lambda (e) 56) ((car (list dsssl4)) 1 z: 23)) 56) (test "dsssl5.1" (dsssl5 'bootstrap :version "18") '(bootstrap "18" () () "raw")) (test "dsssl5.2" ((car (list dsssl5)) 'bootstrap :version "18") '(bootstrap "18" () () "raw")) (test "dsssl6.1" (dsssl6-test1) '((11 22) (11 #f) (a #f))) (test "dsssl6-eval.1" (dsssl6-test1-eval) '((11 22) (11 #f) (a #f))) (test "dsssl6.2" (dsssl6-test2 dsssl6) '((11 22) (11 #f) (a #f))) (test "dsssl6.2b" (dsssl6-test2 (car (list dsssl6))) '((11 22) (11 #f) (a #f))) (test "dsssl6.3" (dsssl6-test3 dsssl6) '((11 22) (11 #f) (a #f))) (test "dsssl6.3b" (dsssl6-test3 (car (list dsssl6))) '((11 22) (11 #f) (a #f))) (test "dsssl6.4" ((car (list dsssl6-test4)) (car (list dsssl6)) 1 2) '(1 2)) (test "dsssl6b.1" (dsssl6b-test1) '((11 22) (11 #f) (a #f))) (test "dsssl6b.2" (dsssl6b-test2 dsssl6b) '((11 22) (11 #f) (a #f))) (test "dsssl6b.2b" (dsssl6b-test2 (car (list dsssl6b))) '((11 22) (11 #f) (a #f))) (test "dsssl6b.3" (dsssl6b-test3 dsssl6b) '((11 22) (11 #f) (a #f))) (test "dsssl6b.3b" (dsssl6b-test3 (car (list dsssl6b))) '((11 22) (11 #f) (a #f))) (test "dsssl6b.4" ((car (list dsssl6b-test4)) (car (list dsssl6b)) 1 2) '(1 2)) (test "dsssl7.1" (dsssl7 43) 43) (test "dsssl7.2" ((car (list dsssl7)) 43) 43) (test "dsssl7.3" (apply (car (list dsssl7)) '(43)) 43) (test "dsssl8.1" (dsssl8 y: 44) 44) (test "dsssl8.2" ((car (list dsssl7)) y: 44) 44) (test "dsssl8.3" (apply (car (list dsssl7)) '(y: 44)) 44) (test "dsssl9.1" (dsssl9 (current-input-port) (current-output-port)) 0) (test "dsssl9.2" ((vector-ref (vector dsssl9) 0) (current-input-port) (current-output-port)) 0) (test "keyword.1" (eq? :foo foo:) #t) (test "keyword.2" (eq? :foo bar:) #f) (test "keyword.3" (eq? :foo :Foo) #f) (test "keyword.4" (eq? (string->keyword "foo") foo:) #t) (test "keyword.5" (eq? (string->keyword "foo") :foo) #t) (test "keyword.6" (eq? (string->keyword "foo:") foo:) #f) (let* ((dt (current-date)) (res (date->seconds dt))) (test "keyword.7" ((if (> res 0) dt->sec list) 1 x: dt) res)) (test "keyword.8" (dsssl-bug :foo #f) #f) (test "dssss11.1" (dsssl11 3 4 5 i: 6 i: 7 8 9) '(3 4 5 i: 6 j: 1 (8 9))) (test "dssss11.2" (apply dsssl11 '(3 4 5 i: 6 i: 7 8 9)) '(3 4 5 i: 6 j: 1 (8 9))) (test "dssss11.3" ((cadr (list dsssl9 dsssl11)) 3 4 5 i: 6 i: 7 8 9) '(3 4 5 i: 6 j: 1 (8 9))))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/recette/dsssl.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dsssl4 ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dsssl6 */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dsssl6b ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dsssl7 ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dsssl8 ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dsssl9 ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dsssl11 ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * DSSSL-mac ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * dt->sec ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * test-dsssl ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / recette / dsssl.scm * / * Author : * / * Creation : Tue Mar 31 09:21:59 1998 * / * Last change : Mon Nov 11 08:39:25 2013 ( serrano ) * / * DSSSL funcall tests * / (module dsssl (import (main "main.scm") (vararity "vararity.scm")) (include "test.sch") (export (test-dsssl) (foo ::int y #!optional z (zz 1) #!rest r #!key i (j 1)) (dsssl2 a #!optional b (c 'c) (d 'd)) (dsssl4 a #!key b (c 'c) (d 'd)) (dsssl6 #!optional (a 'a) b) (dsssl7 #!optional (dsssl7 2) (z dsssl7)) (dsssl8 #!key (y 2) (z y)) (dsssl9 ::input-port ::output-port #!optional (s 1) (o -1)) (dsssl11 x y #!optional z #!key i (j 1) #!rest r) (dsssl-lexical b c #!optional (=::procedure equal?)) (dt->sec a #!key (x #t))) (eval (export dsssl2) (export dsssl3) (export dsssl3b) (export dsssl4) (export dsssl6))) (define (foo x y #!optional z (zz 1) #!rest r #!key i (j 1)) (let ((f (lambda (z y #!key (i 8)) (list z y i)))) (labels ((g (a b #!rest l) (list a b l))) (list x y z zz i: i j: j)))) (define (test-dsssl-eval) (eval '(define (dsssl x y #!optional z (zz 1) #!rest r #!key i (j 1)) (let ((f (lambda (z y #!key (i 8)) (list z y i)))) (labels ((g (a b #!rest l) (list a b l))) (list x y z zz i: i j: j))))) #t) (define (dsssl-lexical b c #!optional (=::procedure equal?)) (= b c)) (define (connect #!optional environment #!key (hostname "localhost")) (cons environment hostname)) * * / (define (dsssl2 a #!optional b (c 'c) (d 'd)) (list a b c d)) (define (dsssl2-test1) (list (dsssl2 11 22 33 44) (dsssl2 11 22 33) (dsssl2 11 22) (dsssl2 11))) (define (dsssl2-test1-eval) (eval '(list (dsssl2 11 22 33 44) (dsssl2 11 22 33) (dsssl2 11 22) (dsssl2 11)))) (define (dsssl2-test2 f) (list (f 11 22 33 44) (f 11 22 33) (f 11 22) (f 11))) (define (dsssl2-test3 f) (list (apply f '(11 22 33 44)) (apply f '(11 22 33)) (apply f '(11 22)) (apply f '(11)))) (define (dsssl2-test4 f . args) (apply f args)) (define (dsssl3-test1) (list (dsssl3 11 22 33 44) (dsssl3 11 22 33) (dsssl3 11 22) (dsssl3 11))) (define (dsssl3-test2) (list ((car (list dsssl3)) 11 22 33 44) ((car (list dsssl3)) 11 22 33) ((car (list dsssl3)) 11 22) ((car (list dsssl3)) 11))) (define (dsssl3b-test1) (list (dsssl3b 11 c: 33 b: 22 d: 44) (dsssl3b 11 b: 22 c: 33) (dsssl3b 11 b: 22) (dsssl3b 11))) (define (dsssl3b-test2) (list ((car (list dsssl3b)) 11 d: 44 b: 22 c: 33) ((car (list dsssl3b)) 11 c: 33 b: 22) ((car (list dsssl3b)) 11 b: 22) ((car (list dsssl3b)) 11))) (define (dsssl4 a #!key b (d 'd) (c 'c)) (list a b c d)) (define (dsssl4-test1) (list (dsssl4 11 c: 33 b: 22 d: 44) (dsssl4 11 b: 22 c: 33) (dsssl4 11 b: 22) (dsssl4 11))) (define (dsssl4-test1-eval) (eval '(list (dsssl4 11 c: 33 b: 22 d: 44) (dsssl4 11 b: 22 c: 33) (dsssl4 11 b: 22) (dsssl4 11)))) (define c c:) (define b b:) (define (dsssl4-test1b) (list (dsssl4 11 d: 44 b: 22 c 33) (dsssl4 11 c 33 b 22) (dsssl4 11 b 22) (dsssl4 11))) (define (dsssl4-test1b-eval) (eval '(let ((c c:) (b b:)) (list (dsssl4 11 d: 44 b: 22 c 33) (dsssl4 11 c 33 b 22) (dsssl4 11 b 22) (dsssl4 11))))) (define (dsssl4-test2 f) (list (f 11 c: 33 b: 22 d: 44) (f 11 c: 33 b: 22 ) (f 11 b: 22) (f 11))) (define (dsssl4-test3 f) (list (apply f (list 11 b: 22 d: 44 c: 33)) (apply f (list 11 c: 33 b: 22)) (apply f (list 11 b: 22)) (apply f (list 11)))) (define (dsssl4-test4 f . args) (apply f args)) * ... * / (define (dsssl5 ident #!key (version #unspecified) (format "raw") (filter #f) (delegate #f) (symbol-table '()) (custom '()) (info '())) (list ident version custom info format)) (define (dsssl6 #!optional (a 'a) b) (list a b)) (define (dsssl6-test1) (list (dsssl6 11 22) (dsssl6 11) (dsssl6))) (define (dsssl6-test1-eval) (eval '(list (dsssl6 11 22) (dsssl6 11) (dsssl6)))) (define (dsssl6-test2 f) (list (f 11 22) (f 11) (f))) (define (dsssl6-test3 f) (list (apply f '(11 22)) (apply f '(11)) (apply f '()))) (define (dsssl6-test4 f . args) (apply f args)) (define dsssl6b dsssl6) (define (dsssl6b-test1) (list (dsssl6b 11 22) (dsssl6b 11) (dsssl6b))) (define (dsssl6b-test2 f) (list (f 11 22) (f 11) (f))) (define (dsssl6b-test3 f) (list (apply f '(11 22)) (apply f '(11)) (apply f '()))) (define (dsssl6b-test4 f . args) (apply f args)) (define (dsssl7 #!optional (dsssl7 2) (z dsssl7)) z) (define (dsssl8 #!key (y 2) (z y)) z) (define (dsssl9 ip::input-port op::output-port #!optional (s 1) (o -1)) (+fx s o)) (define (dsssl11 x y #!optional z #!key i (j 1) #!rest r) (list x y z i: i j: j r)) (define-macro (DSSSL-mac x) x) (define (dt->sec a #!key (x #t)) (date->seconds x)) * dsssl - bug ... * / (define (dsssl-bug #!key (foo::bool #t)) foo) (define (test-dsssl) (test-module "dsssl" "dsssl.scm") (test "dsssl" (foo 1 2 3 4 i: 5) '(1 2 3 4 i: 5 j: 1)) (test "dsssl" (foo 1 2 3 4 i: 5 j: 3) '(1 2 3 4 i: 5 j: 3)) (test "dsssl" ((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7) '(3 4 5 i: 6 j: 1)) (test "dsssl-eps" ((lambda (x y #!optional z #!rest r #!key i (j (DSSSL-mac 1))) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7) '(3 4 5 i: 6 j: 1)) (test "eval" (test-dsssl-eval) #t) (test "eval" (eval '(dsssl 1 2 3 4 i: 5)) '(1 2 3 4 i: 5 j: 1)) (test "eval-eps" (eval '(begin (define-macro (DSSSL-mac x) x) ((lambda (x y #!optional z #!rest r #!key i (j (DSSSL-mac 1))) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7))) '(3 4 5 i: 6 j: 1)) (test "dsssl" (eval '((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7)) '(3 4 5 i: 6 j: 1)) (test "lexical" (dsssl-lexical '(1 2) (list 1 2)) #t) (test "lexical.2" (let ((equal? (lambda (a b) #f))) (dsssl-lexical '(1 2) (list 1 2))) #t) (test "lexical.3" (let ((equal? (lambda (a b) #f))) ((car (list dsssl-lexical)) '(1 2) (list 1 2))) #t) (test "optional+key" (connect 3) '(3 . "localhost")) (test "optional+key" (connect 3 hostname: "hueco") '(3 . "hueco")) (test "optional+rest+key" (eval '((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z r: r i: i j: j)) 3 4 5 6 i: 6)) '(3 4 5 r: (6 i: 6) i: 6 j: 1)) (test "optional+rest+key" (eval '((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z r: r i: i j: j)) 3 4 5 6 7 8 9 i: 6)) '(3 4 5 r: (6 7 8 9 i: 6) i: 6 j: 1)) (test "ucs2-char" (ucs2->integer (integer->ucs2 (char->integer #\a))) (char->integer #\a)) (test "dsssl2.1" (dsssl2-test1) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2-eval.1" (dsssl2-test1-eval) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2.2" (dsssl2-test2 dsssl2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2.2b" (dsssl2-test2 (car (list dsssl2))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2.3" (dsssl2-test3 dsssl2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl2.3b" (dsssl2-test3 (car (list dsssl2))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.1" (dsssl3-test1) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.2" (dsssl2-test2 dsssl3) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.2b" (dsssl2-test2 (car (list dsssl3))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.3" (dsssl2-test3 dsssl3) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.3" (dsssl2-test4 dsssl3 11 22 33 44) '(11 22 33 44)) (test "dsssl3.3" ((car (list dsssl2-test4)) (car (list dsssl3)) 11 22 33 44) '(11 22 33 44)) (test "dsssl3.3b" (dsssl2-test3 (car (list dsssl3))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.4" (dsssl3-test2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.5" (dsssl3b-test1) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.6" (dsssl3b-test2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl3.5" (dsssl3b-test2) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.1" (dsssl4-test1) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4-eval.1" (dsssl4-test1-eval) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.1b" (dsssl4-test1b) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4-eval.1b" (dsssl4-test1b-eval) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.2" (dsssl4-test2 dsssl4) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.2b" (dsssl4-test2 (car (list dsssl4))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.3" (dsssl4-test3 dsssl4) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4.3" (dsssl4-test4 dsssl4 11 b: 22 d: 44 c: 33) '(11 22 33 44)) (test "dsssl4.3" ((car (list dsssl4-test4)) (car (list dsssl4)) 11 b: 22 d: 44 c: 33) '(11 22 33 44)) (test "dsssl4.3b" (dsssl4-test3 (car (list dsssl4))) '((11 22 33 44) (11 22 33 d) (11 22 c d) (11 #f c d))) (test "dsssl4-error" (with-handler (lambda (e) 56) ((car (list dsssl4)) 1 z: 23)) 56) (test "dsssl5.1" (dsssl5 'bootstrap :version "18") '(bootstrap "18" () () "raw")) (test "dsssl5.2" ((car (list dsssl5)) 'bootstrap :version "18") '(bootstrap "18" () () "raw")) (test "dsssl6.1" (dsssl6-test1) '((11 22) (11 #f) (a #f))) (test "dsssl6-eval.1" (dsssl6-test1-eval) '((11 22) (11 #f) (a #f))) (test "dsssl6.2" (dsssl6-test2 dsssl6) '((11 22) (11 #f) (a #f))) (test "dsssl6.2b" (dsssl6-test2 (car (list dsssl6))) '((11 22) (11 #f) (a #f))) (test "dsssl6.3" (dsssl6-test3 dsssl6) '((11 22) (11 #f) (a #f))) (test "dsssl6.3b" (dsssl6-test3 (car (list dsssl6))) '((11 22) (11 #f) (a #f))) (test "dsssl6.4" ((car (list dsssl6-test4)) (car (list dsssl6)) 1 2) '(1 2)) (test "dsssl6b.1" (dsssl6b-test1) '((11 22) (11 #f) (a #f))) (test "dsssl6b.2" (dsssl6b-test2 dsssl6b) '((11 22) (11 #f) (a #f))) (test "dsssl6b.2b" (dsssl6b-test2 (car (list dsssl6b))) '((11 22) (11 #f) (a #f))) (test "dsssl6b.3" (dsssl6b-test3 dsssl6b) '((11 22) (11 #f) (a #f))) (test "dsssl6b.3b" (dsssl6b-test3 (car (list dsssl6b))) '((11 22) (11 #f) (a #f))) (test "dsssl6b.4" ((car (list dsssl6b-test4)) (car (list dsssl6b)) 1 2) '(1 2)) (test "dsssl7.1" (dsssl7 43) 43) (test "dsssl7.2" ((car (list dsssl7)) 43) 43) (test "dsssl7.3" (apply (car (list dsssl7)) '(43)) 43) (test "dsssl8.1" (dsssl8 y: 44) 44) (test "dsssl8.2" ((car (list dsssl7)) y: 44) 44) (test "dsssl8.3" (apply (car (list dsssl7)) '(y: 44)) 44) (test "dsssl9.1" (dsssl9 (current-input-port) (current-output-port)) 0) (test "dsssl9.2" ((vector-ref (vector dsssl9) 0) (current-input-port) (current-output-port)) 0) (test "keyword.1" (eq? :foo foo:) #t) (test "keyword.2" (eq? :foo bar:) #f) (test "keyword.3" (eq? :foo :Foo) #f) (test "keyword.4" (eq? (string->keyword "foo") foo:) #t) (test "keyword.5" (eq? (string->keyword "foo") :foo) #t) (test "keyword.6" (eq? (string->keyword "foo:") foo:) #f) (let* ((dt (current-date)) (res (date->seconds dt))) (test "keyword.7" ((if (> res 0) dt->sec list) 1 x: dt) res)) (test "keyword.8" (dsssl-bug :foo #f) #f) (test "dssss11.1" (dsssl11 3 4 5 i: 6 i: 7 8 9) '(3 4 5 i: 6 j: 1 (8 9))) (test "dssss11.2" (apply dsssl11 '(3 4 5 i: 6 i: 7 8 9)) '(3 4 5 i: 6 j: 1 (8 9))) (test "dssss11.3" ((cadr (list dsssl9 dsssl11)) 3 4 5 i: 6 i: 7 8 9) '(3 4 5 i: 6 j: 1 (8 9))))
010a807a5accfed72a31ad92beb1cc567d708b7f38435e452c50d8d3b9436789
tatut/reagent-leaflet
core.cljs
(ns reagent-leaflet.core (:require [reagent.core :as reagent :refer [atom]])) ;;;;;;;;; ;; Define the React lifecycle callbacks to manage the LeafletJS ;; Javascript objects. (declare update-leaflet-geometries) (defn- leaflet-did-mount [this] "Initialize LeafletJS map for a newly mounted map component." (let [mapspec (:mapspec (reagent/state this)) leaflet (js/L.map (:id mapspec)) view (:view mapspec) zoom (:zoom mapspec)] (.setView leaflet (clj->js @view) @zoom) (doseq [{:keys [type url] :as layer-spec} (:layers mapspec)] (let [layer (case type :tile (js/L.tileLayer url (clj->js {:attribution (:attribution layer-spec)}) ) :wms (js/L.tileLayer.wms url (clj->js {:format "image/png" :fillOpacity 1.0 })))] ;;(.log js/console "L.tileLayer = " layer) (.addTo layer leaflet))) ( .log js / console " L.map = " leaflet ) (reagent/set-state this {:leaflet leaflet :geometries-map {}}) ;; If mapspec defines callbacks, bind them to leaflet (when-let [on-click (:on-click mapspec)] (.on leaflet "click" (fn [e] (on-click [(-> e .-latlng .-lat) (-> e .-latlng .-lng)])))) ;; Add callback for leaflet pos/zoom changes ;; watcher for pos/zoom atoms (.on leaflet "move" (fn [e] (let [c (.getCenter leaflet)] (reset! zoom (.getZoom leaflet)) (reset! view [(.-lat c) (.-lng c)])))) (add-watch view ::view-update (fn [_ _ old-view new-view] ( .log js / console " change view : " ( clj->js old - view ) " = > " ( clj->js new - view ) ) (when (not= old-view new-view) (.setView leaflet (clj->js new-view) @zoom)))) (add-watch zoom ::zoom-update (fn [_ _ old-zoom new-zoom] (when (not= old-zoom new-zoom) (.setZoom leaflet new-zoom)))) ;; If the mapspec has an atom containing geometries, add watcher ;; so that we update all LeafletJS objects (when-let [g (:geometries mapspec)] (add-watch g ::geometries-update (fn [_ _ _ new-geometries] (update-leaflet-geometries this new-geometries)))))) (defn- leaflet-will-update [this old-state new-state] (update-leaflet-geometries this (-> this reagent/state :mapspec :geometries deref))) (defn- leaflet-render [this] (let [mapspec (-> this reagent/state :mapspec)] [:div {:id (:id mapspec) :style {:width (:width mapspec) :height (:height mapspec)}}])) ;;;;;;;;;; ;; Code to sync ClojureScript geometries vector data to LeafletJS ;; shape objects. (defmulti create-shape :type) (defmethod create-shape :polygon [{:keys [coordinates]}] (js/L.polygon (clj->js coordinates) #js {:color "red" :fillOpacity 0.5})) (defmethod create-shape :line [{:keys [coordinates]}] (js/L.polyline (clj->js coordinates) #js {:color "blue"})) (defmethod create-shape :point [{:keys [coordinates]}] (js/L.circle (clj->js (first coordinates)) 10 #js {:color "green"})) (defn- update-leaflet-geometries [component geometries] "Update the LeafletJS layers based on the data, mutates the LeafletJS map object." (let [{:keys [leaflet geometries-map]} (reagent/state component) geometries-set (into #{} geometries)] ;; Remove all LeafletJS shape objects that are no longer in the new geometries (doseq [removed (keep (fn [[geom shape]] (when-not (geometries-set geom) shape)) geometries-map)] ;;(.log js/console "Removed: " removed) (.removeLayer leaflet removed)) ;; Create new shapes for new geometries and update the geometries map (loop [new-geometries-map {} [geom & geometries] geometries] (if-not geom ;; Update component state with the new geometries map (reagent/set-state component {:geometries-map new-geometries-map}) (if-let [existing-shape (geometries-map geom)] ;; Have existing shape, don't need to do anything (recur (assoc new-geometries-map geom existing-shape) geometries) ;; No existing shape, create a new shape and add it to the map (let [shape (create-shape geom)] ;;(.log js/console "Added: " (pr-str geom)) (.addTo shape leaflet) (recur (assoc new-geometries-map geom shape) geometries))))))) ;;;;;;;;; ;; The LeafletJS Reagent component. (defn leaflet [mapspec] "A LeafletJS map component." (reagent/create-class {:get-initial-state (fn [_] {:mapspec mapspec}) :component-did-mount leaflet-did-mount :component-will-update leaflet-will-update :render leaflet-render}))
null
https://raw.githubusercontent.com/tatut/reagent-leaflet/edd68b3dba2bd9c10f5bf2b7af25747663eed789/src/reagent_leaflet/core.cljs
clojure
Define the React lifecycle callbacks to manage the LeafletJS Javascript objects. (.log js/console "L.tileLayer = " layer) If mapspec defines callbacks, bind them to leaflet Add callback for leaflet pos/zoom changes watcher for pos/zoom atoms If the mapspec has an atom containing geometries, add watcher so that we update all LeafletJS objects Code to sync ClojureScript geometries vector data to LeafletJS shape objects. Remove all LeafletJS shape objects that are no longer in the new geometries (.log js/console "Removed: " removed) Create new shapes for new geometries and update the geometries map Update component state with the new geometries map Have existing shape, don't need to do anything No existing shape, create a new shape and add it to the map (.log js/console "Added: " (pr-str geom)) The LeafletJS Reagent component.
(ns reagent-leaflet.core (:require [reagent.core :as reagent :refer [atom]])) (declare update-leaflet-geometries) (defn- leaflet-did-mount [this] "Initialize LeafletJS map for a newly mounted map component." (let [mapspec (:mapspec (reagent/state this)) leaflet (js/L.map (:id mapspec)) view (:view mapspec) zoom (:zoom mapspec)] (.setView leaflet (clj->js @view) @zoom) (doseq [{:keys [type url] :as layer-spec} (:layers mapspec)] (let [layer (case type :tile (js/L.tileLayer url (clj->js {:attribution (:attribution layer-spec)}) ) :wms (js/L.tileLayer.wms url (clj->js {:format "image/png" :fillOpacity 1.0 })))] (.addTo layer leaflet))) ( .log js / console " L.map = " leaflet ) (reagent/set-state this {:leaflet leaflet :geometries-map {}}) (when-let [on-click (:on-click mapspec)] (.on leaflet "click" (fn [e] (on-click [(-> e .-latlng .-lat) (-> e .-latlng .-lng)])))) (.on leaflet "move" (fn [e] (let [c (.getCenter leaflet)] (reset! zoom (.getZoom leaflet)) (reset! view [(.-lat c) (.-lng c)])))) (add-watch view ::view-update (fn [_ _ old-view new-view] ( .log js / console " change view : " ( clj->js old - view ) " = > " ( clj->js new - view ) ) (when (not= old-view new-view) (.setView leaflet (clj->js new-view) @zoom)))) (add-watch zoom ::zoom-update (fn [_ _ old-zoom new-zoom] (when (not= old-zoom new-zoom) (.setZoom leaflet new-zoom)))) (when-let [g (:geometries mapspec)] (add-watch g ::geometries-update (fn [_ _ _ new-geometries] (update-leaflet-geometries this new-geometries)))))) (defn- leaflet-will-update [this old-state new-state] (update-leaflet-geometries this (-> this reagent/state :mapspec :geometries deref))) (defn- leaflet-render [this] (let [mapspec (-> this reagent/state :mapspec)] [:div {:id (:id mapspec) :style {:width (:width mapspec) :height (:height mapspec)}}])) (defmulti create-shape :type) (defmethod create-shape :polygon [{:keys [coordinates]}] (js/L.polygon (clj->js coordinates) #js {:color "red" :fillOpacity 0.5})) (defmethod create-shape :line [{:keys [coordinates]}] (js/L.polyline (clj->js coordinates) #js {:color "blue"})) (defmethod create-shape :point [{:keys [coordinates]}] (js/L.circle (clj->js (first coordinates)) 10 #js {:color "green"})) (defn- update-leaflet-geometries [component geometries] "Update the LeafletJS layers based on the data, mutates the LeafletJS map object." (let [{:keys [leaflet geometries-map]} (reagent/state component) geometries-set (into #{} geometries)] (doseq [removed (keep (fn [[geom shape]] (when-not (geometries-set geom) shape)) geometries-map)] (.removeLayer leaflet removed)) (loop [new-geometries-map {} [geom & geometries] geometries] (if-not geom (reagent/set-state component {:geometries-map new-geometries-map}) (if-let [existing-shape (geometries-map geom)] (recur (assoc new-geometries-map geom existing-shape) geometries) (let [shape (create-shape geom)] (.addTo shape leaflet) (recur (assoc new-geometries-map geom shape) geometries))))))) (defn leaflet [mapspec] "A LeafletJS map component." (reagent/create-class {:get-initial-state (fn [_] {:mapspec mapspec}) :component-did-mount leaflet-did-mount :component-will-update leaflet-will-update :render leaflet-render}))
f1229430037f8fc4a95f42f713006e6c59ae290fee8931fba91654ec416ad798
gar1t/erlang-cli
cli_opt.erl
-module(cli_opt). -export([new/2]). -export([key/1, desc/1, has_arg/1, short/1, long/1, metavar/1, visible/1]). -export([int_val/4]). -record(opt, {key, desc, has_arg, short, long, metavar, visible}). %% =================================================================== %% New %% =================================================================== new(Key, Opts) -> {Short, Long} = short_long_from_opts(Opts, Key), #opt{ key=Key, desc=desc_from_opts(Opts), has_arg=has_arg_from_opts(Opts), short=Short, long=Long, metavar=metavar_from_opts(Opts), visible=visible_from_opts(Opts) }. desc_from_opts(Opts) -> proplists:get_value(desc, Opts, ""). short_long_from_opts(Opts, Key) -> short_long_from_name(name_from_opts(Opts, Key)). name_from_opts(Opts, Key) -> Default = fun() -> long_opt_from_key(Key) end, opt_val(name, Opts, Default). long_opt_from_key(Key) -> "--" ++ replace(atom_to_list(Key), "_", "-"). short_long_from_name(Name) -> Pattern = "^(?:(-.))?(?:, )?(?:(--.+))?$", case re:run(Name, Pattern, [{capture, all_but_first, list}]) of {match, ["", Long]} -> {undefined, Long}; {match, [Short, Long]} -> {Short, Long}; {match, [Short]} -> {Short, undefined}; nomatch -> error({bad_option_name, Name}) end. has_arg_from_opts(Opts) -> Default = fun() -> default_has_arg(Opts) end, opt_val(has_arg, Opts, Default). default_has_arg(Opts) -> apply_boolopt_map( [{flag, no}, {no_arg, no}, {optional_arg, optional}, {'_', yes}], Opts). metavar_from_opts(Opts) -> Default = fun() -> default_metavar(Opts) end, opt_val(metavar, Opts, Default). default_metavar(Opts) -> apply_boolopt_map( [{flag, undefined}, {no_arg, undefined}, {'_', "VALUE"}], Opts). visible_from_opts(Opts) -> not proplists:get_bool(hidden, Opts). %% =================================================================== Attrs %% =================================================================== key(#opt{key=Key}) -> Key. desc(#opt{desc=Desc}) -> Desc. has_arg(#opt{has_arg=HasArg}) -> HasArg. short(#opt{short=Short}) -> Short. long(#opt{long=Long}) -> Long. metavar(#opt{metavar=Metavar}) -> Metavar. visible(#opt{visible=Visible}) -> Visible. %% =================================================================== %% Converters %% =================================================================== int_val(Key, Opts, Default, ErrMsg) -> case proplists:get_value(Key, Opts) of undefined -> Default; Str -> str_to_int(Str, ErrMsg) end. str_to_int(Str, ErrMsg) -> try list_to_integer(Str) catch error:badarg -> throw({error, ErrMsg}) end. %% =================================================================== %% Helpers %% =================================================================== opt_val(Key, Opts, Default) -> case proplists:get_value(Key, Opts, '$undefined') of '$undefined' when is_function(Default) -> Default(); '$undefined' -> Default; Val -> Val end. apply_boolopt_map([{'_', Result}|_], _Opts) -> Result; apply_boolopt_map([{Opt, Result}|Rest], Opts) -> case proplists:get_bool(Opt, Opts) of true -> Result; false -> apply_boolopt_map(Rest, Opts) end. replace(Str, Replace, With) -> re:replace(Str, Replace, With, [{return, list}]).
null
https://raw.githubusercontent.com/gar1t/erlang-cli/4f2b097c43a6959f842969c036e2816e8626fabb/src/cli_opt.erl
erlang
=================================================================== New =================================================================== =================================================================== =================================================================== =================================================================== Converters =================================================================== =================================================================== Helpers ===================================================================
-module(cli_opt). -export([new/2]). -export([key/1, desc/1, has_arg/1, short/1, long/1, metavar/1, visible/1]). -export([int_val/4]). -record(opt, {key, desc, has_arg, short, long, metavar, visible}). new(Key, Opts) -> {Short, Long} = short_long_from_opts(Opts, Key), #opt{ key=Key, desc=desc_from_opts(Opts), has_arg=has_arg_from_opts(Opts), short=Short, long=Long, metavar=metavar_from_opts(Opts), visible=visible_from_opts(Opts) }. desc_from_opts(Opts) -> proplists:get_value(desc, Opts, ""). short_long_from_opts(Opts, Key) -> short_long_from_name(name_from_opts(Opts, Key)). name_from_opts(Opts, Key) -> Default = fun() -> long_opt_from_key(Key) end, opt_val(name, Opts, Default). long_opt_from_key(Key) -> "--" ++ replace(atom_to_list(Key), "_", "-"). short_long_from_name(Name) -> Pattern = "^(?:(-.))?(?:, )?(?:(--.+))?$", case re:run(Name, Pattern, [{capture, all_but_first, list}]) of {match, ["", Long]} -> {undefined, Long}; {match, [Short, Long]} -> {Short, Long}; {match, [Short]} -> {Short, undefined}; nomatch -> error({bad_option_name, Name}) end. has_arg_from_opts(Opts) -> Default = fun() -> default_has_arg(Opts) end, opt_val(has_arg, Opts, Default). default_has_arg(Opts) -> apply_boolopt_map( [{flag, no}, {no_arg, no}, {optional_arg, optional}, {'_', yes}], Opts). metavar_from_opts(Opts) -> Default = fun() -> default_metavar(Opts) end, opt_val(metavar, Opts, Default). default_metavar(Opts) -> apply_boolopt_map( [{flag, undefined}, {no_arg, undefined}, {'_', "VALUE"}], Opts). visible_from_opts(Opts) -> not proplists:get_bool(hidden, Opts). Attrs key(#opt{key=Key}) -> Key. desc(#opt{desc=Desc}) -> Desc. has_arg(#opt{has_arg=HasArg}) -> HasArg. short(#opt{short=Short}) -> Short. long(#opt{long=Long}) -> Long. metavar(#opt{metavar=Metavar}) -> Metavar. visible(#opt{visible=Visible}) -> Visible. int_val(Key, Opts, Default, ErrMsg) -> case proplists:get_value(Key, Opts) of undefined -> Default; Str -> str_to_int(Str, ErrMsg) end. str_to_int(Str, ErrMsg) -> try list_to_integer(Str) catch error:badarg -> throw({error, ErrMsg}) end. opt_val(Key, Opts, Default) -> case proplists:get_value(Key, Opts, '$undefined') of '$undefined' when is_function(Default) -> Default(); '$undefined' -> Default; Val -> Val end. apply_boolopt_map([{'_', Result}|_], _Opts) -> Result; apply_boolopt_map([{Opt, Result}|Rest], Opts) -> case proplists:get_bool(Opt, Opts) of true -> Result; false -> apply_boolopt_map(Rest, Opts) end. replace(Str, Replace, With) -> re:replace(Str, Replace, With, [{return, list}]).
b07a28c074b49fcbc07d8c0b72ab0b977af72cc90514b95e6bab9905d4348869
transient-haskell/transient-stack
Testspark.hs
{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable #-} module Main where import Transient.Base import Transient.Stream.Resource import Data.Char import Control.Monad.IO.Class main= keep . threads 0 $ do chunk <- sourceFile "../transient.cabal" liftIO $ print chunk return $ map toUpper chunk `sinkFile` "outfile"
null
https://raw.githubusercontent.com/transient-haskell/transient-stack/dde6f6613a946d57bb70879a5c0e7e5a73a91dbe/transient-universe/tests/Testspark.hs
haskell
# LANGUAGE ScopedTypeVariables, DeriveDataTypeable #
module Main where import Transient.Base import Transient.Stream.Resource import Data.Char import Control.Monad.IO.Class main= keep . threads 0 $ do chunk <- sourceFile "../transient.cabal" liftIO $ print chunk return $ map toUpper chunk `sinkFile` "outfile"
c8d1d405c2937106fe46fdfe7b63bb53bd102728e613fd999f732b9431abb78e
onixie/w32api
user32.lisp
(defpackage #:w32api.user32 (:use #:common-lisp #:cffi #:w32api.type) (:export GetSystemMetrics GetProcessWindowStation EnumDesktopsW CreateDesktopW OpenDesktopW OpenInputDesktop SwitchDesktop CloseDesktop SetThreadDesktop GetThreadDesktop GetUserObjectInformationW SetUserObjectInformationW EnumDisplayMonitors MonitorFromPoint MonitorFromRect MonitorFromWindow GetMonitorInfoW RegisterClassExW UnregisterClassW DefWindowProcW CallWindowProcW GetClassNameW GetClassInfoExW GetClassLongPtrW SetClassLongPtrW ;; CreateWindowA CreateWindowExW FindWindowExW GetDesktopWindow SetParent GetParent GetAncestor GetWindow EnumChildWindows EnumWindows EnumDesktopWindows EnumThreadWindows GetTopWindow GetWindowThreadProcessId GetWindowThreadId GetWindowProcessId GetWindowTextLengthW GetWindowTextW SetWindowTextW SetWindowLongPtrW GetWindowLongPtrW SetWindowStyle GetWindowStyle SetFocus GetFocus SetActiveWindow GetActiveWindow SetForegroundWindow GetForegroundWindow LockSetForegroundWindow CloseWindow OpenIcon ShowWindow AnimateWindow EnableWindow SwitchToThisWindow BringWindowToTop UpdateWindow MoveWindow SetWindowPos DestroyWindow CascadeWindows TileWindows IsWindow IsWindowUnicode IsWindowEnabled IsWindowVisible IsChild IsIconic IsZoomed GetDC GetWindowDC ReleaseDC WindowFromDC BeginPaint EndPaint GetWindowRect GetClientRect InvalidateRect ValidateRect InvalidateRgn ValidateRgn GetWindowRgn SetWindowRgn GetUpdateRect GetUpdateRgn CreateAcceleratorTableW TranslateAcceleratorW GetMessageW GetMessageTime PeekMessageW PostMessageW SendMessageW PostThreadMessageW PostQuitMessage WaitMessage TranslateMessage DispatchMessageW GetSysColor GetSysColorBrush MessageBoxW RGB GetRValue GetGValue GETBValue GetKeyState GetAsyncKeyState GetKeyboardState MapVirtualKeyW MapWindowPoints AdjustWindowRectEx SetWindowExtendedStyle GetWindowExtendedStyle GetCursorPos )) (in-package #:w32api.user32) (define-foreign-library user32 (:win32 "user32.dll")) (use-foreign-library "user32") (defcfun "GetProcessWindowStation" HWINSTA) (defcfun "EnumDesktopsW" :boolean (hwinsta HWINSTA) (lpEnumFunc :pointer) (lParam LPARAM) ) (defcfun "CreateDesktopW" HDESK (lpszDesktop :string) (lpszDevice :string) (pDevmode (:pointer (:struct DEVMODE))) (dwFlags DF_FLAG) (dwDesiredAccess DA_FLAG) (lpsa (:pointer (:struct SECURITY_ATTRIBUTES))) ) (defcfun "OpenDesktopW" HDESK (lpszDesktop :string) (dwFlags DF_FLAG) (fInherit :boolean) (dwDesiredAccess DA_FLAG)) (defcfun "OpenInputDesktop" HDESK (dwFlags DF_FLAG) (fInherit :boolean) (dwDesiredAccess DA_FLAG)) (defcfun "SwitchDesktop" :boolean (hDesktop HDESK)) (defcfun "CloseDesktop" :boolean (hDesktop HDESK)) (defcfun "SetThreadDesktop" :boolean (hDesktop HDESK)) (defcfun "GetThreadDesktop" HDESK (dwThreadId DWORD)) (defcfun "GetUserObjectInformationW" :boolean (hObj HANDLE) (nIndex UOI_ENUM) (pvInfo (:pointer :void)) (nLength DWORD) (lpnLengthNeeded (:pointer DWORD))) (defcfun "SetUserObjectInformationW" :boolean (hObj HANDLE) (nIndex UOI_ENUM) (pvInfo (:pointer :void)) (nLength DWORD)) (defcfun "EnumDisplayMonitors" :boolean (hdc HDC) (lprcClip (:pointer (:struct RECT))) (lpfnEnum :pointer) (dwData LPARAM)) (defcfun "MonitorFromPoint" HMONITOR (pt (:pointer (:struct POINT))) (dwFlags MONITOR_FLAG)) (defcfun "MonitorFromRect" HMONITOR (lprc (:pointer (:struct RECT))) (dwFlags MONITOR_FLAG)) (defcfun "MonitorFromWindow" HMONITOR (hwnd HWND) (dwFlags MONITOR_FLAG)) (defcfun "GetMonitorInfoW" :boolean (hMonitor HMONITOR) (lpmi (:pointer (:struct MONITORINFOEX)))) (defcfun "RegisterClassExW" C_ATOM (lpwcx (:pointer (:struct WNDCLASSEX)))) (defcfun "UnregisterClassW" :boolean (lpClassName :string) (hInstance HINSTANCE)) (defcfun "GetClassInfoExW" :boolean (hinst HINSTANCE) (lpszClass :string) (lpwcx (:pointer (:struct WNDCLASSEX)))) (defcfun "GetClassNameW" :boolean (hWnd HWND) (lpClassName :pointer) (nMaxCount :int)) (defcfun "SetClassLongPtrW" ULONG_PTR (hWnd HWND) (nIndex GCL_ENUM) (dwNewLong LONG_PTR)) (defcfun "GetClassLongPtrW" ULONG_PTR (hWnd HWND) (nIndex GCL_ENUM)) (defcfun "CreateWindowExW" HWND (dwExStyle WS_EX_FLAG) (lpClassName :string) (lpWindowName :string) (dwStyle WND_STYLE) (x :int) (y :int) (nWidth :int) (nHeight :int) (hWndParent HWND) (hMenu HMENU) (hInstance HINSTANCE) (lpParam (:pointer :void))) (defcfun "GetWindow" HWND (hWnd HWND) (uCmd GW_ENUM)) = ( GetWindow ... : CHILD ) (hWnd HWND)) (defcfun "GetDesktopWindow" HWND) (defcfun "SetParent" HWND (hWndChild HWND) (hWndNewParent HWND)) (defcfun "GetParent" HWND (hWnd HWND)) (defcfun "GetAncestor" HWND (hWnd HWND) (gaFlags GA_ENUM)) (defcfun "EnumDesktopWindows" :boolean (hDesktop HDESK) (lpfn :pointer) (lParam LPARAM) ) (defcfun "EnumWindows" :boolean (lpEnumFunc :pointer) (lParam LPARAM) ) (defcfun "EnumChildWindows" :boolean (hWndParent HWND) (lpEnumFunc :pointer) (lParam LPARAM)) (defcfun "EnumThreadWindows" :boolean (dwThreadId DWORD) (lpfn :pointer) (lParam LPARAM)) (defcfun #+x86 ("SetWindowLongW" SetWindowLongPtrW) #+x86-64 "SetWindowLongPtrW" LONG_PTR (hWnd HWND) (nIndex GWLP_ENUM) (dwNewLong LONG_PTR)) (defcfun #+x86 ("GetWindowLongW" GetWindowLongPtrW) #+x86-64 "GetWindowLongPtrW" LONG_PTR (hWnd HWND) (nIndex GWLP_ENUM)) (defun SetWindowStyle (hWnd styles) (foreign-funcall #+x86-64 "SetWindowLongPtrW" #+x86 "SetWindowLongW" HWND hWnd GWLP_ENUM :GWL_STYLE WND_STYLE styles WND_STYLE)) (defun GetWindowStyle (hWnd) (foreign-funcall #+x86-64 "GetWindowLongPtrW" #+x86 "GetWindowLongW" HWND hWnd GWLP_ENUM :GWL_STYLE WND_STYLE)) (defun SetWindowExtendedStyle (hWnd styles) (foreign-funcall #+x86-64 "SetWindowLongPtrW" #+x86 "SetWindowLongW" HWND hWnd GWLP_ENUM :GWL_EXSTYLE WS_EX_FLAG styles WS_EX_FLAG)) (defun GetWindowExtendedStyle (hWnd) (foreign-funcall #+x86-64 "GetWindowLongPtrW" #+x86 "GetWindowLongW" HWND hWnd GWLP_ENUM :GWL_EXSTYLE WS_EX_FLAG)) (defcfun "GetWindowThreadProcessId" DWORD (hWnd HWND) (lpdwProcessId (:pointer DWORD))) (defun GetWindowThreadId (hWnd) (foreign-funcall "GetWindowThreadProcessId" HWND hWnd (:pointer DWORD) (null-pointer) DWORD)) (defun GetWindowProcessId (hWnd) (with-foreign-object (procId 'DWORD) (foreign-funcall "GetWindowThreadProcessId" HWND hWnd (:pointer DWORD) procId DWORD) (mem-ref procId 'DWORD))) (defcfun "ShowWindow" :boolean (hWnd HWND) (nCmdShow SW_ENUM)) (defcfun "AnimateWindow" :boolean (hwnd HWND) (dwTime DWORD) (dwFlags DWORD)) (defcfun "EnableWindow" :boolean (hWnd HWND) (bEnable :boolean)) (defcfun "SwitchToThisWindow" :void (hWnd HWND) (fAltTab :boolean)) (defcfun "BringWindowToTop" :void (hWnd HWND)) (defcfun "SetFocus" :boolean (hWnd HWND)) (defcfun "GetFocus" HWND) (defcfun "SetActiveWindow" :boolean (hWnd HWND)) (defcfun "GetActiveWindow" HWND) (defcfun "SetForegroundWindow" :boolean (hWnd HWND)) ; (defcfun "GetForegroundWindow" HWND) (defcfun "LockSetForegroundWindow" :boolean (uLockCode :uint)) (defcfun "CloseWindow" :boolean (hWnd HWND)) (defcfun "OpenIcon" :boolean (hWnd HWND)) (defcfun "FindWindowExW" HWND (hwndParent HWND) (hwndChildAfter HWND) (lpszClass :string) (lpszWindow :string)) (defcfun "IsChild" :boolean (hWndParent HWND) (hWnd HWND)) (defcfun "IsWindow" :boolean (hWnd HWND)) (defcfun "IsWindowUnicode" :boolean (hWnd HWND)) (defcfun "IsWindowVisible" :boolean (hWnd HWND)) (defcfun "IsWindowEnabled" :boolean (hWnd HWND)) (defcfun "IsIconic" :boolean (hWnd HWND)) (defcfun "IsZoomed" :boolean (hWnd HWND)) (defcfun "DestroyWindow" :boolean (hWnd HWND)) (defcfun "DefWindowProcW" LRESULT (hWnd HWND) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "CallWindowProcW" LRESULT (lpPrevWndFunc :pointer) (hWnd HWND) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "GetWindowTextLengthW" :int (hWnd HWND)) (defcfun "GetWindowTextW" :boolean (hWnd HWND) (lpString :string) (nMaxCount :int)) (defcfun "SetWindowTextW" :boolean (hWnd HWND) (lpString :string)) (defcfun "TileWindows" WORD (hwndParent HWND) (wHow MDITILE_FLAG) (lpRect (:pointer (:struct RECT))) (cKids :uint) (lpKids (:pointer HWND))) (defcfun "CascadeWindows" WORD (hwndParent HWND) (wHow MDITILE_FLAG) (lpRect (:pointer (:struct RECT))) (cKids :uint) (lpKids (:pointer HWND))) (defcfun "CreateAcceleratorTableW" HACCEL (lpaccl (:pointer (:struct ACCEL))) (cEntries :int)) (defcfun "TranslateAcceleratorW" :boolean (hWnd HWND) (hAccTable HACCEL) (lpMsg (:pointer (:struct MSG)))) (defcfun "GetMessageW" :int ;be aware of return -1 when attached window destroyed (lpMsg (:pointer (:struct MSG))) (hWnd HWND) (wMsgFilterMin :uint) (wMsgFilterMax :uint)) (defcfun "GetMessageTime" :long) (defcfun "PeekMessageW" :boolean (lpMsg (:pointer (:struct MSG))) (hWnd HWND) (wMsgFilterMin :uint) (wMsgFilterMax :uint) (wRemoveMsg PM_FLAG) ) (defcfun "PostMessageW" :boolean (hWnd HWND) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "SendMessageW" :boolean (hWnd HWND) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "PostThreadMessageW" :boolean (idThread DWORD) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "WaitMessage" :boolean) (defcfun "TranslateMessage" :boolean (lpMsg (:pointer (:struct MSG)))) (defcfun "DispatchMessageW" LRESULT (lpMsg (:pointer (:struct MSG)))) (defcfun "PostQuitMessage" :void (id :int)) ;;; (defcfun "UpdateWindow" :boolean (hWnd HWND)) (defcfun "GetDC" HDC (hWnd HWND)) (defcfun "GetWindowDC" HDC (hWnd HWND)) (defcfun "ReleaseDC" :boolean (hWnd HWND) (hDC HDC)) (defcfun "WindowFromDC" HWND (hDC HDC)) (defcfun "BeginPaint" HDC (hwnd HWND) (lpPaint (:pointer (:struct PAINTSTRUCT)))) (defcfun "EndPaint" :boolean (hwnd HWND) (lpPaint (:pointer (:struct PAINTSTRUCT)))) (defcfun "GetWindowRect" :boolean (hwnd HWND) (lpRect (:pointer (:struct RECT)))) (defcfun "GetClientRect" :boolean (hwnd HWND) (lpRect (:pointer (:struct RECT)))) (defcfun "MoveWindow" :boolean (hwnd HWND) (X :int) (Y :int) (nWidth :int) (nHeight :int) (bRepaint :boolean)) (defcfun "SetWindowPos" :boolean (hWnd HWND) (hWndInsertAfter HWND_ENUM) (X :int) (Y :int) (cx :int) (cy :int) (uFlags SWP_FLAG)) (defcfun "InvalidateRect" :boolean (hWnd HWND) (lpRect (:pointer (:struct RECT))) (bErase :boolean)) (defcfun "ValidateRect" :boolean (hWnd HWND) (lpRect (:pointer (:struct RECT)))) (defcfun "InvalidateRgn" :boolean (hWnd HWND) (hRgn HRGN) (bErase :boolean)) (defcfun "ValidateRgn" :boolean (hWnd HWND) (hRgn HRGN)) (defcfun "GetWindowRgn" GWR_RESULT_ENUM (hWnd HWND) (hRgn HRGN)) (defcfun "SetWindowRgn" :boolean (hWnd HWND) (hRgn HRGN) (bRedraw :boolean)) (defcfun "GetUpdateRect" :boolean (hWnd HWND) (lpRect (:pointer (:struct RECT))) (bErase :boolean)) (defcfun "GetUpdateRgn" :boolean (hWnd HWND) (bRgn HRGN) (bErase :boolean)) (defcfun "WindowFromPoint" HWND (Point (:pointer (:struct POINT)))) (defcfun "WindowFromPhysicalPoint" HWND (Point (:pointer (:struct POINT)))) (defcfun "ChildWindowFromPointEx" HWND (hWndParent HWND) (Point (:pointer (:struct POINT))) (uFlags :uint)) (defcfun "RealChildWindowFromPoint" HWND (hWndParent HWND) (ptParentClientCoords (:pointer (:struct POINT)))) (defcfun "GetSystemMetrics" :int (nIndex SM_ENUM)) (defcfun "GetSysColorBrush" HBRUSH (nIndex COLOR_ENUM)) (defcfun "GetSysColor" COLORREF (nIndex COLOR_ENUM)) (defcfun "MessageBoxW" MB_RESULT_ENUM (hWnd HWND) (lpText :string) (lpCaption :string) (uType MB_FLAG)) (defun RGB (r g b) (declare (inline) (type (unsigned-byte 8) r g b)) (with-foreign-object (color 'COLORREF) (setf (mem-ref color 'COLORREF) (logior (ash b 16) (ash g 8) r)))) (defun GetRValue (color) (declare (inline)) (the (unsigned-byte 8) (logand color #x000000ff))) (defun GetGValue (color) (declare (inline)) (the (unsigned-byte 8) (ash (logand color #x0000ff00) -8))) (defun GetBValue (color) (declare (inline)) (the (unsigned-byte 8) (ash (logand color #x00ff0000) -16))) (defcfun "GetKeyState" :short (nVirtKey VK_ENUM)) (defcfun "GetAsyncKeyState" :short (nVirtKey VK_ENUM)) (defcfun "GetKeyboardState" :boolean (lpKeyState (:pointer C_BYTE))) (defcfun "MapVirtualKeyW" :uint (uCode :uint) (uMapType MAPVK_ENUM)) (defcfun "MapWindowPoints" :int (hWndFrom HWND) (hWndTo HWND) (lpPoints :pointer) (cPoints :uint)) (defcfun "AdjustWindowRectEx" :boolean (lpRect (:pointer (:struct RECT))) (dwStyle WND_STYLE) (bMenu :boolean) (dwExStyle WS_EX_FLAG)) (defcfun "GetCursorPos" :boolean (lpPoint (:pointer (:struct POINT))))
null
https://raw.githubusercontent.com/onixie/w32api/bc2c17a3ff493b4dc22c8c0479ca1bf0bdcce5cc/api/user32.lisp
lisp
CreateWindowA be aware of return -1 when attached window destroyed
(defpackage #:w32api.user32 (:use #:common-lisp #:cffi #:w32api.type) (:export GetSystemMetrics GetProcessWindowStation EnumDesktopsW CreateDesktopW OpenDesktopW OpenInputDesktop SwitchDesktop CloseDesktop SetThreadDesktop GetThreadDesktop GetUserObjectInformationW SetUserObjectInformationW EnumDisplayMonitors MonitorFromPoint MonitorFromRect MonitorFromWindow GetMonitorInfoW RegisterClassExW UnregisterClassW DefWindowProcW CallWindowProcW GetClassNameW GetClassInfoExW GetClassLongPtrW SetClassLongPtrW CreateWindowExW FindWindowExW GetDesktopWindow SetParent GetParent GetAncestor GetWindow EnumChildWindows EnumWindows EnumDesktopWindows EnumThreadWindows GetTopWindow GetWindowThreadProcessId GetWindowThreadId GetWindowProcessId GetWindowTextLengthW GetWindowTextW SetWindowTextW SetWindowLongPtrW GetWindowLongPtrW SetWindowStyle GetWindowStyle SetFocus GetFocus SetActiveWindow GetActiveWindow SetForegroundWindow GetForegroundWindow LockSetForegroundWindow CloseWindow OpenIcon ShowWindow AnimateWindow EnableWindow SwitchToThisWindow BringWindowToTop UpdateWindow MoveWindow SetWindowPos DestroyWindow CascadeWindows TileWindows IsWindow IsWindowUnicode IsWindowEnabled IsWindowVisible IsChild IsIconic IsZoomed GetDC GetWindowDC ReleaseDC WindowFromDC BeginPaint EndPaint GetWindowRect GetClientRect InvalidateRect ValidateRect InvalidateRgn ValidateRgn GetWindowRgn SetWindowRgn GetUpdateRect GetUpdateRgn CreateAcceleratorTableW TranslateAcceleratorW GetMessageW GetMessageTime PeekMessageW PostMessageW SendMessageW PostThreadMessageW PostQuitMessage WaitMessage TranslateMessage DispatchMessageW GetSysColor GetSysColorBrush MessageBoxW RGB GetRValue GetGValue GETBValue GetKeyState GetAsyncKeyState GetKeyboardState MapVirtualKeyW MapWindowPoints AdjustWindowRectEx SetWindowExtendedStyle GetWindowExtendedStyle GetCursorPos )) (in-package #:w32api.user32) (define-foreign-library user32 (:win32 "user32.dll")) (use-foreign-library "user32") (defcfun "GetProcessWindowStation" HWINSTA) (defcfun "EnumDesktopsW" :boolean (hwinsta HWINSTA) (lpEnumFunc :pointer) (lParam LPARAM) ) (defcfun "CreateDesktopW" HDESK (lpszDesktop :string) (lpszDevice :string) (pDevmode (:pointer (:struct DEVMODE))) (dwFlags DF_FLAG) (dwDesiredAccess DA_FLAG) (lpsa (:pointer (:struct SECURITY_ATTRIBUTES))) ) (defcfun "OpenDesktopW" HDESK (lpszDesktop :string) (dwFlags DF_FLAG) (fInherit :boolean) (dwDesiredAccess DA_FLAG)) (defcfun "OpenInputDesktop" HDESK (dwFlags DF_FLAG) (fInherit :boolean) (dwDesiredAccess DA_FLAG)) (defcfun "SwitchDesktop" :boolean (hDesktop HDESK)) (defcfun "CloseDesktop" :boolean (hDesktop HDESK)) (defcfun "SetThreadDesktop" :boolean (hDesktop HDESK)) (defcfun "GetThreadDesktop" HDESK (dwThreadId DWORD)) (defcfun "GetUserObjectInformationW" :boolean (hObj HANDLE) (nIndex UOI_ENUM) (pvInfo (:pointer :void)) (nLength DWORD) (lpnLengthNeeded (:pointer DWORD))) (defcfun "SetUserObjectInformationW" :boolean (hObj HANDLE) (nIndex UOI_ENUM) (pvInfo (:pointer :void)) (nLength DWORD)) (defcfun "EnumDisplayMonitors" :boolean (hdc HDC) (lprcClip (:pointer (:struct RECT))) (lpfnEnum :pointer) (dwData LPARAM)) (defcfun "MonitorFromPoint" HMONITOR (pt (:pointer (:struct POINT))) (dwFlags MONITOR_FLAG)) (defcfun "MonitorFromRect" HMONITOR (lprc (:pointer (:struct RECT))) (dwFlags MONITOR_FLAG)) (defcfun "MonitorFromWindow" HMONITOR (hwnd HWND) (dwFlags MONITOR_FLAG)) (defcfun "GetMonitorInfoW" :boolean (hMonitor HMONITOR) (lpmi (:pointer (:struct MONITORINFOEX)))) (defcfun "RegisterClassExW" C_ATOM (lpwcx (:pointer (:struct WNDCLASSEX)))) (defcfun "UnregisterClassW" :boolean (lpClassName :string) (hInstance HINSTANCE)) (defcfun "GetClassInfoExW" :boolean (hinst HINSTANCE) (lpszClass :string) (lpwcx (:pointer (:struct WNDCLASSEX)))) (defcfun "GetClassNameW" :boolean (hWnd HWND) (lpClassName :pointer) (nMaxCount :int)) (defcfun "SetClassLongPtrW" ULONG_PTR (hWnd HWND) (nIndex GCL_ENUM) (dwNewLong LONG_PTR)) (defcfun "GetClassLongPtrW" ULONG_PTR (hWnd HWND) (nIndex GCL_ENUM)) (defcfun "CreateWindowExW" HWND (dwExStyle WS_EX_FLAG) (lpClassName :string) (lpWindowName :string) (dwStyle WND_STYLE) (x :int) (y :int) (nWidth :int) (nHeight :int) (hWndParent HWND) (hMenu HMENU) (hInstance HINSTANCE) (lpParam (:pointer :void))) (defcfun "GetWindow" HWND (hWnd HWND) (uCmd GW_ENUM)) = ( GetWindow ... : CHILD ) (hWnd HWND)) (defcfun "GetDesktopWindow" HWND) (defcfun "SetParent" HWND (hWndChild HWND) (hWndNewParent HWND)) (defcfun "GetParent" HWND (hWnd HWND)) (defcfun "GetAncestor" HWND (hWnd HWND) (gaFlags GA_ENUM)) (defcfun "EnumDesktopWindows" :boolean (hDesktop HDESK) (lpfn :pointer) (lParam LPARAM) ) (defcfun "EnumWindows" :boolean (lpEnumFunc :pointer) (lParam LPARAM) ) (defcfun "EnumChildWindows" :boolean (hWndParent HWND) (lpEnumFunc :pointer) (lParam LPARAM)) (defcfun "EnumThreadWindows" :boolean (dwThreadId DWORD) (lpfn :pointer) (lParam LPARAM)) (defcfun #+x86 ("SetWindowLongW" SetWindowLongPtrW) #+x86-64 "SetWindowLongPtrW" LONG_PTR (hWnd HWND) (nIndex GWLP_ENUM) (dwNewLong LONG_PTR)) (defcfun #+x86 ("GetWindowLongW" GetWindowLongPtrW) #+x86-64 "GetWindowLongPtrW" LONG_PTR (hWnd HWND) (nIndex GWLP_ENUM)) (defun SetWindowStyle (hWnd styles) (foreign-funcall #+x86-64 "SetWindowLongPtrW" #+x86 "SetWindowLongW" HWND hWnd GWLP_ENUM :GWL_STYLE WND_STYLE styles WND_STYLE)) (defun GetWindowStyle (hWnd) (foreign-funcall #+x86-64 "GetWindowLongPtrW" #+x86 "GetWindowLongW" HWND hWnd GWLP_ENUM :GWL_STYLE WND_STYLE)) (defun SetWindowExtendedStyle (hWnd styles) (foreign-funcall #+x86-64 "SetWindowLongPtrW" #+x86 "SetWindowLongW" HWND hWnd GWLP_ENUM :GWL_EXSTYLE WS_EX_FLAG styles WS_EX_FLAG)) (defun GetWindowExtendedStyle (hWnd) (foreign-funcall #+x86-64 "GetWindowLongPtrW" #+x86 "GetWindowLongW" HWND hWnd GWLP_ENUM :GWL_EXSTYLE WS_EX_FLAG)) (defcfun "GetWindowThreadProcessId" DWORD (hWnd HWND) (lpdwProcessId (:pointer DWORD))) (defun GetWindowThreadId (hWnd) (foreign-funcall "GetWindowThreadProcessId" HWND hWnd (:pointer DWORD) (null-pointer) DWORD)) (defun GetWindowProcessId (hWnd) (with-foreign-object (procId 'DWORD) (foreign-funcall "GetWindowThreadProcessId" HWND hWnd (:pointer DWORD) procId DWORD) (mem-ref procId 'DWORD))) (defcfun "ShowWindow" :boolean (hWnd HWND) (nCmdShow SW_ENUM)) (defcfun "AnimateWindow" :boolean (hwnd HWND) (dwTime DWORD) (dwFlags DWORD)) (defcfun "EnableWindow" :boolean (hWnd HWND) (bEnable :boolean)) (defcfun "SwitchToThisWindow" :void (hWnd HWND) (fAltTab :boolean)) (defcfun "BringWindowToTop" :void (hWnd HWND)) (defcfun "SetFocus" :boolean (hWnd HWND)) (defcfun "GetFocus" HWND) (defcfun "SetActiveWindow" :boolean (hWnd HWND)) (defcfun "GetActiveWindow" HWND) (defcfun "SetForegroundWindow" :boolean (defcfun "GetForegroundWindow" HWND) (defcfun "LockSetForegroundWindow" :boolean (uLockCode :uint)) (defcfun "CloseWindow" :boolean (hWnd HWND)) (defcfun "OpenIcon" :boolean (hWnd HWND)) (defcfun "FindWindowExW" HWND (hwndParent HWND) (hwndChildAfter HWND) (lpszClass :string) (lpszWindow :string)) (defcfun "IsChild" :boolean (hWndParent HWND) (hWnd HWND)) (defcfun "IsWindow" :boolean (hWnd HWND)) (defcfun "IsWindowUnicode" :boolean (hWnd HWND)) (defcfun "IsWindowVisible" :boolean (hWnd HWND)) (defcfun "IsWindowEnabled" :boolean (hWnd HWND)) (defcfun "IsIconic" :boolean (hWnd HWND)) (defcfun "IsZoomed" :boolean (hWnd HWND)) (defcfun "DestroyWindow" :boolean (hWnd HWND)) (defcfun "DefWindowProcW" LRESULT (hWnd HWND) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "CallWindowProcW" LRESULT (lpPrevWndFunc :pointer) (hWnd HWND) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "GetWindowTextLengthW" :int (hWnd HWND)) (defcfun "GetWindowTextW" :boolean (hWnd HWND) (lpString :string) (nMaxCount :int)) (defcfun "SetWindowTextW" :boolean (hWnd HWND) (lpString :string)) (defcfun "TileWindows" WORD (hwndParent HWND) (wHow MDITILE_FLAG) (lpRect (:pointer (:struct RECT))) (cKids :uint) (lpKids (:pointer HWND))) (defcfun "CascadeWindows" WORD (hwndParent HWND) (wHow MDITILE_FLAG) (lpRect (:pointer (:struct RECT))) (cKids :uint) (lpKids (:pointer HWND))) (defcfun "CreateAcceleratorTableW" HACCEL (lpaccl (:pointer (:struct ACCEL))) (cEntries :int)) (defcfun "TranslateAcceleratorW" :boolean (hWnd HWND) (hAccTable HACCEL) (lpMsg (:pointer (:struct MSG)))) (lpMsg (:pointer (:struct MSG))) (hWnd HWND) (wMsgFilterMin :uint) (wMsgFilterMax :uint)) (defcfun "GetMessageTime" :long) (defcfun "PeekMessageW" :boolean (lpMsg (:pointer (:struct MSG))) (hWnd HWND) (wMsgFilterMin :uint) (wMsgFilterMax :uint) (wRemoveMsg PM_FLAG) ) (defcfun "PostMessageW" :boolean (hWnd HWND) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "SendMessageW" :boolean (hWnd HWND) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "PostThreadMessageW" :boolean (idThread DWORD) (Msg WND_MESSAGE) (wParam WPARAM) (lParam LPARAM)) (defcfun "WaitMessage" :boolean) (defcfun "TranslateMessage" :boolean (lpMsg (:pointer (:struct MSG)))) (defcfun "DispatchMessageW" LRESULT (lpMsg (:pointer (:struct MSG)))) (defcfun "PostQuitMessage" :void (id :int)) (defcfun "UpdateWindow" :boolean (hWnd HWND)) (defcfun "GetDC" HDC (hWnd HWND)) (defcfun "GetWindowDC" HDC (hWnd HWND)) (defcfun "ReleaseDC" :boolean (hWnd HWND) (hDC HDC)) (defcfun "WindowFromDC" HWND (hDC HDC)) (defcfun "BeginPaint" HDC (hwnd HWND) (lpPaint (:pointer (:struct PAINTSTRUCT)))) (defcfun "EndPaint" :boolean (hwnd HWND) (lpPaint (:pointer (:struct PAINTSTRUCT)))) (defcfun "GetWindowRect" :boolean (hwnd HWND) (lpRect (:pointer (:struct RECT)))) (defcfun "GetClientRect" :boolean (hwnd HWND) (lpRect (:pointer (:struct RECT)))) (defcfun "MoveWindow" :boolean (hwnd HWND) (X :int) (Y :int) (nWidth :int) (nHeight :int) (bRepaint :boolean)) (defcfun "SetWindowPos" :boolean (hWnd HWND) (hWndInsertAfter HWND_ENUM) (X :int) (Y :int) (cx :int) (cy :int) (uFlags SWP_FLAG)) (defcfun "InvalidateRect" :boolean (hWnd HWND) (lpRect (:pointer (:struct RECT))) (bErase :boolean)) (defcfun "ValidateRect" :boolean (hWnd HWND) (lpRect (:pointer (:struct RECT)))) (defcfun "InvalidateRgn" :boolean (hWnd HWND) (hRgn HRGN) (bErase :boolean)) (defcfun "ValidateRgn" :boolean (hWnd HWND) (hRgn HRGN)) (defcfun "GetWindowRgn" GWR_RESULT_ENUM (hWnd HWND) (hRgn HRGN)) (defcfun "SetWindowRgn" :boolean (hWnd HWND) (hRgn HRGN) (bRedraw :boolean)) (defcfun "GetUpdateRect" :boolean (hWnd HWND) (lpRect (:pointer (:struct RECT))) (bErase :boolean)) (defcfun "GetUpdateRgn" :boolean (hWnd HWND) (bRgn HRGN) (bErase :boolean)) (defcfun "WindowFromPoint" HWND (Point (:pointer (:struct POINT)))) (defcfun "WindowFromPhysicalPoint" HWND (Point (:pointer (:struct POINT)))) (defcfun "ChildWindowFromPointEx" HWND (hWndParent HWND) (Point (:pointer (:struct POINT))) (uFlags :uint)) (defcfun "RealChildWindowFromPoint" HWND (hWndParent HWND) (ptParentClientCoords (:pointer (:struct POINT)))) (defcfun "GetSystemMetrics" :int (nIndex SM_ENUM)) (defcfun "GetSysColorBrush" HBRUSH (nIndex COLOR_ENUM)) (defcfun "GetSysColor" COLORREF (nIndex COLOR_ENUM)) (defcfun "MessageBoxW" MB_RESULT_ENUM (hWnd HWND) (lpText :string) (lpCaption :string) (uType MB_FLAG)) (defun RGB (r g b) (declare (inline) (type (unsigned-byte 8) r g b)) (with-foreign-object (color 'COLORREF) (setf (mem-ref color 'COLORREF) (logior (ash b 16) (ash g 8) r)))) (defun GetRValue (color) (declare (inline)) (the (unsigned-byte 8) (logand color #x000000ff))) (defun GetGValue (color) (declare (inline)) (the (unsigned-byte 8) (ash (logand color #x0000ff00) -8))) (defun GetBValue (color) (declare (inline)) (the (unsigned-byte 8) (ash (logand color #x00ff0000) -16))) (defcfun "GetKeyState" :short (nVirtKey VK_ENUM)) (defcfun "GetAsyncKeyState" :short (nVirtKey VK_ENUM)) (defcfun "GetKeyboardState" :boolean (lpKeyState (:pointer C_BYTE))) (defcfun "MapVirtualKeyW" :uint (uCode :uint) (uMapType MAPVK_ENUM)) (defcfun "MapWindowPoints" :int (hWndFrom HWND) (hWndTo HWND) (lpPoints :pointer) (cPoints :uint)) (defcfun "AdjustWindowRectEx" :boolean (lpRect (:pointer (:struct RECT))) (dwStyle WND_STYLE) (bMenu :boolean) (dwExStyle WS_EX_FLAG)) (defcfun "GetCursorPos" :boolean (lpPoint (:pointer (:struct POINT))))
4dca973d9cf0825d7682668faac91ec833dff82b2a503f091d1f7ef51f231ca0
panda-planner-dev/ipc2020-domains
p-10.lisp
(defproblem problem domain ( (In_City HauptbahnhofUlm Ulm) (In_City HauptbahnhofMuenchen Muenchen) (At_Vehicle Eisenbahnwagen HauptbahnhofUlm) (At_Vehicle Lokomotive HauptbahnhofUlm) (Connects UlmMuenchenRailRoute HauptbahnhofUlm HauptbahnhofMuenchen) (Available UlmMuenchenRailRoute) (Available Lokomotive) (PV_Compatible Essen Eisenbahnwagen) (RV_Compatible UlmMuenchenRailRoute Lokomotive) (At_Package Essen HauptbahnhofUlm) (type_City Muenchen) (type_City Ulm) (type_City_Location HauptbahnhofMuenchen) (type_City_Location HauptbahnhofUlm) (type_Equipment_Position Eisenbahnwagen) (type_Equipment_Position HauptbahnhofMuenchen) (type_Equipment_Position HauptbahnhofUlm) (type_Equipment_Position Lokomotive) (type_Equipment_Position Muenchen) (type_Equipment_Position Ulm) (type_Food Essen) (type_Location HauptbahnhofMuenchen) (type_Location HauptbahnhofUlm) (type_Location Muenchen) (type_Location Ulm) (type_Object Eisenbahnwagen) (type_Object Essen) (type_Object Lokomotive) (type_Package Essen) (type_Package_Storage_Position Eisenbahnwagen) (type_Package_Storage_Position HauptbahnhofMuenchen) (type_Package_Storage_Position HauptbahnhofUlm) (type_Package_Storage_Position Lokomotive) (type_Package_Storage_Position Muenchen) (type_Package_Storage_Position Ulm) (type_Perishable Essen) (type_Physical Eisenbahnwagen) (type_Physical Essen) (type_Rail_Route UlmMuenchenRailRoute) (type_Refrigerated Eisenbahnwagen) (type_Refrigerated_Regular_Traincar Eisenbahnwagen) (type_Refrigerated_Vehicle Eisenbahnwagen) (type_Regular Eisenbahnwagen) (type_Regular Essen) (type_Regular_Vehicle Eisenbahnwagen) (type_Route UlmMuenchenRailRoute) (type_Speciality Eisenbahnwagen) (type_TCenter HauptbahnhofMuenchen) (type_TCenter HauptbahnhofUlm) (type_Thing Eisenbahnwagen) (type_Thing Essen) (type_Thing HauptbahnhofMuenchen) (type_Thing HauptbahnhofUlm) (type_Thing Lokomotive) (type_Thing Muenchen) (type_Thing Ulm) (type_Thing UlmMuenchenRailRoute) (type_Train Lokomotive) (type_Train_Station HauptbahnhofMuenchen) (type_Train_Station HauptbahnhofUlm) (type_Traincar Eisenbahnwagen) (type_Vehicle Eisenbahnwagen) (type_Vehicle Lokomotive) (type_Vehicle_Position Eisenbahnwagen) (type_Vehicle_Position HauptbahnhofMuenchen) (type_Vehicle_Position HauptbahnhofUlm) (type_Vehicle_Position Muenchen) (type_Vehicle_Position Ulm) (type_sort_for_Eisenbahnwagen Eisenbahnwagen) (type_sort_for_Essen Essen) (type_sort_for_HauptbahnhofMuenchen HauptbahnhofMuenchen) (type_sort_for_HauptbahnhofUlm HauptbahnhofUlm) (type_sort_for_Lokomotive Lokomotive) (type_sort_for_Muenchen Muenchen) (type_sort_for_Ulm Ulm) (type_sort_for_UlmMuenchenRailRoute UlmMuenchenRailRoute) ) ((__top)) )
null
https://raw.githubusercontent.com/panda-planner-dev/ipc2020-domains/9adb54325d3df35907adc7115fcc65f0ce5953cc/partial-order/UM-Translog/other/SHOP2/p-10.lisp
lisp
(defproblem problem domain ( (In_City HauptbahnhofUlm Ulm) (In_City HauptbahnhofMuenchen Muenchen) (At_Vehicle Eisenbahnwagen HauptbahnhofUlm) (At_Vehicle Lokomotive HauptbahnhofUlm) (Connects UlmMuenchenRailRoute HauptbahnhofUlm HauptbahnhofMuenchen) (Available UlmMuenchenRailRoute) (Available Lokomotive) (PV_Compatible Essen Eisenbahnwagen) (RV_Compatible UlmMuenchenRailRoute Lokomotive) (At_Package Essen HauptbahnhofUlm) (type_City Muenchen) (type_City Ulm) (type_City_Location HauptbahnhofMuenchen) (type_City_Location HauptbahnhofUlm) (type_Equipment_Position Eisenbahnwagen) (type_Equipment_Position HauptbahnhofMuenchen) (type_Equipment_Position HauptbahnhofUlm) (type_Equipment_Position Lokomotive) (type_Equipment_Position Muenchen) (type_Equipment_Position Ulm) (type_Food Essen) (type_Location HauptbahnhofMuenchen) (type_Location HauptbahnhofUlm) (type_Location Muenchen) (type_Location Ulm) (type_Object Eisenbahnwagen) (type_Object Essen) (type_Object Lokomotive) (type_Package Essen) (type_Package_Storage_Position Eisenbahnwagen) (type_Package_Storage_Position HauptbahnhofMuenchen) (type_Package_Storage_Position HauptbahnhofUlm) (type_Package_Storage_Position Lokomotive) (type_Package_Storage_Position Muenchen) (type_Package_Storage_Position Ulm) (type_Perishable Essen) (type_Physical Eisenbahnwagen) (type_Physical Essen) (type_Rail_Route UlmMuenchenRailRoute) (type_Refrigerated Eisenbahnwagen) (type_Refrigerated_Regular_Traincar Eisenbahnwagen) (type_Refrigerated_Vehicle Eisenbahnwagen) (type_Regular Eisenbahnwagen) (type_Regular Essen) (type_Regular_Vehicle Eisenbahnwagen) (type_Route UlmMuenchenRailRoute) (type_Speciality Eisenbahnwagen) (type_TCenter HauptbahnhofMuenchen) (type_TCenter HauptbahnhofUlm) (type_Thing Eisenbahnwagen) (type_Thing Essen) (type_Thing HauptbahnhofMuenchen) (type_Thing HauptbahnhofUlm) (type_Thing Lokomotive) (type_Thing Muenchen) (type_Thing Ulm) (type_Thing UlmMuenchenRailRoute) (type_Train Lokomotive) (type_Train_Station HauptbahnhofMuenchen) (type_Train_Station HauptbahnhofUlm) (type_Traincar Eisenbahnwagen) (type_Vehicle Eisenbahnwagen) (type_Vehicle Lokomotive) (type_Vehicle_Position Eisenbahnwagen) (type_Vehicle_Position HauptbahnhofMuenchen) (type_Vehicle_Position HauptbahnhofUlm) (type_Vehicle_Position Muenchen) (type_Vehicle_Position Ulm) (type_sort_for_Eisenbahnwagen Eisenbahnwagen) (type_sort_for_Essen Essen) (type_sort_for_HauptbahnhofMuenchen HauptbahnhofMuenchen) (type_sort_for_HauptbahnhofUlm HauptbahnhofUlm) (type_sort_for_Lokomotive Lokomotive) (type_sort_for_Muenchen Muenchen) (type_sort_for_Ulm Ulm) (type_sort_for_UlmMuenchenRailRoute UlmMuenchenRailRoute) ) ((__top)) )
9e0ba5cf45efcc1021c12589687380e4fa4289a87bb5178a81f40f9c826a6181
Rober-t/apxr_run
apxr_run_sup.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright ( C ) 2018 ApproximateReality %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%---------------------------------------------------------------------------- @doc ApxrRun top level supervisor . %%% @end %%%---------------------------------------------------------------------------- -module(apxr_run_sup). -behaviour(supervisor). Start / Stop -export([ start_link/0 ]). %% Supervisor callbacks -export([ init/1 ]). %%%============================================================================ %%% Types %%%============================================================================ -type sup_flags() :: #{ intensity => non_neg_integer(), period => pos_integer(), strategy => one_for_all | one_for_one | rest_for_one | simple_one_for_one }. -type child_spec() :: [#{ id := _, start := {atom(), atom(), undefined | [any()]}, modules => dynamic | [atom()], restart => permanent | temporary | transient, shutdown => brutal_kill | infinity | non_neg_integer(), type => supervisor | worker }]. -export_type([ sup_flags/0, child_spec/0 ]). %%%============================================================================ %%% API %%%============================================================================ %%----------------------------------------------------------------------------- %% @doc Starts the supervisor. %% @end %%----------------------------------------------------------------------------- -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %%%============================================================================ %%% Supervisor callbacks %%%============================================================================ %%----------------------------------------------------------------------------- @private @doc Whenever a supervisor is started using supervisor : start_link , %% this function is called by the new process to find out about restart %% strategy, maximum restart frequency and child specifications. %% @end %%----------------------------------------------------------------------------- -spec init([]) -> {ok, {sup_flags(), child_spec()}}. init([]) -> ets:new(cowpat, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), SupFlags = #{ strategy => one_for_all, intensity => 1, period => 5 }, DB = #{ id => db, start => {db, start_link, []}, restart => permanent, shutdown => 5000, type => worker, modules => [db] }, PolisSup = #{ id => polis_sup, start => {polis_sup, start_link, []}, restart => permanent, shutdown => infinity, type => supervisor, modules => [polis_sup] }, PolisMgr = #{ id => polis_mgr, start => {polis_mgr, start_link, []}, restart => permanent, shutdown => 5000, type => worker, modules => [polis_mgr] }, ChildSpecs = [DB, PolisSup, PolisMgr], {ok, {SupFlags, ChildSpecs}}. %%%============================================================================ Internal functions %%%============================================================================
null
https://raw.githubusercontent.com/Rober-t/apxr_run/9c62ab028af7ff3768ffe3f27b8eef1799540f05/src/apxr_run_sup.erl
erlang
---------------------------------------------------------------------------- @end ---------------------------------------------------------------------------- Supervisor callbacks ============================================================================ Types ============================================================================ ============================================================================ API ============================================================================ ----------------------------------------------------------------------------- @doc Starts the supervisor. @end ----------------------------------------------------------------------------- ============================================================================ Supervisor callbacks ============================================================================ ----------------------------------------------------------------------------- this function is called by the new process to find out about restart strategy, maximum restart frequency and child specifications. @end ----------------------------------------------------------------------------- ============================================================================ ============================================================================
Copyright ( C ) 2018 ApproximateReality @doc ApxrRun top level supervisor . -module(apxr_run_sup). -behaviour(supervisor). Start / Stop -export([ start_link/0 ]). -export([ init/1 ]). -type sup_flags() :: #{ intensity => non_neg_integer(), period => pos_integer(), strategy => one_for_all | one_for_one | rest_for_one | simple_one_for_one }. -type child_spec() :: [#{ id := _, start := {atom(), atom(), undefined | [any()]}, modules => dynamic | [atom()], restart => permanent | temporary | transient, shutdown => brutal_kill | infinity | non_neg_integer(), type => supervisor | worker }]. -export_type([ sup_flags/0, child_spec/0 ]). -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). @private @doc Whenever a supervisor is started using supervisor : start_link , -spec init([]) -> {ok, {sup_flags(), child_spec()}}. init([]) -> ets:new(cowpat, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), SupFlags = #{ strategy => one_for_all, intensity => 1, period => 5 }, DB = #{ id => db, start => {db, start_link, []}, restart => permanent, shutdown => 5000, type => worker, modules => [db] }, PolisSup = #{ id => polis_sup, start => {polis_sup, start_link, []}, restart => permanent, shutdown => infinity, type => supervisor, modules => [polis_sup] }, PolisMgr = #{ id => polis_mgr, start => {polis_mgr, start_link, []}, restart => permanent, shutdown => 5000, type => worker, modules => [polis_mgr] }, ChildSpecs = [DB, PolisSup, PolisMgr], {ok, {SupFlags, ChildSpecs}}. Internal functions
788ec49b86c42d5138d822fb73f907bbeae71562e70104db8d777f05fae6d6fa
Haskell-ITA/fuga
Common.hs
module Common where import Data.Flat import Types applyDirection :: Direction -> Position -> Position applyDirection N (x,y) = (x, y + 1) applyDirection S (x,y) = (x, y - 1) applyDirection E (x,y) = (x + 1, y) applyDirection W (x,y) = (x - 1, y) messageOrError :: Either DecodeException c -> c messageOrError = either (\x -> error ("Invalid message: " ++ show x)) id
null
https://raw.githubusercontent.com/Haskell-ITA/fuga/7fffc42b5943f53ec6270b2a38b24e6bf6c580da/lib/Common.hs
haskell
module Common where import Data.Flat import Types applyDirection :: Direction -> Position -> Position applyDirection N (x,y) = (x, y + 1) applyDirection S (x,y) = (x, y - 1) applyDirection E (x,y) = (x + 1, y) applyDirection W (x,y) = (x - 1, y) messageOrError :: Either DecodeException c -> c messageOrError = either (\x -> error ("Invalid message: " ++ show x)) id
a8f3224dda77e044c7300db0f85aebce1056167958140092b36e418b13540c16
rubenbarroso/EOPL
1.scm
(let ((time-stamp "Time-stamp: <2001-05-10 05:30:06 dfried>")) (eopl:printf "1.scm: code for chapter 1 ~a~%" (substring time-stamp 13 29))) (define count-nodes (lambda (s) (if (number? s) 1 (+ (count-nodes (cadr s)) (count-nodes (caddr s)) 1)))) (define list-of-numbers? (lambda (lst) (if (null? lst) #t (and ;\new3 (number? (car lst)) (list-of-numbers? (cdr lst)))))) (define nth-elt (lambda (lst n) (if (null? lst) (eopl:error 'nth-elt "List too short by ~s elements.~%" (+ n 1)) (if (zero? n) (car lst) (nth-elt (cdr lst) (- n 1)))))) (define remove (lambda (s los) (if (null? los) '() (if (eqv? (car los) s) \new1 (cons (car los) (remove s (cdr los))))))) (define subst (lambda (new old slist) (if (null? slist) '() (cons ;\new3 (subst-in-symbol-expression new old (car slist)) (subst new old (cdr slist)))))) (define subst-in-symbol-expression (lambda (new old se) (if (symbol? se) ;\new3 (if (eqv? se old) new se) (subst new old se)))) (define notate-depth (lambda (slist) (notate-depth-in-s-list slist 0))) (define notate-depth-in-s-list (lambda (slist d) '() (cons (notate-depth-in-symbol-expression (car slist) d) (notate-depth-in-s-list (cdr slist) d))))) (define notate-depth-in-symbol-expression (lambda (se d) (if (symbol? se) (list se d) (notate-depth-in-s-list se (+ d 1))))) (define list-sum (lambda (lon) (if (null? lon) 0 (+ (car lon) (list-sum (cdr lon)))))) (define partial-vector-sum (lambda (von n) (if (zero? n) 0 (+ (vector-ref von (- n 1)) (partial-vector-sum von (- n 1)))))) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This one will be in the text. ; ;;; (define vector-sum ; ;;; (lambda (von) ; ;;; (partial-vector-sum von (vector-length von)))) ; ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define vector-sum (lambda (von) (letrec ((partial-sum (lambda (n) (if (zero? n) 0 (+ (vector-ref von (- n 1)) (partial-sum (- n 1))))))) (partial-sum (vector-length von))))) (define occurs-free? (lambda (var exp) (cond ((symbol? exp) (eqv? var exp)) ((eqv? (car exp) 'lambda) (and (not (eqv? (caadr exp) var)) (occurs-free? var (caddr exp)))) (else (or (occurs-free? var (car exp)) (occurs-free? var (cadr exp))))))) (define occurs-bound? (lambda (var exp) (cond ((symbol? exp) #f) ((eqv? (car exp) 'lambda) (or (occurs-bound? var (caddr exp)) (and (eqv? (caadr exp) var) (occurs-free? var (caddr exp))))) (else (or (occurs-bound? var (car exp)) (occurs-bound? var (cadr exp)))))))
null
https://raw.githubusercontent.com/rubenbarroso/EOPL/f9b3c03c2fcbaddf64694ee3243d54be95bfe31d/src/interps/1.scm
scheme
\new3 \new3 \new3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; This one will be in the text. ; (define vector-sum ; (lambda (von) ; (partial-vector-sum von (vector-length von)))) ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(let ((time-stamp "Time-stamp: <2001-05-10 05:30:06 dfried>")) (eopl:printf "1.scm: code for chapter 1 ~a~%" (substring time-stamp 13 29))) (define count-nodes (lambda (s) (if (number? s) 1 (+ (count-nodes (cadr s)) (count-nodes (caddr s)) 1)))) (define list-of-numbers? (lambda (lst) (if (null? lst) #t (number? (car lst)) (list-of-numbers? (cdr lst)))))) (define nth-elt (lambda (lst n) (if (null? lst) (eopl:error 'nth-elt "List too short by ~s elements.~%" (+ n 1)) (if (zero? n) (car lst) (nth-elt (cdr lst) (- n 1)))))) (define remove (lambda (s los) (if (null? los) '() (if (eqv? (car los) s) \new1 (cons (car los) (remove s (cdr los))))))) (define subst (lambda (new old slist) (if (null? slist) '() (subst-in-symbol-expression new old (car slist)) (subst new old (cdr slist)))))) (define subst-in-symbol-expression (lambda (new old se) (if (eqv? se old) new se) (subst new old se)))) (define notate-depth (lambda (slist) (notate-depth-in-s-list slist 0))) (define notate-depth-in-s-list (lambda (slist d) '() (cons (notate-depth-in-symbol-expression (car slist) d) (notate-depth-in-s-list (cdr slist) d))))) (define notate-depth-in-symbol-expression (lambda (se d) (if (symbol? se) (list se d) (notate-depth-in-s-list se (+ d 1))))) (define list-sum (lambda (lon) (if (null? lon) 0 (+ (car lon) (list-sum (cdr lon)))))) (define partial-vector-sum (lambda (von n) (if (zero? n) 0 (+ (vector-ref von (- n 1)) (partial-vector-sum von (- n 1)))))) (define vector-sum (lambda (von) (letrec ((partial-sum (lambda (n) (if (zero? n) 0 (+ (vector-ref von (- n 1)) (partial-sum (- n 1))))))) (partial-sum (vector-length von))))) (define occurs-free? (lambda (var exp) (cond ((symbol? exp) (eqv? var exp)) ((eqv? (car exp) 'lambda) (and (not (eqv? (caadr exp) var)) (occurs-free? var (caddr exp)))) (else (or (occurs-free? var (car exp)) (occurs-free? var (cadr exp))))))) (define occurs-bound? (lambda (var exp) (cond ((symbol? exp) #f) ((eqv? (car exp) 'lambda) (or (occurs-bound? var (caddr exp)) (and (eqv? (caadr exp) var) (occurs-free? var (caddr exp))))) (else (or (occurs-bound? var (car exp)) (occurs-bound? var (cadr exp)))))))
bf49381250e0a49d11838f93cfa31d2fb3cd6b590452ff63eb97154d65dc3290
returntocorp/ocaml-tree-sitter-core
Indent.ml
(* Simple, functional pretty-printer. *) open Printf module Types = struct type node = | Line of string | Block of node list | Inline of node list | Space | Group of node list end open Types type t = node list (* Expand Inline nodes, remove empty blocks. *) let rec simplify l = List.map simplify_node l |> List.flatten and simplify_node = function | Line _ as x -> [x] | Block l -> (match simplify l with | [] -> [] | l -> [Block l] ) | Inline l -> (match simplify l with | [] -> [] | l -> l ) | Space -> [Space] | Group l -> (match simplify l with | [] -> [] | l -> [Group l] ) let really_collapse nodes = let buf = Buffer.create 100 in let rec add nodes = List.iter add_node nodes and add_node = function | Line s -> Buffer.add_string buf s | Block nodes -> add nodes | Inline nodes -> add nodes | Space -> Buffer.add_char buf ' ' | Group nodes -> add nodes in add nodes; Line (Buffer.contents buf) module Size = struct (* Length of a collapsible group. If None, the group is not collapsible. *) type t = int option let max_len = 60 let add a b : t = match a, b with | None, _ | _, None -> None | Some a, Some b -> let len = a + b in if len <= max_len then Some len else None end let collapse nodes = let rec collapse nodes = let l = List.map collapse_node nodes in let size = List.fold_left (fun acc (size, _node) -> Size.add acc size) (Some 0) l in size, List.map snd l and collapse_node = function | Line s as x -> Some (String.length s), x | Block [node] -> let size, node = collapse_node node in size, Block [node] | Block nodes -> let _size, nodes = collapse nodes in None, Block nodes | Inline _ -> assert false (* removed by 'simplify' *) | Space -> Some 1, Space | Group nodes -> let size, nodes = collapse nodes in if size <> None then size, really_collapse nodes else size, Group nodes in snd (collapse nodes) let rec print_node buf indent (x : node) = match x with | Line s -> bprintf buf "%s%s\n" (String.make indent ' ') s | Block nodes -> print buf (indent + 2) nodes | Inline _ -> assert false (* removed by 'simplify' *) | Space -> () | Group nodes -> print buf indent nodes and print buf indent nodes = List.iter (print_node buf indent) nodes let to_string nodes = let buf = Buffer.create 1000 in print buf 0 (simplify nodes |> collapse); Buffer.contents buf let to_channel oc nodes = let data = to_string nodes in output_string oc data; flush oc let to_file output_file nodes = let data = to_string nodes in let oc = open_out_bin output_file in Fun.protect ~finally:(fun () -> close_out_noerr oc) (fun () -> output_string oc data)
null
https://raw.githubusercontent.com/returntocorp/ocaml-tree-sitter-core/3ed014873a0eed91fe7a0e6eb32bed29efa91dfa/src/gen/lib/Indent.ml
ocaml
Simple, functional pretty-printer. Expand Inline nodes, remove empty blocks. Length of a collapsible group. If None, the group is not collapsible. removed by 'simplify' removed by 'simplify'
open Printf module Types = struct type node = | Line of string | Block of node list | Inline of node list | Space | Group of node list end open Types type t = node list let rec simplify l = List.map simplify_node l |> List.flatten and simplify_node = function | Line _ as x -> [x] | Block l -> (match simplify l with | [] -> [] | l -> [Block l] ) | Inline l -> (match simplify l with | [] -> [] | l -> l ) | Space -> [Space] | Group l -> (match simplify l with | [] -> [] | l -> [Group l] ) let really_collapse nodes = let buf = Buffer.create 100 in let rec add nodes = List.iter add_node nodes and add_node = function | Line s -> Buffer.add_string buf s | Block nodes -> add nodes | Inline nodes -> add nodes | Space -> Buffer.add_char buf ' ' | Group nodes -> add nodes in add nodes; Line (Buffer.contents buf) module Size = struct type t = int option let max_len = 60 let add a b : t = match a, b with | None, _ | _, None -> None | Some a, Some b -> let len = a + b in if len <= max_len then Some len else None end let collapse nodes = let rec collapse nodes = let l = List.map collapse_node nodes in let size = List.fold_left (fun acc (size, _node) -> Size.add acc size) (Some 0) l in size, List.map snd l and collapse_node = function | Line s as x -> Some (String.length s), x | Block [node] -> let size, node = collapse_node node in size, Block [node] | Block nodes -> let _size, nodes = collapse nodes in None, Block nodes | Space -> Some 1, Space | Group nodes -> let size, nodes = collapse nodes in if size <> None then size, really_collapse nodes else size, Group nodes in snd (collapse nodes) let rec print_node buf indent (x : node) = match x with | Line s -> bprintf buf "%s%s\n" (String.make indent ' ') s | Block nodes -> print buf (indent + 2) nodes | Space -> () | Group nodes -> print buf indent nodes and print buf indent nodes = List.iter (print_node buf indent) nodes let to_string nodes = let buf = Buffer.create 1000 in print buf 0 (simplify nodes |> collapse); Buffer.contents buf let to_channel oc nodes = let data = to_string nodes in output_string oc data; flush oc let to_file output_file nodes = let data = to_string nodes in let oc = open_out_bin output_file in Fun.protect ~finally:(fun () -> close_out_noerr oc) (fun () -> output_string oc data)
d8452f6887832fd9be8443425090036784c2e7361faf3066efeffd45d351c614
dpiponi/Moodler
TopologicalSort.hs
# LANGUAGE FlexibleContexts # module TopologicalSort(topologicalSort) where import Control.Monad.State import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S import MoodlerSymbols import Synth import Utils import Debug.Trace inputSource :: Out -> Maybe ModuleName inputSource Disconnected = Nothing inputSource (Out src _) = Just src -- Topological sort of synth nodes working backwards from -- output. topologicalSort :: Synth -> Module -> [Module] topologicalSort synth out = trace("!!! " ++ show (M.keys synth)) $ fst $ execState (orderNodes out) ([], S.empty) where orderNodes modl@Module { _getNodeName = name , _inputNodes = inputs} = do (orderedNodes, visited) <- get trace ("Visiting " ++ show name ++ "inps = " ++ show inputs) $ unless (name `S.member` visited) $ do put (modl : orderedNodes, S.insert name visited) forM_ (unique (mapMaybe inputSource (M.elems inputs))) $ \nodeName -> let err = error ("failed to find " ++ _getModuleName nodeName ++ " in a " ++ _getModuleName name) node = fromMaybe err (M.lookup nodeName synth) in orderNodes node
null
https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/src/TopologicalSort.hs
haskell
Topological sort of synth nodes working backwards from output.
# LANGUAGE FlexibleContexts # module TopologicalSort(topologicalSort) where import Control.Monad.State import Data.Maybe import qualified Data.Map as M import qualified Data.Set as S import MoodlerSymbols import Synth import Utils import Debug.Trace inputSource :: Out -> Maybe ModuleName inputSource Disconnected = Nothing inputSource (Out src _) = Just src topologicalSort :: Synth -> Module -> [Module] topologicalSort synth out = trace("!!! " ++ show (M.keys synth)) $ fst $ execState (orderNodes out) ([], S.empty) where orderNodes modl@Module { _getNodeName = name , _inputNodes = inputs} = do (orderedNodes, visited) <- get trace ("Visiting " ++ show name ++ "inps = " ++ show inputs) $ unless (name `S.member` visited) $ do put (modl : orderedNodes, S.insert name visited) forM_ (unique (mapMaybe inputSource (M.elems inputs))) $ \nodeName -> let err = error ("failed to find " ++ _getModuleName nodeName ++ " in a " ++ _getModuleName name) node = fromMaybe err (M.lookup nodeName synth) in orderNodes node
f8afce640296ef79c03f695fb99c881a416fb1334c78fab25ed259461a288509
huangjs/cl
comm.lisp
-*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The data in this file contains enhancments. ;;;;; ;;; ;;;;; Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ; ;;; All rights reserved ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) * * ( c ) Copyright 1982 Massachusetts Institute of Technology * * (macsyma-module comm) (declare-top (special $exptsubst $linechar $nolabels $inflag $piece $dispflag $gradefs $props $dependencies derivflag derivlist $linenum $partswitch linelable nn* dn* islinp $powerdisp atvars atp $errexp $derivsubst $dotdistrib $opsubst $subnumsimp $transrun in-p substp $sqrtdispflag $pfeformat dummy-variable-operators)) ;; op and opr properties (defvar *opr-table* (make-hash-table :test #'equal)) (defmfun getopr0 (x) (or (and (symbolp x) (get x 'opr)) (and (stringp x) (gethash x *opr-table*)))) (defmfun getopr (x) (or (getopr0 x) x)) (defmfun putopr (x y) (or (and (symbolp x) (setf (get x 'opr) y)) (and (stringp x) (setf (gethash x *opr-table*) y)))) (defmfun remopr (x) (or (and (symbolp x) (remprop x 'opr)) (and (stringp x) (remhash x *opr-table*)))) (mapc #'(lambda (x) (putprop (car x) (cadr x) 'op) (putopr (cadr x) (car x))) '((mplus "+") (mminus "-") (mtimes "*") (mexpt "**") (mexpt "^") (mnctimes ".") (rat "/") (mquotient "/") (mncexpt "^^") (mequal "=") (mgreaterp ">") (mlessp "<") (mleqp "<=") (mgeqp ">=") (mnotequal "#") (mand "and") (mor "or") (mnot "not") (msetq ":") (mdefine ":=") (mdefmacro "::=") (mquote "'") (mlist "[") (mset "::") (mfactorial "!") (marrow "-->") (mprogn "(") (mcond "if"))) (mapc #'(lambda (x) (putprop (car x) (cadr x) 'op)) '((mqapply $subvar) (bigfloat $bfloat))) (setq $exptsubst nil $partswitch nil $inflag nil $gradefs '((mlist simp)) $dependencies '((mlist simp)) atvars '($@1 $@2 $@3 $@4) atp nil islinp nil lnorecurse nil $derivsubst nil timesp nil $opsubst t in-p nil substp nil) (defmvar $vect_cross nil "If TRUE allows DIFF(X~Y,T) to work where ~ is defined in VECT where VECT_CROSS is set to TRUE . " ) (defmfun $substitute (old new &optional (expr nil three-arg?)) (cond (three-arg? (maxima-substitute old new expr)) (t (let ((l old) (z new)) (cond ((and ($listp l) ($listp (cadr l)) (null (cddr l))) ($substitute (cadr l) z)) ((notloreq l) (improper-arg-err l '$substitute)) ((eq (caar l) 'mequal) (maxima-substitute (caddr l) (cadr l) z)) (t (do ((l (cdr l) (cdr l))) ((null l) z) (setq z ($substitute (car l) z))))))))) (declare-top (special x y oprx opry negxpty timesp)) (defmfun maxima-substitute (x y z) ; The args to SUBSTITUTE are assumed to be simplified. (declare (special x y )) (let ((in-p t) (substp t)) (if (and (mnump y) (= (signum1 y) 1)) (let ($sqrtdispflag ($pfeformat t)) (setq z (nformat-all z)))) (simplifya (if (atom y) (cond ((equal y -1) (setq y '((mminus) 1)) (subst2 (nformat-all z))) (t (cond ((and (not (symbolp x)) (functionp x)) (let ((tem (gensym))) (setf (get tem 'operators) 'application-operator) (setf (symbol-function tem) x) (setq x tem)))) (let ((oprx (getopr x)) (opry (getopr y))) (declare (special oprx opry )) (subst1 z)))) (let ((negxpty (if (and (eq (caar y) 'mexpt) (= (signum1 (caddr y)) 1)) (mul2 -1 (caddr y)))) (timesp (if (eq (caar y) 'mtimes) (setq y (nformat y))))) (declare (special negxpty timesp)) (subst2 z))) nil))) Remainder of page is update from F302 --gsb ;;Used in COMM2 (AT), limit, and below. (defvar dummy-variable-operators '(%product %sum %laplace %integrate %limit %at)) (defun subst1 (z) ; Y is an atom (cond ((atom z) (if (equal y z) x z)) ((specrepp z) (subst1 (specdisrep z))) ((eq (caar z) 'bigfloat) z) ((and (eq (caar z) 'rat) (or (equal y (cadr z)) (equal y (caddr z)))) (div (subst1 (cadr z)) (subst1 (caddr z)))) ((at-substp z) (subst-except-second-arg x y z)) ((and (eq y t) (eq (caar z) 'mcond)) (list (cons (caar z) nil) (subst1 (cadr z)) (subst1 (caddr z)) (cadddr z) (subst1 (car (cddddr z))))) (t (let ((margs (mapcar #'subst1 (cdr z)))) (if (and $opsubst (or (eq opry (caar z)) (and (eq (caar z) 'rat) (eq opry 'mquotient)))) (if (or (numberp x) (member x '(t nil $%e $%pi $%i) :test #'eq) (and (not (atom x)) (not (or (eq (car x) 'lambda) (eq (caar x) 'lambda))))) (if (or (and (member 'array (cdar z) :test #'eq) (or (and (mnump x) $subnumsimp) (and (not (mnump x)) (not (atom x))))) ($subvarp x)) (let ((substp 'mqapply)) (subst0 (list* '(mqapply) x margs) z)) (merror (intl:gettext "subst: cannot substitute ~M for operator ~M in expression ~M") x y z)) (subst0 (cons (cons oprx nil) margs) z)) (subst0 (cons (cons (caar z) nil) margs) z)))))) (defun subst2 (z) (let (newexpt) (cond ((atom z) z) ((specrepp z) (subst2 (specdisrep z))) ((and atp (member (caar z) '(%derivative %laplace) :test #'eq)) z) ((at-substp z) z) ((alike1 y z) x) ((and timesp (eq (caar z) 'mtimes) (alike1 y (setq z (nformat z)))) x) ((and (eq (caar y) 'mexpt) (eq (caar z) 'mexpt) (alike1 (cadr y) (cadr z)) (setq newexpt (cond ((alike1 negxpty (caddr z)) -1) ($exptsubst (expthack (caddr y) (caddr z)))))) (list '(mexpt) x newexpt)) ((and $derivsubst (eq (caar y) '%derivative) (eq (caar z) '%derivative) (alike1 (cadr y) (cadr z))) (let ((tail (subst-diff-match (cddr y) (cdr z)))) (cond ((null tail) z) (t (cons (cons (caar z) nil) (cons x (cdr tail))))))) (t (recur-apply #'subst2 z))))) replace y with x in z , but leave z 's second arg unchanged . This is for cases like at(integrate(x , x , a , b ) , [ x=3 ] ) where second arg of integrate binds a new variable x , and we do not wish to subst 3 for x inside integrand . (defun subst-except-second-arg (x y z) (append (list (car z) if ( third z ) is new var that shadows y leave ( second z ) unchanged otherwise replace y with x in ( second z ) (third z)) ; never change integration var (mapcar (lambda (z) (subst1 z)) ; do subst in limits of integral (cdddr z)))) (declare-top (unspecial x y oprx opry negxpty timesp)) (defmfun subst0 (new old) (cond ((atom new) new) ((alike (cdr new) (cdr old)) (cond ((eq (caar new) (caar old)) old) (t (simplifya (cons (cons (caar new) (member 'array (cdar old) :test #'eq)) (cdr old)) nil)))) ((member 'array (cdar old) :test #'eq) (simplifya (cons (cons (caar new) '(array)) (cdr new)) nil)) (t (simplifya new nil)))) (defun expthack (y z) (prog (nn* dn* yn yd zn zd qd) (cond ((and (mnump y) (mnump z)) (return (if (numberp (setq y (div* z y))) y))) ((atom z) (if (not (mnump y)) (return nil))) ((or (ratnump z) (eq (caar z) 'mplus)) (return nil))) ( CSIMP ) sets NN * and DN * (setq yn nn* yd dn*) (numden z) (setq zn nn* zd dn*) (setq qd (cond ((and (equal zd 1) (equal yd 1)) 1) ((prog2 (numden (div* zd yd)) (and (equal dn* 1) (equal nn* 1))) 1) ((equal nn* 1) (div* 1 dn*)) ((equal dn* 1) nn*) (t (return nil)))) (numden (div* zn yn)) (if (equal dn* 1) (return (div* nn* qd))))) (defun subst-diff-match (l1 l2) (do ((l l1 (cddr l)) (l2 (copy-list l2)) (failed nil nil)) ((null l) l2) (do ((l2 l2 (cddr l2))) ((null (cdr l2)) (setq failed t)) (if (alike1 (car l) (cadr l2)) (if (and (fixnump (cadr l)) (fixnump (caddr l2))) (cond ((< (cadr l) (caddr l2)) (return (rplacd (cdr l2) (cons (- (caddr l2) (cadr l)) (cdddr l2))))) ((= (cadr l) (caddr l2)) (return (rplacd l2 (cdddr l2)))) (t (return (setq failed t)))) (return (setq failed t))))) (if failed (return nil)))) ;;This probably should be a subst or macro. (defun at-substp (z) (and atp (or (member (caar z) '(%derivative %del) :test #'eq) (member (caar z) dummy-variable-operators :test #'eq)))) (defmfun recur-apply (fun e) (cond ((eq (caar e) 'bigfloat) e) ((specrepp e) (funcall fun (specdisrep e))) (t (let ((newargs (mapcar fun (cdr e)))) (if (alike newargs (cdr e)) e (simplifya (cons (cons (caar e) (member 'array (cdar e) :test #'eq)) newargs) nil)))))) (defmfun $depends (&rest args) (when (oddp (length args)) (merror (intl:gettext "depends: number of arguments must be even."))) (do ((args args (cddr args)) (l)) ((null args) (i-$dependencies (nreverse l))) (if ($listp (first args)) (mapc #'(lambda (e) (push (depends1 e (second args)) l)) (cdr (first args))) (push (depends1 (first args) (second args)) l)))) (defun depends1 (x y) (nonsymchk x '$depends) (cons (cons x nil) (if ($listp y) (cdr y) (cons y nil)))) (defmspec $dependencies (form) (i-$dependencies (cdr form))) (defmfun i-$dependencies (l) (dolist (z l) (cond ((atom z) (merror (intl:gettext "depends: argument must be a non-atomic expression; found ~M") z)) ((or (eq (caar z) 'mqapply) (member 'array (cdar z) :test #'eq)) (merror (intl:gettext "depends: argument cannot be a subscripted expression; found ~M") z)) (t (let ((y (mget (caar z) 'depends))) (mputprop (caar z) (setq y (union* (reverse (cdr z)) y)) 'depends) (unless (cdr $dependencies) (setq $dependencies (copy-list '((mlist simp))))) (add2lnc (cons (cons (caar z) nil) y) $dependencies))))) (cons '(mlist simp) l)) (defmspec $gradef (l) (setq l (cdr l)) (let ((z (car l)) (n 0)) (cond ((atom z) (if (not (= (length l) 3)) (merror (intl:gettext "gradef: expected exactly three arguments."))) (mputprop z (cons (cons (cadr l) (meval (caddr l))) (mget z '$atomgrad)) '$atomgrad) (i-$dependencies (cons (list (ncons z) (cadr l)) nil)) (add2lnc z $props) z) ((or (mopp1 (caar z)) (member 'array (cdar z) :test #'eq)) (merror (intl:gettext "gradef: argument cannot be a built-in operator or subscripted expression; found ~M") z)) ((prog2 (setq n (- (length z) (length l))) (minusp n)) (wna-err '$gradef)) (t (do ((zl (cdr z) (cdr zl))) ((null zl)) (if (not (symbolp (car zl))) (merror (intl:gettext "gradef: argument must be a symbol; found ~M") (car zl)))) (setq l (nconc (mapcar #'(lambda (x) (remsimp (meval x))) (cdr l)) (mapcar #'(lambda (x) (list '(%derivative) z x 1)) (nthcdr (- (length z) n) z)))) (putprop (caar z) (sublis (mapcar #'cons (cdr z) (mapcar #'stripdollar (cdr z))) (cons (cdr z) l)) 'grad) (or (cdr $gradefs) (setq $gradefs (copy-list '((mlist simp))))) (add2lnc (cons (cons (caar z) nil) (cdr z)) $gradefs) z)))) (defmfun $diff (&rest args) (declare (dynamic-extent args)) (let (derivlist) (deriv args))) (defmfun $del (e) (stotaldiff e)) (defun deriv (e) (prog (exp z count) (cond ((null e) (wna-err '$diff)) ((null (cdr e)) (return (stotaldiff (car e)))) ((null (cddr e)) (nconc e '(1)))) (setq exp (car e) z (setq e (copy-list e))) loop (if (or (null derivlist) (member (cadr z) derivlist :test #'equal)) (go doit)) DERIVLIST is set by $ EV (setq z (cdr z)) loop2(cond ((cdr z) (go loop)) ((null (cdr e)) (return exp)) (t (go noun))) doit (cond ((nonvarcheck (cadr z) '$diff)) ((null (cddr z)) (wna-err '$diff)) ((not (eq (ml-typep (caddr z)) 'fixnum)) (go noun)) ((minusp (setq count (caddr z))) (merror (intl:gettext "diff: order of derivative must be a nonnegative integer; found ~M") count))) loop1(cond ((zerop count) (rplacd z (cdddr z)) (go loop2)) ((equal (setq exp (sdiff exp (cadr z))) 0) (return 0))) (setq count (1- count)) (go loop1) noun (return (diff%deriv (cons exp (cdr e)))))) (defun chainrule (e x) (let (w) (cond (islinp (if (and (not (atom e)) (eq (caar e) '%derivative) (not (freel (cdr e) x))) (diff%deriv (list e x 1)) 0)) ((atomgrad e x)) ((not (setq w (mget (cond ((atom e) e) ((member 'array (cdar e) :test #'eq) (caar e)) ((atom (cadr e)) (cadr e)) (t (caaadr e))) 'depends))) 0) (t (let (derivflag) (addn (mapcar #'(lambda (u) (let ((y (sdiff u x))) (if (equal y 0) 0 (list '(mtimes) (or (atomgrad e u) (list '(%derivative) e u 1)) y)))) w) nil)))))) (defun atomgrad (e x) (let (y) (and (atom e) (setq y (mget e '$atomgrad)) (assolike x y)))) (defun depends (e x) (cond ((alike1 e x) t) ((mnump e) nil) ((atom e) (mget e 'depends)) (t (or (depends (caar e) x) (dependsl (cdr e) x))))) (defun dependsl (l x) (dolist (u l) (if (depends u x) (return t)))) The args to SDIFF are assumed to be simplified . ;; Remove a special representation from the variable of differentiation (setq x (specrepcheck x)) (cond ((alike1 e x) 1) ((mnump e) 0) ((or (atom e) (member 'array (cdar e) :test #'eq)) (chainrule e x)) ((eq (caar e) 'mrat) (ratdx e x)) ((eq (caar e) 'mpois) ($poisdiff e x)) ; Poisson series ((eq (caar e) 'mplus) (addn (sdiffmap (cdr e) x) t)) ((mbagp e) (cons (car e) (sdiffmap (cdr e) x))) ((member (caar e) '(%sum %product) :test #'eq) (diffsumprod e x)) ((eq (caar e) '%at) (diff-%at e x)) ((not (depends e x)) 0) ((eq (caar e) 'mtimes) (addn (sdifftimes (cdr e) x) t)) ((eq (caar e) 'mexpt) (diffexpt e x)) ((eq (caar e) 'mnctimes) (let (($dotdistrib t)) (add2 (ncmuln (cons (sdiff (cadr e) x) (cddr e)) t) (ncmul2 (cadr e) (sdiff (cons '(mnctimes) (cddr e)) x))))) ((and $vect_cross (eq (caar e) '|$~|)) (add2* `((|$~|) ,(cadr e) ,(sdiff (caddr e) x)) `((|$~|) ,(sdiff (cadr e) x) ,(caddr e)))) ((eq (caar e) 'mncexpt) (diffncexpt e x)) ((member (caar e) '(%log %plog) :test #'eq) (sdiffgrad (cond ((and (not (atom (cadr e))) (eq (caaadr e) 'mabs)) (cons (car e) (cdadr e))) (t e)) x)) ((eq (caar e) '%derivative) (cond ((or (atom (cadr e)) (member 'array (cdaadr e) :test #'eq)) (chainrule e x)) ((freel (cddr e) x) (diff%deriv (cons (sdiff (cadr e) x) (cddr e)))) (t (diff%deriv (list e x 1))))) ((member (caar e) '(%binomial $beta) :test #'eq) (let ((efact ($makefact e))) (mul2 (factor (sdiff efact x)) (div e efact)))) ((eq (caar e) '%integrate) (diffint e x)) ((eq (caar e) '%laplace) (difflaplace e x)) ((eq (caar e) '%at) (diff-%at e x)) ; This rule is not correct. We cut it out. ( ( member ( caar e ) ' ( % realpart % imagpart ) : test # ' eq ) ( list ( cons ( caar e ) nil ) ( sdiff ( cadr e ) x ) ) ) ((and (eq (caar e) 'mqapply) (eq (caaadr e) '$%f)) ;; Handle %f, hypergeometric function ;; The derivative of % f[p , q]([a1, ... ,ap],[b1, ... ,bq],z ) is ;; ;; a1*a2*...*ap/(b1*b2*...*bq) * % f[p , q]([a1 + 1,a2 + 1, ... ,ap+1],[b1 + 1,b2 + 1, ... ,bq+1],z ) (let* ((arg1 (cdr (third e))) (arg2 (cdr (fourth e))) (v (fifth e))) (mul (sdiff v x) (div (mull arg1) (mull arg2)) `((mqapply) (($%f array) ,(length arg1) ,(length arg2)) ((mlist) ,@(incr1 arg1)) ((mlist) ,@(incr1 arg2)) ,v)))) (t (sdiffgrad e x)))) (defun sdiffgrad (e x) (let ((fun (caar e)) grad args result) (cond ((and (eq fun 'mqapply) (oldget (caaadr e) 'grad)) Change the array function f[n](x ) to f(n , x ) , call sdiffgrad again . (setq result (sdiffgrad (cons (cons (caaadr e) nil) (append (cdadr e) (cddr e))) x)) ;; If noun form for f(n,x), adjust the noun form for f[n](x) (if (isinop result '%derivative) (if (not (depends e x)) 0 (diff%deriv (list e x 1))) result)) ;; extension for pdiff. ((and (get '$pderivop 'operators) (sdiffgrad-pdiff e x))) two line extension for hypergeometric . ((and (equal fun '$hypergeometric) (get '$hypergeometric 'operators)) (diff-hypergeometric (second e) (third e) (fourth e) x)) ((or (eq fun 'mqapply) (null (setq grad (oldget fun 'grad)))) (if (not (depends e x)) 0 (diff%deriv (list e x 1)))) ((not (= (length (cdr e)) (length (car grad)))) (merror (intl:gettext "~:M: expected exactly ~M arguments.") fun (length (car grad)))) (t (setq args (sdiffmap (cdr e) x)) (setq result (addn (mapcar #'mul2 (cdr (substitutel (cdr e) (car grad) (do ((l1 (cdr grad) (cdr l1)) (args args (cdr args)) (l2)) ((null l1) (cons '(mlist) (nreverse l2))) (setq l2 (cons (cond ((equal (car args) 0) 0) ((functionp (car l1)) ;; Evaluate a lambda expression ;; given as a derivative. (apply (car l1) (cdr e))) (t (car l1))) l2))))) args) t)) (if (or (null result) (not (freeof nil result))) ;; A derivative has returned NIL. Return a noun form. (if (not (depends e x)) 0 (diff%deriv (list e x 1))) result))))) (defun sdiffmap (e x) (mapcar #'(lambda (term) (sdiff term x)) e)) (defun sdifftimes (l x) (prog (term left out) loop (setq term (car l) l (cdr l)) (setq out (cons (muln (cons (sdiff term x) (append left l)) t) out)) (if (null l) (return out)) (setq left (cons term left)) (go loop))) (defun diffexpt (e x) (if (mnump (caddr e)) (mul3 (caddr e) (power (cadr e) (addk (caddr e) -1)) (sdiff (cadr e) x)) (mul2 e (add2 (mul3 (power (cadr e) -1) (caddr e) (sdiff (cadr e) x)) (mul2 (simplifya (list '(%log) (cadr e)) t) (sdiff (caddr e) x)))))) (defun diff%deriv (e) (let (derivflag) (simplifya (cons '(%derivative) e) t))) ;; grad properties (let ((header '(x))) (mapc #'(lambda (z) (putprop (car z) (cons header (cdr z)) 'grad)) All these GRAD templates have been simplified and then the SIMP flags ;; (which are unnecessary) have been removed to save core space. '((%log ((mexpt) x -1)) (%plog ((mexpt) x -1)) (%gamma ((mtimes) ((mqapply) (($psi array) 0) x) ((%gamma) x))) (mfactorial ((mtimes) ((mqapply) (($psi array) 0) ((mplus) 1 x)) ((mfactorial) x))) (%sin ((%cos) x)) (%cos ((mtimes) -1 ((%sin) x))) (%tan ((mexpt) ((%sec) x) 2)) (%cot ((mtimes) -1 ((mexpt) ((%csc) x) 2))) (%sec ((mtimes) ((%sec) x) ((%tan) x))) (%csc ((mtimes) -1 ((%cot) x) ((%csc) x))) (%asin ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x 2))) ((rat) -1 2))) (%acos ((mtimes) -1 ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x 2))) ((rat) -1 2)))) (%atan ((mexpt) ((mplus) 1 ((mexpt) x 2)) -1)) (%acot ((mtimes) -1 ((mexpt) ((mplus) 1 ((mexpt) x 2)) -1))) (%acsc ((mtimes) -1 ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x -2))) ((rat) -1 2)) ((mexpt) x -2))) (%asec ((mtimes) ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x -2))) ((rat) -1 2)) ((mexpt) x -2))) (%sinh ((%cosh) x)) (%cosh ((%sinh) x)) (%tanh ((mexpt) ((%sech) x) 2)) (%coth ((mtimes) -1 ((mexpt) ((%csch) x) 2))) (%sech ((mtimes) -1 ((%sech) x) ((%tanh) x))) (%csch ((mtimes) -1 ((%coth) x) ((%csch) x))) (%asinh ((mexpt) ((mplus) 1 ((mexpt) x 2)) ((rat) -1 2))) (%acosh ((mexpt) ((mplus) -1 ((mexpt) x 2)) ((rat) -1 2))) (%atanh ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x 2))) -1)) (%acoth ((mtimes) -1 ((mexpt) ((mplus) -1 ((mexpt) x 2)) -1))) (%asech ((mtimes) -1 ((mexpt) ((mplus) -1 ((mexpt) x -2)) ((rat) -1 2)) ((mexpt) x -2))) (%acsch ((mtimes) -1 ((mexpt) ((mplus) 1 ((mexpt) x -2)) ((rat) -1 2)) ((mexpt) x -2))) (mabs ((mtimes) x ((mexpt) ((mabs) x) -1))) (%erf ((mtimes) 2 ((mexpt) $%pi ((rat) -1 2)) ((mexpt) $%e ((mtimes) -1 ((mexpt) x 2))))) ))) (defprop $atan2 ((x y) ((mtimes) y ((mexpt) ((mplus) ((mexpt) x 2) ((mexpt) y 2)) -1)) ((mtimes) -1 x ((mexpt) ((mplus) ((mexpt) x 2) ((mexpt) y 2)) -1))) grad) (defprop $li ((n x) Do not put a noun form on the property list , but NIL . ; SDIFFGRAD generates the noun form. ; ((%derivative) ((mqapply) (($li array) n) x) n 1) nil ((mtimes) ((mqapply) (($li array) ((mplus) -1 n)) x) ((mexpt) x -1))) grad) (defprop $psi ((n x) Do not put a noun form on the property list , but NIL . ; SDIFFGRAD generates the noun form. nil ((mqapply) (($psi array) ((mplus) 1 n)) x)) grad) (defmfun atvarschk (argl) (do ((largl (length argl) (1- largl)) (latvrs (length atvars)) (l)) ((not (< latvrs largl)) (nconc atvars l)) (setq l (cons (implode (cons '$ (cons '@ (mexploden largl)))) l)))) (defmfun notloreq (x) (or (atom x) (not (member (caar x) '(mlist mequal) :test #'eq)) (and (eq (caar x) 'mlist) (dolist (u (cdr x)) (if (not (mequalp u)) (return t)))))) (defmfun substitutel (l1 l2 e) "l1 is a list of expressions. l2 is a list of variables. For each element in list l2, substitute corresponding element of l1 into e" (do ((l1 l1 (cdr l1)) (l2 l2 (cdr l2))) ((null l1) e) (setq e (maxima-substitute (car l1) (car l2) e)))) (defmfun union* (a b) (do ((a a (cdr a)) (x b)) ((null a) x) (if (not (memalike (car a) b)) (setq x (cons (car a) x))))) (defmfun intersect* (a b) (do ((a a (cdr a)) (x)) ((null a) x) (if (memalike (car a) b) (setq x (cons (car a) x))))) (defmfun nthelem (n e) (car (nthcdr (1- n) e))) (defmfun delsimp (e) (delete 'simp (copy-list e) :count 1 :test #'eq)) (defmfun remsimp (e) (if (atom e) e (cons (delsimp (car e)) (mapcar #'remsimp (cdr e))))) (defmfun $trunc (e) (cond ((atom e) e) ((eq (caar e) 'mplus) (cons (append (car e) '(trunc)) (cdr e))) ((mbagp e) (cons (car e) (mapcar #'$trunc (cdr e)))) ((specrepp e) ($trunc (specdisrep e))) (t e))) (defmfun nonvarcheck (e fn) (if (or (mnump e) (maxima-integerp e) (and (not (atom e)) (not (eq (caar e) 'mqapply)) (mopp1 (caar e)))) (merror (intl:gettext "~:M: second argument must be a variable; found ~M") fn e))) (defmspec $ldisplay (form) (disp1 (cdr form) t t)) (defmfun $ldisp (&rest args) (declare (dynamic-extent args)) (disp1 args t nil)) (defmspec $display (form) (disp1 (cdr form) nil t)) (defmfun $disp (&rest args) (declare (dynamic-extent args)) (disp1 args nil nil)) (defun disp1 (ll lablist eqnsp) (if lablist (setq lablist (cons '(mlist simp) nil))) (do ((ll ll (cdr ll)) (l) (ans) ($dispflag t) (tim 0)) ((null ll) (or lablist '$done)) (setq l (car ll) ans (if eqnsp (meval l) l)) (if (and eqnsp (not (mequalp ans))) (setq ans (list '(mequal simp) (disp2 l) ans))) (if lablist (nconc lablist (cons (elabel ans) nil))) (setq tim (get-internal-run-time)) (displa (list '(mlable) (if lablist linelable) ans)) (mterpri) (timeorg tim))) (defun disp2 (e) (cond ((atom e) e) ((eq (caar e) 'mqapply) (cons '(mqapply) (cons (cons (caadr e) (mapcar #'meval (cdadr e))) (mapcar #'meval (cddr e))))) ((eq (caar e) 'msetq) (disp2 (cadr e))) ((eq (caar e) 'mset) (disp2 (meval (cadr e)))) ((eq (caar e) 'mlist) (cons (car e) (mapcar #'disp2 (cdr e)))) ((mspecfunp (caar e)) e) (t (cons (car e) (mapcar #'meval (cdr e)))))) Construct a new intermediate result label , ; and bind it to the expression e. ; The global flag $NOLABELS is ignored; the label is always bound. ; Otherwise (if ELABEL were to observe $NOLABELS) it would be ; impossible to programmatically refer to intermediate result expression. (defmfun elabel (e) (if (not (checklabel $linechar)) (setq $linenum (1+ $linenum))) (let (($nolabels nil)) ; <-- This is pretty ugly. MAKELABEL should take another argument. (makelabel $linechar)) (setf (symbol-value linelable) e) linelable) (defmfun $dispterms (e) (cond ((or (atom e) (eq (caar e) 'bigfloat)) (displa e)) ((specrepp e) ($dispterms (specdisrep e))) (t (let (($dispflag t)) (mterpri) (displa (getop (mop e))) (do ((e (if (and (eq (caar e) 'mplus) (not $powerdisp)) (reverse (cdr e)) (margs e)) (cdr e))) ((null e)) (mterpri) (displa (car e)) (mterpri))) (mterpri))) '$done) (defmfun $dispform (e &optional (flag nil flag?)) (when (and flag? (not (eq flag '$all))) (merror (intl:gettext "dispform: second argument, if present, must be 'all'; found ~M") flag)) (if (or (atom e) (atom (setq e (if flag? (nformat-all e) (nformat e)))) (member 'simp (cdar e) :test #'eq)) e (cons (cons (caar e) (cons 'simp (cdar e))) (if (and (eq (caar e) 'mplus) (not $powerdisp)) (reverse (cdr e)) (cdr e))))) These functions implement the functions $ op and . (defmfun $op (expr) ($part expr 0)) (defmfun $operatorp (expr oplist) (if ($listp oplist) ($member ($op expr) oplist) (equal ($op expr) oplist))) (defmfun $part (&rest args) (declare (dynamic-extent args)) (mpart args nil nil $inflag '$part)) (defmfun $inpart (&rest args) (declare (dynamic-extent args)) (mpart args nil nil t '$inpart)) (defmspec $substpart (l) (let ((substp t)) (mpart (cdr l) t nil $inflag '$substpart))) (defmspec $substinpart (l) (let ((substp t)) (mpart (cdr l) t nil t '$substinpart))) (defmfun part1 (arglist substflag dispflag inflag) ; called only by TRANSLATE (let ((substp t)) (mpart arglist substflag dispflag inflag '$substpart))) (defmfun mpart (arglist substflag dispflag inflag fn) (prog (substitem arg arg1 exp exp1 exp* sevlist count prevcount n specp lastelem lastcount) (setq specp (or substflag dispflag)) (if substflag (setq substitem (car arglist) arglist (cdr arglist))) (if (null arglist) (wna-err '$part)) (setq exp (if substflag (meval (car arglist)) (car arglist))) (when (null (setq arglist (cdr arglist))) (setq $piece exp) (return (cond (substflag (meval substitem)) (dispflag (box exp dispflag)) (t exp)))) (cond ((not inflag) (cond ((or (and ($listp exp) (null (cdr arglist))) (and ($matrixp exp) (or (null (cdr arglist)) (null (cddr arglist))))) (setq inflag t)) ((not specp) (setq exp (nformat exp))) (t (setq exp (nformat-all exp))))) ((specrepp exp) (setq exp (specdisrep exp)))) (when (and (atom exp) (null $partswitch)) (merror (intl:gettext "~:M: argument must be a non-atomic expression; found ~:M") fn exp)) (when (and inflag specp) (setq exp (copy-tree exp))) (setq exp* exp) start (cond ((or (atom exp) (eq (caar exp) 'bigfloat)) (go err)) ((equal (setq arg (if substflag (meval (car arglist)) (car arglist))) 0) (setq arglist (cdr arglist)) (cond ((mnump substitem) (merror (intl:gettext "~:M: argument cannot be a number; found ~M") fn substitem)) ((and specp arglist) (if (eq (caar exp) 'mqapply) (prog2 (setq exp (cadr exp)) (go start)) NOT CLEAR WHAT IS INVALID HERE . OH WELL . (merror (intl:gettext "~:M: invalid operator.") fn))) (t (setq $piece (getop (mop exp))) (return (cond (substflag (setq substitem (getopr (meval substitem))) (cond ((mnump substitem) (merror (intl:gettext "~:M: argument cannot be a number; found ~M") fn substitem)) ((not (atom substitem)) (if (not (eq (caar exp) 'mqapply)) (rplaca (rplacd exp (cons (car exp) (cdr exp))) '(mqapply))) (rplaca (cdr exp) substitem) (return (resimplify exp*))) ((eq (caar exp) 'mqapply) (rplacd exp (cddr exp)))) (rplaca exp (cons substitem (if (and (member 'array (cdar exp) :test #'eq) (not (mopp substitem))) '(array)))) (resimplify exp*)) (dispflag (rplacd exp (cdr (box (copy-tree exp) dispflag))) (rplaca exp (if (eq dispflag t) '(mbox) '(mlabox))) (resimplify exp*)) (t (when arglist (setq exp $piece) (go a)) $piece)))))) ((not (atom arg)) (go several)) ((not (fixnump arg)) (merror (intl:gettext "~:M: argument must be an integer; found ~M") fn arg)) ((< arg 0) (go bad))) (if (eq (caar exp) 'mqapply) (setq exp (cdr exp))) loop (cond ((not (zerop arg)) (setq arg (1- arg) exp (cdr exp)) (if (null exp) (go err)) (go loop)) ((null (setq arglist (cdr arglist))) (return (cond (substflag (setq $piece (resimplify (car exp))) (rplaca exp (meval substitem)) (resimplify exp*)) (dispflag (setq $piece (resimplify (car exp))) (rplaca exp (box (car exp) dispflag)) (resimplify exp*)) (inflag (setq $piece (car exp))) (t (setq $piece (simplify (car exp)))))))) (setq exp (car exp)) a (cond ((and (not inflag) (not specp)) (setq exp (nformat exp))) ((specrepp exp) (setq exp (specdisrep exp)))) (go start) err (cond ((eq $partswitch 'mapply) (merror (intl:gettext "part: invalid index of list or matrix."))) ($partswitch (return (setq $piece '$end))) (t (merror (intl:gettext "~:M: fell off the end.") fn))) bad (improper-arg-err arg fn) several (if (or (not (member (caar arg) '(mlist $allbut) :test #'eq)) (cdr arglist)) (go bad)) (setq exp1 (cons (caar exp) (if (member 'array (cdar exp) :test #'eq) '(array)))) (if (eq (caar exp) 'mqapply) (setq sevlist (list (cadr exp) exp1) exp (cddr exp)) (setq sevlist (ncons exp1) exp (cdr exp))) (setq arg1 (cdr arg) prevcount 0 exp1 exp) (dolist (arg* arg1) (if (not (fixnump arg*)) (merror (intl:gettext "~:M: argument must be an integer; found ~M") fn arg*))) (when (and specp (eq (caar arg) 'mlist)) (if substflag (setq lastelem (car (last arg1)))) (setq arg1 (sort (copy-list arg1) #'<))) (when (eq (caar arg) '$allbut) (setq n (length exp)) (dolist (i arg1) (if (or (< i 1) (> i n)) (merror (intl:gettext "~:M: index must be in range 1 to ~M, inclusive; found ~M") fn n i))) (do ((i n (1- i)) (arg2)) ((= i 0) (setq arg1 arg2)) (if (not (member i arg1 :test #'equal)) (setq arg2 (cons i arg2)))) (if substflag (setq lastelem (car (last arg1))))) (if (null arg1) (if specp (go bad) (go end))) (if substflag (setq lastcount lastelem)) sevloop (if specp (setq count (- (car arg1) prevcount) prevcount (car arg1)) (setq count (car arg1))) (if (< count 1) (go bad)) (if (and substflag (< (car arg1) lastelem)) (setq lastcount (1- lastcount))) count(cond ((null exp) (go err)) ((not (= count 1)) (setq count (1- count) exp (cdr exp)) (go count))) (setq sevlist (cons (car exp) sevlist)) (setq arg1 (cdr arg1)) end (cond ((null arg1) (setq sevlist (nreverse sevlist)) (setq $piece (if (or inflag (not specp)) (simplify sevlist) (resimplify sevlist))) (return (cond (substflag (rplaca (nthcdr (1- lastcount) exp1) (meval substitem)) (resimplify exp*)) (dispflag (rplaca exp (box (car exp) dispflag)) (resimplify exp*)) (t $piece)))) (substflag (if (null (cdr exp)) (go err)) (rplaca exp (cadr exp)) (rplacd exp (cddr exp))) (dispflag (rplaca exp (box (car exp) dispflag)) (setq exp (cdr exp))) (t (setq exp exp1))) (go sevloop))) (defmfun getop (x) (or (and (symbolp x) (get x 'op)) x)) (defmfun $listp (x) (and (not (atom x)) (not (atom (car x))) (eq (caar x) 'mlist))) (defmfun $cons (x e) (atomchk (setq e (specrepcheck e)) '$cons t) (mcons-exp-args e (cons x (margs e)))) (defmfun $endcons (x e) (atomchk (setq e (specrepcheck e)) '$endcons t) (mcons-exp-args e (append (margs e) (ncons x)))) (defmfun $reverse (e) (atomchk (setq e (format1 e)) '$reverse nil) (mcons-exp-args e (reverse (margs e)))) (defmfun $append (&rest args) (if (null args) '((mlist simp)) (let ((arg1 (specrepcheck (first args))) op arrp) (atomchk arg1 '$append nil) (setq op (mop arg1) arrp (if (member 'array (cdar arg1) :test #'eq) t)) (mcons-exp-args arg1 (apply #'append (mapcar #'(lambda (u) (atomchk (setq u (specrepcheck u)) '$append nil) (unless (and (alike1 op (mop u)) (eq arrp (if (member 'array (cdar u) :test #'eq) t))) (merror (intl:gettext "append: operators of arguments must all be the same."))) (margs u)) args)))))) (defun mcons-exp-args (e args) (if (eq (caar e) 'mqapply) (list* (delsimp (car e)) (cadr e) args) (cons (if (eq (caar e) 'mlist) (car e) (delsimp (car e))) args))) (defmfun $member (x e) (atomchk (setq e ($totaldisrep e)) '$member t) (if (memalike ($totaldisrep x) (margs e)) t)) (defmfun atomchk (e fun 2ndp) (if (or (atom e) (eq (caar e) 'bigfloat)) (merror (intl:gettext "~:M: ~Margument must be a non-atomic expression; found ~M") fun (if 2ndp "2nd " "") e))) (defmfun format1 (e) (cond (($listp e) e) ($inflag (specrepcheck e)) (t (nformat e)))) (defmfun $first (e) (atomchk (setq e (format1 e)) '$first nil) (if (null (cdr e)) (merror (intl:gettext "first: empty argument."))) (car (margs e))) This macro is used to create functions second thru tenth . ;; Rather than try to modify mformat for ~:R, use the quoted symbol (macrolet ((make-nth (si i) (let ((sim (intern (concatenate 'string "$" (symbol-name si))))) `(defmfun ,sim (e) (atomchk (setq e (format1 e)) ',sim nil) (if (< (length (margs e)) ,i) (merror (intl:gettext "~:M: no such element in ~M") ',sim e)) (,si (margs e)))))) (make-nth second 2) (make-nth third 3) (make-nth fourth 4) (make-nth fifth 5) (make-nth sixth 6) (make-nth seventh 7) (make-nth eighth 8) (make-nth ninth 9) (make-nth tenth 10)) (defmfun $rest (e &optional (n 1 n?)) (prog (m fun fun1 revp) (when (and n? (equal n 0)) (return e)) (atomchk (setq m (format1 e)) '$rest nil) (cond ((and n? (not (fixnump n))) (merror (intl:gettext "rest: second argument, if present, must be an integer; found ~M") n)) ((minusp n) (setq n (- n) revp t))) (if (< (length (margs m)) n) (if $partswitch (return '$end) (merror (intl:gettext "rest: fell off the end.")))) (setq fun (car m)) (when (eq (car fun) 'mqapply) (setq fun1 (cadr m) m (cdr m))) (setq m (cdr m)) (when revp (setq m (reverse m))) (setq m (nthcdr n m)) (setq m (cons (if (eq (car fun) 'mlist) fun (delsimp fun)) (if revp (nreverse m) m))) (when (eq (car fun) 'mqapply) (return (cons (car m) (cons fun1 (cdr m))))) (return m))) (defmfun $last (e) (atomchk (setq e (format1 e)) '$last nil) (when (null (cdr e)) (merror (intl:gettext "last: empty argument."))) (car (last e))) (defmfun $args (e) (atomchk (setq e (format1 e)) '$args nil) (cons '(mlist) (margs e))) (defmfun $delete (x l &optional (n -1 n?)) (when (and n? (or (not (fixnump n)) (minusp n))) ; if n is set, it must be a nonneg fixnum (merror (intl:gettext "delete: third argument, if present, must be a nonnegative integer; found ~M") n)) (atomchk (setq l (specrepcheck l)) '$delete t) (setq x (specrepcheck x) l (cons (delsimp (car l)) (copy-list (cdr l)))) (do ((l1 (if (eq (caar l) 'mqapply) (cdr l) l))) ((or (null (cdr l1)) (zerop n)) l) (if (alike1 x (specrepcheck (cadr l1))) (progn (decf n) (rplacd l1 (cddr l1))) (setq l1 (cdr l1))))) (defmfun $length (e) (setq e (cond (($listp e) e) ((or $inflag (not ($ratp e))) (specrepcheck e)) (t ($ratdisrep e)))) (cond ((symbolp e) (merror (intl:gettext "length: argument cannot be a symbol; found ~:M") e)) ((or (numberp e) (eq (caar e) 'bigfloat)) (if (and (not $inflag) (mnegp e)) 1 (merror (intl:gettext "length: argument cannot be a number; found ~:M") e))) ((or $inflag (not (member (caar e) '(mtimes mexpt) :test #'eq))) (length (margs e))) ((eq (caar e) 'mexpt) (if (and (alike1 (caddr e) '((rat simp) 1 2)) $sqrtdispflag) 1 2)) (t (length (cdr (nformat e)))))) (defmfun $atom (x) (setq x (specrepcheck x)) (or (atom x) (eq (caar x) 'bigfloat))) (defmfun $symbolp (x) (setq x (specrepcheck x)) (symbolp x)) (defmfun $num (e) (let (x) (cond ((atom e) e) ((eq (caar e) 'mrat) ($ratnumer e)) ((eq (caar e) 'rat) (cadr e)) ((eq (caar (setq x (nformat e))) 'mquotient) (simplify (cadr x))) ((and (eq (caar x) 'mminus) (not (atom (setq x (cadr x)))) (eq (caar x) 'mquotient)) (simplify (list '(mtimes) -1 (cadr x)))) (t e)))) (defmfun $denom (e) (cond ((atom e) 1) ((eq (caar e) 'mrat) ($ratdenom e)) ((eq (caar e) 'rat) (caddr e)) ((or (eq (caar (setq e (nformat e))) 'mquotient) (and (eq (caar e) 'mminus) (not (atom (setq e (cadr e)))) (eq (caar e) 'mquotient))) (simplify (caddr e))) (t 1))) (defmfun $entier (e) (take '($floor) e)) (defmfun $fix (e) (take '($floor) e)) (defmfun $float (e) (cond ((numberp e) (float e)) ((and (symbolp e) (mget e '$numer))) ((or (atom e) (member 'array (cdar e) :test #'eq)) e) ((eq (caar e) 'rat) (fpcofrat e)) ((eq (caar e) 'bigfloat) (fp2flo e)) ((member (caar e) '(mexpt mncexpt) :test #'eq) avoid x^2 - > x^2.0 , allow % e^%pi - > 23.14 (let ((res (recur-apply #'$float e))) (if (floatp res) res (list (ncons (caar e)) ($float (cadr e)) (caddr e))))) (t (recur-apply #'$float e)))) (defmfun $coeff (e x &optional (n 1)) (if (equal n 0) (coeff e x 0) (coeff e (power x n) 1))) (defmfun coeff (e var pow) (simplify (cond ((alike1 e var) (if (equal pow 1) 1 0)) ((atom e) (if (equal pow 0) e 0)) ((eq (caar e) 'mexpt) (cond ((alike1 (cadr e) var) (if (or (equal pow 0) (not (alike1 (caddr e) pow))) 0 1)) ((equal pow 0) e) (t 0))) ((or (eq (caar e) 'mplus) (mbagp e)) (cons (if (eq (caar e) 'mplus) '(mplus) (car e)) (mapcar #'(lambda (e) (coeff e var pow)) (cdr e)))) ((eq (caar e) 'mrat) (ratcoeff e var pow)) ((equal pow 0) (if (free e var) e 0)) ((eq (caar e) 'mtimes) (let ((term (if (equal pow 1) var (power var pow)))) (if (memalike term (cdr e)) ($delete term e 1) 0))) (t 0)))) (declare-top (special powers var hiflg num flag)) (defmfun $hipow (e var) (findpowers e t)) ;; These work best on expanded "simple" expressions. (defmfun $lopow (e var) (findpowers e nil)) (defun findpowers (e hiflg) (let (powers num flag) (findpowers1 e) (cond ((null powers) (if (null num) 0 num)) (t (when num (setq powers (cons num powers))) (maximin powers (if hiflg '$max '$min)))))) (defun findpowers1 (e) (cond ((alike1 e var) (checkpow 1)) ((atom e)) ((eq (caar e) 'mplus) (cond ((not (freel (cdr e) var)) (do ((e (cdr e) (cdr e))) ((null e)) (setq flag nil) (findpowers1 (car e)) (if (null flag) (checkpow 0)))))) ((and (eq (caar e) 'mexpt) (alike1 (cadr e) var)) (checkpow (caddr e))) ((specrepp e) (findpowers1 (specdisrep e))) (t (mapc #'findpowers1 (cdr e))))) (defun checkpow (pow) (setq flag t) (cond ((not (numberp pow)) (setq powers (cons pow powers))) ((null num) (setq num pow)) (hiflg (if (> pow num) (setq num pow))) ((< pow num) (setq num pow)))) (declare-top (unspecial powers var hiflg num flag))
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/src/comm.lisp
lisp
Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; The data in this file contains enhancments. ;;;;; ;;;;; ; ; ; ; All rights reserved ;;;;; op and opr properties The args to SUBSTITUTE are assumed to be simplified. Used in COMM2 (AT), limit, and below. Y is an atom never change integration var do subst in limits of integral This probably should be a subst or macro. Remove a special representation from the variable of differentiation Poisson series This rule is not correct. We cut it out. Handle %f, hypergeometric function a1*a2*...*ap/(b1*b2*...*bq) If noun form for f(n,x), adjust the noun form for f[n](x) extension for pdiff. Evaluate a lambda expression given as a derivative. A derivative has returned NIL. Return a noun form. grad properties (which are unnecessary) have been removed to save core space. SDIFFGRAD generates the noun form. ((%derivative) ((mqapply) (($li array) n) x) n 1) SDIFFGRAD generates the noun form. and bind it to the expression e. The global flag $NOLABELS is ignored; the label is always bound. Otherwise (if ELABEL were to observe $NOLABELS) it would be impossible to programmatically refer to intermediate result expression. <-- This is pretty ugly. MAKELABEL should take another argument. called only by TRANSLATE Rather than try to modify mformat for ~:R, use the quoted symbol if n is set, it must be a nonneg fixnum These work best on expanded "simple" expressions.
(in-package :maxima) * * ( c ) Copyright 1982 Massachusetts Institute of Technology * * (macsyma-module comm) (declare-top (special $exptsubst $linechar $nolabels $inflag $piece $dispflag $gradefs $props $dependencies derivflag derivlist $linenum $partswitch linelable nn* dn* islinp $powerdisp atvars atp $errexp $derivsubst $dotdistrib $opsubst $subnumsimp $transrun in-p substp $sqrtdispflag $pfeformat dummy-variable-operators)) (defvar *opr-table* (make-hash-table :test #'equal)) (defmfun getopr0 (x) (or (and (symbolp x) (get x 'opr)) (and (stringp x) (gethash x *opr-table*)))) (defmfun getopr (x) (or (getopr0 x) x)) (defmfun putopr (x y) (or (and (symbolp x) (setf (get x 'opr) y)) (and (stringp x) (setf (gethash x *opr-table*) y)))) (defmfun remopr (x) (or (and (symbolp x) (remprop x 'opr)) (and (stringp x) (remhash x *opr-table*)))) (mapc #'(lambda (x) (putprop (car x) (cadr x) 'op) (putopr (cadr x) (car x))) '((mplus "+") (mminus "-") (mtimes "*") (mexpt "**") (mexpt "^") (mnctimes ".") (rat "/") (mquotient "/") (mncexpt "^^") (mequal "=") (mgreaterp ">") (mlessp "<") (mleqp "<=") (mgeqp ">=") (mnotequal "#") (mand "and") (mor "or") (mnot "not") (msetq ":") (mdefine ":=") (mdefmacro "::=") (mquote "'") (mlist "[") (mset "::") (mfactorial "!") (marrow "-->") (mprogn "(") (mcond "if"))) (mapc #'(lambda (x) (putprop (car x) (cadr x) 'op)) '((mqapply $subvar) (bigfloat $bfloat))) (setq $exptsubst nil $partswitch nil $inflag nil $gradefs '((mlist simp)) $dependencies '((mlist simp)) atvars '($@1 $@2 $@3 $@4) atp nil islinp nil lnorecurse nil $derivsubst nil timesp nil $opsubst t in-p nil substp nil) (defmvar $vect_cross nil "If TRUE allows DIFF(X~Y,T) to work where ~ is defined in VECT where VECT_CROSS is set to TRUE . " ) (defmfun $substitute (old new &optional (expr nil three-arg?)) (cond (three-arg? (maxima-substitute old new expr)) (t (let ((l old) (z new)) (cond ((and ($listp l) ($listp (cadr l)) (null (cddr l))) ($substitute (cadr l) z)) ((notloreq l) (improper-arg-err l '$substitute)) ((eq (caar l) 'mequal) (maxima-substitute (caddr l) (cadr l) z)) (t (do ((l (cdr l) (cdr l))) ((null l) z) (setq z ($substitute (car l) z))))))))) (declare-top (special x y oprx opry negxpty timesp)) (declare (special x y )) (let ((in-p t) (substp t)) (if (and (mnump y) (= (signum1 y) 1)) (let ($sqrtdispflag ($pfeformat t)) (setq z (nformat-all z)))) (simplifya (if (atom y) (cond ((equal y -1) (setq y '((mminus) 1)) (subst2 (nformat-all z))) (t (cond ((and (not (symbolp x)) (functionp x)) (let ((tem (gensym))) (setf (get tem 'operators) 'application-operator) (setf (symbol-function tem) x) (setq x tem)))) (let ((oprx (getopr x)) (opry (getopr y))) (declare (special oprx opry )) (subst1 z)))) (let ((negxpty (if (and (eq (caar y) 'mexpt) (= (signum1 (caddr y)) 1)) (mul2 -1 (caddr y)))) (timesp (if (eq (caar y) 'mtimes) (setq y (nformat y))))) (declare (special negxpty timesp)) (subst2 z))) nil))) Remainder of page is update from F302 --gsb (defvar dummy-variable-operators '(%product %sum %laplace %integrate %limit %at)) (cond ((atom z) (if (equal y z) x z)) ((specrepp z) (subst1 (specdisrep z))) ((eq (caar z) 'bigfloat) z) ((and (eq (caar z) 'rat) (or (equal y (cadr z)) (equal y (caddr z)))) (div (subst1 (cadr z)) (subst1 (caddr z)))) ((at-substp z) (subst-except-second-arg x y z)) ((and (eq y t) (eq (caar z) 'mcond)) (list (cons (caar z) nil) (subst1 (cadr z)) (subst1 (caddr z)) (cadddr z) (subst1 (car (cddddr z))))) (t (let ((margs (mapcar #'subst1 (cdr z)))) (if (and $opsubst (or (eq opry (caar z)) (and (eq (caar z) 'rat) (eq opry 'mquotient)))) (if (or (numberp x) (member x '(t nil $%e $%pi $%i) :test #'eq) (and (not (atom x)) (not (or (eq (car x) 'lambda) (eq (caar x) 'lambda))))) (if (or (and (member 'array (cdar z) :test #'eq) (or (and (mnump x) $subnumsimp) (and (not (mnump x)) (not (atom x))))) ($subvarp x)) (let ((substp 'mqapply)) (subst0 (list* '(mqapply) x margs) z)) (merror (intl:gettext "subst: cannot substitute ~M for operator ~M in expression ~M") x y z)) (subst0 (cons (cons oprx nil) margs) z)) (subst0 (cons (cons (caar z) nil) margs) z)))))) (defun subst2 (z) (let (newexpt) (cond ((atom z) z) ((specrepp z) (subst2 (specdisrep z))) ((and atp (member (caar z) '(%derivative %laplace) :test #'eq)) z) ((at-substp z) z) ((alike1 y z) x) ((and timesp (eq (caar z) 'mtimes) (alike1 y (setq z (nformat z)))) x) ((and (eq (caar y) 'mexpt) (eq (caar z) 'mexpt) (alike1 (cadr y) (cadr z)) (setq newexpt (cond ((alike1 negxpty (caddr z)) -1) ($exptsubst (expthack (caddr y) (caddr z)))))) (list '(mexpt) x newexpt)) ((and $derivsubst (eq (caar y) '%derivative) (eq (caar z) '%derivative) (alike1 (cadr y) (cadr z))) (let ((tail (subst-diff-match (cddr y) (cdr z)))) (cond ((null tail) z) (t (cons (cons (caar z) nil) (cons x (cdr tail))))))) (t (recur-apply #'subst2 z))))) replace y with x in z , but leave z 's second arg unchanged . This is for cases like at(integrate(x , x , a , b ) , [ x=3 ] ) where second arg of integrate binds a new variable x , and we do not wish to subst 3 for x inside integrand . (defun subst-except-second-arg (x y z) (append (list (car z) if ( third z ) is new var that shadows y leave ( second z ) unchanged otherwise replace y with x in ( second z ) (cdddr z)))) (declare-top (unspecial x y oprx opry negxpty timesp)) (defmfun subst0 (new old) (cond ((atom new) new) ((alike (cdr new) (cdr old)) (cond ((eq (caar new) (caar old)) old) (t (simplifya (cons (cons (caar new) (member 'array (cdar old) :test #'eq)) (cdr old)) nil)))) ((member 'array (cdar old) :test #'eq) (simplifya (cons (cons (caar new) '(array)) (cdr new)) nil)) (t (simplifya new nil)))) (defun expthack (y z) (prog (nn* dn* yn yd zn zd qd) (cond ((and (mnump y) (mnump z)) (return (if (numberp (setq y (div* z y))) y))) ((atom z) (if (not (mnump y)) (return nil))) ((or (ratnump z) (eq (caar z) 'mplus)) (return nil))) ( CSIMP ) sets NN * and DN * (setq yn nn* yd dn*) (numden z) (setq zn nn* zd dn*) (setq qd (cond ((and (equal zd 1) (equal yd 1)) 1) ((prog2 (numden (div* zd yd)) (and (equal dn* 1) (equal nn* 1))) 1) ((equal nn* 1) (div* 1 dn*)) ((equal dn* 1) nn*) (t (return nil)))) (numden (div* zn yn)) (if (equal dn* 1) (return (div* nn* qd))))) (defun subst-diff-match (l1 l2) (do ((l l1 (cddr l)) (l2 (copy-list l2)) (failed nil nil)) ((null l) l2) (do ((l2 l2 (cddr l2))) ((null (cdr l2)) (setq failed t)) (if (alike1 (car l) (cadr l2)) (if (and (fixnump (cadr l)) (fixnump (caddr l2))) (cond ((< (cadr l) (caddr l2)) (return (rplacd (cdr l2) (cons (- (caddr l2) (cadr l)) (cdddr l2))))) ((= (cadr l) (caddr l2)) (return (rplacd l2 (cdddr l2)))) (t (return (setq failed t)))) (return (setq failed t))))) (if failed (return nil)))) (defun at-substp (z) (and atp (or (member (caar z) '(%derivative %del) :test #'eq) (member (caar z) dummy-variable-operators :test #'eq)))) (defmfun recur-apply (fun e) (cond ((eq (caar e) 'bigfloat) e) ((specrepp e) (funcall fun (specdisrep e))) (t (let ((newargs (mapcar fun (cdr e)))) (if (alike newargs (cdr e)) e (simplifya (cons (cons (caar e) (member 'array (cdar e) :test #'eq)) newargs) nil)))))) (defmfun $depends (&rest args) (when (oddp (length args)) (merror (intl:gettext "depends: number of arguments must be even."))) (do ((args args (cddr args)) (l)) ((null args) (i-$dependencies (nreverse l))) (if ($listp (first args)) (mapc #'(lambda (e) (push (depends1 e (second args)) l)) (cdr (first args))) (push (depends1 (first args) (second args)) l)))) (defun depends1 (x y) (nonsymchk x '$depends) (cons (cons x nil) (if ($listp y) (cdr y) (cons y nil)))) (defmspec $dependencies (form) (i-$dependencies (cdr form))) (defmfun i-$dependencies (l) (dolist (z l) (cond ((atom z) (merror (intl:gettext "depends: argument must be a non-atomic expression; found ~M") z)) ((or (eq (caar z) 'mqapply) (member 'array (cdar z) :test #'eq)) (merror (intl:gettext "depends: argument cannot be a subscripted expression; found ~M") z)) (t (let ((y (mget (caar z) 'depends))) (mputprop (caar z) (setq y (union* (reverse (cdr z)) y)) 'depends) (unless (cdr $dependencies) (setq $dependencies (copy-list '((mlist simp))))) (add2lnc (cons (cons (caar z) nil) y) $dependencies))))) (cons '(mlist simp) l)) (defmspec $gradef (l) (setq l (cdr l)) (let ((z (car l)) (n 0)) (cond ((atom z) (if (not (= (length l) 3)) (merror (intl:gettext "gradef: expected exactly three arguments."))) (mputprop z (cons (cons (cadr l) (meval (caddr l))) (mget z '$atomgrad)) '$atomgrad) (i-$dependencies (cons (list (ncons z) (cadr l)) nil)) (add2lnc z $props) z) ((or (mopp1 (caar z)) (member 'array (cdar z) :test #'eq)) (merror (intl:gettext "gradef: argument cannot be a built-in operator or subscripted expression; found ~M") z)) ((prog2 (setq n (- (length z) (length l))) (minusp n)) (wna-err '$gradef)) (t (do ((zl (cdr z) (cdr zl))) ((null zl)) (if (not (symbolp (car zl))) (merror (intl:gettext "gradef: argument must be a symbol; found ~M") (car zl)))) (setq l (nconc (mapcar #'(lambda (x) (remsimp (meval x))) (cdr l)) (mapcar #'(lambda (x) (list '(%derivative) z x 1)) (nthcdr (- (length z) n) z)))) (putprop (caar z) (sublis (mapcar #'cons (cdr z) (mapcar #'stripdollar (cdr z))) (cons (cdr z) l)) 'grad) (or (cdr $gradefs) (setq $gradefs (copy-list '((mlist simp))))) (add2lnc (cons (cons (caar z) nil) (cdr z)) $gradefs) z)))) (defmfun $diff (&rest args) (declare (dynamic-extent args)) (let (derivlist) (deriv args))) (defmfun $del (e) (stotaldiff e)) (defun deriv (e) (prog (exp z count) (cond ((null e) (wna-err '$diff)) ((null (cdr e)) (return (stotaldiff (car e)))) ((null (cddr e)) (nconc e '(1)))) (setq exp (car e) z (setq e (copy-list e))) loop (if (or (null derivlist) (member (cadr z) derivlist :test #'equal)) (go doit)) DERIVLIST is set by $ EV (setq z (cdr z)) loop2(cond ((cdr z) (go loop)) ((null (cdr e)) (return exp)) (t (go noun))) doit (cond ((nonvarcheck (cadr z) '$diff)) ((null (cddr z)) (wna-err '$diff)) ((not (eq (ml-typep (caddr z)) 'fixnum)) (go noun)) ((minusp (setq count (caddr z))) (merror (intl:gettext "diff: order of derivative must be a nonnegative integer; found ~M") count))) loop1(cond ((zerop count) (rplacd z (cdddr z)) (go loop2)) ((equal (setq exp (sdiff exp (cadr z))) 0) (return 0))) (setq count (1- count)) (go loop1) noun (return (diff%deriv (cons exp (cdr e)))))) (defun chainrule (e x) (let (w) (cond (islinp (if (and (not (atom e)) (eq (caar e) '%derivative) (not (freel (cdr e) x))) (diff%deriv (list e x 1)) 0)) ((atomgrad e x)) ((not (setq w (mget (cond ((atom e) e) ((member 'array (cdar e) :test #'eq) (caar e)) ((atom (cadr e)) (cadr e)) (t (caaadr e))) 'depends))) 0) (t (let (derivflag) (addn (mapcar #'(lambda (u) (let ((y (sdiff u x))) (if (equal y 0) 0 (list '(mtimes) (or (atomgrad e u) (list '(%derivative) e u 1)) y)))) w) nil)))))) (defun atomgrad (e x) (let (y) (and (atom e) (setq y (mget e '$atomgrad)) (assolike x y)))) (defun depends (e x) (cond ((alike1 e x) t) ((mnump e) nil) ((atom e) (mget e 'depends)) (t (or (depends (caar e) x) (dependsl (cdr e) x))))) (defun dependsl (l x) (dolist (u l) (if (depends u x) (return t)))) The args to SDIFF are assumed to be simplified . (setq x (specrepcheck x)) (cond ((alike1 e x) 1) ((mnump e) 0) ((or (atom e) (member 'array (cdar e) :test #'eq)) (chainrule e x)) ((eq (caar e) 'mrat) (ratdx e x)) ((eq (caar e) 'mplus) (addn (sdiffmap (cdr e) x) t)) ((mbagp e) (cons (car e) (sdiffmap (cdr e) x))) ((member (caar e) '(%sum %product) :test #'eq) (diffsumprod e x)) ((eq (caar e) '%at) (diff-%at e x)) ((not (depends e x)) 0) ((eq (caar e) 'mtimes) (addn (sdifftimes (cdr e) x) t)) ((eq (caar e) 'mexpt) (diffexpt e x)) ((eq (caar e) 'mnctimes) (let (($dotdistrib t)) (add2 (ncmuln (cons (sdiff (cadr e) x) (cddr e)) t) (ncmul2 (cadr e) (sdiff (cons '(mnctimes) (cddr e)) x))))) ((and $vect_cross (eq (caar e) '|$~|)) (add2* `((|$~|) ,(cadr e) ,(sdiff (caddr e) x)) `((|$~|) ,(sdiff (cadr e) x) ,(caddr e)))) ((eq (caar e) 'mncexpt) (diffncexpt e x)) ((member (caar e) '(%log %plog) :test #'eq) (sdiffgrad (cond ((and (not (atom (cadr e))) (eq (caaadr e) 'mabs)) (cons (car e) (cdadr e))) (t e)) x)) ((eq (caar e) '%derivative) (cond ((or (atom (cadr e)) (member 'array (cdaadr e) :test #'eq)) (chainrule e x)) ((freel (cddr e) x) (diff%deriv (cons (sdiff (cadr e) x) (cddr e)))) (t (diff%deriv (list e x 1))))) ((member (caar e) '(%binomial $beta) :test #'eq) (let ((efact ($makefact e))) (mul2 (factor (sdiff efact x)) (div e efact)))) ((eq (caar e) '%integrate) (diffint e x)) ((eq (caar e) '%laplace) (difflaplace e x)) ((eq (caar e) '%at) (diff-%at e x)) ( ( member ( caar e ) ' ( % realpart % imagpart ) : test # ' eq ) ( list ( cons ( caar e ) nil ) ( sdiff ( cadr e ) x ) ) ) ((and (eq (caar e) 'mqapply) (eq (caaadr e) '$%f)) The derivative of % f[p , q]([a1, ... ,ap],[b1, ... ,bq],z ) is * % f[p , q]([a1 + 1,a2 + 1, ... ,ap+1],[b1 + 1,b2 + 1, ... ,bq+1],z ) (let* ((arg1 (cdr (third e))) (arg2 (cdr (fourth e))) (v (fifth e))) (mul (sdiff v x) (div (mull arg1) (mull arg2)) `((mqapply) (($%f array) ,(length arg1) ,(length arg2)) ((mlist) ,@(incr1 arg1)) ((mlist) ,@(incr1 arg2)) ,v)))) (t (sdiffgrad e x)))) (defun sdiffgrad (e x) (let ((fun (caar e)) grad args result) (cond ((and (eq fun 'mqapply) (oldget (caaadr e) 'grad)) Change the array function f[n](x ) to f(n , x ) , call sdiffgrad again . (setq result (sdiffgrad (cons (cons (caaadr e) nil) (append (cdadr e) (cddr e))) x)) (if (isinop result '%derivative) (if (not (depends e x)) 0 (diff%deriv (list e x 1))) result)) ((and (get '$pderivop 'operators) (sdiffgrad-pdiff e x))) two line extension for hypergeometric . ((and (equal fun '$hypergeometric) (get '$hypergeometric 'operators)) (diff-hypergeometric (second e) (third e) (fourth e) x)) ((or (eq fun 'mqapply) (null (setq grad (oldget fun 'grad)))) (if (not (depends e x)) 0 (diff%deriv (list e x 1)))) ((not (= (length (cdr e)) (length (car grad)))) (merror (intl:gettext "~:M: expected exactly ~M arguments.") fun (length (car grad)))) (t (setq args (sdiffmap (cdr e) x)) (setq result (addn (mapcar #'mul2 (cdr (substitutel (cdr e) (car grad) (do ((l1 (cdr grad) (cdr l1)) (args args (cdr args)) (l2)) ((null l1) (cons '(mlist) (nreverse l2))) (setq l2 (cons (cond ((equal (car args) 0) 0) ((functionp (car l1)) (apply (car l1) (cdr e))) (t (car l1))) l2))))) args) t)) (if (or (null result) (not (freeof nil result))) (if (not (depends e x)) 0 (diff%deriv (list e x 1))) result))))) (defun sdiffmap (e x) (mapcar #'(lambda (term) (sdiff term x)) e)) (defun sdifftimes (l x) (prog (term left out) loop (setq term (car l) l (cdr l)) (setq out (cons (muln (cons (sdiff term x) (append left l)) t) out)) (if (null l) (return out)) (setq left (cons term left)) (go loop))) (defun diffexpt (e x) (if (mnump (caddr e)) (mul3 (caddr e) (power (cadr e) (addk (caddr e) -1)) (sdiff (cadr e) x)) (mul2 e (add2 (mul3 (power (cadr e) -1) (caddr e) (sdiff (cadr e) x)) (mul2 (simplifya (list '(%log) (cadr e)) t) (sdiff (caddr e) x)))))) (defun diff%deriv (e) (let (derivflag) (simplifya (cons '(%derivative) e) t))) (let ((header '(x))) (mapc #'(lambda (z) (putprop (car z) (cons header (cdr z)) 'grad)) All these GRAD templates have been simplified and then the SIMP flags '((%log ((mexpt) x -1)) (%plog ((mexpt) x -1)) (%gamma ((mtimes) ((mqapply) (($psi array) 0) x) ((%gamma) x))) (mfactorial ((mtimes) ((mqapply) (($psi array) 0) ((mplus) 1 x)) ((mfactorial) x))) (%sin ((%cos) x)) (%cos ((mtimes) -1 ((%sin) x))) (%tan ((mexpt) ((%sec) x) 2)) (%cot ((mtimes) -1 ((mexpt) ((%csc) x) 2))) (%sec ((mtimes) ((%sec) x) ((%tan) x))) (%csc ((mtimes) -1 ((%cot) x) ((%csc) x))) (%asin ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x 2))) ((rat) -1 2))) (%acos ((mtimes) -1 ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x 2))) ((rat) -1 2)))) (%atan ((mexpt) ((mplus) 1 ((mexpt) x 2)) -1)) (%acot ((mtimes) -1 ((mexpt) ((mplus) 1 ((mexpt) x 2)) -1))) (%acsc ((mtimes) -1 ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x -2))) ((rat) -1 2)) ((mexpt) x -2))) (%asec ((mtimes) ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x -2))) ((rat) -1 2)) ((mexpt) x -2))) (%sinh ((%cosh) x)) (%cosh ((%sinh) x)) (%tanh ((mexpt) ((%sech) x) 2)) (%coth ((mtimes) -1 ((mexpt) ((%csch) x) 2))) (%sech ((mtimes) -1 ((%sech) x) ((%tanh) x))) (%csch ((mtimes) -1 ((%coth) x) ((%csch) x))) (%asinh ((mexpt) ((mplus) 1 ((mexpt) x 2)) ((rat) -1 2))) (%acosh ((mexpt) ((mplus) -1 ((mexpt) x 2)) ((rat) -1 2))) (%atanh ((mexpt) ((mplus) 1 ((mtimes) -1 ((mexpt) x 2))) -1)) (%acoth ((mtimes) -1 ((mexpt) ((mplus) -1 ((mexpt) x 2)) -1))) (%asech ((mtimes) -1 ((mexpt) ((mplus) -1 ((mexpt) x -2)) ((rat) -1 2)) ((mexpt) x -2))) (%acsch ((mtimes) -1 ((mexpt) ((mplus) 1 ((mexpt) x -2)) ((rat) -1 2)) ((mexpt) x -2))) (mabs ((mtimes) x ((mexpt) ((mabs) x) -1))) (%erf ((mtimes) 2 ((mexpt) $%pi ((rat) -1 2)) ((mexpt) $%e ((mtimes) -1 ((mexpt) x 2))))) ))) (defprop $atan2 ((x y) ((mtimes) y ((mexpt) ((mplus) ((mexpt) x 2) ((mexpt) y 2)) -1)) ((mtimes) -1 x ((mexpt) ((mplus) ((mexpt) x 2) ((mexpt) y 2)) -1))) grad) (defprop $li ((n x) Do not put a noun form on the property list , but NIL . nil ((mtimes) ((mqapply) (($li array) ((mplus) -1 n)) x) ((mexpt) x -1))) grad) (defprop $psi ((n x) Do not put a noun form on the property list , but NIL . nil ((mqapply) (($psi array) ((mplus) 1 n)) x)) grad) (defmfun atvarschk (argl) (do ((largl (length argl) (1- largl)) (latvrs (length atvars)) (l)) ((not (< latvrs largl)) (nconc atvars l)) (setq l (cons (implode (cons '$ (cons '@ (mexploden largl)))) l)))) (defmfun notloreq (x) (or (atom x) (not (member (caar x) '(mlist mequal) :test #'eq)) (and (eq (caar x) 'mlist) (dolist (u (cdr x)) (if (not (mequalp u)) (return t)))))) (defmfun substitutel (l1 l2 e) "l1 is a list of expressions. l2 is a list of variables. For each element in list l2, substitute corresponding element of l1 into e" (do ((l1 l1 (cdr l1)) (l2 l2 (cdr l2))) ((null l1) e) (setq e (maxima-substitute (car l1) (car l2) e)))) (defmfun union* (a b) (do ((a a (cdr a)) (x b)) ((null a) x) (if (not (memalike (car a) b)) (setq x (cons (car a) x))))) (defmfun intersect* (a b) (do ((a a (cdr a)) (x)) ((null a) x) (if (memalike (car a) b) (setq x (cons (car a) x))))) (defmfun nthelem (n e) (car (nthcdr (1- n) e))) (defmfun delsimp (e) (delete 'simp (copy-list e) :count 1 :test #'eq)) (defmfun remsimp (e) (if (atom e) e (cons (delsimp (car e)) (mapcar #'remsimp (cdr e))))) (defmfun $trunc (e) (cond ((atom e) e) ((eq (caar e) 'mplus) (cons (append (car e) '(trunc)) (cdr e))) ((mbagp e) (cons (car e) (mapcar #'$trunc (cdr e)))) ((specrepp e) ($trunc (specdisrep e))) (t e))) (defmfun nonvarcheck (e fn) (if (or (mnump e) (maxima-integerp e) (and (not (atom e)) (not (eq (caar e) 'mqapply)) (mopp1 (caar e)))) (merror (intl:gettext "~:M: second argument must be a variable; found ~M") fn e))) (defmspec $ldisplay (form) (disp1 (cdr form) t t)) (defmfun $ldisp (&rest args) (declare (dynamic-extent args)) (disp1 args t nil)) (defmspec $display (form) (disp1 (cdr form) nil t)) (defmfun $disp (&rest args) (declare (dynamic-extent args)) (disp1 args nil nil)) (defun disp1 (ll lablist eqnsp) (if lablist (setq lablist (cons '(mlist simp) nil))) (do ((ll ll (cdr ll)) (l) (ans) ($dispflag t) (tim 0)) ((null ll) (or lablist '$done)) (setq l (car ll) ans (if eqnsp (meval l) l)) (if (and eqnsp (not (mequalp ans))) (setq ans (list '(mequal simp) (disp2 l) ans))) (if lablist (nconc lablist (cons (elabel ans) nil))) (setq tim (get-internal-run-time)) (displa (list '(mlable) (if lablist linelable) ans)) (mterpri) (timeorg tim))) (defun disp2 (e) (cond ((atom e) e) ((eq (caar e) 'mqapply) (cons '(mqapply) (cons (cons (caadr e) (mapcar #'meval (cdadr e))) (mapcar #'meval (cddr e))))) ((eq (caar e) 'msetq) (disp2 (cadr e))) ((eq (caar e) 'mset) (disp2 (meval (cadr e)))) ((eq (caar e) 'mlist) (cons (car e) (mapcar #'disp2 (cdr e)))) ((mspecfunp (caar e)) e) (t (cons (car e) (mapcar #'meval (cdr e)))))) Construct a new intermediate result label , (defmfun elabel (e) (if (not (checklabel $linechar)) (setq $linenum (1+ $linenum))) (makelabel $linechar)) (setf (symbol-value linelable) e) linelable) (defmfun $dispterms (e) (cond ((or (atom e) (eq (caar e) 'bigfloat)) (displa e)) ((specrepp e) ($dispterms (specdisrep e))) (t (let (($dispflag t)) (mterpri) (displa (getop (mop e))) (do ((e (if (and (eq (caar e) 'mplus) (not $powerdisp)) (reverse (cdr e)) (margs e)) (cdr e))) ((null e)) (mterpri) (displa (car e)) (mterpri))) (mterpri))) '$done) (defmfun $dispform (e &optional (flag nil flag?)) (when (and flag? (not (eq flag '$all))) (merror (intl:gettext "dispform: second argument, if present, must be 'all'; found ~M") flag)) (if (or (atom e) (atom (setq e (if flag? (nformat-all e) (nformat e)))) (member 'simp (cdar e) :test #'eq)) e (cons (cons (caar e) (cons 'simp (cdar e))) (if (and (eq (caar e) 'mplus) (not $powerdisp)) (reverse (cdr e)) (cdr e))))) These functions implement the functions $ op and . (defmfun $op (expr) ($part expr 0)) (defmfun $operatorp (expr oplist) (if ($listp oplist) ($member ($op expr) oplist) (equal ($op expr) oplist))) (defmfun $part (&rest args) (declare (dynamic-extent args)) (mpart args nil nil $inflag '$part)) (defmfun $inpart (&rest args) (declare (dynamic-extent args)) (mpart args nil nil t '$inpart)) (defmspec $substpart (l) (let ((substp t)) (mpart (cdr l) t nil $inflag '$substpart))) (defmspec $substinpart (l) (let ((substp t)) (mpart (cdr l) t nil t '$substinpart))) (let ((substp t)) (mpart arglist substflag dispflag inflag '$substpart))) (defmfun mpart (arglist substflag dispflag inflag fn) (prog (substitem arg arg1 exp exp1 exp* sevlist count prevcount n specp lastelem lastcount) (setq specp (or substflag dispflag)) (if substflag (setq substitem (car arglist) arglist (cdr arglist))) (if (null arglist) (wna-err '$part)) (setq exp (if substflag (meval (car arglist)) (car arglist))) (when (null (setq arglist (cdr arglist))) (setq $piece exp) (return (cond (substflag (meval substitem)) (dispflag (box exp dispflag)) (t exp)))) (cond ((not inflag) (cond ((or (and ($listp exp) (null (cdr arglist))) (and ($matrixp exp) (or (null (cdr arglist)) (null (cddr arglist))))) (setq inflag t)) ((not specp) (setq exp (nformat exp))) (t (setq exp (nformat-all exp))))) ((specrepp exp) (setq exp (specdisrep exp)))) (when (and (atom exp) (null $partswitch)) (merror (intl:gettext "~:M: argument must be a non-atomic expression; found ~:M") fn exp)) (when (and inflag specp) (setq exp (copy-tree exp))) (setq exp* exp) start (cond ((or (atom exp) (eq (caar exp) 'bigfloat)) (go err)) ((equal (setq arg (if substflag (meval (car arglist)) (car arglist))) 0) (setq arglist (cdr arglist)) (cond ((mnump substitem) (merror (intl:gettext "~:M: argument cannot be a number; found ~M") fn substitem)) ((and specp arglist) (if (eq (caar exp) 'mqapply) (prog2 (setq exp (cadr exp)) (go start)) NOT CLEAR WHAT IS INVALID HERE . OH WELL . (merror (intl:gettext "~:M: invalid operator.") fn))) (t (setq $piece (getop (mop exp))) (return (cond (substflag (setq substitem (getopr (meval substitem))) (cond ((mnump substitem) (merror (intl:gettext "~:M: argument cannot be a number; found ~M") fn substitem)) ((not (atom substitem)) (if (not (eq (caar exp) 'mqapply)) (rplaca (rplacd exp (cons (car exp) (cdr exp))) '(mqapply))) (rplaca (cdr exp) substitem) (return (resimplify exp*))) ((eq (caar exp) 'mqapply) (rplacd exp (cddr exp)))) (rplaca exp (cons substitem (if (and (member 'array (cdar exp) :test #'eq) (not (mopp substitem))) '(array)))) (resimplify exp*)) (dispflag (rplacd exp (cdr (box (copy-tree exp) dispflag))) (rplaca exp (if (eq dispflag t) '(mbox) '(mlabox))) (resimplify exp*)) (t (when arglist (setq exp $piece) (go a)) $piece)))))) ((not (atom arg)) (go several)) ((not (fixnump arg)) (merror (intl:gettext "~:M: argument must be an integer; found ~M") fn arg)) ((< arg 0) (go bad))) (if (eq (caar exp) 'mqapply) (setq exp (cdr exp))) loop (cond ((not (zerop arg)) (setq arg (1- arg) exp (cdr exp)) (if (null exp) (go err)) (go loop)) ((null (setq arglist (cdr arglist))) (return (cond (substflag (setq $piece (resimplify (car exp))) (rplaca exp (meval substitem)) (resimplify exp*)) (dispflag (setq $piece (resimplify (car exp))) (rplaca exp (box (car exp) dispflag)) (resimplify exp*)) (inflag (setq $piece (car exp))) (t (setq $piece (simplify (car exp)))))))) (setq exp (car exp)) a (cond ((and (not inflag) (not specp)) (setq exp (nformat exp))) ((specrepp exp) (setq exp (specdisrep exp)))) (go start) err (cond ((eq $partswitch 'mapply) (merror (intl:gettext "part: invalid index of list or matrix."))) ($partswitch (return (setq $piece '$end))) (t (merror (intl:gettext "~:M: fell off the end.") fn))) bad (improper-arg-err arg fn) several (if (or (not (member (caar arg) '(mlist $allbut) :test #'eq)) (cdr arglist)) (go bad)) (setq exp1 (cons (caar exp) (if (member 'array (cdar exp) :test #'eq) '(array)))) (if (eq (caar exp) 'mqapply) (setq sevlist (list (cadr exp) exp1) exp (cddr exp)) (setq sevlist (ncons exp1) exp (cdr exp))) (setq arg1 (cdr arg) prevcount 0 exp1 exp) (dolist (arg* arg1) (if (not (fixnump arg*)) (merror (intl:gettext "~:M: argument must be an integer; found ~M") fn arg*))) (when (and specp (eq (caar arg) 'mlist)) (if substflag (setq lastelem (car (last arg1)))) (setq arg1 (sort (copy-list arg1) #'<))) (when (eq (caar arg) '$allbut) (setq n (length exp)) (dolist (i arg1) (if (or (< i 1) (> i n)) (merror (intl:gettext "~:M: index must be in range 1 to ~M, inclusive; found ~M") fn n i))) (do ((i n (1- i)) (arg2)) ((= i 0) (setq arg1 arg2)) (if (not (member i arg1 :test #'equal)) (setq arg2 (cons i arg2)))) (if substflag (setq lastelem (car (last arg1))))) (if (null arg1) (if specp (go bad) (go end))) (if substflag (setq lastcount lastelem)) sevloop (if specp (setq count (- (car arg1) prevcount) prevcount (car arg1)) (setq count (car arg1))) (if (< count 1) (go bad)) (if (and substflag (< (car arg1) lastelem)) (setq lastcount (1- lastcount))) count(cond ((null exp) (go err)) ((not (= count 1)) (setq count (1- count) exp (cdr exp)) (go count))) (setq sevlist (cons (car exp) sevlist)) (setq arg1 (cdr arg1)) end (cond ((null arg1) (setq sevlist (nreverse sevlist)) (setq $piece (if (or inflag (not specp)) (simplify sevlist) (resimplify sevlist))) (return (cond (substflag (rplaca (nthcdr (1- lastcount) exp1) (meval substitem)) (resimplify exp*)) (dispflag (rplaca exp (box (car exp) dispflag)) (resimplify exp*)) (t $piece)))) (substflag (if (null (cdr exp)) (go err)) (rplaca exp (cadr exp)) (rplacd exp (cddr exp))) (dispflag (rplaca exp (box (car exp) dispflag)) (setq exp (cdr exp))) (t (setq exp exp1))) (go sevloop))) (defmfun getop (x) (or (and (symbolp x) (get x 'op)) x)) (defmfun $listp (x) (and (not (atom x)) (not (atom (car x))) (eq (caar x) 'mlist))) (defmfun $cons (x e) (atomchk (setq e (specrepcheck e)) '$cons t) (mcons-exp-args e (cons x (margs e)))) (defmfun $endcons (x e) (atomchk (setq e (specrepcheck e)) '$endcons t) (mcons-exp-args e (append (margs e) (ncons x)))) (defmfun $reverse (e) (atomchk (setq e (format1 e)) '$reverse nil) (mcons-exp-args e (reverse (margs e)))) (defmfun $append (&rest args) (if (null args) '((mlist simp)) (let ((arg1 (specrepcheck (first args))) op arrp) (atomchk arg1 '$append nil) (setq op (mop arg1) arrp (if (member 'array (cdar arg1) :test #'eq) t)) (mcons-exp-args arg1 (apply #'append (mapcar #'(lambda (u) (atomchk (setq u (specrepcheck u)) '$append nil) (unless (and (alike1 op (mop u)) (eq arrp (if (member 'array (cdar u) :test #'eq) t))) (merror (intl:gettext "append: operators of arguments must all be the same."))) (margs u)) args)))))) (defun mcons-exp-args (e args) (if (eq (caar e) 'mqapply) (list* (delsimp (car e)) (cadr e) args) (cons (if (eq (caar e) 'mlist) (car e) (delsimp (car e))) args))) (defmfun $member (x e) (atomchk (setq e ($totaldisrep e)) '$member t) (if (memalike ($totaldisrep x) (margs e)) t)) (defmfun atomchk (e fun 2ndp) (if (or (atom e) (eq (caar e) 'bigfloat)) (merror (intl:gettext "~:M: ~Margument must be a non-atomic expression; found ~M") fun (if 2ndp "2nd " "") e))) (defmfun format1 (e) (cond (($listp e) e) ($inflag (specrepcheck e)) (t (nformat e)))) (defmfun $first (e) (atomchk (setq e (format1 e)) '$first nil) (if (null (cdr e)) (merror (intl:gettext "first: empty argument."))) (car (margs e))) This macro is used to create functions second thru tenth . (macrolet ((make-nth (si i) (let ((sim (intern (concatenate 'string "$" (symbol-name si))))) `(defmfun ,sim (e) (atomchk (setq e (format1 e)) ',sim nil) (if (< (length (margs e)) ,i) (merror (intl:gettext "~:M: no such element in ~M") ',sim e)) (,si (margs e)))))) (make-nth second 2) (make-nth third 3) (make-nth fourth 4) (make-nth fifth 5) (make-nth sixth 6) (make-nth seventh 7) (make-nth eighth 8) (make-nth ninth 9) (make-nth tenth 10)) (defmfun $rest (e &optional (n 1 n?)) (prog (m fun fun1 revp) (when (and n? (equal n 0)) (return e)) (atomchk (setq m (format1 e)) '$rest nil) (cond ((and n? (not (fixnump n))) (merror (intl:gettext "rest: second argument, if present, must be an integer; found ~M") n)) ((minusp n) (setq n (- n) revp t))) (if (< (length (margs m)) n) (if $partswitch (return '$end) (merror (intl:gettext "rest: fell off the end.")))) (setq fun (car m)) (when (eq (car fun) 'mqapply) (setq fun1 (cadr m) m (cdr m))) (setq m (cdr m)) (when revp (setq m (reverse m))) (setq m (nthcdr n m)) (setq m (cons (if (eq (car fun) 'mlist) fun (delsimp fun)) (if revp (nreverse m) m))) (when (eq (car fun) 'mqapply) (return (cons (car m) (cons fun1 (cdr m))))) (return m))) (defmfun $last (e) (atomchk (setq e (format1 e)) '$last nil) (when (null (cdr e)) (merror (intl:gettext "last: empty argument."))) (car (last e))) (defmfun $args (e) (atomchk (setq e (format1 e)) '$args nil) (cons '(mlist) (margs e))) (defmfun $delete (x l &optional (n -1 n?)) (merror (intl:gettext "delete: third argument, if present, must be a nonnegative integer; found ~M") n)) (atomchk (setq l (specrepcheck l)) '$delete t) (setq x (specrepcheck x) l (cons (delsimp (car l)) (copy-list (cdr l)))) (do ((l1 (if (eq (caar l) 'mqapply) (cdr l) l))) ((or (null (cdr l1)) (zerop n)) l) (if (alike1 x (specrepcheck (cadr l1))) (progn (decf n) (rplacd l1 (cddr l1))) (setq l1 (cdr l1))))) (defmfun $length (e) (setq e (cond (($listp e) e) ((or $inflag (not ($ratp e))) (specrepcheck e)) (t ($ratdisrep e)))) (cond ((symbolp e) (merror (intl:gettext "length: argument cannot be a symbol; found ~:M") e)) ((or (numberp e) (eq (caar e) 'bigfloat)) (if (and (not $inflag) (mnegp e)) 1 (merror (intl:gettext "length: argument cannot be a number; found ~:M") e))) ((or $inflag (not (member (caar e) '(mtimes mexpt) :test #'eq))) (length (margs e))) ((eq (caar e) 'mexpt) (if (and (alike1 (caddr e) '((rat simp) 1 2)) $sqrtdispflag) 1 2)) (t (length (cdr (nformat e)))))) (defmfun $atom (x) (setq x (specrepcheck x)) (or (atom x) (eq (caar x) 'bigfloat))) (defmfun $symbolp (x) (setq x (specrepcheck x)) (symbolp x)) (defmfun $num (e) (let (x) (cond ((atom e) e) ((eq (caar e) 'mrat) ($ratnumer e)) ((eq (caar e) 'rat) (cadr e)) ((eq (caar (setq x (nformat e))) 'mquotient) (simplify (cadr x))) ((and (eq (caar x) 'mminus) (not (atom (setq x (cadr x)))) (eq (caar x) 'mquotient)) (simplify (list '(mtimes) -1 (cadr x)))) (t e)))) (defmfun $denom (e) (cond ((atom e) 1) ((eq (caar e) 'mrat) ($ratdenom e)) ((eq (caar e) 'rat) (caddr e)) ((or (eq (caar (setq e (nformat e))) 'mquotient) (and (eq (caar e) 'mminus) (not (atom (setq e (cadr e)))) (eq (caar e) 'mquotient))) (simplify (caddr e))) (t 1))) (defmfun $entier (e) (take '($floor) e)) (defmfun $fix (e) (take '($floor) e)) (defmfun $float (e) (cond ((numberp e) (float e)) ((and (symbolp e) (mget e '$numer))) ((or (atom e) (member 'array (cdar e) :test #'eq)) e) ((eq (caar e) 'rat) (fpcofrat e)) ((eq (caar e) 'bigfloat) (fp2flo e)) ((member (caar e) '(mexpt mncexpt) :test #'eq) avoid x^2 - > x^2.0 , allow % e^%pi - > 23.14 (let ((res (recur-apply #'$float e))) (if (floatp res) res (list (ncons (caar e)) ($float (cadr e)) (caddr e))))) (t (recur-apply #'$float e)))) (defmfun $coeff (e x &optional (n 1)) (if (equal n 0) (coeff e x 0) (coeff e (power x n) 1))) (defmfun coeff (e var pow) (simplify (cond ((alike1 e var) (if (equal pow 1) 1 0)) ((atom e) (if (equal pow 0) e 0)) ((eq (caar e) 'mexpt) (cond ((alike1 (cadr e) var) (if (or (equal pow 0) (not (alike1 (caddr e) pow))) 0 1)) ((equal pow 0) e) (t 0))) ((or (eq (caar e) 'mplus) (mbagp e)) (cons (if (eq (caar e) 'mplus) '(mplus) (car e)) (mapcar #'(lambda (e) (coeff e var pow)) (cdr e)))) ((eq (caar e) 'mrat) (ratcoeff e var pow)) ((equal pow 0) (if (free e var) e 0)) ((eq (caar e) 'mtimes) (let ((term (if (equal pow 1) var (power var pow)))) (if (memalike term (cdr e)) ($delete term e 1) 0))) (t 0)))) (declare-top (special powers var hiflg num flag)) (defmfun $hipow (e var) (findpowers e t)) (defmfun $lopow (e var) (findpowers e nil)) (defun findpowers (e hiflg) (let (powers num flag) (findpowers1 e) (cond ((null powers) (if (null num) 0 num)) (t (when num (setq powers (cons num powers))) (maximin powers (if hiflg '$max '$min)))))) (defun findpowers1 (e) (cond ((alike1 e var) (checkpow 1)) ((atom e)) ((eq (caar e) 'mplus) (cond ((not (freel (cdr e) var)) (do ((e (cdr e) (cdr e))) ((null e)) (setq flag nil) (findpowers1 (car e)) (if (null flag) (checkpow 0)))))) ((and (eq (caar e) 'mexpt) (alike1 (cadr e) var)) (checkpow (caddr e))) ((specrepp e) (findpowers1 (specdisrep e))) (t (mapc #'findpowers1 (cdr e))))) (defun checkpow (pow) (setq flag t) (cond ((not (numberp pow)) (setq powers (cons pow powers))) ((null num) (setq num pow)) (hiflg (if (> pow num) (setq num pow))) ((< pow num) (setq num pow)))) (declare-top (unspecial powers var hiflg num flag))
e1f2bebebf6f6c073aa47003c9a5ce588205b763abd6e92456f455eddfc5bf4b
ashinn/chibi-scheme
hamt-test.scm
HAMT Core Tests Copyright MMXV - MMXVII . All rights reserved . ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. HAMT Core Tests (define (run-hamt-core-tests) (test-begin "hamt-core") (test-group "(hash-array-mapped-trie fragment->mask)" (test-equal = 0 (fragment->mask 0)) (test-equal = 1 (fragment->mask 1)) (test-equal = 3 (fragment->mask 2)) (test-equal = 7 (fragment->mask 3))) (test-end))
null
https://raw.githubusercontent.com/ashinn/chibi-scheme/8b27ce97265e5028c61b2386a86a2c43c1cfba0d/lib/srfi/146/hamt-test.scm
scheme
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
HAMT Core Tests Copyright MMXV - MMXVII . All rights reserved . files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , HAMT Core Tests (define (run-hamt-core-tests) (test-begin "hamt-core") (test-group "(hash-array-mapped-trie fragment->mask)" (test-equal = 0 (fragment->mask 0)) (test-equal = 1 (fragment->mask 1)) (test-equal = 3 (fragment->mask 2)) (test-equal = 7 (fragment->mask 3))) (test-end))
374fc533688c6564aca176b4f7d389d94f103bcd1c64b3088dd79e4adf40228f
janestreet/accessor_base
accessor_list.mli
open! Base open! Import (** See also: [Accessor_core.List] *) (** Access [()] iff the list is empty. *) val nil : (_, unit, 'a list, [< variant ]) Accessor.t (** Access the head and tail of a list, if it is nonempty. *) val cons : ( 'i -> 'a * 'a list -> 'b * 'b list , 'i -> 'a list -> 'b list , [< variant ] ) Accessor.General.t (** Access an element at a specified position in a list, if the list is long enough to have such an element. *) val nth : int -> (_, 'a, 'a list, [< optional ]) Accessor.t (** Access a reversed version of a list. *) val reversed : ( 'i -> 'a list -> 'b list , 'i -> 'a list -> 'b list , [< isomorphism ] ) Accessor.General.t (** [prefixed prefix ~equal] verifies that a list starts with [prefix], accessing the suffix left after stripping the prefix if so. *) val prefixed : 'a list -> equal:('a -> 'a -> bool) -> (_, 'a list, 'a list, [< variant ]) Accessor.t (** [suffixed suffix ~equal] verifies that a list ends with [suffix], accessing the prefix left after stripping the suffix if so. *) val suffixed : 'a list -> equal:('a -> 'a -> bool) -> (_, 'a list, 'a list, [< variant ]) Accessor.t (** Access every element in a list. *) val each : ('i -> 'a -> 'b, 'i -> 'a list -> 'b list, [< many ]) Accessor.General.t (** Like [each], but also provides you with the index of each element. *) val eachi : (int * 'it -> 'a -> 'b, 'it -> 'a list -> 'b list, [< many ]) Accessor.General.t include Accessor.Monad.S with type 'a t := 'a list
null
https://raw.githubusercontent.com/janestreet/accessor_base/8384c29a37e557168ae8a43b2a5a531f0ffc16e4/src/accessor_list.mli
ocaml
* See also: [Accessor_core.List] * Access [()] iff the list is empty. * Access the head and tail of a list, if it is nonempty. * Access an element at a specified position in a list, if the list is long enough to have such an element. * Access a reversed version of a list. * [prefixed prefix ~equal] verifies that a list starts with [prefix], accessing the suffix left after stripping the prefix if so. * [suffixed suffix ~equal] verifies that a list ends with [suffix], accessing the prefix left after stripping the suffix if so. * Access every element in a list. * Like [each], but also provides you with the index of each element.
open! Base open! Import val nil : (_, unit, 'a list, [< variant ]) Accessor.t val cons : ( 'i -> 'a * 'a list -> 'b * 'b list , 'i -> 'a list -> 'b list , [< variant ] ) Accessor.General.t val nth : int -> (_, 'a, 'a list, [< optional ]) Accessor.t val reversed : ( 'i -> 'a list -> 'b list , 'i -> 'a list -> 'b list , [< isomorphism ] ) Accessor.General.t val prefixed : 'a list -> equal:('a -> 'a -> bool) -> (_, 'a list, 'a list, [< variant ]) Accessor.t val suffixed : 'a list -> equal:('a -> 'a -> bool) -> (_, 'a list, 'a list, [< variant ]) Accessor.t val each : ('i -> 'a -> 'b, 'i -> 'a list -> 'b list, [< many ]) Accessor.General.t val eachi : (int * 'it -> 'a -> 'b, 'it -> 'a list -> 'b list, [< many ]) Accessor.General.t include Accessor.Monad.S with type 'a t := 'a list
725c475b3eaa58478dc98884efcf92e212c1c71013dc92cfd2f8e2a1d07dd952
RyanGlScott/gists
WorkingAroundT12564.hs
# LANGUAGE DataKinds # {-# LANGUAGE GADTs #-} # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module WorkingAroundT12564 where import Data.Kind import Data.Type.Equality data Nat = Z | S Nat type family Len (xs :: [a]) :: Nat where Len '[] = Z Len (_:xs) = S (Len xs) data Fin :: Nat -> Type where FZ :: Fin (S n) FS :: Fin n -> Fin (S n) ----- -- Attempt 1 (failed) ----- type family At ( xs : : [ a ] ) ( i : : Fin ( Len xs ) ) : : a where At ( x : _ ) FZ = x At ( _ : xs ) ( FS i ) = At xs i type family At (xs :: [a]) (i :: Fin (Len xs)) :: a where At (x:_) FZ = x At (_:xs) (FS i) = At xs i -} • Illegal type synonym family application ‘ _ 1 ’ in instance : At @a ( ( ' :) @a x _ 1 ) ( ' FZ @(Len @a _ 1 ) ) • In the equations for closed type family ‘ At ’ In the type family declaration for ‘ At ’ | | At ( x : _ ) FZ = x | ^^^^^^^^^^^^^^^^^^^^ • Illegal type synonym family application ‘Len @a _1’ in instance: At @a ((':) @a x _1) ('FZ @(Len @a _1)) • In the equations for closed type family ‘At’ In the type family declaration for ‘At’ | | At (x:_) FZ = x | ^^^^^^^^^^^^^^^^^^^^ -} ----- Attempt 2 ----- data LenProp :: forall a. [a] -> Nat -> Type where LenNil :: LenProp '[] Z LenCons :: LenProp xs n -> LenProp (x:xs) (S n) type family At' (xs :: [a]) (lp :: LenProp xs n) (i :: Fin n) :: a where At' (x:_) (LenCons _) FZ = x At' (_:xs) (LenCons lp) (FS i) = At' xs lp i type family EncodeLenProp (xs :: [a]) :: LenProp xs (Len xs) where EncodeLenProp '[] = LenNil EncodeLenProp (_:xs) = LenCons (EncodeLenProp xs) type family At (xs :: [a]) (i :: Fin (Len xs)) :: a where At xs i = At' xs (EncodeLenProp xs) i -- Unit tests test1 :: At '[True] FZ :~: True test1 = Refl test2 :: At [True, False] FZ :~: True test2 = Refl test3 :: At [True, False] (FS FZ) :~: False test3 = Refl ----- -- Attempt 2 (alternative approach) ----- data Vec :: Nat -> Type -> Type where VNil :: Vec Z a (:>) :: a -> Vec n a -> Vec (S n) a type family ListToVec (l :: [a]) :: Vec (Len l) a where ListToVec '[] = VNil ListToVec (x:xs) = x :> ListToVec xs type family AtAlternative' (xs :: Vec n a) (i :: Fin n) :: a where AtAlternative' (x :> _) FZ = x AtAlternative' (_ :> xs) (FS i) = AtAlternative' xs i type family AtAlternative (xs :: [a]) (i :: Fin (Len xs)) :: a where AtAlternative xs i = AtAlternative' (ListToVec xs) i -- Unit tests test1Alternative :: AtAlternative '[True] FZ :~: True test1Alternative = Refl test2Alternative :: AtAlternative [True, False] FZ :~: True test2Alternative = Refl test3Alternative :: AtAlternative [True, False] (FS FZ) :~: False test3Alternative = Refl
null
https://raw.githubusercontent.com/RyanGlScott/gists/81a033bc52c721d566d724122818e422718552a9/src/WorkingAroundT12564.hs
haskell
# LANGUAGE GADTs # --- Attempt 1 (failed) --- --- --- Unit tests --- Attempt 2 (alternative approach) --- Unit tests
# LANGUAGE DataKinds # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module WorkingAroundT12564 where import Data.Kind import Data.Type.Equality data Nat = Z | S Nat type family Len (xs :: [a]) :: Nat where Len '[] = Z Len (_:xs) = S (Len xs) data Fin :: Nat -> Type where FZ :: Fin (S n) FS :: Fin n -> Fin (S n) type family At ( xs : : [ a ] ) ( i : : Fin ( Len xs ) ) : : a where At ( x : _ ) FZ = x At ( _ : xs ) ( FS i ) = At xs i type family At (xs :: [a]) (i :: Fin (Len xs)) :: a where At (x:_) FZ = x At (_:xs) (FS i) = At xs i -} • Illegal type synonym family application ‘ _ 1 ’ in instance : At @a ( ( ' :) @a x _ 1 ) ( ' FZ @(Len @a _ 1 ) ) • In the equations for closed type family ‘ At ’ In the type family declaration for ‘ At ’ | | At ( x : _ ) FZ = x | ^^^^^^^^^^^^^^^^^^^^ • Illegal type synonym family application ‘Len @a _1’ in instance: At @a ((':) @a x _1) ('FZ @(Len @a _1)) • In the equations for closed type family ‘At’ In the type family declaration for ‘At’ | | At (x:_) FZ = x | ^^^^^^^^^^^^^^^^^^^^ -} Attempt 2 data LenProp :: forall a. [a] -> Nat -> Type where LenNil :: LenProp '[] Z LenCons :: LenProp xs n -> LenProp (x:xs) (S n) type family At' (xs :: [a]) (lp :: LenProp xs n) (i :: Fin n) :: a where At' (x:_) (LenCons _) FZ = x At' (_:xs) (LenCons lp) (FS i) = At' xs lp i type family EncodeLenProp (xs :: [a]) :: LenProp xs (Len xs) where EncodeLenProp '[] = LenNil EncodeLenProp (_:xs) = LenCons (EncodeLenProp xs) type family At (xs :: [a]) (i :: Fin (Len xs)) :: a where At xs i = At' xs (EncodeLenProp xs) i test1 :: At '[True] FZ :~: True test1 = Refl test2 :: At [True, False] FZ :~: True test2 = Refl test3 :: At [True, False] (FS FZ) :~: False test3 = Refl data Vec :: Nat -> Type -> Type where VNil :: Vec Z a (:>) :: a -> Vec n a -> Vec (S n) a type family ListToVec (l :: [a]) :: Vec (Len l) a where ListToVec '[] = VNil ListToVec (x:xs) = x :> ListToVec xs type family AtAlternative' (xs :: Vec n a) (i :: Fin n) :: a where AtAlternative' (x :> _) FZ = x AtAlternative' (_ :> xs) (FS i) = AtAlternative' xs i type family AtAlternative (xs :: [a]) (i :: Fin (Len xs)) :: a where AtAlternative xs i = AtAlternative' (ListToVec xs) i test1Alternative :: AtAlternative '[True] FZ :~: True test1Alternative = Refl test2Alternative :: AtAlternative [True, False] FZ :~: True test2Alternative = Refl test3Alternative :: AtAlternative [True, False] (FS FZ) :~: False test3Alternative = Refl
767827296ca8315ab0660efcaba699a1746a98508df33d572cc01116e2113463
hexresearch/nixdeploy
Aeson.hs
-- | Overrides aeson TH functions to generate instances module Deployment.Nix.Aeson( A.deriveJSON , dropPrefixOptions ) where import Control.Monad import Data.Aeson.TH (Options (..), SumEncoding (..)) import Data.Aeson.Types (camelTo2, ToJSON(..), FromJSON(..), Value(..)) import Data.Char (isUpper, toLower, isLower, isPunctuation) import Data.List (findIndex) import Data.Monoid import Data.Text (unpack) import qualified Data.Aeson.TH as A | Converts first symbol to lower case headToLower :: String -> String headToLower [] = [] headToLower (x:xs) = toLower x : xs | Drop prefix of name until first upper letter is occured stripFieldPrefix :: String -> String stripFieldPrefix = dropWhile (not . isUpper) -- | Strip prefix of name that exactly matches specified prefix stripExactPrefix :: String -- ^ Prefix -> String -- ^ Name -> String -- ^ Name without prefix stripExactPrefix = go where go [] name = name go (p : ps) name@(x : xs) | p == x = go ps xs | otherwise = name go _ [] = [] -- | Remove from names things like ' and etc dropPunctuation :: String -> String dropPunctuation = filter (not . isPunctuation) -- | Drop upper case prefixes from constructor names -- -- Example: > > > stripConstructorPrefix " ABCombo " " Combo " -- > > > stripConstructorPrefix " Combo " " Combo " stripConstructorPrefix :: String -> String stripConstructorPrefix t = maybe t (flip drop t . decrementSafe) $ findIndex isLower t where decrementSafe 0 = 0 decrementSafe i = i - 1 -- | Options for aeson TH generator, that generates following fields: -- -- * without punctuation -- * without lowercase prefix -- -- And generates constructor tags without uppercase prefixes with -- 'stripConstructorPrefix'. -- Sums are encoded as one object with only one field corresponding the -- constructor used. dropPrefixOptions :: Options dropPrefixOptions = A.defaultOptions { fieldLabelModifier = headToLower . stripFieldPrefix . dropPunctuation , constructorTagModifier = stripConstructorPrefix , sumEncoding = ObjectWithSingleField }
null
https://raw.githubusercontent.com/hexresearch/nixdeploy/d68c3555662490fbe1c304f8343d1590bc3f6f15/src/Deployment/Nix/Aeson.hs
haskell
| Overrides aeson TH functions to generate instances | Strip prefix of name that exactly matches specified prefix ^ Prefix ^ Name ^ Name without prefix | Remove from names things like ' and etc | Drop upper case prefixes from constructor names Example: | Options for aeson TH generator, that generates following fields: * without punctuation * without lowercase prefix And generates constructor tags without uppercase prefixes with 'stripConstructorPrefix'. constructor used.
module Deployment.Nix.Aeson( A.deriveJSON , dropPrefixOptions ) where import Control.Monad import Data.Aeson.TH (Options (..), SumEncoding (..)) import Data.Aeson.Types (camelTo2, ToJSON(..), FromJSON(..), Value(..)) import Data.Char (isUpper, toLower, isLower, isPunctuation) import Data.List (findIndex) import Data.Monoid import Data.Text (unpack) import qualified Data.Aeson.TH as A | Converts first symbol to lower case headToLower :: String -> String headToLower [] = [] headToLower (x:xs) = toLower x : xs | Drop prefix of name until first upper letter is occured stripFieldPrefix :: String -> String stripFieldPrefix = dropWhile (not . isUpper) stripExactPrefix = go where go [] name = name go (p : ps) name@(x : xs) | p == x = go ps xs | otherwise = name go _ [] = [] dropPunctuation :: String -> String dropPunctuation = filter (not . isPunctuation) > > > stripConstructorPrefix " ABCombo " " Combo " > > > stripConstructorPrefix " Combo " " Combo " stripConstructorPrefix :: String -> String stripConstructorPrefix t = maybe t (flip drop t . decrementSafe) $ findIndex isLower t where decrementSafe 0 = 0 decrementSafe i = i - 1 Sums are encoded as one object with only one field corresponding the dropPrefixOptions :: Options dropPrefixOptions = A.defaultOptions { fieldLabelModifier = headToLower . stripFieldPrefix . dropPunctuation , constructorTagModifier = stripConstructorPrefix , sumEncoding = ObjectWithSingleField }
8bd74b11c39121ff84494d0a71d537c1192836ac40a92e9f061dca2e2f9248e5
swlkr/majestic-web
html.clj
(ns {{name}}.html (:require [hiccup.page :refer [html5 include-css include-js]] [hiccup.form :refer [hidden-field text-field submit-button]] [ring.middleware.anti-forgery :refer [*anti-forgery-token*]])) (defn layout [content] (html5 [:head [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (include-css "//unpkg.com/tachyons@4.7.0/css/tachyons.min.css")] [:body content (include-js "//cdnjs.cloudflare.com/ajax/libs/turbolinks/5.0.0/turbolinks.min.js")])) (defn center [& content] [:div {:class "flex flex-column justify-center items-center vh-100"} content]) (defn link ([url content attrs] [:a (merge {:href url} attrs) content]) ([url content] (link url content nil))) (defn info [content] (when (not (nil? content)) [:div {:class "pa3 w-100 mb2 bg-lightest-blue navy tc"} [:span {:class "lh-title"} content]])) (defn render-optional [optional] (if (true? optional) [:span {:class "normal black-80"} "(optional)"] nil)) (defn label ([{:keys [for optional]} & content] [:label {:for for :class "f6 b db mb2"} content (render-optional optional)]) ([content] [:label {:class "f6 b db mb2"} content])) (defn input [{:keys [type name value placeholder class]}] [:input {:name name :class (str "input-reset ba b--black-20 pa2 mb2 db w-100" (or class "")) :type type :placeholder placeholder :value (or value "")}]) (defn submit [value] [:input {:class "b bn ph3 pv2 input-reset bg-blue white grow pointer f6 dib w-100" :type "submit" :value value}]) (defn csrf-field [] (hidden-field "__anti-forgery-token" *anti-forgery-token*)) (defn form [{:keys [method action]} & content] [:form {:method (or method "post") :action action :class "pa4 black-80"} (csrf-field) content]) (defn error-page [error] (let [message (.getMessage error)] (layout (center message)))) (defn forbidden-page [] (layout (center "I can't let you do that"))) (defn not-found-page [] (layout (center "Sorry, couldn't find what you were looking for")))
null
https://raw.githubusercontent.com/swlkr/majestic-web/3d247f6b5ccc4ff3662a64544a4ca27beada971b/resources/leiningen/new/majestic_web/html.clj
clojure
(ns {{name}}.html (:require [hiccup.page :refer [html5 include-css include-js]] [hiccup.form :refer [hidden-field text-field submit-button]] [ring.middleware.anti-forgery :refer [*anti-forgery-token*]])) (defn layout [content] (html5 [:head [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (include-css "//unpkg.com/tachyons@4.7.0/css/tachyons.min.css")] [:body content (include-js "//cdnjs.cloudflare.com/ajax/libs/turbolinks/5.0.0/turbolinks.min.js")])) (defn center [& content] [:div {:class "flex flex-column justify-center items-center vh-100"} content]) (defn link ([url content attrs] [:a (merge {:href url} attrs) content]) ([url content] (link url content nil))) (defn info [content] (when (not (nil? content)) [:div {:class "pa3 w-100 mb2 bg-lightest-blue navy tc"} [:span {:class "lh-title"} content]])) (defn render-optional [optional] (if (true? optional) [:span {:class "normal black-80"} "(optional)"] nil)) (defn label ([{:keys [for optional]} & content] [:label {:for for :class "f6 b db mb2"} content (render-optional optional)]) ([content] [:label {:class "f6 b db mb2"} content])) (defn input [{:keys [type name value placeholder class]}] [:input {:name name :class (str "input-reset ba b--black-20 pa2 mb2 db w-100" (or class "")) :type type :placeholder placeholder :value (or value "")}]) (defn submit [value] [:input {:class "b bn ph3 pv2 input-reset bg-blue white grow pointer f6 dib w-100" :type "submit" :value value}]) (defn csrf-field [] (hidden-field "__anti-forgery-token" *anti-forgery-token*)) (defn form [{:keys [method action]} & content] [:form {:method (or method "post") :action action :class "pa4 black-80"} (csrf-field) content]) (defn error-page [error] (let [message (.getMessage error)] (layout (center message)))) (defn forbidden-page [] (layout (center "I can't let you do that"))) (defn not-found-page [] (layout (center "Sorry, couldn't find what you were looking for")))
758e2c9ed5593659e35619f371d6abdfce4be419f489413444fb4041da88885b
aperiodic/many-worlds
api.clj
(ns many-worlds.api (:require [clojure.edn :as edn] [compojure.core :refer [GET PUT routes]] [compojure.route :as route] [quil.core :as quil] [quil.applet :refer [*applet*]] [qutils.animation :as _a] ; purely to load the defrecords [qutils.curve :as _c] ; purely to load the defrecords [ring.adapter.jetty :refer [run-jetty]] [ring.middleware.cors :refer [wrap-cors]] [ring.middleware.keyword-params :refer [wrap-keyword-params]] [ring.middleware.params :refer [wrap-params]] [ring.util.response :as resp]) (:import [java.awt Color] [java.awt.image BufferedImage] [java.io ByteArrayInputStream ByteArrayOutputStream] [javax.imageio ImageIO] [qutils.animation Animation] [qutils.curve Curve])) (defn parse-frame-opts ([opts] (parse-frame-opts opts nil)) ([opts state] (let [{t-str :t, w-str :width, h-str :height} opts t (let [t (edn/read-string (or t-str "latest"))] (if (number? t) t (or (-> state :path keys last) 0))) read-dim (fn [string] (let [value (edn/read-string (or string "-1"))] (if (and (number? value) (pos? value)) value nil)))] {:t t, :width (read-dim w-str), :height (read-dim h-str)}))) (defn- argb->rgb [image w h] (let [rgb-image (BufferedImage. w h BufferedImage/TYPE_INT_RGB) graphics (.createGraphics rgb-image)] (.drawImage graphics image 0 0 Color/WHITE nil) rgb-image)) (defn ^BufferedImage render-frame "Given a quil sketch, the default width and height, the sketch's configure and draw functions, and the `t` (time) and `s` (scale) at which to render sketch, return a rendering of the sketch subject to `t` and `s` as a BufferedImage." [sketch w h configure! draw! t s] (binding [*applet* sketch] (let [w' (int (* w s)) h' (int (* h s)) g (quil/create-graphics w' h' :java2d)] (quil/with-graphics g (configure!) (quil/scale (double s)) (draw! t)) (-> (.getImage g) (argb->rgb w' h'))))) (defn handler "Given a state atom, a var containing a quil sketch, nominal sketch width and height, and configure and draw functions for the sketch, define an API handler that serves rendered images of the sketch, the state atom's current value, and can reset the state atom with a submitted state value. The `draw!` function must be a function of `t`. Any other state it wishes to rely on it must handle itself; if only the current position of the bezier walk is needed, then `t` alone will suffice. The `configure!` function should *not* be the sketch's setup function, since it will be called every time that a frame is rendered. The purpose of the `configure!` function is to set any global quil sketch options such as smoothing or color mode. There is no guarantee that any of these global sketch settings will be persisted between renderings. Here's a detailed breakdown of the routes that the handler serves: - GET '/state' Return the EDN-serialized contents of the state atom. Does not accept any query parameters. - PUT '/state' Replace the sketch's state atom with the state submitted in the request body. The request body must be in EDN format. Does not accept any query parameters. Returns a 302 redirect to 'frame.png?t=latest'. - GET '/frame.png' Return a PNG rendering of the sketch by calling the `configure!` and `draw!` functions. Accepts three query parameters: `t`, `width` and `height`. The size of the frame may be defined by specifying either the `width` or `height` in pixels. The returned image will have the specified length in that dimension, with the other dimension scaled as appropriate to preserve the sketch's aspect ratio. If both are specified, only the `width` value is used, and the height is again derived using the aspect ratio. The time of the frame is governed by the `t` query parameter. If it's a number that number is used directly; if it's not a number, or it's not provided, then the time corresponding to the start of the last generated bezier segment of the random walk is used." [!state sketch-var w h configure! draw!] (-> (routes (GET "/state" [] (pr-str @!state)) (PUT "/state" [:as {body :body}] (reset! !state (read-string (slurp body))) {:status 204}) (GET "/frame.bmp" [t width height] (let [frame-opts {:t t, :width width, :height height} {:keys [t width height]} (parse-frame-opts frame-opts @!state) scale (cond width (/ width (* w 1.0)) height (/ height (* h 1.0)) :else 1) image (render-frame @sketch-var w h configure! draw! t scale) stream (new ByteArrayOutputStream)] (ImageIO/write image "BMP" stream) {:status 200 :headers {"Content-Type" "image/bmp"} :body (ByteArrayInputStream. (.toByteArray stream))})) ;; console application (GET "/" [] (resp/resource-response "public/index.html")) (route/resources "")) (wrap-cors #".*localhost(:\d+)?") wrap-keyword-params wrap-params))
null
https://raw.githubusercontent.com/aperiodic/many-worlds/be6401e973f8107d22f5ad865fda0ae63e52ab6f/src/clj/many_worlds/api.clj
clojure
purely to load the defrecords purely to load the defrecords if only the current position of the bezier walk if it's not a number, or it's console application
(ns many-worlds.api (:require [clojure.edn :as edn] [compojure.core :refer [GET PUT routes]] [compojure.route :as route] [quil.core :as quil] [quil.applet :refer [*applet*]] [ring.adapter.jetty :refer [run-jetty]] [ring.middleware.cors :refer [wrap-cors]] [ring.middleware.keyword-params :refer [wrap-keyword-params]] [ring.middleware.params :refer [wrap-params]] [ring.util.response :as resp]) (:import [java.awt Color] [java.awt.image BufferedImage] [java.io ByteArrayInputStream ByteArrayOutputStream] [javax.imageio ImageIO] [qutils.animation Animation] [qutils.curve Curve])) (defn parse-frame-opts ([opts] (parse-frame-opts opts nil)) ([opts state] (let [{t-str :t, w-str :width, h-str :height} opts t (let [t (edn/read-string (or t-str "latest"))] (if (number? t) t (or (-> state :path keys last) 0))) read-dim (fn [string] (let [value (edn/read-string (or string "-1"))] (if (and (number? value) (pos? value)) value nil)))] {:t t, :width (read-dim w-str), :height (read-dim h-str)}))) (defn- argb->rgb [image w h] (let [rgb-image (BufferedImage. w h BufferedImage/TYPE_INT_RGB) graphics (.createGraphics rgb-image)] (.drawImage graphics image 0 0 Color/WHITE nil) rgb-image)) (defn ^BufferedImage render-frame "Given a quil sketch, the default width and height, the sketch's configure and draw functions, and the `t` (time) and `s` (scale) at which to render sketch, return a rendering of the sketch subject to `t` and `s` as a BufferedImage." [sketch w h configure! draw! t s] (binding [*applet* sketch] (let [w' (int (* w s)) h' (int (* h s)) g (quil/create-graphics w' h' :java2d)] (quil/with-graphics g (configure!) (quil/scale (double s)) (draw! t)) (-> (.getImage g) (argb->rgb w' h'))))) (defn handler "Given a state atom, a var containing a quil sketch, nominal sketch width and height, and configure and draw functions for the sketch, define an API handler that serves rendered images of the sketch, the state atom's current value, and can reset the state atom with a submitted state value. The `draw!` function must be a function of `t`. Any other state it wishes to is needed, then `t` alone will suffice. The `configure!` function should *not* be the sketch's setup function, since it will be called every time that a frame is rendered. The purpose of the `configure!` function is to set any global quil sketch options such as smoothing or color mode. There is no guarantee that any of these global sketch settings will be persisted between renderings. Here's a detailed breakdown of the routes that the handler serves: - GET '/state' Return the EDN-serialized contents of the state atom. Does not accept any query parameters. - PUT '/state' Replace the sketch's state atom with the state submitted in the request body. The request body must be in EDN format. Does not accept any query parameters. Returns a 302 redirect to 'frame.png?t=latest'. - GET '/frame.png' Return a PNG rendering of the sketch by calling the `configure!` and `draw!` functions. Accepts three query parameters: `t`, `width` and `height`. The size of the frame may be defined by specifying either the `width` or `height` in pixels. The returned image will have the specified length in that dimension, with the other dimension scaled as appropriate to preserve the sketch's aspect ratio. If both are specified, only the `width` value is used, and the height is again derived using the aspect ratio. The time of the frame is governed by the `t` query parameter. If not provided, then the time corresponding to the start of the last generated bezier segment of the random walk is used." [!state sketch-var w h configure! draw!] (-> (routes (GET "/state" [] (pr-str @!state)) (PUT "/state" [:as {body :body}] (reset! !state (read-string (slurp body))) {:status 204}) (GET "/frame.bmp" [t width height] (let [frame-opts {:t t, :width width, :height height} {:keys [t width height]} (parse-frame-opts frame-opts @!state) scale (cond width (/ width (* w 1.0)) height (/ height (* h 1.0)) :else 1) image (render-frame @sketch-var w h configure! draw! t scale) stream (new ByteArrayOutputStream)] (ImageIO/write image "BMP" stream) {:status 200 :headers {"Content-Type" "image/bmp"} :body (ByteArrayInputStream. (.toByteArray stream))})) (GET "/" [] (resp/resource-response "public/index.html")) (route/resources "")) (wrap-cors #".*localhost(:\d+)?") wrap-keyword-params wrap-params))
846109705d40d774d6b220617d738047d9d287766e51037c4643237b25bad20a
margnus1/kid-mud
colour.erl
Copyright ( c ) 2012 , , and See the file license.txt for copying permission . -module(colour). -include_lib("eunit/include/eunit.hrl"). -export([text/2, text/3]). -type io_list() :: [integer() | io_list()]. -type colour() :: black | red | green | yellow | blue | magenta | cyan | white. @doc Formats the text Text with foreground colour Foreground %% @todo Implement it -spec text(_Foreground :: colour(), Text :: io_list()) -> io_list(). text(Foreground, Text) -> ["<span style='color:", atom_to_list(Foreground), "'>", Text, "</span>"]. %% The control characters are escaped by io:fprint so this is currently useless [ 27 , 91 , $ 9 , $ 0 + ) , $ m , Text , 27 , 91 , $ m ] . %% @doc Formats the text Text with foreground colour Foreground %% and background colour Background %% @end %% @todo Implement it -spec text(_Foreground :: colour(), _Background :: colour(), Text :: io_list()) -> io_list(). text(Foreground, Background, Text) -> ["<span style='color:", atom_to_list(Foreground), " ;background-color:", atom_to_list(Background), "'>", Text, "</span>"].
null
https://raw.githubusercontent.com/margnus1/kid-mud/56d759593e79d9c8ba7c45f9fc716d65de2554a7/src/colour.erl
erlang
@todo Implement it The control characters are escaped by io:fprint so this is currently useless @doc and background colour Background @end @todo Implement it
Copyright ( c ) 2012 , , and See the file license.txt for copying permission . -module(colour). -include_lib("eunit/include/eunit.hrl"). -export([text/2, text/3]). -type io_list() :: [integer() | io_list()]. -type colour() :: black | red | green | yellow | blue | magenta | cyan | white. @doc Formats the text Text with foreground colour Foreground -spec text(_Foreground :: colour(), Text :: io_list()) -> io_list(). text(Foreground, Text) -> ["<span style='color:", atom_to_list(Foreground), "'>", Text, "</span>"]. [ 27 , 91 , $ 9 , $ 0 + ) , $ m , Text , 27 , 91 , $ m ] . Formats the text Text with foreground colour Foreground -spec text(_Foreground :: colour(), _Background :: colour(), Text :: io_list()) -> io_list(). text(Foreground, Background, Text) -> ["<span style='color:", atom_to_list(Foreground), " ;background-color:", atom_to_list(Background), "'>", Text, "</span>"].
86af837e7e6e86ce05a67aeee9f081e6100fd8388e335de01d82544980a81794
mrosset/nomad
repl.scm
;; repl.scm Copyright ( C ) 2017 - 2018 < > This file is part of Nomad Nomad is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. Nomad is distributed in the hope that it will be useful , but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ;; See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along ;; with this program. If not, see </>. (define-module (nomad repl) #:use-module (ice-9 rdelim) #:use-module (ice-9 readline) #:use-module (ice-9 threads) #:use-module (nomad app) #:use-module (nomad options) #:use-module (rnrs bytevectors) #:use-module (ice-9 textual-ports) #:use-module (system repl coop-server) #:use-module (system repl server) #:export ( repl-server server-force-delete server-start server-start-coop socket-file)) (define socket-file "/tmp/nomad-socket") (define repl-server #f) (define (poll-server) (poll-coop-repl-server repl-server) (usleep 100000) (poll-server)) (define (server-start-coop socket-file) (when (file-exists? socket-file) (delete-file socket-file)) (set! repl-server (spawn-coop-repl-server (make-unix-domain-server-socket #:path socket-file))) (make-thread (poll-server))) (define (server-start socket-file) "Spawn a UNIX domain sockert REPL in a new thread. The file is the value of socket-file." (when (file-exists? socket-file) (delete-file socket-file)) (spawn-server (make-unix-domain-server-socket #:path socket-file))) (define (socket-exists? socket-file) (access? socket-file R_OK)) ;; FIXME: if socket clients are connected, (server-force-delete) will throw an excpetion . Which gives us a truncated Backtrace to ;; stderr. More then likely the end user wants to kill connected ;; clients. Maybe we should prompt the user? Either way we should ;; handle the exception in a cleaner way. (define (server-force-delete socket-file) "Unconditionally delete connection file. Stops REPL server and client connections first." (stop-server-and-clients!) (delete-file socket-file)) (define (read-socket port) (do ((line (read-line port) (read-line port))) ((eof-object? line)) (display line) (newline))) (define client-port #f) (define (read-until-prompt port) "Read from PORT until prompt has been read or the end-of-file was reached." (while #t (let ((c (get-char port))) (when (eof-object? c) (break)) ;; if char is > and there is a space after, assume this is the ;; prompt and stop (when (and (char=? c #\>) (char=? (lookahead-char port) #\space)) (get-char port) (break)) (display c)))) (define (client-start path) "Starts a client connected to a guile unix socket REPL server" (when (not (access? path W_OK)) (display "socket is not readable") (exit)) ;; setup readline (activate-readline) (set-readline-prompt! "> ") ;; create port and enter readline loop (let ((port (socket PF_UNIX SOCK_STREAM 0))) (connect port AF_UNIX path) (read-until-prompt port) (newline) (while #t (let ((line (readline))) (write-line line port) (read-until-prompt port) (newline))))) (define-public (write-socket input socket-file) "Write string INPUT to guile unix socket at SOCKET-FILE. The guile instance on the socket will evaluate INPUT expression. It is not possible to return anything from the socket at this point" (let ((port (socket PF_UNIX SOCK_STREAM 0))) (catch #t (lambda () (connect port AF_UNIX socket-file) (write-line input port)) (lambda (key . parameters) (format #t "~s: ~s ~s" key parameters socket-file)))))
null
https://raw.githubusercontent.com/mrosset/nomad/c94a65ede94d86eff039d2ef62d5ef3df609568a/scheme/nomad/repl.scm
scheme
repl.scm (at your option) any later version. WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. with this program. If not, see </>. FIXME: if socket clients are connected, (server-force-delete) will stderr. More then likely the end user wants to kill connected clients. Maybe we should prompt the user? Either way we should handle the exception in a cleaner way. if char is > and there is a space after, assume this is the prompt and stop setup readline create port and enter readline loop
Copyright ( C ) 2017 - 2018 < > This file is part of Nomad Nomad is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or Nomad is distributed in the hope that it will be useful , but You should have received a copy of the GNU General Public License along (define-module (nomad repl) #:use-module (ice-9 rdelim) #:use-module (ice-9 readline) #:use-module (ice-9 threads) #:use-module (nomad app) #:use-module (nomad options) #:use-module (rnrs bytevectors) #:use-module (ice-9 textual-ports) #:use-module (system repl coop-server) #:use-module (system repl server) #:export ( repl-server server-force-delete server-start server-start-coop socket-file)) (define socket-file "/tmp/nomad-socket") (define repl-server #f) (define (poll-server) (poll-coop-repl-server repl-server) (usleep 100000) (poll-server)) (define (server-start-coop socket-file) (when (file-exists? socket-file) (delete-file socket-file)) (set! repl-server (spawn-coop-repl-server (make-unix-domain-server-socket #:path socket-file))) (make-thread (poll-server))) (define (server-start socket-file) "Spawn a UNIX domain sockert REPL in a new thread. The file is the value of socket-file." (when (file-exists? socket-file) (delete-file socket-file)) (spawn-server (make-unix-domain-server-socket #:path socket-file))) (define (socket-exists? socket-file) (access? socket-file R_OK)) throw an excpetion . Which gives us a truncated Backtrace to (define (server-force-delete socket-file) "Unconditionally delete connection file. Stops REPL server and client connections first." (stop-server-and-clients!) (delete-file socket-file)) (define (read-socket port) (do ((line (read-line port) (read-line port))) ((eof-object? line)) (display line) (newline))) (define client-port #f) (define (read-until-prompt port) "Read from PORT until prompt has been read or the end-of-file was reached." (while #t (let ((c (get-char port))) (when (eof-object? c) (break)) (when (and (char=? c #\>) (char=? (lookahead-char port) #\space)) (get-char port) (break)) (display c)))) (define (client-start path) "Starts a client connected to a guile unix socket REPL server" (when (not (access? path W_OK)) (display "socket is not readable") (exit)) (activate-readline) (set-readline-prompt! "> ") (let ((port (socket PF_UNIX SOCK_STREAM 0))) (connect port AF_UNIX path) (read-until-prompt port) (newline) (while #t (let ((line (readline))) (write-line line port) (read-until-prompt port) (newline))))) (define-public (write-socket input socket-file) "Write string INPUT to guile unix socket at SOCKET-FILE. The guile instance on the socket will evaluate INPUT expression. It is not possible to return anything from the socket at this point" (let ((port (socket PF_UNIX SOCK_STREAM 0))) (catch #t (lambda () (connect port AF_UNIX socket-file) (write-line input port)) (lambda (key . parameters) (format #t "~s: ~s ~s" key parameters socket-file)))))
5e722f37785bd374320f14bdc807af6c17f0bfe2e847cfec7b70a925e8539d9d
DavidAlphaFox/RabbitMQ
rabbit_access_control.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_access_control). -include("rabbit.hrl"). -export([check_user_pass_login/2, check_user_login/2, check_user_loopback/2, check_vhost_access/2, check_resource_access/3]). %%---------------------------------------------------------------------------- -ifdef(use_specs). -export_type([permission_atom/0]). -type(permission_atom() :: 'configure' | 'read' | 'write'). -spec(check_user_pass_login/2 :: (rabbit_types:username(), rabbit_types:password()) -> {'ok', rabbit_types:user()} | {'refused', string(), [any()]}). -spec(check_user_login/2 :: (rabbit_types:username(), [{atom(), any()}]) -> {'ok', rabbit_types:user()} | {'refused', string(), [any()]}). -spec(check_user_loopback/2 :: (rabbit_types:username(), rabbit_net:socket() | inet:ip_address()) -> 'ok' | 'not_allowed'). -spec(check_vhost_access/2 :: (rabbit_types:user(), rabbit_types:vhost()) -> 'ok' | rabbit_types:channel_exit()). -spec(check_resource_access/3 :: (rabbit_types:user(), rabbit_types:r(atom()), permission_atom()) -> 'ok' | rabbit_types:channel_exit()). -endif. %%---------------------------------------------------------------------------- check_user_pass_login(Username, Password) -> check_user_login(Username, [{password, Password}]). check_user_login(Username, AuthProps) -> {ok, Modules} = application:get_env(rabbit, auth_backends), R = lists:foldl( fun ({ModN, ModZ}, {refused, _, _}) -> %% Different modules for authN vs authZ. So authenticate %% with authN module, then if that succeeds do %% passwordless (i.e pre-authenticated) login with authZ %% module, and use the #user{} the latter gives us. case try_login(ModN, Username, AuthProps) of {ok, _} -> try_login(ModZ, Username, []); Else -> Else end; (Mod, {refused, _, _}) -> %% Same module for authN and authZ. Just take the result %% it gives us try_login(Mod, Username, AuthProps); (_, {ok, User}) -> %% We've successfully authenticated. Skip to the end... {ok, User} end, {refused, "No modules checked '~s'", [Username]}, Modules), rabbit_event:notify(case R of {ok, _User} -> user_authentication_success; _ -> user_authentication_failure end, [{name, Username}]), R. try_login(Module, Username, AuthProps) -> case Module:check_user_login(Username, AuthProps) of {error, E} -> {refused, "~s failed authenticating ~s: ~p~n", [Module, Username, E]}; Else -> Else end. check_user_loopback(Username, SockOrAddr) -> {ok, Users} = application:get_env(rabbit, loopback_users), case rabbit_net:is_loopback(SockOrAddr) orelse not lists:member(Username, Users) of true -> ok; false -> not_allowed end. check_vhost_access(User = #user{ username = Username, auth_backend = Module }, VHostPath) -> check_access( fun() -> TODO this could be an andalso shortcut under > R13A case rabbit_vhost:exists(VHostPath) of false -> false; true -> Module:check_vhost_access(User, VHostPath) end end, Module, "access to vhost '~s' refused for user '~s'", [VHostPath, Username]). check_resource_access(User, R = #resource{kind = exchange, name = <<"">>}, Permission) -> check_resource_access(User, R#resource{name = <<"amq.default">>}, Permission); check_resource_access(User = #user{username = Username, auth_backend = Module}, Resource, Permission) -> check_access( fun() -> Module:check_resource_access(User, Resource, Permission) end, Module, "access to ~s refused for user '~s'", [rabbit_misc:rs(Resource), Username]). check_access(Fun, Module, ErrStr, ErrArgs) -> Allow = case Fun() of {error, E} -> rabbit_log:error(ErrStr ++ " by ~s: ~p~n", ErrArgs ++ [Module, E]), false; Else -> Else end, case Allow of true -> ok; false -> rabbit_misc:protocol_error(access_refused, ErrStr, ErrArgs) end.
null
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/src/rabbit_access_control.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Different modules for authN vs authZ. So authenticate with authN module, then if that succeeds do passwordless (i.e pre-authenticated) login with authZ module, and use the #user{} the latter gives us. Same module for authN and authZ. Just take the result it gives us We've successfully authenticated. Skip to the end...
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_access_control). -include("rabbit.hrl"). -export([check_user_pass_login/2, check_user_login/2, check_user_loopback/2, check_vhost_access/2, check_resource_access/3]). -ifdef(use_specs). -export_type([permission_atom/0]). -type(permission_atom() :: 'configure' | 'read' | 'write'). -spec(check_user_pass_login/2 :: (rabbit_types:username(), rabbit_types:password()) -> {'ok', rabbit_types:user()} | {'refused', string(), [any()]}). -spec(check_user_login/2 :: (rabbit_types:username(), [{atom(), any()}]) -> {'ok', rabbit_types:user()} | {'refused', string(), [any()]}). -spec(check_user_loopback/2 :: (rabbit_types:username(), rabbit_net:socket() | inet:ip_address()) -> 'ok' | 'not_allowed'). -spec(check_vhost_access/2 :: (rabbit_types:user(), rabbit_types:vhost()) -> 'ok' | rabbit_types:channel_exit()). -spec(check_resource_access/3 :: (rabbit_types:user(), rabbit_types:r(atom()), permission_atom()) -> 'ok' | rabbit_types:channel_exit()). -endif. check_user_pass_login(Username, Password) -> check_user_login(Username, [{password, Password}]). check_user_login(Username, AuthProps) -> {ok, Modules} = application:get_env(rabbit, auth_backends), R = lists:foldl( fun ({ModN, ModZ}, {refused, _, _}) -> case try_login(ModN, Username, AuthProps) of {ok, _} -> try_login(ModZ, Username, []); Else -> Else end; (Mod, {refused, _, _}) -> try_login(Mod, Username, AuthProps); (_, {ok, User}) -> {ok, User} end, {refused, "No modules checked '~s'", [Username]}, Modules), rabbit_event:notify(case R of {ok, _User} -> user_authentication_success; _ -> user_authentication_failure end, [{name, Username}]), R. try_login(Module, Username, AuthProps) -> case Module:check_user_login(Username, AuthProps) of {error, E} -> {refused, "~s failed authenticating ~s: ~p~n", [Module, Username, E]}; Else -> Else end. check_user_loopback(Username, SockOrAddr) -> {ok, Users} = application:get_env(rabbit, loopback_users), case rabbit_net:is_loopback(SockOrAddr) orelse not lists:member(Username, Users) of true -> ok; false -> not_allowed end. check_vhost_access(User = #user{ username = Username, auth_backend = Module }, VHostPath) -> check_access( fun() -> TODO this could be an andalso shortcut under > R13A case rabbit_vhost:exists(VHostPath) of false -> false; true -> Module:check_vhost_access(User, VHostPath) end end, Module, "access to vhost '~s' refused for user '~s'", [VHostPath, Username]). check_resource_access(User, R = #resource{kind = exchange, name = <<"">>}, Permission) -> check_resource_access(User, R#resource{name = <<"amq.default">>}, Permission); check_resource_access(User = #user{username = Username, auth_backend = Module}, Resource, Permission) -> check_access( fun() -> Module:check_resource_access(User, Resource, Permission) end, Module, "access to ~s refused for user '~s'", [rabbit_misc:rs(Resource), Username]). check_access(Fun, Module, ErrStr, ErrArgs) -> Allow = case Fun() of {error, E} -> rabbit_log:error(ErrStr ++ " by ~s: ~p~n", ErrArgs ++ [Module, E]), false; Else -> Else end, case Allow of true -> ok; false -> rabbit_misc:protocol_error(access_refused, ErrStr, ErrArgs) end.
06a236976573af2c0cef40ab64260ab1a7f79103be3f4caa8be5c49d69977434
ericclack/overtone-loops
pattern_03_06.clj
(ns overtone-loops.dph-book.pattern-03-06 (:use [overtone.live] [overtone-loops.loops] [overtone-loops.samples])) ;; Stop any currently playing music and clear any patterns (set-up) BAR1 BAR2 BAR3 BAR4 ;; 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & (defloop closed-hhs 1/2 cymbal-closed [7 5 7 4 6 3 8 4 ]) (defloop sds 1/2 snare [_ _ 8 _ _ _ 8 _ ]) (defloop kicks 1/2 kick [8 _ _ _ 8 _ _ _ 8 _ _ _ 8 8 _ _ 8 8 _ _ _ 8 _ _ 8 8 _ 8 _ 8 _ 8]) ;; Variations 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & (def kicks02 [8 _ _ _ 8 _ _ _ 8 _ _ _ 8 8 _ _]) (def kicks03 [8 _ _ _ 8 _ _ _ 8 _ _ _ 8 8 _ _ 8 8 _ _ _ 8 _ _]) (def sds1 [_ _ 8 _ _ 8 _ 8]) (def kicks1 [8 _ _ 8 8 _ _ _]) (def sds2 [_ _ 8 _ 8 _ 8 _]) (def kicks2 [8 _ _ 8 _ 8 _ _]) (def sds3 [_ 8 _ _ _ _ 8 _]) (def kicks3 [8 _ _ 8 8 _ _ 8]) (def sds4 [_ 8 _ _ 8 _ 8 _]) (def kicks4 [8 _ 8 8 _ 8 _ _]) (bpm 160) (beats-in-bar 4) ;; We use at-bar to schedule the loops (at-bar 1 same HH pattern all the way through (closed-hhs) (sds) (kicks) ) ;; Now mix it up: ;; Bars 5-8 (at-bar 5 3 bar ) (at-bar 8 (sds sds1) (kicks kicks1) ) (at-bar 9 2 bar ) (at-bar 11 (sds sds3) (kicks kicks3) ) (at-bar 12 (sds sds4) (kicks kicks4) ) (at-bar 13 ;; Bars 13-16 (sds :first) (kicks kicks02) ) (at-bar 15 (sds sds2) (kicks kicks2) ) (at-bar 16 (sds sds1) (kicks kicks1) ) Back to usual 17 - 20 (at-bar 17 (sds :first) (kicks :first) ) (at-bar 21 (sds []) (kicks []) ) (at-bar 22 (closed-hhs [])) ;;(stop)
null
https://raw.githubusercontent.com/ericclack/overtone-loops/54b0c230c1e6bd3d378583af982db4e9ae4bda69/src/overtone_loops/dph_book/pattern_03_06.clj
clojure
Stop any currently playing music and clear any patterns 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & Variations We use at-bar to schedule the loops Now mix it up: Bars 5-8 Bars 13-16 (stop)
(ns overtone-loops.dph-book.pattern-03-06 (:use [overtone.live] [overtone-loops.loops] [overtone-loops.samples])) (set-up) BAR1 BAR2 BAR3 BAR4 (defloop closed-hhs 1/2 cymbal-closed [7 5 7 4 6 3 8 4 ]) (defloop sds 1/2 snare [_ _ 8 _ _ _ 8 _ ]) (defloop kicks 1/2 kick [8 _ _ _ 8 _ _ _ 8 _ _ _ 8 8 _ _ 8 8 _ _ _ 8 _ _ 8 8 _ 8 _ 8 _ 8]) 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & // 1 & 2 & 3 & 4 & (def kicks02 [8 _ _ _ 8 _ _ _ 8 _ _ _ 8 8 _ _]) (def kicks03 [8 _ _ _ 8 _ _ _ 8 _ _ _ 8 8 _ _ 8 8 _ _ _ 8 _ _]) (def sds1 [_ _ 8 _ _ 8 _ 8]) (def kicks1 [8 _ _ 8 8 _ _ _]) (def sds2 [_ _ 8 _ 8 _ 8 _]) (def kicks2 [8 _ _ 8 _ 8 _ _]) (def sds3 [_ 8 _ _ _ _ 8 _]) (def kicks3 [8 _ _ 8 8 _ _ 8]) (def sds4 [_ 8 _ _ 8 _ 8 _]) (def kicks4 [8 _ 8 8 _ 8 _ _]) (bpm 160) (beats-in-bar 4) (at-bar 1 same HH pattern all the way through (closed-hhs) (sds) (kicks) ) (at-bar 5 3 bar ) (at-bar 8 (sds sds1) (kicks kicks1) ) (at-bar 9 2 bar ) (at-bar 11 (sds sds3) (kicks kicks3) ) (at-bar 12 (sds sds4) (kicks kicks4) ) (at-bar 13 (sds :first) (kicks kicks02) ) (at-bar 15 (sds sds2) (kicks kicks2) ) (at-bar 16 (sds sds1) (kicks kicks1) ) Back to usual 17 - 20 (at-bar 17 (sds :first) (kicks :first) ) (at-bar 21 (sds []) (kicks []) ) (at-bar 22 (closed-hhs []))
83593d8c2f30463f91bcf62020eb6cd5bfc08647bad772530bad38711810d09e
lexi-lambda/litpub
api-unit.rkt
#lang racket/unit (require "../model.rkt" "../util/client-ip.rkt" "../util/jsexpr.rkt" "api-sig.rkt") (import) (export api^) (define (story-likes:create req story-id) (let ([ip (client-ip req)]) (create-story-like! story-id ip) (response/jsexpr #:code 201 #:message #"Created" `#hasheq((status . "ok") (score . ,(story-count-likes story-id)))))) (define (story-likes:destroy req story-id) (let ([ip (client-ip req)]) (destroy-story-like! story-id ip) (response/jsexpr `#hasheq((status . "ok") (score . ,(story-count-likes story-id))))))
null
https://raw.githubusercontent.com/lexi-lambda/litpub/2f326c1c0e0ee8cad0b8b3f7f7b4a49a02ac62b5/handler/api-unit.rkt
racket
#lang racket/unit (require "../model.rkt" "../util/client-ip.rkt" "../util/jsexpr.rkt" "api-sig.rkt") (import) (export api^) (define (story-likes:create req story-id) (let ([ip (client-ip req)]) (create-story-like! story-id ip) (response/jsexpr #:code 201 #:message #"Created" `#hasheq((status . "ok") (score . ,(story-count-likes story-id)))))) (define (story-likes:destroy req story-id) (let ([ip (client-ip req)]) (destroy-story-like! story-id ip) (response/jsexpr `#hasheq((status . "ok") (score . ,(story-count-likes story-id))))))
b920105759c8095a37fb1271b6bca070d5af1a2bb35caf7a49b32d1cbed30962
pablo-meier/ScrabbleCheat
movesearch_tests.erl
-module(movesearch_tests). -include_lib("eunit/include/eunit.hrl"). runs Eunit tests from a .eunit directory ; cd out , maybe %% later find a way to more cleanly set $PROJECT_HOME or some such %% var. -define(TESTDICT, lists:concat([code:priv_dir(scrabblecheat), "/testdict.dict"])). -import(game_parser, [new_board/0]). -import(board, [place_word/4, get_tile/3]). -import(gaddag, [get_branch_from_string/2]). -import(tile, [get_tile_location/1, new_tile/4]). -import(move, [new_move/0, duplicate_moves/2]). -import(followstruct, [make_followstruct/5]). -import(movesearch, [generate_move_candidate_locations/1, get_zoomtiles/3, create_origin_followstructs/2, get_moves_from_candidate/5]). get_fixture_gaddag() -> case whereis(giant_bintrie) of undefined -> ok; _Else -> unregister(giant_bintrie) end, bin_trie:start_from_file(?TESTDICT), bin_trie:get_root(twl06). sample_board() -> Empty = new_board(), place_word("CARE", down, {7,7}, Empty). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Getting candidate locations candidate_location1_test() -> Lst = generate_move_candidate_locations(sample_board()), lists:foreach(fun (X) -> ?assert(contains_tile(X, Lst)) end, [{6,7},{11,7},{7,6},{7,8},{8,6},{8,8},{9,6},{9,8},{10,6},{10,8}]). candidate_location2_test() -> Board = place_word("POPPYCOCK", right, {6,2}, new_board()), Lst = generate_move_candidate_locations(Board), lists:foreach(fun (X) -> ?assert(contains_tile(X, Lst)) end, [{6,1},{6,11},{7,2},{7,3},{7,4},{7,5},{7,8},{7,9},{7,10}, {5,2},{5,3},{5,4},{5,5},{5,8},{5,9},{5,10}]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Zoomtiles zoomtile_first_test() -> Board = sample_board(), Gaddag = get_fixture_gaddag(), SolutionPairs = [{new_tile(none,none,6,7), [get_tile(10, 7, Board)]}, {new_tile(none,none,7,6), [get_tile(7, 7, Board)]}, {new_tile(none,none,8,6), [get_tile(8, 7, Board)]}, {new_tile(none,none,11,7), [get_tile(7, 7, Board)]}, {new_tile(none,none,9,8), [get_tile(9, 7, Board)]}], lists:foreach(fun ({Candidate, Solution}) -> Result = lists:map(fun ({X, _, _}) -> X end, get_zoomtiles(Candidate, Board, Gaddag)), ?assert(Result == Solution) end, SolutionPairs). zoomtile_second_test() -> Board = board:place_word("BLE", right, {8, 8}, sample_board()), Gaddag = get_fixture_gaddag(), SolutionPairs = [{new_tile(none,none,6,7), [get_tile(10, 7, Board)]}, {new_tile(none,none,7,6), [get_tile(7, 7, Board)]}, {new_tile(none,none,8,6), [get_tile(8, 10, Board)]}, {new_tile(none,none,8,11), [get_tile(8, 7, Board)]}, {new_tile(none,none,9,8), [get_tile(9, 7, Board), get_tile(8, 8, Board)]}, {new_tile(none,none,7,8), [get_tile(7, 7, Board), get_tile(8, 8, Board)]}], lists:foreach(fun ({Candidate, Solution}) -> Result = lists:map(fun ({X, _, _}) -> X end, get_zoomtiles(Candidate, Board, Gaddag)), ?assert(Result == Solution) end, SolutionPairs). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Move Generation get_move_from_candidate_open_horiz_test() -> Direction = left, Gaddag = get_branch_from_string("ELBA",get_fixture_gaddag()), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(7, 6, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 10, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , ABLER , TABLE , TABLES , STABLE Solutions = [{move, [{{character, $S}, none, {7,6}}]}, {move, [{{character, $R}, none, {7,11}}]}, {move, [{{character, $T}, none, {7,6}}]}, {move, [{{character, $T}, none, {7,6}},{{character, $S}, none, {7,11}}]}, {move, [{{character, $T}, none, {7,6}},{{character, $S}, none, {7,5}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). get_move_from_candidate_open_vert_test() -> Direction = up, Gaddag = get_branch_from_string("ELBA", get_fixture_gaddag()), Board = place_word("ABLE", down, {7,7}, new_board()), Candidate = get_tile(6, 7, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(10, 7, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , ABLER , TABLES , STABLE Solutions = [{move, [{{character, $S}, none, {6,7}}]}, {move, [{{character, $R}, none, {11,7}}]}, {move, [{{character, $T}, none, {6,7}}]}, {move, [{{character, $T}, none, {6,7}},{{character, $S}, none, {11,7}}]}, {move, [{{character, $T}, none, {6,7}},{{character, $S}, none, {5,7}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). %% Walls left_wall_candidate_generate_test() -> Direction = right, Gaddag = get_branch_from_string("A&BLE", get_fixture_gaddag()), Board = place_word("ABLE", right, {7,1}, new_board()), Candidate = get_tile(7, 5, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 1, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , ABLER , TABLES , STABLE Solutions = [{move, [{{character, $R}, none, {7,5}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). right_wall_candidate_generate_test() -> Direction = left, Gaddag = get_branch_from_string("ELBA", get_fixture_gaddag()), Board = place_word("ABLE", right, {7,12}, new_board()), Candidate = get_tile(7, 11, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 15, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , STABLE Solutions = [{move, [{{character, $S}, none, {7,11}}]}, {move, [{{character, $T}, none, {7,11}}]}, {move, [{{character, $T}, none, {7,11}},{{character, $S}, none, {7,10}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). top_wall_candidate_generate_test() -> Direction = down, Gaddag = get_branch_from_string("A&BLE", get_fixture_gaddag()), Board = place_word("ABLE", down, {1,7}, new_board()), Candidate = get_tile(5,7, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(1,7, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , ABLER , TABLES , STABLE Solutions = [{move, [{{character, $R}, none, {5,7}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). bottom_wall_candidate_generate_test() -> Direction = up, Gaddag = get_branch_from_string("ELBA", get_fixture_gaddag()), Board = place_word("ABLE", down, {12,7}, new_board()), Candidate = get_tile(11, 7, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(15, 7, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , STABLE Solutions = [{move, [{{character, $S}, none, {11,7}}]}, {move, [{{character, $T}, none, {11,7}}]}, {move, [{{character, $T}, none, {11,7}},{{character, $S}, none, {10,7}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). Corners perpendicular_leftwise_test() -> Direction = up, Gaddag = get_fixture_gaddag(), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(7, 6, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 6, Board), Rack = "LASSO", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Test LASSO , where second 'S ' hooks onto ABLE for SABLE Solutions = [{move, [{{character, $L}, none, {4,6}}, {{character, $A}, none, {5,6}}, {{character, $S}, triple_letter_score, {6,6}}, {{character, $S}, none, {7,6}}, {{character, $O}, none, {8,6}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). perpendicular_underside_test() -> Direction = left, Gaddag = get_fixture_gaddag(), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(8, 7, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(8, 7, Board), Rack = "ZYGOTE", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), %% Test ZYGOTE, where 'TE' hooks onto bottom of AB in ABLE Solutions = [{move, [{{character, $Z}, none, {8,3}}, {{character, $Y}, double_letter_score, {8,4}}, {{character, $G}, none, {8,5}}, {{character, $O}, none, {8,6}}, {{character, $T}, none, {8,7}}, {{character, $E}, double_word_score, {8,8}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). perpendicular_upperside_test() -> Direction = left, Gaddag = get_fixture_gaddag(), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(6, 9, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(6, 9, Board), Rack = "ABHOR", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Test ABHOR , where ' AB ' hooks onto top of LE in ABLE I made up the word AL , it 's in the test dictionary Solutions = [{move, [{{character, $A}, none, {6,9}}, {{character, $B}, triple_letter_score, {6,10}}, {{character, $H}, none, {6,11}}, {{character, $O}, none, {6,12}}, {{character, $R}, none, {6,13}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). perpendicular_rightside_test() -> Direction = up, Gaddag = get_fixture_gaddag(), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(7, 11, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 11, Board), Rack = "CHRONO", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Test CHRONO , where ' R ' hooks onto ABLE to form ABLER Solution = {move, [{{character, $C}, double_word_score, {5,11}}, {{character, $H}, none, {6,11}}, {{character, $R}, none, {7,11}}, {{character, $O}, none, {8,11}}, {{character, $N}, none, {9,11}}, {{character, $O}, none, {10,11}}]}, ?assert(lists:any(fun (Y) -> duplicate_moves(Solution, Y) end, Run)). %% this has been crashing in the client, worth automating able_zygote_test() -> Gaddag = get_fixture_gaddag(), Board = place_word("ZYGOTE", right, {8,4}, place_word("ABLE", right, {7,8}, new_board())), Rack = "PAULIE", Moves = movesearch:get_all_moves(Board, Rack, Gaddag), ?assert(lists:any(fun (X) -> move:duplicate_moves(X, {move, [{{character, $A}, none, {9,5}}]}) end, Moves)). %% this has been crashing in the client, worth automating sigma_perpendicular_test() -> Gaddag = get_fixture_gaddag(), Board = place_word("ZYGOTE", right, {8,4}, place_word("ABLE", right, {7,8}, new_board())), Rack = "SIGMA", Moves = movesearch:get_all_moves(Board, Rack, Gaddag), ForbiddenMove = {move, [{{character, $S}, none, {8, 10}}, {{character, $I}, none, {9,10}}, {{character, $G}, triple_letter_score, {10,10}}, {{character, $M}, none, {11,10}}, {{character, $A}, none, {12,10}}]}, Forbidden2 = {move, [{{character, $A}, none, {8, 10}}, {{character, $M}, none, {8,11}}]}, ?assert(lists:all(fun (X) -> not move:duplicate_moves(X, ForbiddenMove) end, Moves)), ?assert(lists:all(fun (X) -> not move:duplicate_moves(X, Forbidden2) end, Moves)). %% Another incorrect move generation, from not checking neighbors in same plane. stigma_peps_test() -> Gaddag = get_fixture_gaddag(), LetterPlacements = [{"ABLE", right, {7,7}}, {"Z", down, {6,9}}, {"OTYS", down, {8,9}}, {"IZY", right, {11,10}}], FirstBoard = lists:foldl(fun ({Word, Dir, Loc}, Accum) -> place_word(Word, Dir, Loc, Accum) end, new_board(), LetterPlacements), Rack = "SIGMAT", Moves = movesearch:get_all_moves(FirstBoard, Rack, Gaddag), ForbiddenMove = {move, [{{character, $S}, none, {8,3}}, {{character, $T}, double_letter_score, {8,4}}, {{character, $I}, none, {8,5}}, {{character, $G}, none, {8,6}}, {{character, $M}, none, {8,7}}, {{character, $A}, double_word_score, {8,8}}]}, ?assert(lists:all(fun (X) -> not move:duplicate_moves(X, ForbiddenMove) end, Moves)), NextBoard = place_word("MIR", down, {8,11}, place_word("AS", down, {12,11}, FirstBoard)), NewMoves = movesearch:get_all_moves(NextBoard, "SLTNPEP", Gaddag), % Salt-n-Pepa's here! Forbidden2 = {move, [{{character, $P}, none, {4,11}}, {{character, $E}, none, {5,11}}, {{character, $P}, none, {6,11}}, {{character, $S}, none, {7,11}}]}, ?assert(lists:all(fun (X) -> not move:duplicate_moves(X, Forbidden2) end, NewMoves)). island_1_test() -> Gaddag = get_fixture_gaddag(), PreBoard = place_word("BAS", down, {7,8}, place_word("TERM", right, {10,7}, new_board())), Board = place_word("TRA", down, {7,10}, PreBoard), Rack = "TARYO", Moves = movesearch:get_all_moves(Board, Rack, Gaddag), The word BAT , between BASE and TRAM Connected1 = {move, [{{character, $A}, double_letter_score, {7, 9}}]}, %% The word TARRY, between BASE and TRAM Connected2 = {move, [{{character, $T}, none, {8, 7}}, {{character, $R}, none, {8, 9}}, {{character, $Y}, none, {8, 11}}]}, ?assert(lists:any(fun (X) -> move:duplicate_moves(X, Connected1) end, Moves)), ?assert(lists:any(fun (X) -> move:duplicate_moves(X, Connected2) end, Moves)). %% Bug where we forget to remove 'none' values after get_adjacent calls %% in finding zoomtiles for candidates. Below is a case where it failed. candidate_on_edge_test() -> Gaddag = get_fixture_gaddag(), Board = place_word("AFOUL", down, {10,10}, new_board()), Rack = "SLUANIQ", %% Should not throw error -- function clause, get_tile_letter, [none] movesearch:get_all_moves(Board, Rack, Gaddag). %% No Moves? %% Crosses Wildcards wildcard_1_test() -> Direction = left, Gaddag = get_branch_from_string("ELBA", get_fixture_gaddag()), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(7, 6, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 10, Board), Rack = "*", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Test CHRONO , where ' R ' hooks onto ABLE to form ABLER Solutions = [{move, [{{wildcard, $T}, none, {7,6}}]}, {move, [{{wildcard, $S}, none, {7,6}}]}, {move, [{{wildcard, $R}, none, {7,11}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HELPERS %% Test whether or not the list contains the parametrized tile. contains_tile({Row, Col}, Lst) -> Return = lists:any(fun (X) -> {Row2, Col2} = get_tile_location(X), Row =:= Row2 andalso Col =:= Col2 end, Lst), case Return of true -> true; _False -> io:format("~p,~p Were not present. ~n", [Row,Col]) end.
null
https://raw.githubusercontent.com/pablo-meier/ScrabbleCheat/718cb768a910f2ba7ca6cd1d2aae0e342849bf0a/code/server/test/eunit/movesearch_tests.erl
erlang
later find a way to more cleanly set $PROJECT_HOME or some such var. Getting candidate locations Zoomtiles Move Generation Walls Test ZYGOTE, where 'TE' hooks onto bottom of AB in ABLE this has been crashing in the client, worth automating this has been crashing in the client, worth automating Another incorrect move generation, from not checking neighbors in same plane. Salt-n-Pepa's here! The word TARRY, between BASE and TRAM Bug where we forget to remove 'none' values after get_adjacent calls in finding zoomtiles for candidates. Below is a case where it failed. Should not throw error -- function clause, get_tile_letter, [none] No Moves? Crosses HELPERS Test whether or not the list contains the parametrized tile.
-module(movesearch_tests). -include_lib("eunit/include/eunit.hrl"). runs Eunit tests from a .eunit directory ; cd out , maybe -define(TESTDICT, lists:concat([code:priv_dir(scrabblecheat), "/testdict.dict"])). -import(game_parser, [new_board/0]). -import(board, [place_word/4, get_tile/3]). -import(gaddag, [get_branch_from_string/2]). -import(tile, [get_tile_location/1, new_tile/4]). -import(move, [new_move/0, duplicate_moves/2]). -import(followstruct, [make_followstruct/5]). -import(movesearch, [generate_move_candidate_locations/1, get_zoomtiles/3, create_origin_followstructs/2, get_moves_from_candidate/5]). get_fixture_gaddag() -> case whereis(giant_bintrie) of undefined -> ok; _Else -> unregister(giant_bintrie) end, bin_trie:start_from_file(?TESTDICT), bin_trie:get_root(twl06). sample_board() -> Empty = new_board(), place_word("CARE", down, {7,7}, Empty). candidate_location1_test() -> Lst = generate_move_candidate_locations(sample_board()), lists:foreach(fun (X) -> ?assert(contains_tile(X, Lst)) end, [{6,7},{11,7},{7,6},{7,8},{8,6},{8,8},{9,6},{9,8},{10,6},{10,8}]). candidate_location2_test() -> Board = place_word("POPPYCOCK", right, {6,2}, new_board()), Lst = generate_move_candidate_locations(Board), lists:foreach(fun (X) -> ?assert(contains_tile(X, Lst)) end, [{6,1},{6,11},{7,2},{7,3},{7,4},{7,5},{7,8},{7,9},{7,10}, {5,2},{5,3},{5,4},{5,5},{5,8},{5,9},{5,10}]). zoomtile_first_test() -> Board = sample_board(), Gaddag = get_fixture_gaddag(), SolutionPairs = [{new_tile(none,none,6,7), [get_tile(10, 7, Board)]}, {new_tile(none,none,7,6), [get_tile(7, 7, Board)]}, {new_tile(none,none,8,6), [get_tile(8, 7, Board)]}, {new_tile(none,none,11,7), [get_tile(7, 7, Board)]}, {new_tile(none,none,9,8), [get_tile(9, 7, Board)]}], lists:foreach(fun ({Candidate, Solution}) -> Result = lists:map(fun ({X, _, _}) -> X end, get_zoomtiles(Candidate, Board, Gaddag)), ?assert(Result == Solution) end, SolutionPairs). zoomtile_second_test() -> Board = board:place_word("BLE", right, {8, 8}, sample_board()), Gaddag = get_fixture_gaddag(), SolutionPairs = [{new_tile(none,none,6,7), [get_tile(10, 7, Board)]}, {new_tile(none,none,7,6), [get_tile(7, 7, Board)]}, {new_tile(none,none,8,6), [get_tile(8, 10, Board)]}, {new_tile(none,none,8,11), [get_tile(8, 7, Board)]}, {new_tile(none,none,9,8), [get_tile(9, 7, Board), get_tile(8, 8, Board)]}, {new_tile(none,none,7,8), [get_tile(7, 7, Board), get_tile(8, 8, Board)]}], lists:foreach(fun ({Candidate, Solution}) -> Result = lists:map(fun ({X, _, _}) -> X end, get_zoomtiles(Candidate, Board, Gaddag)), ?assert(Result == Solution) end, SolutionPairs). get_move_from_candidate_open_horiz_test() -> Direction = left, Gaddag = get_branch_from_string("ELBA",get_fixture_gaddag()), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(7, 6, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 10, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , ABLER , TABLE , TABLES , STABLE Solutions = [{move, [{{character, $S}, none, {7,6}}]}, {move, [{{character, $R}, none, {7,11}}]}, {move, [{{character, $T}, none, {7,6}}]}, {move, [{{character, $T}, none, {7,6}},{{character, $S}, none, {7,11}}]}, {move, [{{character, $T}, none, {7,6}},{{character, $S}, none, {7,5}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). get_move_from_candidate_open_vert_test() -> Direction = up, Gaddag = get_branch_from_string("ELBA", get_fixture_gaddag()), Board = place_word("ABLE", down, {7,7}, new_board()), Candidate = get_tile(6, 7, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(10, 7, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , ABLER , TABLES , STABLE Solutions = [{move, [{{character, $S}, none, {6,7}}]}, {move, [{{character, $R}, none, {11,7}}]}, {move, [{{character, $T}, none, {6,7}}]}, {move, [{{character, $T}, none, {6,7}},{{character, $S}, none, {11,7}}]}, {move, [{{character, $T}, none, {6,7}},{{character, $S}, none, {5,7}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). left_wall_candidate_generate_test() -> Direction = right, Gaddag = get_branch_from_string("A&BLE", get_fixture_gaddag()), Board = place_word("ABLE", right, {7,1}, new_board()), Candidate = get_tile(7, 5, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 1, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , ABLER , TABLES , STABLE Solutions = [{move, [{{character, $R}, none, {7,5}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). right_wall_candidate_generate_test() -> Direction = left, Gaddag = get_branch_from_string("ELBA", get_fixture_gaddag()), Board = place_word("ABLE", right, {7,12}, new_board()), Candidate = get_tile(7, 11, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 15, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , STABLE Solutions = [{move, [{{character, $S}, none, {7,11}}]}, {move, [{{character, $T}, none, {7,11}}]}, {move, [{{character, $T}, none, {7,11}},{{character, $S}, none, {7,10}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). top_wall_candidate_generate_test() -> Direction = down, Gaddag = get_branch_from_string("A&BLE", get_fixture_gaddag()), Board = place_word("ABLE", down, {1,7}, new_board()), Candidate = get_tile(5,7, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(1,7, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , ABLER , TABLES , STABLE Solutions = [{move, [{{character, $R}, none, {5,7}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). bottom_wall_candidate_generate_test() -> Direction = up, Gaddag = get_branch_from_string("ELBA", get_fixture_gaddag()), Board = place_word("ABLE", down, {12,7}, new_board()), Candidate = get_tile(11, 7, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(15, 7, Board), Rack = "TRS", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Should include SABLE , TABLE , STABLE Solutions = [{move, [{{character, $S}, none, {11,7}}]}, {move, [{{character, $T}, none, {11,7}}]}, {move, [{{character, $T}, none, {11,7}},{{character, $S}, none, {10,7}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). Corners perpendicular_leftwise_test() -> Direction = up, Gaddag = get_fixture_gaddag(), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(7, 6, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 6, Board), Rack = "LASSO", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Test LASSO , where second 'S ' hooks onto ABLE for SABLE Solutions = [{move, [{{character, $L}, none, {4,6}}, {{character, $A}, none, {5,6}}, {{character, $S}, triple_letter_score, {6,6}}, {{character, $S}, none, {7,6}}, {{character, $O}, none, {8,6}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). perpendicular_underside_test() -> Direction = left, Gaddag = get_fixture_gaddag(), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(8, 7, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(8, 7, Board), Rack = "ZYGOTE", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Solutions = [{move, [{{character, $Z}, none, {8,3}}, {{character, $Y}, double_letter_score, {8,4}}, {{character, $G}, none, {8,5}}, {{character, $O}, none, {8,6}}, {{character, $T}, none, {8,7}}, {{character, $E}, double_word_score, {8,8}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). perpendicular_upperside_test() -> Direction = left, Gaddag = get_fixture_gaddag(), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(6, 9, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(6, 9, Board), Rack = "ABHOR", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Test ABHOR , where ' AB ' hooks onto top of LE in ABLE I made up the word AL , it 's in the test dictionary Solutions = [{move, [{{character, $A}, none, {6,9}}, {{character, $B}, triple_letter_score, {6,10}}, {{character, $H}, none, {6,11}}, {{character, $O}, none, {6,12}}, {{character, $R}, none, {6,13}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). perpendicular_rightside_test() -> Direction = up, Gaddag = get_fixture_gaddag(), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(7, 11, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 11, Board), Rack = "CHRONO", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Test CHRONO , where ' R ' hooks onto ABLE to form ABLER Solution = {move, [{{character, $C}, double_word_score, {5,11}}, {{character, $H}, none, {6,11}}, {{character, $R}, none, {7,11}}, {{character, $O}, none, {8,11}}, {{character, $N}, none, {9,11}}, {{character, $O}, none, {10,11}}]}, ?assert(lists:any(fun (Y) -> duplicate_moves(Solution, Y) end, Run)). able_zygote_test() -> Gaddag = get_fixture_gaddag(), Board = place_word("ZYGOTE", right, {8,4}, place_word("ABLE", right, {7,8}, new_board())), Rack = "PAULIE", Moves = movesearch:get_all_moves(Board, Rack, Gaddag), ?assert(lists:any(fun (X) -> move:duplicate_moves(X, {move, [{{character, $A}, none, {9,5}}]}) end, Moves)). sigma_perpendicular_test() -> Gaddag = get_fixture_gaddag(), Board = place_word("ZYGOTE", right, {8,4}, place_word("ABLE", right, {7,8}, new_board())), Rack = "SIGMA", Moves = movesearch:get_all_moves(Board, Rack, Gaddag), ForbiddenMove = {move, [{{character, $S}, none, {8, 10}}, {{character, $I}, none, {9,10}}, {{character, $G}, triple_letter_score, {10,10}}, {{character, $M}, none, {11,10}}, {{character, $A}, none, {12,10}}]}, Forbidden2 = {move, [{{character, $A}, none, {8, 10}}, {{character, $M}, none, {8,11}}]}, ?assert(lists:all(fun (X) -> not move:duplicate_moves(X, ForbiddenMove) end, Moves)), ?assert(lists:all(fun (X) -> not move:duplicate_moves(X, Forbidden2) end, Moves)). stigma_peps_test() -> Gaddag = get_fixture_gaddag(), LetterPlacements = [{"ABLE", right, {7,7}}, {"Z", down, {6,9}}, {"OTYS", down, {8,9}}, {"IZY", right, {11,10}}], FirstBoard = lists:foldl(fun ({Word, Dir, Loc}, Accum) -> place_word(Word, Dir, Loc, Accum) end, new_board(), LetterPlacements), Rack = "SIGMAT", Moves = movesearch:get_all_moves(FirstBoard, Rack, Gaddag), ForbiddenMove = {move, [{{character, $S}, none, {8,3}}, {{character, $T}, double_letter_score, {8,4}}, {{character, $I}, none, {8,5}}, {{character, $G}, none, {8,6}}, {{character, $M}, none, {8,7}}, {{character, $A}, double_word_score, {8,8}}]}, ?assert(lists:all(fun (X) -> not move:duplicate_moves(X, ForbiddenMove) end, Moves)), NextBoard = place_word("MIR", down, {8,11}, place_word("AS", down, {12,11}, FirstBoard)), Forbidden2 = {move, [{{character, $P}, none, {4,11}}, {{character, $E}, none, {5,11}}, {{character, $P}, none, {6,11}}, {{character, $S}, none, {7,11}}]}, ?assert(lists:all(fun (X) -> not move:duplicate_moves(X, Forbidden2) end, NewMoves)). island_1_test() -> Gaddag = get_fixture_gaddag(), PreBoard = place_word("BAS", down, {7,8}, place_word("TERM", right, {10,7}, new_board())), Board = place_word("TRA", down, {7,10}, PreBoard), Rack = "TARYO", Moves = movesearch:get_all_moves(Board, Rack, Gaddag), The word BAT , between BASE and TRAM Connected1 = {move, [{{character, $A}, double_letter_score, {7, 9}}]}, Connected2 = {move, [{{character, $T}, none, {8, 7}}, {{character, $R}, none, {8, 9}}, {{character, $Y}, none, {8, 11}}]}, ?assert(lists:any(fun (X) -> move:duplicate_moves(X, Connected1) end, Moves)), ?assert(lists:any(fun (X) -> move:duplicate_moves(X, Connected2) end, Moves)). candidate_on_edge_test() -> Gaddag = get_fixture_gaddag(), Board = place_word("AFOUL", down, {10,10}, new_board()), Rack = "SLUANIQ", movesearch:get_all_moves(Board, Rack, Gaddag). Wildcards wildcard_1_test() -> Direction = left, Gaddag = get_branch_from_string("ELBA", get_fixture_gaddag()), Board = place_word("ABLE", right, {7,7}, new_board()), Candidate = get_tile(7, 6, Board), Followstruct = make_followstruct(Candidate, Direction, Gaddag, Board, new_move()), Zoomtile = get_tile(7, 10, Board), Rack = "*", Accum = [], Run = get_moves_from_candidate(Followstruct, Zoomtile, Rack, Accum, Gaddag), Test CHRONO , where ' R ' hooks onto ABLE to form ABLER Solutions = [{move, [{{wildcard, $T}, none, {7,6}}]}, {move, [{{wildcard, $S}, none, {7,6}}]}, {move, [{{wildcard, $R}, none, {7,11}}]}], lists:foreach(fun (X) -> ?assert(lists:any(fun (Y) -> duplicate_moves(X, Y) end, Run)) end, Solutions). contains_tile({Row, Col}, Lst) -> Return = lists:any(fun (X) -> {Row2, Col2} = get_tile_location(X), Row =:= Row2 andalso Col =:= Col2 end, Lst), case Return of true -> true; _False -> io:format("~p,~p Were not present. ~n", [Row,Col]) end.
2e622e95d5113d029ccc2c68bcf9d3b23b19bda34f75103f8c7ad94c68e6464a
lowasser/TrieMap
Buildable.hs
# LANGUAGE BangPatterns , UnboxedTuples , MagicHash , NamedFieldPuns , RecordWildCards , FlexibleInstances , MultiParamTypeClasses # # LANGUAGE TypeFamilies # module Data.TrieMap.WordMap.Buildable (WordStack) where import Data.TrieMap.TrieKey import Data.Word import Data.TrieMap.WordMap.Base import Data.TrieMap.WordMap.Searchable () import GHC.Exts instance Buildable (TrieMap Word) Word where type UStack (TrieMap Word) = SNode # INLINE uFold # uFold = fmap WordMap . defaultUFold type AStack (TrieMap Word) = WordStack # INLINE aFold # aFold = fmap WordMap . fromAscList type DAStack (TrieMap Word) = WordStack # INLINE daFold # daFold = aFold const # INLINE fromAscList # fromAscList :: Sized a => (a -> a -> a) -> Foldl WordStack Key a (SNode a) fromAscList f = Foldl{zero = nil, ..} where begin kx vx = WordStack kx vx Nada snoc (WordStack kx vx stk) kz vz | kx == kz = WordStack kx (f vz vx) stk | otherwise = WordStack kz vz $ reduce (branchMask kx kz) kx (singleton kx vx) stk reduce : : Mask - > Prefix - > a - > Stack a - > Stack a reduce !m !px !tx (Push py ty stk') | shorter m mxy = reduce m pxy (bin' pxy mxy ty tx) stk' where mxy = branchMask px py; pxy = mask px mxy reduce _ px tx stk = Push px tx stk done (WordStack kx vx stk) = case finish kx (singleton kx vx) stk of (# sz#, node #) -> SNode {sz = I# sz#, node} finish !px !tx (Push py ty stk) = finish p (join' py ty px tx) stk where m = branchMask px py; p = mask px m finish _ SNode{sz, node} Nada = (# unbox sz, node #) join' p1 t1 p2 t2 = SNode{sz = sz t1 + sz t2, node = Bin p m t1 t2} where m = branchMask p1 p2 p = mask p1 m data WordStack a = WordStack !Key a (Stack a) data Stack a = Push !Prefix !(SNode a) !(Stack a) | Nada
null
https://raw.githubusercontent.com/lowasser/TrieMap/1ab52b8d83469974a629f2aa577a85de3f9e867a/Data/TrieMap/WordMap/Buildable.hs
haskell
# LANGUAGE BangPatterns , UnboxedTuples , MagicHash , NamedFieldPuns , RecordWildCards , FlexibleInstances , MultiParamTypeClasses # # LANGUAGE TypeFamilies # module Data.TrieMap.WordMap.Buildable (WordStack) where import Data.TrieMap.TrieKey import Data.Word import Data.TrieMap.WordMap.Base import Data.TrieMap.WordMap.Searchable () import GHC.Exts instance Buildable (TrieMap Word) Word where type UStack (TrieMap Word) = SNode # INLINE uFold # uFold = fmap WordMap . defaultUFold type AStack (TrieMap Word) = WordStack # INLINE aFold # aFold = fmap WordMap . fromAscList type DAStack (TrieMap Word) = WordStack # INLINE daFold # daFold = aFold const # INLINE fromAscList # fromAscList :: Sized a => (a -> a -> a) -> Foldl WordStack Key a (SNode a) fromAscList f = Foldl{zero = nil, ..} where begin kx vx = WordStack kx vx Nada snoc (WordStack kx vx stk) kz vz | kx == kz = WordStack kx (f vz vx) stk | otherwise = WordStack kz vz $ reduce (branchMask kx kz) kx (singleton kx vx) stk reduce : : Mask - > Prefix - > a - > Stack a - > Stack a reduce !m !px !tx (Push py ty stk') | shorter m mxy = reduce m pxy (bin' pxy mxy ty tx) stk' where mxy = branchMask px py; pxy = mask px mxy reduce _ px tx stk = Push px tx stk done (WordStack kx vx stk) = case finish kx (singleton kx vx) stk of (# sz#, node #) -> SNode {sz = I# sz#, node} finish !px !tx (Push py ty stk) = finish p (join' py ty px tx) stk where m = branchMask px py; p = mask px m finish _ SNode{sz, node} Nada = (# unbox sz, node #) join' p1 t1 p2 t2 = SNode{sz = sz t1 + sz t2, node = Bin p m t1 t2} where m = branchMask p1 p2 p = mask p1 m data WordStack a = WordStack !Key a (Stack a) data Stack a = Push !Prefix !(SNode a) !(Stack a) | Nada
f87129f4476ad18aece16261ff8613b79716c5f5ee08797251c7fa59788fd40d
wdebeaum/step
phrase.lisp
;;;; ;;;; W::phrase ;;;; (define-words :pos W::n :templ COUNT-PRED-TEMPL :words ( (W::phrase (SENSES ((LF-PARENT ONT::linguistic-component) ;linguistic-object) (EXAMPLE "type a word or phrase in the box") (meta-data :origin task-learning :entry-date 20050817 :change-date nil :wn ("phrase%1:10:00") :comments nil) ) ) ) ))
null
https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/phrase.lisp
lisp
W::phrase linguistic-object)
(define-words :pos W::n :templ COUNT-PRED-TEMPL :words ( (W::phrase (SENSES (EXAMPLE "type a word or phrase in the box") (meta-data :origin task-learning :entry-date 20050817 :change-date nil :wn ("phrase%1:10:00") :comments nil) ) ) ) ))
633bc3a9e1293ffa72b6380c950dc73dfd20c086f446968704e0e006d1a88d41
ocaml-flambda/ocaml-jst
bytepackager.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2002 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) " Package " a set of .cmo files into one .cmo file having the original compilation units as sub - modules . original compilation units as sub-modules. *) val package_files: ppf_dump:Format.formatter -> Env.t -> string list -> string -> unit type error = Forward_reference of string * Ident.t | Multiple_definition of string * Ident.t | Not_an_object_file of string | Illegal_renaming of Compilation_unit.Name.t * string * string | File_not_found of string exception Error of error val report_error: Format.formatter -> error -> unit val reset: unit -> unit
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/1bb6c797df7c63ddae1fc2e6f403a0ee9896cc8e/bytecomp/bytepackager.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************
, projet Cristal , INRIA Rocquencourt Copyright 2002 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the " Package " a set of .cmo files into one .cmo file having the original compilation units as sub - modules . original compilation units as sub-modules. *) val package_files: ppf_dump:Format.formatter -> Env.t -> string list -> string -> unit type error = Forward_reference of string * Ident.t | Multiple_definition of string * Ident.t | Not_an_object_file of string | Illegal_renaming of Compilation_unit.Name.t * string * string | File_not_found of string exception Error of error val report_error: Format.formatter -> error -> unit val reset: unit -> unit
acff7467703d1f1580edb7f96846c2b8702546023d20a24feae9ddec0c7e8318
kazu-yamamoto/cab
Main.hs
module Main where import Control.Exception (Handler(..)) import qualified Control.Exception as E (catches) import Control.Monad (when) import Data.List (isPrefixOf, intercalate) import Data.Maybe (isNothing) import Distribution.Cab import System.Console.GetOpt (ArgOrder(..), OptDescr(..), getOpt') import System.Environment (getArgs) import System.Exit (ExitCode, exitFailure) import System.IO import Commands import Doc import Help import Options import Run import Types ---------------------------------------------------------------- main :: IO () main = flip E.catches handlers $ do oargs <- getArgs let pargs = parseArgs getOptDB oargs checkOptions1 pargs illegalOptionsAndExit let Right (args,opts0) = pargs when (args == []) helpAndExit when (OptHelp `elem` opts0) $ helpCommandAndExit args [] [] let opts1 = filter (/= OptHelp) opts0 act:params = args mcmdspec = commandSpecByName act (commandDB helpCommandAndExit) when (isNothing mcmdspec) (illegalCommandAndExit act) let Just cmdspec = mcmdspec checkOptions2 opts1 cmdspec oargs illegalOptionsAndExit run cmdspec params opts1 where handlers = [Handler handleExit] handleExit :: ExitCode -> IO () handleExit _ = return () ---------------------------------------------------------------- illegalCommandAndExit :: String -> IO () illegalCommandAndExit x = do hPutStrLn stderr $ "Illegal command: " ++ x exitFailure ---------------------------------------------------------------- illegalOptionsAndExit :: UnknownOptPrinter illegalOptionsAndExit xs = do -- FixME hPutStrLn stderr $ "Illegal options: " ++ intercalate " " xs exitFailure ---------------------------------------------------------------- type ParsedArgs = Either [UnknownOpt] ([Arg],[Option]) parseArgs :: [GetOptSpec] -> [Arg] -> ParsedArgs parseArgs db args = case getOpt' Permute db args of (o,n,[],[]) -> Right (n,o) (_,_,unknowns,_) -> Left unknowns ---------------------------------------------------------------- type UnknownOpt = String type UnknownOptPrinter = [UnknownOpt] -> IO () ---------------------------------------------------------------- checkOptions1 :: ParsedArgs -> UnknownOptPrinter -> IO () checkOptions1 (Left es) func = func es checkOptions1 _ _ = return () ---------------------------------------------------------------- checkOptions2 :: [Option] -> CommandSpec -> [Arg] -> UnknownOptPrinter -> IO () checkOptions2 opts cmdspec oargs func = when (unknowns /= []) $ func (concatMap (resolveOptionString oargs) unknowns) where unknowns = unknownOptions opts cmdspec unknownOptions :: [Option] -> CommandSpec -> [Switch] unknownOptions opts cmdspec = chk specified supported where chk [] _ = [] chk (x:xs) ys | x `elem` ys = chk xs ys | otherwise = x : chk xs ys specified = map toSwitch opts supported = map fst $ switches cmdspec resolveOptionString :: [Arg] -> Switch -> [UnknownOpt] resolveOptionString oargs sw = case lookup sw optionDB of Nothing -> error "resolveOptionString" Just gspec -> let (s,l) = getOptNames gspec in checkShort s ++ checkLong l where checkShort s = filter (==s) oargs checkLong l = filter (l `isPrefixOf`) oargs getOptNames :: GetOptSpec -> (String,String) getOptNames (Option (c:_) (s:_) _ _) = ('-':[c],'-':'-':s) getOptNames _ = error "getOptNames"
null
https://raw.githubusercontent.com/kazu-yamamoto/cab/a7bdc7129b079b2d980e529c6ad8c4c6e0456d23/src/Main.hs
haskell
-------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- FixME -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- --------------------------------------------------------------
module Main where import Control.Exception (Handler(..)) import qualified Control.Exception as E (catches) import Control.Monad (when) import Data.List (isPrefixOf, intercalate) import Data.Maybe (isNothing) import Distribution.Cab import System.Console.GetOpt (ArgOrder(..), OptDescr(..), getOpt') import System.Environment (getArgs) import System.Exit (ExitCode, exitFailure) import System.IO import Commands import Doc import Help import Options import Run import Types main :: IO () main = flip E.catches handlers $ do oargs <- getArgs let pargs = parseArgs getOptDB oargs checkOptions1 pargs illegalOptionsAndExit let Right (args,opts0) = pargs when (args == []) helpAndExit when (OptHelp `elem` opts0) $ helpCommandAndExit args [] [] let opts1 = filter (/= OptHelp) opts0 act:params = args mcmdspec = commandSpecByName act (commandDB helpCommandAndExit) when (isNothing mcmdspec) (illegalCommandAndExit act) let Just cmdspec = mcmdspec checkOptions2 opts1 cmdspec oargs illegalOptionsAndExit run cmdspec params opts1 where handlers = [Handler handleExit] handleExit :: ExitCode -> IO () handleExit _ = return () illegalCommandAndExit :: String -> IO () illegalCommandAndExit x = do hPutStrLn stderr $ "Illegal command: " ++ x exitFailure illegalOptionsAndExit :: UnknownOptPrinter hPutStrLn stderr $ "Illegal options: " ++ intercalate " " xs exitFailure type ParsedArgs = Either [UnknownOpt] ([Arg],[Option]) parseArgs :: [GetOptSpec] -> [Arg] -> ParsedArgs parseArgs db args = case getOpt' Permute db args of (o,n,[],[]) -> Right (n,o) (_,_,unknowns,_) -> Left unknowns type UnknownOpt = String type UnknownOptPrinter = [UnknownOpt] -> IO () checkOptions1 :: ParsedArgs -> UnknownOptPrinter -> IO () checkOptions1 (Left es) func = func es checkOptions1 _ _ = return () checkOptions2 :: [Option] -> CommandSpec -> [Arg] -> UnknownOptPrinter -> IO () checkOptions2 opts cmdspec oargs func = when (unknowns /= []) $ func (concatMap (resolveOptionString oargs) unknowns) where unknowns = unknownOptions opts cmdspec unknownOptions :: [Option] -> CommandSpec -> [Switch] unknownOptions opts cmdspec = chk specified supported where chk [] _ = [] chk (x:xs) ys | x `elem` ys = chk xs ys | otherwise = x : chk xs ys specified = map toSwitch opts supported = map fst $ switches cmdspec resolveOptionString :: [Arg] -> Switch -> [UnknownOpt] resolveOptionString oargs sw = case lookup sw optionDB of Nothing -> error "resolveOptionString" Just gspec -> let (s,l) = getOptNames gspec in checkShort s ++ checkLong l where checkShort s = filter (==s) oargs checkLong l = filter (l `isPrefixOf`) oargs getOptNames :: GetOptSpec -> (String,String) getOptNames (Option (c:_) (s:_) _ _) = ('-':[c],'-':'-':s) getOptNames _ = error "getOptNames"
84639e0cc411cd83ce87af4e8f6c742328568630199271f753c4e755601ad910
nuvla/api-server
group.cljc
(ns sixsq.nuvla.server.resources.spec.group (:require [clojure.spec.alpha :as s] [sixsq.nuvla.server.resources.spec.common :as common] [sixsq.nuvla.server.util.spec :as su] [spec-tools.core :as st])) (def user-id-regex #"^user/[a-zA-Z0-9-]+$") (def group-id-regex #"^group/([a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?)?$") (s/def ::user-id (assoc (st/spec (s/and string? #(re-matches user-id-regex %))) :name "user-id" :json-schema/type "string" :json-schema/display-name "user ID" :json-schema/description "user identifier")) (s/def ::group-id (assoc (st/spec (s/and string? #(re-matches group-id-regex %))) :name "group-id" :json-schema/type "string" :json-schema/display-name "group ID" :json-schema/description "group identifier")) (s/def ::users (assoc (st/spec (s/coll-of ::user-id :distinct true)) :name "users" :json-schema/type "array" :json-schema/description "list of users in this group" :json-schema/order 20)) (s/def ::parents (assoc (st/spec (s/coll-of ::group-id :distinct true)) :name "parents" :json-schema/type "array" :json-schema/description "list of parents groups" :json-schema/server-managed true :json-schema/order 30)) (s/def ::schema (su/only-keys-maps common/common-attrs {:req-un [::users] :opt-un [::parents]}))
null
https://raw.githubusercontent.com/nuvla/api-server/a595d6956c4f9eae0d6ba96f8af4f1c813f67131/code/src/sixsq/nuvla/server/resources/spec/group.cljc
clojure
(ns sixsq.nuvla.server.resources.spec.group (:require [clojure.spec.alpha :as s] [sixsq.nuvla.server.resources.spec.common :as common] [sixsq.nuvla.server.util.spec :as su] [spec-tools.core :as st])) (def user-id-regex #"^user/[a-zA-Z0-9-]+$") (def group-id-regex #"^group/([a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?)?$") (s/def ::user-id (assoc (st/spec (s/and string? #(re-matches user-id-regex %))) :name "user-id" :json-schema/type "string" :json-schema/display-name "user ID" :json-schema/description "user identifier")) (s/def ::group-id (assoc (st/spec (s/and string? #(re-matches group-id-regex %))) :name "group-id" :json-schema/type "string" :json-schema/display-name "group ID" :json-schema/description "group identifier")) (s/def ::users (assoc (st/spec (s/coll-of ::user-id :distinct true)) :name "users" :json-schema/type "array" :json-schema/description "list of users in this group" :json-schema/order 20)) (s/def ::parents (assoc (st/spec (s/coll-of ::group-id :distinct true)) :name "parents" :json-schema/type "array" :json-schema/description "list of parents groups" :json-schema/server-managed true :json-schema/order 30)) (s/def ::schema (su/only-keys-maps common/common-attrs {:req-un [::users] :opt-un [::parents]}))
23944669bdd4fdd09404eeabee3c0cba5b0268acc0935097ceee1e6c1b4874be
psandahl/hats
CallbackTests.hs
module CallbackTests ( callingCallbacks ) where import Control.Concurrent.MVar import Control.Monad (when) import Data.Maybe (isNothing, isJust) import System.Timeout (timeout) import Test.HUnit import Gnatsd import Network.Nats -- | Check that callbacks are called when needed at connection and -- disconnection. callingCallbacks :: Assertion callingCallbacks = do connect <- newEmptyMVar disconnect <- newEmptyMVar let settings = defaultSettings { connectedTo = connected connect , disconnectedFrom = disconnected disconnect } g1 <- startGnatsd withNats settings [defaultURI] $ \_nats -> do -- Wait for connection. c1 <- timeout oneSec $ takeMVar connect when (isNothing c1) $ do stopGnatsd g1 assertFailure "Shall have connectedTo callback" -- Check that no disconnect has happen. d1 <- tryTakeMVar disconnect when (isJust d1) $ do stopGnatsd g1 assertFailure "Shall have no disconnectedFrom callback" -- Shoot down gnatsd ... stopGnatsd g1 -- Now a disconnect shall have happen. d2 <- timeout oneSec $ takeMVar disconnect when (isNothing d2) $ assertFailure "Shall have disconnectedFrom callback" -- Start gnatsd again ... g2 <- startGnatsd -- Check that we have a new connect callback. c2 <- timeout oneSec $ takeMVar connect when (isNothing c2) $ do stopGnatsd g2 assertFailure "Shall have connectedTo callback" -- Done. Close. stopGnatsd g2 oneSec :: Int oneSec = 1000000 connected :: MVar () -> SockAddr -> IO () connected sync sockAddr = do putStrLn $ "Connected to: " ++ show sockAddr putMVar sync () disconnected :: MVar () -> SockAddr -> IO () disconnected sync sockAddr = do putStrLn $ "Disconnected from: " ++ show sockAddr putMVar sync ()
null
https://raw.githubusercontent.com/psandahl/hats/2503edefbda64209d20509b075b3ab90cac39b8d/test/CallbackTests.hs
haskell
| Check that callbacks are called when needed at connection and disconnection. Wait for connection. Check that no disconnect has happen. Shoot down gnatsd ... Now a disconnect shall have happen. Start gnatsd again ... Check that we have a new connect callback. Done. Close.
module CallbackTests ( callingCallbacks ) where import Control.Concurrent.MVar import Control.Monad (when) import Data.Maybe (isNothing, isJust) import System.Timeout (timeout) import Test.HUnit import Gnatsd import Network.Nats callingCallbacks :: Assertion callingCallbacks = do connect <- newEmptyMVar disconnect <- newEmptyMVar let settings = defaultSettings { connectedTo = connected connect , disconnectedFrom = disconnected disconnect } g1 <- startGnatsd withNats settings [defaultURI] $ \_nats -> do c1 <- timeout oneSec $ takeMVar connect when (isNothing c1) $ do stopGnatsd g1 assertFailure "Shall have connectedTo callback" d1 <- tryTakeMVar disconnect when (isJust d1) $ do stopGnatsd g1 assertFailure "Shall have no disconnectedFrom callback" stopGnatsd g1 d2 <- timeout oneSec $ takeMVar disconnect when (isNothing d2) $ assertFailure "Shall have disconnectedFrom callback" g2 <- startGnatsd c2 <- timeout oneSec $ takeMVar connect when (isNothing c2) $ do stopGnatsd g2 assertFailure "Shall have connectedTo callback" stopGnatsd g2 oneSec :: Int oneSec = 1000000 connected :: MVar () -> SockAddr -> IO () connected sync sockAddr = do putStrLn $ "Connected to: " ++ show sockAddr putMVar sync () disconnected :: MVar () -> SockAddr -> IO () disconnected sync sockAddr = do putStrLn $ "Disconnected from: " ++ show sockAddr putMVar sync ()
3ee3ff5e1172963ac6e1103bb98b6440b8807f750ff473ab60b519c485872d92
nha/boot-uglify
boot_task.clj
(ns nha.boot-uglify.boot-task {:boot/export-tasks true} (:require [clojure.java.io :as io :refer [as-file]] [clojure.string :as string] [boot.pod :as pod] [boot.core :as core :refer [deftask tmp-dir! tmp-get tmp-path tmp-file commit! rm add-resource]] [boot.util :as util] [boot.file :as file] [boot.task-helpers :as helpers] [clojure.java.shell :as shell :refer [sh]] [nha.boot-uglify.uglifyjs :refer [uglify-str]] [nha.boot-uglify.minify-js :as minify-js-impl]) (:import [java.io StringWriter] [javax.script ScriptEngine ScriptEngineManager ScriptException ScriptEngineFactory])) (def default-options {:sequences true, ; join consecutive statemets with the “comma operator” optimize property access : a["foo " ] → a.foo :dead_code true, ; discard unreachable code :drop_debugger true, ; discard “debugger” statements :unsafe false, ; some unsafe optimizations :conditionals true, ; optimize if-s and conditional expressions :comparisons true, ; optimize comparisons :evaluate true, ; evaluate constant expressions :booleans true, ; optimize boolean expressions :loops true, ; optimize loops :unused true, ; drop unused variables/functions :hoist_funs true, ; hoist function declarations :hoist_vars false, ; hoist variable declarations :if_return true, ; optimize if-s followed by return/continue :join_vars true, ; join var declarations :cascade true, ; try to cascade `right` into `left` in sequences :side_effects true, ; drop side-effect-free statements :warnings true, ; warn about potentially dangerous optimizations/code :global_defs {}, ; global definitions :mangle false ; mangle names }) (def cljs-version "1.7.228") (defn cljs-depdendency [] (let [proj-deps (core/get-env :dependencies) cljs-dep? (first (filter (comp #{'org.clojure/clojurescript} first) proj-deps)) cljs-exists? (io/resource "cljs/build/api.clj")] (cond org.clojure/clojurescript in project ( non - transitive ) - do nothing cljs-dep? nil cljs.core on classpath , org.clojure/clojurescript not in project cljs-exists? (do (util/warn "WARNING: No ClojureScript in project dependencies but ClojureScript was found in classpath. Adding direct dependency is adviced.\n") nil) no cljs on classpath , no project dep , add cljs dep to pod :else ['org.clojure/clojurescript cljs-version]))) (def ^:private deps "ClojureScript dependency to load in the pod if none is provided via project" (delay (filter identity [(cljs-depdendency) '[boot/core "2.6.0"] '[cheshire "5.6.1"] '[org.apache.commons/commons-lang3 "3.4"]]))) (defn find-mainfiles [fileset ids] "From -oss/boot-cljs/blob/master/src/adzerk/boot_cljs.clj#L84-L92" (let [re-pat #(re-pattern (str "^\\Q" % "\\E\\.cljs\\.edn$")) select (if (seq ids) #(core/by-re (map re-pat ids) %) #(core/by-ext [".cljs.edn"] %))] (->> fileset core/input-files select (sort-by :path)))) (defn read-cljs-edn "Modified from -oss/boot-cljs/blob/master/src/adzerk/boot_cljs.clj#L50" [tmp-file] (let [file (core/tmp-file tmp-file) path (core/tmp-path tmp-file)] (assoc (read-string (slurp file)) :path (.getPath file) :rel-path path :id (string/replace (.getName file) #"\.cljs\.edn$" "")))) (defn make-pod "From boot-template" [] (future (-> (core/get-env) (update-in [:dependencies] (fnil into []) deps) (update-in [:resource-paths] (fnil into #{}) #{"resources"}) pod/make-pod (.setName "boot-uglify")))) (defn minify-file! [in-file out-file verbose options] (io/make-parents out-file) TODO warn / throw if options are not in : default - options (let [res (minify-js-impl/minify-js (str in-file) (str out-file) options)] (when verbose (util/info (str " minified " res "\n"))) res)) (deftask minify-js "Minify javascript files in a boot project. Assumed to be run after boot-cljs." [i ids IDS #{str} "ids of the builds. If none is passed, compile all .cljs.edn ids. at least main is assumed (since this is the default for boot-cljs)" v verbose bool "Verbose output" o options OPTS edn "option map to pass to Uglify. See . Also, you can pass :mangle true to mangle names."] (let [tmp-main (core/tmp-dir!)] (fn middleware [next-handler] (fn handler [fileset] (core/empty-dir! tmp-main) (util/info "Uglifying JS...\n") (doseq [edn-file-content (map read-cljs-edn (find-mainfiles fileset ids))] (let [js-rel-path (string/replace (:rel-path edn-file-content) #"\.cljs\.edn$" ".js") js-file-get (tmp-get fileset js-rel-path)] (if js-file-get (let [in-file (core/tmp-file js-file-get) out-path js-rel-path ;;(string/replace js-rel-path #"\.js" ".min.js") out-file (io/file tmp-main out-path)] (util/info (str "• " js-rel-path "\n")) (minify-file! in-file out-file verbose options)) (do ignore nil files , since this is probably a file that is not built ( ie . not passed as one of the build : ids ) ;; but issue a warning (util/warn (str "Ignoring " js-rel-path " to suppress this warning pass an :ids argument \n")))))) (-> fileset (core/add-resource tmp-main) core/commit! next-handler)))))
null
https://raw.githubusercontent.com/nha/boot-uglify/df0cffb2734bdd1db2be1fab5fcefdda5f735e68/src/nha/boot_uglify/boot_task.clj
clojure
join consecutive statemets with the “comma operator” discard unreachable code discard “debugger” statements some unsafe optimizations optimize if-s and conditional expressions optimize comparisons evaluate constant expressions optimize boolean expressions optimize loops drop unused variables/functions hoist function declarations hoist variable declarations optimize if-s followed by return/continue join var declarations try to cascade `right` into `left` in sequences drop side-effect-free statements warn about potentially dangerous optimizations/code global definitions mangle names (string/replace js-rel-path #"\.js" ".min.js") but issue a warning
(ns nha.boot-uglify.boot-task {:boot/export-tasks true} (:require [clojure.java.io :as io :refer [as-file]] [clojure.string :as string] [boot.pod :as pod] [boot.core :as core :refer [deftask tmp-dir! tmp-get tmp-path tmp-file commit! rm add-resource]] [boot.util :as util] [boot.file :as file] [boot.task-helpers :as helpers] [clojure.java.shell :as shell :refer [sh]] [nha.boot-uglify.uglifyjs :refer [uglify-str]] [nha.boot-uglify.minify-js :as minify-js-impl]) (:import [java.io StringWriter] [javax.script ScriptEngine ScriptEngineManager ScriptException ScriptEngineFactory])) optimize property access : a["foo " ] → a.foo }) (def cljs-version "1.7.228") (defn cljs-depdendency [] (let [proj-deps (core/get-env :dependencies) cljs-dep? (first (filter (comp #{'org.clojure/clojurescript} first) proj-deps)) cljs-exists? (io/resource "cljs/build/api.clj")] (cond org.clojure/clojurescript in project ( non - transitive ) - do nothing cljs-dep? nil cljs.core on classpath , org.clojure/clojurescript not in project cljs-exists? (do (util/warn "WARNING: No ClojureScript in project dependencies but ClojureScript was found in classpath. Adding direct dependency is adviced.\n") nil) no cljs on classpath , no project dep , add cljs dep to pod :else ['org.clojure/clojurescript cljs-version]))) (def ^:private deps "ClojureScript dependency to load in the pod if none is provided via project" (delay (filter identity [(cljs-depdendency) '[boot/core "2.6.0"] '[cheshire "5.6.1"] '[org.apache.commons/commons-lang3 "3.4"]]))) (defn find-mainfiles [fileset ids] "From -oss/boot-cljs/blob/master/src/adzerk/boot_cljs.clj#L84-L92" (let [re-pat #(re-pattern (str "^\\Q" % "\\E\\.cljs\\.edn$")) select (if (seq ids) #(core/by-re (map re-pat ids) %) #(core/by-ext [".cljs.edn"] %))] (->> fileset core/input-files select (sort-by :path)))) (defn read-cljs-edn "Modified from -oss/boot-cljs/blob/master/src/adzerk/boot_cljs.clj#L50" [tmp-file] (let [file (core/tmp-file tmp-file) path (core/tmp-path tmp-file)] (assoc (read-string (slurp file)) :path (.getPath file) :rel-path path :id (string/replace (.getName file) #"\.cljs\.edn$" "")))) (defn make-pod "From boot-template" [] (future (-> (core/get-env) (update-in [:dependencies] (fnil into []) deps) (update-in [:resource-paths] (fnil into #{}) #{"resources"}) pod/make-pod (.setName "boot-uglify")))) (defn minify-file! [in-file out-file verbose options] (io/make-parents out-file) TODO warn / throw if options are not in : default - options (let [res (minify-js-impl/minify-js (str in-file) (str out-file) options)] (when verbose (util/info (str " minified " res "\n"))) res)) (deftask minify-js "Minify javascript files in a boot project. Assumed to be run after boot-cljs." [i ids IDS #{str} "ids of the builds. If none is passed, compile all .cljs.edn ids. at least main is assumed (since this is the default for boot-cljs)" v verbose bool "Verbose output" o options OPTS edn "option map to pass to Uglify. See . Also, you can pass :mangle true to mangle names."] (let [tmp-main (core/tmp-dir!)] (fn middleware [next-handler] (fn handler [fileset] (core/empty-dir! tmp-main) (util/info "Uglifying JS...\n") (doseq [edn-file-content (map read-cljs-edn (find-mainfiles fileset ids))] (let [js-rel-path (string/replace (:rel-path edn-file-content) #"\.cljs\.edn$" ".js") js-file-get (tmp-get fileset js-rel-path)] (if js-file-get (let [in-file (core/tmp-file js-file-get) out-file (io/file tmp-main out-path)] (util/info (str "• " js-rel-path "\n")) (minify-file! in-file out-file verbose options)) (do ignore nil files , since this is probably a file that is not built ( ie . not passed as one of the build : ids ) (util/warn (str "Ignoring " js-rel-path " to suppress this warning pass an :ids argument \n")))))) (-> fileset (core/add-resource tmp-main) core/commit! next-handler)))))
e31f25df068afe1c8895d26e6ae4510562f4c8b979c366de074bde7744327e93
haskell-beam/beam
Database.hs
module Database.Beam.Migrate.Tool.Database where import Database.Beam.Migrate.Backend import Database.Beam.Migrate.Log import Database.Beam.Migrate.Tool.Backend import Database.Beam.Migrate.Tool.CmdLine import Database.Beam.Migrate.Tool.Registry import Control.Monad import qualified Data.HashMap.Strict as HM listDatabases :: MigrateCmdLine -> IO () listDatabases cmdLine = do reg <- lookupRegistry cmdLine forM_ (HM.toList (migrationRegistryDatabases reg)) $ \(DatabaseName dbName, _) -> putStrLn dbName renameDatabase :: MigrateCmdLine -> DatabaseName -> DatabaseName -> IO () renameDatabase cmdLine from to = updatingRegistry cmdLine $ \reg -> case HM.lookup from (migrationRegistryDatabases reg) of Nothing -> fail ("No such database " ++ unDatabaseName from) Just db -> pure ((), reg { migrationRegistryDatabases = HM.insert to db $ HM.delete from $ migrationRegistryDatabases reg }) showDatabase :: MigrateCmdLine -> DatabaseName -> IO () showDatabase cmdLine dbName@(DatabaseName dbNameStr) = do reg <- lookupRegistry cmdLine case HM.lookup dbName (migrationRegistryDatabases reg) of Nothing -> fail "No such database" Just MigrationDatabase {..} -> do putStrLn ("Database '" ++ dbNameStr ++ "'") putStrLn (" Backend: " ++ unModuleName migrationDbBackend) putStrLn (" Conn : " ++ migrationDbConnString) initDatabase :: MigrateCmdLine -> DatabaseName -> ModuleName -> String -> IO () initDatabase cmdLine dbName moduleName connStr = updatingRegistry cmdLine $ \reg -> do case HM.lookup dbName (migrationRegistryDatabases reg) of Just {} -> fail "Database already exists" Nothing -> do -- Get the constraints and see if the migration table already exists SomeBeamMigrationBackend be@BeamMigrationBackend { backendTransact = transact } <- loadBackend' cmdLine moduleName _ <- transact connStr (ensureBackendTables be) let db = MigrationDatabase moduleName connStr pure ((), reg { migrationRegistryDatabases = HM.insert dbName db (migrationRegistryDatabases reg) })
null
https://raw.githubusercontent.com/haskell-beam/beam/596981a1ea6765b9f311d48a2ec4d8460ebc4b7e/beam-migrate-cli/Database/Beam/Migrate/Tool/Database.hs
haskell
Get the constraints and see if the migration table already exists
module Database.Beam.Migrate.Tool.Database where import Database.Beam.Migrate.Backend import Database.Beam.Migrate.Log import Database.Beam.Migrate.Tool.Backend import Database.Beam.Migrate.Tool.CmdLine import Database.Beam.Migrate.Tool.Registry import Control.Monad import qualified Data.HashMap.Strict as HM listDatabases :: MigrateCmdLine -> IO () listDatabases cmdLine = do reg <- lookupRegistry cmdLine forM_ (HM.toList (migrationRegistryDatabases reg)) $ \(DatabaseName dbName, _) -> putStrLn dbName renameDatabase :: MigrateCmdLine -> DatabaseName -> DatabaseName -> IO () renameDatabase cmdLine from to = updatingRegistry cmdLine $ \reg -> case HM.lookup from (migrationRegistryDatabases reg) of Nothing -> fail ("No such database " ++ unDatabaseName from) Just db -> pure ((), reg { migrationRegistryDatabases = HM.insert to db $ HM.delete from $ migrationRegistryDatabases reg }) showDatabase :: MigrateCmdLine -> DatabaseName -> IO () showDatabase cmdLine dbName@(DatabaseName dbNameStr) = do reg <- lookupRegistry cmdLine case HM.lookup dbName (migrationRegistryDatabases reg) of Nothing -> fail "No such database" Just MigrationDatabase {..} -> do putStrLn ("Database '" ++ dbNameStr ++ "'") putStrLn (" Backend: " ++ unModuleName migrationDbBackend) putStrLn (" Conn : " ++ migrationDbConnString) initDatabase :: MigrateCmdLine -> DatabaseName -> ModuleName -> String -> IO () initDatabase cmdLine dbName moduleName connStr = updatingRegistry cmdLine $ \reg -> do case HM.lookup dbName (migrationRegistryDatabases reg) of Just {} -> fail "Database already exists" Nothing -> do SomeBeamMigrationBackend be@BeamMigrationBackend { backendTransact = transact } <- loadBackend' cmdLine moduleName _ <- transact connStr (ensureBackendTables be) let db = MigrationDatabase moduleName connStr pure ((), reg { migrationRegistryDatabases = HM.insert dbName db (migrationRegistryDatabases reg) })
5e9a070c1dde321fdadbe39b65aebf86ba062262697633b003f74c837d10bd98
AbstractMachinesLab/caramel
env.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Environment handling *) open Types open Misc type summary = Env_empty | Env_value of summary * Ident.t * value_description | Env_type of summary * Ident.t * type_declaration | Env_extension of summary * Ident.t * extension_constructor | Env_module of summary * Ident.t * module_presence * module_declaration | Env_modtype of summary * Ident.t * modtype_declaration | Env_class of summary * Ident.t * class_declaration | Env_cltype of summary * Ident.t * class_type_declaration | Env_open of summary * Path.t (** The string set argument of [Env_open] represents a list of module names to skip, i.e. that won't be imported in the toplevel namespace. *) | Env_functor_arg of summary * Ident.t | Env_constraints of summary * type_declaration Path.Map.t | Env_copy_types of summary * string list | Env_persistent of summary * Ident.t type address = | Aident of Ident.t | Adot of address * int type t val empty: t val initial_safe_string: t val initial_unsafe_string: t val diff: t -> t -> Ident.t list val copy_local: from:t -> t -> t type type_descriptions = constructor_description list * label_description list (* For short-paths *) type iter_cont val iter_types: (Path.t -> Path.t * (type_declaration * type_descriptions) -> unit) -> t -> iter_cont val run_iter_cont: iter_cont list -> (Path.t * iter_cont) list val same_types: t -> t -> bool val used_persistent: unit -> Concr.t val find_shadowed_types: Path.t -> t -> Path.t list val without_cmis: ('a -> 'b) -> 'a -> 'b [ without_cmis f arg ] applies [ f ] to [ arg ] , but does not allow opening cmis during its execution allow opening cmis during its execution *) (* Lookup by paths *) val find_value: Path.t -> t -> value_description val find_type: Path.t -> t -> type_declaration val find_type_descrs: Path.t -> t -> type_descriptions val find_module: Path.t -> t -> module_declaration val find_modtype: Path.t -> t -> modtype_declaration val find_class: Path.t -> t -> class_declaration val find_cltype: Path.t -> t -> class_type_declaration val find_type_expansion: Path.t -> t -> type_expr list * type_expr * int val find_type_expansion_opt: Path.t -> t -> type_expr list * type_expr * int (* Find the manifest type information associated to a type for the sake of the compiler's type-based optimisations. *) val find_modtype_expansion: Path.t -> t -> module_type val find_value_address: Path.t -> t -> address val find_module_address: Path.t -> t -> address val find_class_address: Path.t -> t -> address val find_constructor_address: Path.t -> t -> address val add_functor_arg: Ident.t -> t -> t val is_functor_arg: Path.t -> t -> bool val normalize_module_path: Location.t option -> t -> Path.t -> Path.t (* Normalize the path to a concrete module. If the option is None, allow returning dangling paths. Otherwise raise a Missing_module error, and may add forgotten head as required global. *) val normalize_type_path: Location.t option -> t -> Path.t -> Path.t (* Normalize the prefix part of the type path *) val normalize_path_prefix: Location.t option -> t -> Path.t -> Path.t Normalize the prefix part of other kinds of paths ( value / modtype / etc ) (value/modtype/etc) *) val reset_required_globals: unit -> unit val get_required_globals: unit -> Ident.t list val add_required_global: Ident.t -> unit val has_local_constraints: t -> bool (* Lookup by long identifiers *) ? loc is used to report ' deprecated module ' warnings and other alerts val lookup_value: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * value_description val lookup_constructor: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> constructor_description val lookup_all_constructors: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> (constructor_description * (unit -> unit)) list val lookup_label: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> label_description val lookup_all_labels: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> (label_description * (unit -> unit)) list val lookup_type: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t Since 4.04 , this function no longer returns [ type_description ] . To obtain it , you should either call [ Env.find_type ] , or replace it by [ Typetexp.find_type ] To obtain it, you should either call [Env.find_type], or replace it by [Typetexp.find_type] *) val lookup_module: load:bool -> ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t val lookup_modtype: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * modtype_declaration val lookup_class: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * class_declaration val lookup_cltype: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * class_type_declaration type copy_of_types val make_copy_of_types: string list -> t -> copy_of_types val do_copy_types: copy_of_types -> t -> t (** [do_copy_types copy env] will raise a fatal error if the values in [env] are different from the env passed to [make_copy_of_types]. *) exception Recmodule Raise by lookup_module when the identifier refers to one of the modules of a recursive definition during the computation of its approximation ( see # 5965 ) . to one of the modules of a recursive definition during the computation of its approximation (see #5965). *) (* Insertion by identifier *) val add_value: ?check:(string -> Warnings.t) -> Ident.t -> value_description -> t -> t val add_type: check:bool -> Ident.t -> type_declaration -> t -> t val add_extension: check:bool -> Ident.t -> extension_constructor -> t -> t val add_module: ?arg:bool -> Ident.t -> module_presence -> module_type -> t -> t val add_module_declaration: ?arg:bool -> check:bool -> Ident.t -> module_presence -> module_declaration -> t -> t val add_modtype: Ident.t -> modtype_declaration -> t -> t val add_class: Ident.t -> class_declaration -> t -> t val add_cltype: Ident.t -> class_type_declaration -> t -> t val add_local_type: Path.t -> type_declaration -> t -> t (* Insertion of persistent signatures *) (* [add_persistent_structure id env] is an environment such that module [id] points to the persistent structure contained in the external compilation unit with the same name. The compilation unit itself is looked up in the load path when the contents of the module is accessed. *) val add_persistent_structure : Ident.t -> t -> t (* Returns the set of persistent structures found in the given directory. *) val persistent_structures_of_dir : Load_path.Dir.t -> Misc.String.Set.t (* [filter_non_loaded_persistent f env] removes all the persistent structures that are not yet loaded and for which [f] returns [false]. *) val filter_non_loaded_persistent : (Ident.t -> bool) -> t -> t (* Insertion of all fields of a signature. *) val add_item: signature_item -> t -> t val add_signature: signature -> t -> t (* Insertion of all fields of a signature, relative to the given path. Used to implement open. Returns None if the path refers to a functor, not a structure. *) val open_signature: ?used_slot:bool ref -> ?loc:Location.t -> ?toplevel:bool -> Asttypes.override_flag -> Path.t -> t -> t option val open_pers_signature: string -> t -> t (* Insertion by name *) val enter_value: ?check:(string -> Warnings.t) -> string -> value_description -> t -> Ident.t * t val enter_type: scope:int -> string -> type_declaration -> t -> Ident.t * t val enter_extension: scope:int -> string -> extension_constructor -> t -> Ident.t * t val enter_module: scope:int -> ?arg:bool -> string -> module_presence -> module_type -> t -> Ident.t * t val enter_module_declaration: ?arg:bool -> Ident.t -> module_presence -> module_declaration -> t -> t val enter_modtype: scope:int -> string -> modtype_declaration -> t -> Ident.t * t val enter_class: scope:int -> string -> class_declaration -> t -> Ident.t * t val enter_cltype: scope:int -> string -> class_type_declaration -> t -> Ident.t * t (* Same as [add_signature] but refreshes (new stamp) and rescopes bound idents in the process. *) val enter_signature: scope:int -> signature -> t -> signature * t Initialize the cache of in - core module interfaces . val reset_cache: unit -> unit (* To be called before each toplevel phrase. *) val reset_cache_toplevel: unit -> unit (* Remember the name of the current compilation unit. *) val set_unit_name: string -> unit val get_unit_name: unit -> string (* Read, save a signature to/from a file *) val read_signature: modname -> filepath -> signature (* Arguments: module name, file name. Results: signature. *) val save_signature: alerts:alerts -> signature -> modname -> filepath -> Cmi_format.cmi_infos (* Arguments: signature, module name, file name. *) val save_signature_with_imports: alerts:alerts -> signature -> modname -> filepath -> crcs -> Cmi_format.cmi_infos Arguments : signature , module name , file name , imported units with their CRCs . imported units with their CRCs. *) Return the CRC of the interface of the given compilation unit val crc_of_unit: modname -> Digest.t Return the set of compilation units imported , with their CRC val imports: unit -> crcs may raise Persistent_env . Consistbl . Inconsistency val import_crcs: source:string -> crcs -> unit (* [is_imported_opaque md] returns true if [md] is an opaque imported module *) val is_imported_opaque: modname -> bool (* Summaries -- compact representation of an environment, to be exported in debugging information. *) val summary: t -> summary Return an equivalent environment where all fields have been reset , except the summary . The initial environment can be rebuilt from the summary , using Envaux.env_of_only_summary . except the summary. The initial environment can be rebuilt from the summary, using Envaux.env_of_only_summary. *) val keep_only_summary : t -> t val env_of_only_summary : (summary -> Subst.t -> t) -> t -> t (* Update the short paths table *) val update_short_paths : t -> t (* Return the short paths table *) val short_paths : t -> Short_paths.t (* Error report *) type error = | Missing_module of Location.t * Path.t * Path.t | Illegal_value_name of Location.t * string exception Error of error open Format val report_error: formatter -> error -> unit val mark_value_used: string -> value_description -> unit val mark_module_used: string -> Location.t -> unit val mark_type_used: string -> type_declaration -> unit type constructor_usage = Positive | Pattern | Privatize val mark_constructor_used: constructor_usage -> string -> type_declaration -> string -> unit val mark_constructor: constructor_usage -> t -> string -> constructor_description -> unit val mark_extension_used: constructor_usage -> extension_constructor -> string -> unit val in_signature: bool -> t -> t val is_in_signature: t -> bool val set_value_used_callback: string -> value_description -> (unit -> unit) -> unit val set_type_used_callback: string -> type_declaration -> ((unit -> unit) -> unit) -> unit Forward declaration to break mutual recursion with . val check_modtype_inclusion: (loc:Location.t -> t -> module_type -> Path.t -> module_type -> unit) ref Forward declaration to break mutual recursion with . val check_well_formed_module: (t -> Location.t -> string -> module_type -> unit) ref Forward declaration to break mutual recursion with . val add_delayed_check_forward: ((unit -> unit) -> unit) ref Forward declaration to break mutual recursion with Mtype . val strengthen: (aliasable:bool -> t -> module_type -> Path.t -> module_type) ref Forward declaration to break mutual recursion with Ctype . val same_constr: (t -> type_expr -> type_expr -> bool) ref Forward declaration to break mutual recursion with val shorten_module_path : (t -> Path.t -> Path.t) ref (** Folding over all identifiers (for analysis purpose) *) val fold_values: (string -> Path.t -> value_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_types: (string -> Path.t -> type_declaration * type_descriptions -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_type_decls: (string -> Path.t -> type_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_constructors: (constructor_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_labels: (label_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a (** Persistent structures are only traversed if they are already loaded. *) val fold_modules: (string -> Path.t -> module_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_modtypes: (string -> Path.t -> modtype_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_classes: (string -> Path.t -> class_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_cltypes: (string -> Path.t -> class_type_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a (** Utilities *) val scrape_alias: t -> module_type -> module_type val check_value_name: string -> Location.t -> unit val print_address : Format.formatter -> address -> unit val unbound_class : Path.t * : manage internal state val check_state_consistency: unit -> bool val with_cmis : (unit -> 'a) -> 'a helper for merlin val add_merlin_extension_module: Ident.t -> module_type -> t -> t Compat with 4.10 val find_value_by_name: Longident.t -> t -> Path.t * value_description val find_constructor_by_name: Longident.t -> t -> constructor_description val find_label_by_name: Longident.t -> t -> label_description val find_type_by_name: Longident.t -> t -> Path.t * type_declaration val find_module_by_name: Longident.t -> t -> Path.t * module_declaration val find_modtype_by_name: Longident.t -> t -> Path.t * modtype_declaration
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/ocaml/typing/409/env.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Environment handling * The string set argument of [Env_open] represents a list of module names to skip, i.e. that won't be imported in the toplevel namespace. For short-paths Lookup by paths Find the manifest type information associated to a type for the sake of the compiler's type-based optimisations. Normalize the path to a concrete module. If the option is None, allow returning dangling paths. Otherwise raise a Missing_module error, and may add forgotten head as required global. Normalize the prefix part of the type path Lookup by long identifiers * [do_copy_types copy env] will raise a fatal error if the values in [env] are different from the env passed to [make_copy_of_types]. Insertion by identifier Insertion of persistent signatures [add_persistent_structure id env] is an environment such that module [id] points to the persistent structure contained in the external compilation unit with the same name. The compilation unit itself is looked up in the load path when the contents of the module is accessed. Returns the set of persistent structures found in the given directory. [filter_non_loaded_persistent f env] removes all the persistent structures that are not yet loaded and for which [f] returns [false]. Insertion of all fields of a signature. Insertion of all fields of a signature, relative to the given path. Used to implement open. Returns None if the path refers to a functor, not a structure. Insertion by name Same as [add_signature] but refreshes (new stamp) and rescopes bound idents in the process. To be called before each toplevel phrase. Remember the name of the current compilation unit. Read, save a signature to/from a file Arguments: module name, file name. Results: signature. Arguments: signature, module name, file name. [is_imported_opaque md] returns true if [md] is an opaque imported module Summaries -- compact representation of an environment, to be exported in debugging information. Update the short paths table Return the short paths table Error report * Folding over all identifiers (for analysis purpose) * Persistent structures are only traversed if they are already loaded. * Utilities
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Types open Misc type summary = Env_empty | Env_value of summary * Ident.t * value_description | Env_type of summary * Ident.t * type_declaration | Env_extension of summary * Ident.t * extension_constructor | Env_module of summary * Ident.t * module_presence * module_declaration | Env_modtype of summary * Ident.t * modtype_declaration | Env_class of summary * Ident.t * class_declaration | Env_cltype of summary * Ident.t * class_type_declaration | Env_open of summary * Path.t | Env_functor_arg of summary * Ident.t | Env_constraints of summary * type_declaration Path.Map.t | Env_copy_types of summary * string list | Env_persistent of summary * Ident.t type address = | Aident of Ident.t | Adot of address * int type t val empty: t val initial_safe_string: t val initial_unsafe_string: t val diff: t -> t -> Ident.t list val copy_local: from:t -> t -> t type type_descriptions = constructor_description list * label_description list type iter_cont val iter_types: (Path.t -> Path.t * (type_declaration * type_descriptions) -> unit) -> t -> iter_cont val run_iter_cont: iter_cont list -> (Path.t * iter_cont) list val same_types: t -> t -> bool val used_persistent: unit -> Concr.t val find_shadowed_types: Path.t -> t -> Path.t list val without_cmis: ('a -> 'b) -> 'a -> 'b [ without_cmis f arg ] applies [ f ] to [ arg ] , but does not allow opening cmis during its execution allow opening cmis during its execution *) val find_value: Path.t -> t -> value_description val find_type: Path.t -> t -> type_declaration val find_type_descrs: Path.t -> t -> type_descriptions val find_module: Path.t -> t -> module_declaration val find_modtype: Path.t -> t -> modtype_declaration val find_class: Path.t -> t -> class_declaration val find_cltype: Path.t -> t -> class_type_declaration val find_type_expansion: Path.t -> t -> type_expr list * type_expr * int val find_type_expansion_opt: Path.t -> t -> type_expr list * type_expr * int val find_modtype_expansion: Path.t -> t -> module_type val find_value_address: Path.t -> t -> address val find_module_address: Path.t -> t -> address val find_class_address: Path.t -> t -> address val find_constructor_address: Path.t -> t -> address val add_functor_arg: Ident.t -> t -> t val is_functor_arg: Path.t -> t -> bool val normalize_module_path: Location.t option -> t -> Path.t -> Path.t val normalize_type_path: Location.t option -> t -> Path.t -> Path.t val normalize_path_prefix: Location.t option -> t -> Path.t -> Path.t Normalize the prefix part of other kinds of paths ( value / modtype / etc ) (value/modtype/etc) *) val reset_required_globals: unit -> unit val get_required_globals: unit -> Ident.t list val add_required_global: Ident.t -> unit val has_local_constraints: t -> bool ? loc is used to report ' deprecated module ' warnings and other alerts val lookup_value: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * value_description val lookup_constructor: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> constructor_description val lookup_all_constructors: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> (constructor_description * (unit -> unit)) list val lookup_label: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> label_description val lookup_all_labels: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> (label_description * (unit -> unit)) list val lookup_type: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t Since 4.04 , this function no longer returns [ type_description ] . To obtain it , you should either call [ Env.find_type ] , or replace it by [ Typetexp.find_type ] To obtain it, you should either call [Env.find_type], or replace it by [Typetexp.find_type] *) val lookup_module: load:bool -> ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t val lookup_modtype: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * modtype_declaration val lookup_class: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * class_declaration val lookup_cltype: ?loc:Location.t -> ?mark:bool -> Longident.t -> t -> Path.t * class_type_declaration type copy_of_types val make_copy_of_types: string list -> t -> copy_of_types val do_copy_types: copy_of_types -> t -> t exception Recmodule Raise by lookup_module when the identifier refers to one of the modules of a recursive definition during the computation of its approximation ( see # 5965 ) . to one of the modules of a recursive definition during the computation of its approximation (see #5965). *) val add_value: ?check:(string -> Warnings.t) -> Ident.t -> value_description -> t -> t val add_type: check:bool -> Ident.t -> type_declaration -> t -> t val add_extension: check:bool -> Ident.t -> extension_constructor -> t -> t val add_module: ?arg:bool -> Ident.t -> module_presence -> module_type -> t -> t val add_module_declaration: ?arg:bool -> check:bool -> Ident.t -> module_presence -> module_declaration -> t -> t val add_modtype: Ident.t -> modtype_declaration -> t -> t val add_class: Ident.t -> class_declaration -> t -> t val add_cltype: Ident.t -> class_type_declaration -> t -> t val add_local_type: Path.t -> type_declaration -> t -> t val add_persistent_structure : Ident.t -> t -> t val persistent_structures_of_dir : Load_path.Dir.t -> Misc.String.Set.t val filter_non_loaded_persistent : (Ident.t -> bool) -> t -> t val add_item: signature_item -> t -> t val add_signature: signature -> t -> t val open_signature: ?used_slot:bool ref -> ?loc:Location.t -> ?toplevel:bool -> Asttypes.override_flag -> Path.t -> t -> t option val open_pers_signature: string -> t -> t val enter_value: ?check:(string -> Warnings.t) -> string -> value_description -> t -> Ident.t * t val enter_type: scope:int -> string -> type_declaration -> t -> Ident.t * t val enter_extension: scope:int -> string -> extension_constructor -> t -> Ident.t * t val enter_module: scope:int -> ?arg:bool -> string -> module_presence -> module_type -> t -> Ident.t * t val enter_module_declaration: ?arg:bool -> Ident.t -> module_presence -> module_declaration -> t -> t val enter_modtype: scope:int -> string -> modtype_declaration -> t -> Ident.t * t val enter_class: scope:int -> string -> class_declaration -> t -> Ident.t * t val enter_cltype: scope:int -> string -> class_type_declaration -> t -> Ident.t * t val enter_signature: scope:int -> signature -> t -> signature * t Initialize the cache of in - core module interfaces . val reset_cache: unit -> unit val reset_cache_toplevel: unit -> unit val set_unit_name: string -> unit val get_unit_name: unit -> string val read_signature: modname -> filepath -> signature val save_signature: alerts:alerts -> signature -> modname -> filepath -> Cmi_format.cmi_infos val save_signature_with_imports: alerts:alerts -> signature -> modname -> filepath -> crcs -> Cmi_format.cmi_infos Arguments : signature , module name , file name , imported units with their CRCs . imported units with their CRCs. *) Return the CRC of the interface of the given compilation unit val crc_of_unit: modname -> Digest.t Return the set of compilation units imported , with their CRC val imports: unit -> crcs may raise Persistent_env . Consistbl . Inconsistency val import_crcs: source:string -> crcs -> unit val is_imported_opaque: modname -> bool val summary: t -> summary Return an equivalent environment where all fields have been reset , except the summary . The initial environment can be rebuilt from the summary , using Envaux.env_of_only_summary . except the summary. The initial environment can be rebuilt from the summary, using Envaux.env_of_only_summary. *) val keep_only_summary : t -> t val env_of_only_summary : (summary -> Subst.t -> t) -> t -> t val update_short_paths : t -> t val short_paths : t -> Short_paths.t type error = | Missing_module of Location.t * Path.t * Path.t | Illegal_value_name of Location.t * string exception Error of error open Format val report_error: formatter -> error -> unit val mark_value_used: string -> value_description -> unit val mark_module_used: string -> Location.t -> unit val mark_type_used: string -> type_declaration -> unit type constructor_usage = Positive | Pattern | Privatize val mark_constructor_used: constructor_usage -> string -> type_declaration -> string -> unit val mark_constructor: constructor_usage -> t -> string -> constructor_description -> unit val mark_extension_used: constructor_usage -> extension_constructor -> string -> unit val in_signature: bool -> t -> t val is_in_signature: t -> bool val set_value_used_callback: string -> value_description -> (unit -> unit) -> unit val set_type_used_callback: string -> type_declaration -> ((unit -> unit) -> unit) -> unit Forward declaration to break mutual recursion with . val check_modtype_inclusion: (loc:Location.t -> t -> module_type -> Path.t -> module_type -> unit) ref Forward declaration to break mutual recursion with . val check_well_formed_module: (t -> Location.t -> string -> module_type -> unit) ref Forward declaration to break mutual recursion with . val add_delayed_check_forward: ((unit -> unit) -> unit) ref Forward declaration to break mutual recursion with Mtype . val strengthen: (aliasable:bool -> t -> module_type -> Path.t -> module_type) ref Forward declaration to break mutual recursion with Ctype . val same_constr: (t -> type_expr -> type_expr -> bool) ref Forward declaration to break mutual recursion with val shorten_module_path : (t -> Path.t -> Path.t) ref val fold_values: (string -> Path.t -> value_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_types: (string -> Path.t -> type_declaration * type_descriptions -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_type_decls: (string -> Path.t -> type_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_constructors: (constructor_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_labels: (label_description -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_modules: (string -> Path.t -> module_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_modtypes: (string -> Path.t -> modtype_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_classes: (string -> Path.t -> class_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val fold_cltypes: (string -> Path.t -> class_type_declaration -> 'a -> 'a) -> Longident.t option -> t -> 'a -> 'a val scrape_alias: t -> module_type -> module_type val check_value_name: string -> Location.t -> unit val print_address : Format.formatter -> address -> unit val unbound_class : Path.t * : manage internal state val check_state_consistency: unit -> bool val with_cmis : (unit -> 'a) -> 'a helper for merlin val add_merlin_extension_module: Ident.t -> module_type -> t -> t Compat with 4.10 val find_value_by_name: Longident.t -> t -> Path.t * value_description val find_constructor_by_name: Longident.t -> t -> constructor_description val find_label_by_name: Longident.t -> t -> label_description val find_type_by_name: Longident.t -> t -> Path.t * type_declaration val find_module_by_name: Longident.t -> t -> Path.t * module_declaration val find_modtype_by_name: Longident.t -> t -> Path.t * modtype_declaration
1bbc5c292a12011891740f5f4645a80dfe0014584f9a7d28595d53d433eefb57
haskell-distributed/network-transport-tcp
Internal.hs
-- | Utility functions for TCP sockets module Network.Transport.TCP.Internal ( ControlHeader(..) , encodeControlHeader , decodeControlHeader , ConnectionRequestResponse(..) , encodeConnectionRequestResponse , decodeConnectionRequestResponse , forkServer , recvWithLength , recvExact , recvWord32 , encodeWord32 , tryCloseSocket , tryShutdownSocketBoth , resolveSockAddr , EndPointId , encodeEndPointAddress , decodeEndPointAddress , randomEndPointAddress , ProtocolVersion , currentProtocolVersion ) where #if ! MIN_VERSION_base(4,6,0) import Prelude hiding (catch) #endif import Network.Transport.Internal ( decodeWord32 , encodeWord32 , void , tryIO , forkIOWithUnmask ) import Network.Transport ( EndPointAddress(..) ) #ifdef USE_MOCK_NETWORK import qualified Network.Transport.TCP.Mock.Socket as N #else import qualified Network.Socket as N #endif ( HostName , NameInfoFlag(NI_NUMERICHOST) , ServiceName , Socket , SocketType(Stream) , SocketOption(ReuseAddr) , getAddrInfo , defaultHints , socket , bind , listen , addrFamily , addrAddress , defaultProtocol , setSocketOption , accept , close , socketPort , shutdown , ShutdownCmd(ShutdownBoth) , SockAddr(..) , getNameInfo ) #ifdef USE_MOCK_NETWORK import qualified Network.Transport.TCP.Mock.Socket.ByteString as NBS (recv) #else import qualified Network.Socket.ByteString as NBS (recv) #endif import Data.Word (Word32, Word64) import Control.Monad (forever, when) import Control.Exception (SomeException, catch, bracketOnError, throwIO, mask_) import Control.Concurrent (ThreadId, forkIO) import Control.Concurrent.MVar ( MVar , newEmptyMVar , putMVar , readMVar ) import Control.Monad (forever, when) import Control.Exception ( SomeException , catch , bracketOnError , throwIO , mask_ , mask , finally , onException ) import Control.Applicative ((<$>), (<*>)) import Data.Word (Word32) import Data.ByteString (ByteString) import qualified Data.ByteString as BS (length, concat, null) import Data.ByteString.Lazy.Internal (smallChunkSize) import Data.ByteString.Lazy (toStrict) import qualified Data.ByteString.Char8 as BSC (unpack, pack) import Data.ByteString.Builder (word64BE, toLazyByteString) import Data.Monoid ((<>)) import qualified Data.UUID as UUID import qualified Data.UUID.V4 as UUID -- | Local identifier for an endpoint within this transport type EndPointId = Word32 -- | Identifies the version of the network-transport-tcp protocol. It 's the first piece of data sent when a new heavyweight connection is -- established. type ProtocolVersion = Word32 currentProtocolVersion :: ProtocolVersion currentProtocolVersion = 0x00000000 -- | Control headers data ControlHeader = -- | Tell the remote endpoint that we created a new connection CreatedNewConnection -- | Tell the remote endpoint we will no longer be using a connection | CloseConnection -- | Request to close the connection (see module description) | CloseSocket -- | Sent by an endpoint when it is closed. | CloseEndPoint -- | Message sent to probe a socket | ProbeSocket -- | Acknowledgement of the ProbeSocket message | ProbeSocketAck deriving (Show) decodeControlHeader :: Word32 -> Maybe ControlHeader decodeControlHeader w32 = case w32 of 0 -> Just CreatedNewConnection 1 -> Just CloseConnection 2 -> Just CloseSocket 3 -> Just CloseEndPoint 4 -> Just ProbeSocket 5 -> Just ProbeSocketAck _ -> Nothing encodeControlHeader :: ControlHeader -> Word32 encodeControlHeader ch = case ch of CreatedNewConnection -> 0 CloseConnection -> 1 CloseSocket -> 2 CloseEndPoint -> 3 ProbeSocket -> 4 ProbeSocketAck -> 5 -- | Response sent by /B/ to /A/ when /A/ tries to connect data ConnectionRequestResponse = -- | /B/ does not support the protocol version requested by /A/. ConnectionRequestUnsupportedVersion -- | /B/ accepts the connection | ConnectionRequestAccepted -- | /A/ requested an invalid endpoint | ConnectionRequestInvalid -- | /A/s request crossed with a request from /B/ (see protocols) | ConnectionRequestCrossed -- | /A/ gave an incorrect host (did not match the host that /B/ observed). | ConnectionRequestHostMismatch deriving (Show) decodeConnectionRequestResponse :: Word32 -> Maybe ConnectionRequestResponse decodeConnectionRequestResponse w32 = case w32 of 0xFFFFFFFF -> Just ConnectionRequestUnsupportedVersion 0x00000000 -> Just ConnectionRequestAccepted 0x00000001 -> Just ConnectionRequestInvalid 0x00000002 -> Just ConnectionRequestCrossed 0x00000003 -> Just ConnectionRequestHostMismatch _ -> Nothing encodeConnectionRequestResponse :: ConnectionRequestResponse -> Word32 encodeConnectionRequestResponse crr = case crr of ConnectionRequestUnsupportedVersion -> 0xFFFFFFFF ConnectionRequestAccepted -> 0x00000000 ConnectionRequestInvalid -> 0x00000001 ConnectionRequestCrossed -> 0x00000002 ConnectionRequestHostMismatch -> 0x00000003 | Generate an EndPointAddress which does not encode a host / port / endpointid . -- Such addresses are used for unreachable endpoints, and for ephemeral -- addresses when such endpoints establish new heavyweight connections. randomEndPointAddress :: IO EndPointAddress randomEndPointAddress = do uuid <- UUID.nextRandom return $ EndPointAddress (UUID.toASCIIBytes uuid) -- | Start a server at the specified address. -- -- This sets up a server socket for the specified host and port. Exceptions -- thrown during setup are not caught. -- -- Once the socket is created we spawn a new thread which repeatedly accepts -- incoming connections and executes the given request handler in another -- thread. If any exception occurs the accepting thread terminates and calls the terminationHandler . Threads spawned for previous accepted connections -- are not killed. -- This exception may occur because of a call to 'N.accept', or because the -- thread was explicitly killed. -- -- The request handler is not responsible for closing the socket. It will be -- closed once that handler returns. Take care to ensure that the socket is not -- used after the handler returns, or you will get undefined behavior -- (the file descriptor may be re-used). -- -- The return value includes the port was bound to. This is not always the same -- port as that given in the argument. For example, binding to port 0 actually -- binds to a random port, selected by the OS. forkServer :: N.HostName -- ^ Host -> N.ServiceName -- ^ Port -> Int -- ^ Backlog (maximum number of queued connections) -> Bool -- ^ Set ReuseAddr option? -> (SomeException -> IO ()) -- ^ Error handler. Called with an -- exception raised when -- accepting a connection. -> (SomeException -> IO ()) -- ^ Termination handler. Called -- when the error handler throws -- an exception. -> (IO () -> (N.Socket, N.SockAddr) -> IO ()) -- ^ Request handler. Gets an -- action which completes when -- the socket is closed. -> IO (N.ServiceName, ThreadId) forkServer host port backlog reuseAddr errorHandler terminationHandler requestHandler = do Resolve the specified address . By specification , will never -- return an empty list (but will throw an exception instead) and will return the " best " address first , whatever that means addr:_ <- N.getAddrInfo (Just N.defaultHints) (Just host) (Just port) bracketOnError (N.socket (N.addrFamily addr) N.Stream N.defaultProtocol) tryCloseSocket $ \sock -> do when reuseAddr $ N.setSocketOption sock N.ReuseAddr 1 N.bind sock (N.addrAddress addr) N.listen sock backlog Close up and fill the synchonizing MVar . let release :: ((N.Socket, N.SockAddr), MVar ()) -> IO () release ((sock, _), socketClosed) = N.close sock `finally` putMVar socketClosed () -- Run the request handler. let act restore (sock, sockAddr) = do socketClosed <- newEmptyMVar void $ forkIO $ restore $ do requestHandler (readMVar socketClosed) (sock, sockAddr) `finally` release ((sock, sockAddr), socketClosed) let acceptRequest :: IO () acceptRequest = mask $ \restore -> do -- Async exceptions are masked so that, if accept does give a -- socket, we'll always deliver it to the handler before the -- exception is raised. -- If it's a Right handler then it will eventually be closed. -- If it's a Left handler then we assume the handler itself will -- close it. (sock, sockAddr) <- N.accept sock -- Looks like 'act' will never throw an exception, but to be -- safe we'll close the socket if it does. let handler :: SomeException -> IO () handler _ = N.close sock catch (act restore (sock, sockAddr)) handler -- We start listening for incoming requests in a separate thread. When -- that thread is killed, we close the server socket and the termination -- handler is run. We have to make sure that the exception handler is installed /before/ any asynchronous exception occurs . So we mask _ , then -- fork (the child thread inherits the masked state from the parent), then -- unmask only inside the catch. (,) <$> fmap show (N.socketPort sock) <*> (mask_ $ forkIOWithUnmask $ \unmask -> catch (unmask (forever (catch acceptRequest errorHandler))) $ \ex -> do tryCloseSocket sock terminationHandler ex) -- | Read a length and then a payload of that length, subject to a limit -- on the length. If the length ( first ' ' received ) is greater than the limit then -- an exception is thrown. recvWithLength :: Word32 -> N.Socket -> IO [ByteString] recvWithLength limit sock = do len <- recvWord32 sock when (len > limit) $ throwIO (userError "recvWithLength: limit exceeded") recvExact sock len | Receive a 32 - bit unsigned integer recvWord32 :: N.Socket -> IO Word32 recvWord32 = fmap (decodeWord32 . BS.concat) . flip recvExact 4 -- | Close a socket, ignoring I/O exceptions. tryCloseSocket :: N.Socket -> IO () tryCloseSocket sock = void . tryIO $ N.close sock -- | Shutdown socket sends and receives, ignoring I/O exceptions. tryShutdownSocketBoth :: N.Socket -> IO () tryShutdownSocketBoth sock = void . tryIO $ N.shutdown sock N.ShutdownBoth -- | Read an exact number of bytes from a socket -- -- Throws an I/O exception if the socket closes before the specified -- number of bytes could be read recvExact :: N.Socket -- ^ Socket to read from -> Word32 -- ^ Number of bytes to read -> IO [ByteString] -- ^ Data read recvExact sock len = go [] len where go :: [ByteString] -> Word32 -> IO [ByteString] go acc 0 = return (reverse acc) go acc l = do bs <- NBS.recv sock (fromIntegral l `min` smallChunkSize) if BS.null bs then throwIO (userError "recvExact: Socket closed") else go (bs : acc) (l - fromIntegral (BS.length bs)) -- | Get the numeric host, resolved host (via getNameInfo), and port from a SockAddr . The numeric host is first , then resolved host ( which may be the -- same as the numeric host). Will only give ' Just ' for IPv4 addresses . resolveSockAddr :: N.SockAddr -> IO (Maybe (N.HostName, N.HostName, N.ServiceName)) resolveSockAddr sockAddr = case sockAddr of N.SockAddrInet port host -> do (mResolvedHost, mResolvedPort) <- N.getNameInfo [] True False sockAddr case (mResolvedHost, mResolvedPort) of (Just resolvedHost, Nothing) -> do (Just numericHost, _) <- N.getNameInfo [N.NI_NUMERICHOST] True False sockAddr return $ Just (numericHost, resolvedHost, show port) _ -> error $ concat [ "decodeSockAddr: unexpected resolution " , show sockAddr , " -> " , show mResolvedHost , ", " , show mResolvedPort ] _ -> return Nothing -- | Encode end point address encodeEndPointAddress :: N.HostName -> N.ServiceName -> EndPointId -> EndPointAddress encodeEndPointAddress host port ix = EndPointAddress . BSC.pack $ host ++ ":" ++ port ++ ":" ++ show ix -- | Decode end point address decodeEndPointAddress :: EndPointAddress -> Maybe (N.HostName, N.ServiceName, EndPointId) decodeEndPointAddress (EndPointAddress bs) = case splitMaxFromEnd (== ':') 2 $ BSC.unpack bs of [host, port, endPointIdStr] -> case reads endPointIdStr of [(endPointId, "")] -> Just (host, port, endPointId) _ -> Nothing _ -> Nothing -- | @spltiMaxFromEnd p n xs@ splits list @xs@ at elements matching @p@, -- returning at most @p@ segments -- counting from the /end/ -- > splitMaxFromEnd (= = ' :') 2 " ab : cd : ef : gh " = = [ " ab : cd " , " ef " , " gh " ] splitMaxFromEnd :: (a -> Bool) -> Int -> [a] -> [[a]] splitMaxFromEnd p = \n -> go [[]] n . reverse where -- go :: [[a]] -> Int -> [a] -> [[a]] go accs _ [] = accs go ([] : accs) 0 xs = reverse xs : accs go (acc : accs) n (x:xs) = if p x then go ([] : acc : accs) (n - 1) xs else go ((x : acc) : accs) n xs go _ _ _ = error "Bug in splitMaxFromEnd"
null
https://raw.githubusercontent.com/haskell-distributed/network-transport-tcp/b8bf605ec3aab410664ba519c93f570b848082ef/src/Network/Transport/TCP/Internal.hs
haskell
| Utility functions for TCP sockets | Local identifier for an endpoint within this transport | Identifies the version of the network-transport-tcp protocol. established. | Control headers | Tell the remote endpoint that we created a new connection | Tell the remote endpoint we will no longer be using a connection | Request to close the connection (see module description) | Sent by an endpoint when it is closed. | Message sent to probe a socket | Acknowledgement of the ProbeSocket message | Response sent by /B/ to /A/ when /A/ tries to connect | /B/ does not support the protocol version requested by /A/. | /B/ accepts the connection | /A/ requested an invalid endpoint | /A/s request crossed with a request from /B/ (see protocols) | /A/ gave an incorrect host (did not match the host that /B/ observed). Such addresses are used for unreachable endpoints, and for ephemeral addresses when such endpoints establish new heavyweight connections. | Start a server at the specified address. This sets up a server socket for the specified host and port. Exceptions thrown during setup are not caught. Once the socket is created we spawn a new thread which repeatedly accepts incoming connections and executes the given request handler in another thread. If any exception occurs the accepting thread terminates and calls are not killed. This exception may occur because of a call to 'N.accept', or because the thread was explicitly killed. The request handler is not responsible for closing the socket. It will be closed once that handler returns. Take care to ensure that the socket is not used after the handler returns, or you will get undefined behavior (the file descriptor may be re-used). The return value includes the port was bound to. This is not always the same port as that given in the argument. For example, binding to port 0 actually binds to a random port, selected by the OS. ^ Host ^ Port ^ Backlog (maximum number of queued connections) ^ Set ReuseAddr option? ^ Error handler. Called with an exception raised when accepting a connection. ^ Termination handler. Called when the error handler throws an exception. ^ Request handler. Gets an action which completes when the socket is closed. return an empty list (but will throw an exception instead) and will return Run the request handler. Async exceptions are masked so that, if accept does give a socket, we'll always deliver it to the handler before the exception is raised. If it's a Right handler then it will eventually be closed. If it's a Left handler then we assume the handler itself will close it. Looks like 'act' will never throw an exception, but to be safe we'll close the socket if it does. We start listening for incoming requests in a separate thread. When that thread is killed, we close the server socket and the termination handler is run. We have to make sure that the exception handler is fork (the child thread inherits the masked state from the parent), then unmask only inside the catch. | Read a length and then a payload of that length, subject to a limit on the length. an exception is thrown. | Close a socket, ignoring I/O exceptions. | Shutdown socket sends and receives, ignoring I/O exceptions. | Read an exact number of bytes from a socket Throws an I/O exception if the socket closes before the specified number of bytes could be read ^ Socket to read from ^ Number of bytes to read ^ Data read | Get the numeric host, resolved host (via getNameInfo), and port from a same as the numeric host). | Encode end point address | Decode end point address | @spltiMaxFromEnd p n xs@ splits list @xs@ at elements matching @p@, returning at most @p@ segments -- counting from the /end/ go :: [[a]] -> Int -> [a] -> [[a]]
module Network.Transport.TCP.Internal ( ControlHeader(..) , encodeControlHeader , decodeControlHeader , ConnectionRequestResponse(..) , encodeConnectionRequestResponse , decodeConnectionRequestResponse , forkServer , recvWithLength , recvExact , recvWord32 , encodeWord32 , tryCloseSocket , tryShutdownSocketBoth , resolveSockAddr , EndPointId , encodeEndPointAddress , decodeEndPointAddress , randomEndPointAddress , ProtocolVersion , currentProtocolVersion ) where #if ! MIN_VERSION_base(4,6,0) import Prelude hiding (catch) #endif import Network.Transport.Internal ( decodeWord32 , encodeWord32 , void , tryIO , forkIOWithUnmask ) import Network.Transport ( EndPointAddress(..) ) #ifdef USE_MOCK_NETWORK import qualified Network.Transport.TCP.Mock.Socket as N #else import qualified Network.Socket as N #endif ( HostName , NameInfoFlag(NI_NUMERICHOST) , ServiceName , Socket , SocketType(Stream) , SocketOption(ReuseAddr) , getAddrInfo , defaultHints , socket , bind , listen , addrFamily , addrAddress , defaultProtocol , setSocketOption , accept , close , socketPort , shutdown , ShutdownCmd(ShutdownBoth) , SockAddr(..) , getNameInfo ) #ifdef USE_MOCK_NETWORK import qualified Network.Transport.TCP.Mock.Socket.ByteString as NBS (recv) #else import qualified Network.Socket.ByteString as NBS (recv) #endif import Data.Word (Word32, Word64) import Control.Monad (forever, when) import Control.Exception (SomeException, catch, bracketOnError, throwIO, mask_) import Control.Concurrent (ThreadId, forkIO) import Control.Concurrent.MVar ( MVar , newEmptyMVar , putMVar , readMVar ) import Control.Monad (forever, when) import Control.Exception ( SomeException , catch , bracketOnError , throwIO , mask_ , mask , finally , onException ) import Control.Applicative ((<$>), (<*>)) import Data.Word (Word32) import Data.ByteString (ByteString) import qualified Data.ByteString as BS (length, concat, null) import Data.ByteString.Lazy.Internal (smallChunkSize) import Data.ByteString.Lazy (toStrict) import qualified Data.ByteString.Char8 as BSC (unpack, pack) import Data.ByteString.Builder (word64BE, toLazyByteString) import Data.Monoid ((<>)) import qualified Data.UUID as UUID import qualified Data.UUID.V4 as UUID type EndPointId = Word32 It 's the first piece of data sent when a new heavyweight connection is type ProtocolVersion = Word32 currentProtocolVersion :: ProtocolVersion currentProtocolVersion = 0x00000000 data ControlHeader = CreatedNewConnection | CloseConnection | CloseSocket | CloseEndPoint | ProbeSocket | ProbeSocketAck deriving (Show) decodeControlHeader :: Word32 -> Maybe ControlHeader decodeControlHeader w32 = case w32 of 0 -> Just CreatedNewConnection 1 -> Just CloseConnection 2 -> Just CloseSocket 3 -> Just CloseEndPoint 4 -> Just ProbeSocket 5 -> Just ProbeSocketAck _ -> Nothing encodeControlHeader :: ControlHeader -> Word32 encodeControlHeader ch = case ch of CreatedNewConnection -> 0 CloseConnection -> 1 CloseSocket -> 2 CloseEndPoint -> 3 ProbeSocket -> 4 ProbeSocketAck -> 5 data ConnectionRequestResponse = ConnectionRequestUnsupportedVersion | ConnectionRequestAccepted | ConnectionRequestInvalid | ConnectionRequestCrossed | ConnectionRequestHostMismatch deriving (Show) decodeConnectionRequestResponse :: Word32 -> Maybe ConnectionRequestResponse decodeConnectionRequestResponse w32 = case w32 of 0xFFFFFFFF -> Just ConnectionRequestUnsupportedVersion 0x00000000 -> Just ConnectionRequestAccepted 0x00000001 -> Just ConnectionRequestInvalid 0x00000002 -> Just ConnectionRequestCrossed 0x00000003 -> Just ConnectionRequestHostMismatch _ -> Nothing encodeConnectionRequestResponse :: ConnectionRequestResponse -> Word32 encodeConnectionRequestResponse crr = case crr of ConnectionRequestUnsupportedVersion -> 0xFFFFFFFF ConnectionRequestAccepted -> 0x00000000 ConnectionRequestInvalid -> 0x00000001 ConnectionRequestCrossed -> 0x00000002 ConnectionRequestHostMismatch -> 0x00000003 | Generate an EndPointAddress which does not encode a host / port / endpointid . randomEndPointAddress :: IO EndPointAddress randomEndPointAddress = do uuid <- UUID.nextRandom return $ EndPointAddress (UUID.toASCIIBytes uuid) the terminationHandler . Threads spawned for previous accepted connections -> (IO () -> (N.Socket, N.SockAddr) -> IO ()) -> IO (N.ServiceName, ThreadId) forkServer host port backlog reuseAddr errorHandler terminationHandler requestHandler = do Resolve the specified address . By specification , will never the " best " address first , whatever that means addr:_ <- N.getAddrInfo (Just N.defaultHints) (Just host) (Just port) bracketOnError (N.socket (N.addrFamily addr) N.Stream N.defaultProtocol) tryCloseSocket $ \sock -> do when reuseAddr $ N.setSocketOption sock N.ReuseAddr 1 N.bind sock (N.addrAddress addr) N.listen sock backlog Close up and fill the synchonizing MVar . let release :: ((N.Socket, N.SockAddr), MVar ()) -> IO () release ((sock, _), socketClosed) = N.close sock `finally` putMVar socketClosed () let act restore (sock, sockAddr) = do socketClosed <- newEmptyMVar void $ forkIO $ restore $ do requestHandler (readMVar socketClosed) (sock, sockAddr) `finally` release ((sock, sockAddr), socketClosed) let acceptRequest :: IO () acceptRequest = mask $ \restore -> do (sock, sockAddr) <- N.accept sock let handler :: SomeException -> IO () handler _ = N.close sock catch (act restore (sock, sockAddr)) handler installed /before/ any asynchronous exception occurs . So we mask _ , then (,) <$> fmap show (N.socketPort sock) <*> (mask_ $ forkIOWithUnmask $ \unmask -> catch (unmask (forever (catch acceptRequest errorHandler))) $ \ex -> do tryCloseSocket sock terminationHandler ex) If the length ( first ' ' received ) is greater than the limit then recvWithLength :: Word32 -> N.Socket -> IO [ByteString] recvWithLength limit sock = do len <- recvWord32 sock when (len > limit) $ throwIO (userError "recvWithLength: limit exceeded") recvExact sock len | Receive a 32 - bit unsigned integer recvWord32 :: N.Socket -> IO Word32 recvWord32 = fmap (decodeWord32 . BS.concat) . flip recvExact 4 tryCloseSocket :: N.Socket -> IO () tryCloseSocket sock = void . tryIO $ N.close sock tryShutdownSocketBoth :: N.Socket -> IO () tryShutdownSocketBoth sock = void . tryIO $ N.shutdown sock N.ShutdownBoth recvExact sock len = go [] len where go :: [ByteString] -> Word32 -> IO [ByteString] go acc 0 = return (reverse acc) go acc l = do bs <- NBS.recv sock (fromIntegral l `min` smallChunkSize) if BS.null bs then throwIO (userError "recvExact: Socket closed") else go (bs : acc) (l - fromIntegral (BS.length bs)) SockAddr . The numeric host is first , then resolved host ( which may be the Will only give ' Just ' for IPv4 addresses . resolveSockAddr :: N.SockAddr -> IO (Maybe (N.HostName, N.HostName, N.ServiceName)) resolveSockAddr sockAddr = case sockAddr of N.SockAddrInet port host -> do (mResolvedHost, mResolvedPort) <- N.getNameInfo [] True False sockAddr case (mResolvedHost, mResolvedPort) of (Just resolvedHost, Nothing) -> do (Just numericHost, _) <- N.getNameInfo [N.NI_NUMERICHOST] True False sockAddr return $ Just (numericHost, resolvedHost, show port) _ -> error $ concat [ "decodeSockAddr: unexpected resolution " , show sockAddr , " -> " , show mResolvedHost , ", " , show mResolvedPort ] _ -> return Nothing encodeEndPointAddress :: N.HostName -> N.ServiceName -> EndPointId -> EndPointAddress encodeEndPointAddress host port ix = EndPointAddress . BSC.pack $ host ++ ":" ++ port ++ ":" ++ show ix decodeEndPointAddress :: EndPointAddress -> Maybe (N.HostName, N.ServiceName, EndPointId) decodeEndPointAddress (EndPointAddress bs) = case splitMaxFromEnd (== ':') 2 $ BSC.unpack bs of [host, port, endPointIdStr] -> case reads endPointIdStr of [(endPointId, "")] -> Just (host, port, endPointId) _ -> Nothing _ -> Nothing > splitMaxFromEnd (= = ' :') 2 " ab : cd : ef : gh " = = [ " ab : cd " , " ef " , " gh " ] splitMaxFromEnd :: (a -> Bool) -> Int -> [a] -> [[a]] splitMaxFromEnd p = \n -> go [[]] n . reverse where go accs _ [] = accs go ([] : accs) 0 xs = reverse xs : accs go (acc : accs) n (x:xs) = if p x then go ([] : acc : accs) (n - 1) xs else go ((x : acc) : accs) n xs go _ _ _ = error "Bug in splitMaxFromEnd"
03db7c42f1d9a91d883ec48d1eec9a7602531035af87b1d71912eb620c7e0f66
racket/slideshow
info.rkt
#lang info (define scribblings '(("slideshow.scrbl" (multi-page) (tool))))
null
https://raw.githubusercontent.com/racket/slideshow/4588507e83e9aa859c6841e655b98417d46987e6/slideshow-doc/scribblings/slideshow/info.rkt
racket
#lang info (define scribblings '(("slideshow.scrbl" (multi-page) (tool))))
82f4016fe9c775d549102e1c27c2ae005a0741014a92666c3865ef17f05cdfaf
tomhanika/conexp-clj
contexts_test.clj
;; Copyright ⓒ the conexp-clj developers; all rights reserved. ;; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) ;; which can be found in the file LICENSE at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns conexp.io.contexts-test (:use conexp.base conexp.fca.contexts conexp.fca.many-valued-contexts conexp.io.contexts conexp.io.util-test) (:use clojure.test)) ;;; (def- contexts-oi "Context to use for out-in testing" [(make-context #{"a" "b" "c"} #{"1" "2" "3"} #{["a" "1"] ["a" "3"] ["b" "2"] ["c" "3"]}), (null-context #{})]) (def- contexts-oi-fcalgs [(make-context #{0 1} #{0 1} #{[0 1] [1 0] [1 1]})]) (deftest test-context-out-in (with-testing-data [ctx contexts-oi, fmt (remove #{:binary-csv :anonymous-burmeister :fcalgs :named-binary-csv} (list-context-formats))] (= ctx (out-in ctx 'context fmt))) ;; named-binary-csv cannot export empty context (with-testing-data [ctx [(first contexts-oi)], fmt #{:named-binary-csv}] (= ctx (out-in ctx 'context fmt))) ;; fcalgs can only store contexts with integral objects and attributes >=0, ;; and thus needs to be tested with another context (with-testing-data [ctx contexts-oi-fcalgs, fmt #{:fcalgs}] (= ctx (out-in ctx 'context fmt)))) (defn- possible-isomorphic? "Test for equality of some criteria for context isomorphy. Namely, number of objects and attributes, the size of the incidence relation, and the number of concepts. Only use with small contexts." [ctx1 ctx2] (are [x y] (= (count x) (count y)) (objects ctx1) (objects ctx2) (attributes ctx1) (attributes ctx2) (incidence-relation ctx1) (incidence-relation ctx2) (concepts ctx1) (concepts ctx2))) (deftest test-isomorphic-out-in (with-testing-data [ctx contexts-oi fmt #{:anonymous-burmeister}] (possible-isomorphic? ctx (out-in ctx 'context fmt))) ;; binary-csv cannot export empty context (with-testing-data [ctx [(first contexts-oi)] fmt #{ :binary-csv}] (possible-isomorphic? ctx (out-in ctx 'context fmt)))) ;; (def- contexts-oioi "Contexts to use for out-in-out-in testing" [(make-context #{1 2 3} #{4 5 6} <), (make-context #{'a} #{'+} #{['a '+]})]) (deftest test-context-out-in-out-in (with-testing-data [ctx contexts-oioi, fmt (remove #{:anonymous-burmeister :fcalgs} (list-context-formats))] (out-in-out-in-test ctx 'context fmt)) ;; fcalgs can only store contexts with integral objects and attributes >=0, ;; and thus needs to be tested with another context (with-testing-data [ctx contexts-oi-fcalgs, fmt #{:fcalgs}] (out-in-out-in-test ctx 'context fmt))) (deftest test-anonymous-burmeister-out-in-out-in (with-testing-data [ctx contexts-oioi fmt #{:anonymous-burmeister}] (let [ctx1 (out-in ctx 'context fmt) ctx2 (out-in ctx1 'context fmt)] (possible-isomorphic? ctx1 ctx2 )))) ;; (def- contexts-with-empty-columns "Context with empty columns, to test for corner cases" [(null-context #{}), (null-context #{1 2 3 4}), (null-context #{1 2 3}), (make-context #{1 2 3} #{1 2 3} #{[1 2] [2 3] [3 2]})]) (deftest test-empty-columns (with-testing-data [ctx contexts-with-empty-columns, ;; colibri and fcalgs cannot handle empty rows or columns ;; empty contexts cannot be exported to named-binary-csv or binary-csv fmt (remove #{:colibri :fcalgs :named-binary-csv :binary-csv} (list-context-formats))] (out-in-out-in-test ctx 'context fmt)) (with-testing-data [ctx (rest contexts-with-empty-columns), fmt #{:named-binary-csv :binary-csv}] (out-in-out-in-test ctx 'context fmt))) ;; (def- random-test-contexts (vec (random-contexts 20 50))) (deftest test-for-random-contexts (with-testing-data [ctx random-test-contexts, ;; colibri and fcalgs cannot handle empty rows or columns ;; binary-csv and named-binary-csv cannot handle empty contexts fmt (remove #{:anonymous-burmeister :colibri :fcalgs :binary-csv :named-binary-csv} (list-context-formats))] (out-in-out-in-test ctx 'context fmt)) (with-testing-data [ctx (filter #(not (empty? (incidence-relation %))) random-test-contexts), fmt #{:binary-csv :named-binary-csv}] (out-in-out-in-test ctx 'context fmt))) (deftest test-anonymous-burmeister-out-in-out-in-for-random-contexts (with-testing-data [ctx (random-contexts 20 10), fmt #{:anonymous-burmeister}] (let [ctx1 (out-in ctx 'context fmt) ctx2 (out-in ctx1 'context fmt)] (possible-isomorphic? ctx1 ctx2 )))) ;;; GraphML (seperate testing as it can only be read but not written) (deftest test-graphml (is (thrown-with-msg? IllegalArgumentException #"Specified file does not contain valid XML." (read-context "testing-data/Booth.cxt" :graphml))) (is (thrown-with-msg? IllegalArgumentException #"Specified file not found." (read-context "testing-data/NotExisting.nope" :graphml))) (is (thrown-with-msg? IllegalArgumentException #"All edges and hyperedges of an hypergraph need ids." (read-context "testing-data/graphml/hyper.graphml" :graphml))) (is (thrown-with-msg? IllegalArgumentException #"XML file does not contain GraphML." (read-context "testing-data/graphml/fake.graphml" :graphml))) (is (= (first (read-context "testing-data/graphml/simple.graphml" :graphml)) (make-context #{"n0" "n1" "n2" "n3" "n4" "n5"} #{"n0" "n1" "n2" "n3" "n4" "n5"} #{["n0" "n2"]["n1" "n2"]["n2" "n3"] ["n2" "n0"]["n2" "n1"]["n3" "n2"]}))) (is (= (first (read-context "testing-data/graphml/hyperids.graphml" :graphml)) (make-context #{"n0" "n1" "n2" "n3"} #{"1" "3" "4"} #{["n0" "1"]["n1" "1"]["n2" "1"] ["n1" "3"]["n3" "3"] ["n0" "4"]["n4" "4"]}))) (is (= (first (read-context "testing-data/graphml/fuzzy.graphml" :graphml)) (make-mv-context #{"n0" "n1" "n2"} #{"n0" "n1" "n2"} #{["n0" "n1" "1.0"]["n0" "n2" "1.0"] ["n1" "n2" "2.0"] ["n1" "n0" "1.0"]["n2" "n0" "1.0"] ["n2" "n1" "2.0"]}))) (is (thrown-with-msg? IllegalArgumentException #"Multiple data values for edges are not supported." (read-context "testing-data/graphml/fuzzymulti.graphml" :graphml))) (is (thrown-with-msg? IllegalArgumentException #"Only single values are supported as edge data." (read-context "testing-data/graphml/svg.graphml" :graphml))) (is (= (first (read-context "testing-data/graphml/port.graphml" :graphml)) (make-context #{"n0" "n1"} #{"0" "1"} #{["n0" "0"]["n0" "1"] ["n1" "0"]["n1" "1"]})))) ;;; (deftest test-automatically-identify-input-format-galicia "Test if other input formats throw an error when searching for an input format matching the input file." (if-not (.exists (java.io.File. "testing-data/galicia2.bin.xml")) (warn "Could not verify identifying :galicia input format. Testing file not found.") (let [ctx (read-context "testing-data/galicia2.bin.xml")] (is (= 10 (count (attributes ctx)))) (is (= 10 (count (objects ctx)))) (is (= 27 (count (incidence-relation ctx))))))) (deftest test-json-not-matching-schema "Read a json format that does not match the given schema." (if-not (.exists (java.io.File. "testing-data/digits-lattice.json")) (warn "Could not verify failing validation of context schema. Testing file not found.") (is (thrown? AssertionError (read-context "testing-data/digits-lattice.json" :json))))) (deftest test-json-matching-schema "Read a json format that matches the given schema." (let [file "testing-data/digits-context1.1.json"] (if-not (.exists (java.io.File. file)) (warn "Could not verify validation of context schema. Testing file not found.") (let [ctx (read-context file :json)] (is (= 7 (count (attributes ctx)))) (is (= 10 (count (objects ctx)))) (is (= 47 (count (incidence-relation ctx)))))))) ;;; (deftest test-bug-001 (if-not (.exists (java.io.File. "testing-data/nn_5.half.cex")) (warn "Could not verify bug 001, testing file not found.") (let [ctx (read-context "testing-data/nn_5.half.cex")] (is (= 42 (count (attributes ctx)))) (is (= 10 (count (objects ctx)))) (is (= 120 (count (incidence-relation ctx))))))) ;;; (deftest test-identify-input-format "Test if the automatic identification of the file format works correctly." (with-testing-data [ctx contexts-oi, fmt (remove #{:named-binary-csv :anonymous-burmeister :binary-csv :fcalgs} (list-context-formats))] (= ctx (out-in-without-format ctx 'context fmt))) ;; The null-context in contexts-io cannot be exported to :named-binary-csv ;; format. (with-testing-data [ctx [(first contexts-oi)], fmt #{:named-binary-csv}] (= ctx (out-in-without-format ctx 'context fmt))) ;; During writing / reading in :anonymous-burmeister format, object and ;; attribute names get lost and equality cannot be tested any more. (with-testing-data [ctx contexts-oi, fmt #{:anonymous-burmeister}] (possible-isomorphic? ctx (out-in-without-format ctx 'context fmt))) ;; The null-context in contexts-io cannot be exported to :binary-csv format. ;; During writing / reading in :binary-csv format, object and attribute names ;; get lost and equality cannot be tested any more. (with-testing-data [ctx [(first contexts-oi)], fmt #{:binary-csv}] (possible-isomorphic? ctx (out-in-without-format ctx 'context fmt))) ;; fcalgs test with another context (with-testing-data [ctx contexts-oi-fcalgs, fmt #{:fcalgs}] (= ctx (out-in-without-format ctx 'context fmt)))) (deftest test-ctx->json ;; test that attributes with empty column are not dropped (let [K (make-context-from-matrix [1 2] [:a :b] [1 0 0 0])] (is (= (ctx->json K) {:attributes #{:a :b} :objects #{1 2} :incidence #{[1 :a]}})))) nil
null
https://raw.githubusercontent.com/tomhanika/conexp-clj/9f53c71913fa39b95516c388d9e426bec34e3a77/src/test/clojure/conexp/io/contexts_test.clj
clojure
Copyright ⓒ the conexp-clj developers; all rights reserved. The use and distribution terms for this software are covered by the which can be found in the file LICENSE at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. named-binary-csv cannot export empty context fcalgs can only store contexts with integral objects and attributes >=0, and thus needs to be tested with another context binary-csv cannot export empty context fcalgs can only store contexts with integral objects and attributes >=0, and thus needs to be tested with another context colibri and fcalgs cannot handle empty rows or columns empty contexts cannot be exported to named-binary-csv or binary-csv colibri and fcalgs cannot handle empty rows or columns binary-csv and named-binary-csv cannot handle empty contexts GraphML (seperate testing as it can only be read but not written) The null-context in contexts-io cannot be exported to :named-binary-csv format. During writing / reading in :anonymous-burmeister format, object and attribute names get lost and equality cannot be tested any more. The null-context in contexts-io cannot be exported to :binary-csv format. During writing / reading in :binary-csv format, object and attribute names get lost and equality cannot be tested any more. fcalgs test with another context test that attributes with empty column are not dropped
Eclipse Public License 1.0 ( -1.0.php ) (ns conexp.io.contexts-test (:use conexp.base conexp.fca.contexts conexp.fca.many-valued-contexts conexp.io.contexts conexp.io.util-test) (:use clojure.test)) (def- contexts-oi "Context to use for out-in testing" [(make-context #{"a" "b" "c"} #{"1" "2" "3"} #{["a" "1"] ["a" "3"] ["b" "2"] ["c" "3"]}), (null-context #{})]) (def- contexts-oi-fcalgs [(make-context #{0 1} #{0 1} #{[0 1] [1 0] [1 1]})]) (deftest test-context-out-in (with-testing-data [ctx contexts-oi, fmt (remove #{:binary-csv :anonymous-burmeister :fcalgs :named-binary-csv} (list-context-formats))] (= ctx (out-in ctx 'context fmt))) (with-testing-data [ctx [(first contexts-oi)], fmt #{:named-binary-csv}] (= ctx (out-in ctx 'context fmt))) (with-testing-data [ctx contexts-oi-fcalgs, fmt #{:fcalgs}] (= ctx (out-in ctx 'context fmt)))) (defn- possible-isomorphic? "Test for equality of some criteria for context isomorphy. Namely, number of objects and attributes, the size of the incidence relation, and the number of concepts. Only use with small contexts." [ctx1 ctx2] (are [x y] (= (count x) (count y)) (objects ctx1) (objects ctx2) (attributes ctx1) (attributes ctx2) (incidence-relation ctx1) (incidence-relation ctx2) (concepts ctx1) (concepts ctx2))) (deftest test-isomorphic-out-in (with-testing-data [ctx contexts-oi fmt #{:anonymous-burmeister}] (possible-isomorphic? ctx (out-in ctx 'context fmt))) (with-testing-data [ctx [(first contexts-oi)] fmt #{ :binary-csv}] (possible-isomorphic? ctx (out-in ctx 'context fmt)))) (def- contexts-oioi "Contexts to use for out-in-out-in testing" [(make-context #{1 2 3} #{4 5 6} <), (make-context #{'a} #{'+} #{['a '+]})]) (deftest test-context-out-in-out-in (with-testing-data [ctx contexts-oioi, fmt (remove #{:anonymous-burmeister :fcalgs} (list-context-formats))] (out-in-out-in-test ctx 'context fmt)) (with-testing-data [ctx contexts-oi-fcalgs, fmt #{:fcalgs}] (out-in-out-in-test ctx 'context fmt))) (deftest test-anonymous-burmeister-out-in-out-in (with-testing-data [ctx contexts-oioi fmt #{:anonymous-burmeister}] (let [ctx1 (out-in ctx 'context fmt) ctx2 (out-in ctx1 'context fmt)] (possible-isomorphic? ctx1 ctx2 )))) (def- contexts-with-empty-columns "Context with empty columns, to test for corner cases" [(null-context #{}), (null-context #{1 2 3 4}), (null-context #{1 2 3}), (make-context #{1 2 3} #{1 2 3} #{[1 2] [2 3] [3 2]})]) (deftest test-empty-columns (with-testing-data [ctx contexts-with-empty-columns, fmt (remove #{:colibri :fcalgs :named-binary-csv :binary-csv} (list-context-formats))] (out-in-out-in-test ctx 'context fmt)) (with-testing-data [ctx (rest contexts-with-empty-columns), fmt #{:named-binary-csv :binary-csv}] (out-in-out-in-test ctx 'context fmt))) (def- random-test-contexts (vec (random-contexts 20 50))) (deftest test-for-random-contexts (with-testing-data [ctx random-test-contexts, fmt (remove #{:anonymous-burmeister :colibri :fcalgs :binary-csv :named-binary-csv} (list-context-formats))] (out-in-out-in-test ctx 'context fmt)) (with-testing-data [ctx (filter #(not (empty? (incidence-relation %))) random-test-contexts), fmt #{:binary-csv :named-binary-csv}] (out-in-out-in-test ctx 'context fmt))) (deftest test-anonymous-burmeister-out-in-out-in-for-random-contexts (with-testing-data [ctx (random-contexts 20 10), fmt #{:anonymous-burmeister}] (let [ctx1 (out-in ctx 'context fmt) ctx2 (out-in ctx1 'context fmt)] (possible-isomorphic? ctx1 ctx2 )))) (deftest test-graphml (is (thrown-with-msg? IllegalArgumentException #"Specified file does not contain valid XML." (read-context "testing-data/Booth.cxt" :graphml))) (is (thrown-with-msg? IllegalArgumentException #"Specified file not found." (read-context "testing-data/NotExisting.nope" :graphml))) (is (thrown-with-msg? IllegalArgumentException #"All edges and hyperedges of an hypergraph need ids." (read-context "testing-data/graphml/hyper.graphml" :graphml))) (is (thrown-with-msg? IllegalArgumentException #"XML file does not contain GraphML." (read-context "testing-data/graphml/fake.graphml" :graphml))) (is (= (first (read-context "testing-data/graphml/simple.graphml" :graphml)) (make-context #{"n0" "n1" "n2" "n3" "n4" "n5"} #{"n0" "n1" "n2" "n3" "n4" "n5"} #{["n0" "n2"]["n1" "n2"]["n2" "n3"] ["n2" "n0"]["n2" "n1"]["n3" "n2"]}))) (is (= (first (read-context "testing-data/graphml/hyperids.graphml" :graphml)) (make-context #{"n0" "n1" "n2" "n3"} #{"1" "3" "4"} #{["n0" "1"]["n1" "1"]["n2" "1"] ["n1" "3"]["n3" "3"] ["n0" "4"]["n4" "4"]}))) (is (= (first (read-context "testing-data/graphml/fuzzy.graphml" :graphml)) (make-mv-context #{"n0" "n1" "n2"} #{"n0" "n1" "n2"} #{["n0" "n1" "1.0"]["n0" "n2" "1.0"] ["n1" "n2" "2.0"] ["n1" "n0" "1.0"]["n2" "n0" "1.0"] ["n2" "n1" "2.0"]}))) (is (thrown-with-msg? IllegalArgumentException #"Multiple data values for edges are not supported." (read-context "testing-data/graphml/fuzzymulti.graphml" :graphml))) (is (thrown-with-msg? IllegalArgumentException #"Only single values are supported as edge data." (read-context "testing-data/graphml/svg.graphml" :graphml))) (is (= (first (read-context "testing-data/graphml/port.graphml" :graphml)) (make-context #{"n0" "n1"} #{"0" "1"} #{["n0" "0"]["n0" "1"] ["n1" "0"]["n1" "1"]})))) (deftest test-automatically-identify-input-format-galicia "Test if other input formats throw an error when searching for an input format matching the input file." (if-not (.exists (java.io.File. "testing-data/galicia2.bin.xml")) (warn "Could not verify identifying :galicia input format. Testing file not found.") (let [ctx (read-context "testing-data/galicia2.bin.xml")] (is (= 10 (count (attributes ctx)))) (is (= 10 (count (objects ctx)))) (is (= 27 (count (incidence-relation ctx))))))) (deftest test-json-not-matching-schema "Read a json format that does not match the given schema." (if-not (.exists (java.io.File. "testing-data/digits-lattice.json")) (warn "Could not verify failing validation of context schema. Testing file not found.") (is (thrown? AssertionError (read-context "testing-data/digits-lattice.json" :json))))) (deftest test-json-matching-schema "Read a json format that matches the given schema." (let [file "testing-data/digits-context1.1.json"] (if-not (.exists (java.io.File. file)) (warn "Could not verify validation of context schema. Testing file not found.") (let [ctx (read-context file :json)] (is (= 7 (count (attributes ctx)))) (is (= 10 (count (objects ctx)))) (is (= 47 (count (incidence-relation ctx)))))))) (deftest test-bug-001 (if-not (.exists (java.io.File. "testing-data/nn_5.half.cex")) (warn "Could not verify bug 001, testing file not found.") (let [ctx (read-context "testing-data/nn_5.half.cex")] (is (= 42 (count (attributes ctx)))) (is (= 10 (count (objects ctx)))) (is (= 120 (count (incidence-relation ctx))))))) (deftest test-identify-input-format "Test if the automatic identification of the file format works correctly." (with-testing-data [ctx contexts-oi, fmt (remove #{:named-binary-csv :anonymous-burmeister :binary-csv :fcalgs} (list-context-formats))] (= ctx (out-in-without-format ctx 'context fmt))) (with-testing-data [ctx [(first contexts-oi)], fmt #{:named-binary-csv}] (= ctx (out-in-without-format ctx 'context fmt))) (with-testing-data [ctx contexts-oi, fmt #{:anonymous-burmeister}] (possible-isomorphic? ctx (out-in-without-format ctx 'context fmt))) (with-testing-data [ctx [(first contexts-oi)], fmt #{:binary-csv}] (possible-isomorphic? ctx (out-in-without-format ctx 'context fmt))) (with-testing-data [ctx contexts-oi-fcalgs, fmt #{:fcalgs}] (= ctx (out-in-without-format ctx 'context fmt)))) (deftest test-ctx->json (let [K (make-context-from-matrix [1 2] [:a :b] [1 0 0 0])] (is (= (ctx->json K) {:attributes #{:a :b} :objects #{1 2} :incidence #{[1 :a]}})))) nil
1ca95b15991971324923e154ea42b00f7d556cfdfc367daaf94c954b79331980
yuriy-chumak/ol
Windows.scm
(setq user32 (load-dynamic-library "user32.dll")) (setq gdi32 (load-dynamic-library "gdi32.dll")) (setq opengl32 (load-dynamic-library "opengl32.dll")) (setq CreateWindowEx (user32 fft-void* "CreateWindowExW" fft-int type-string-wide type-string-wide fft-int fft-int fft-int fft-int fft-int fft-void* fft-void* fft-void* fft-void*)) (setq GetDC (user32 fft-void* "GetDC" fft-void*)) (setq ShowWindow (user32 fft-int "ShowWindow" fft-void* fft-int)) (setq ChoosePixelFormat(gdi32 fft-int "ChoosePixelFormat" fft-void* fft-void*)) (setq SetPixelFormat (gdi32 fft-int "SetPixelFormat" fft-void* fft-int fft-void*)) (setq SwapBuffers (gdi32 fft-int "SwapBuffers" fft-void*)) (setq SetWindowLong (user32 fft-void* "SetWindowLongW" fft-void* fft-int type-callable)) (setq GetWindowLongPtr (user32 fft-void* "GetWindowLongPtrW" fft-void* fft-int)) (setq SetWindowLongPtr (user32 fft-void* "SetWindowLongPtrW" fft-void* fft-int type-callable)) (setq DefWindowProc (user32 fft-long "DefWindowProcW" fft-void* fft-unsigned-int fft-void* fft-void*)) (setq GetWindowRect (user32 fft-int "GetWindowRect" fft-void* (fft& fft-int))) (setq wglCreateContext (opengl32 type-vptr "wglCreateContext" fft-void*)) (setq wglMakeCurrent (opengl32 fft-int "wglMakeCurrent" fft-void* fft-void*)) ; functions (define (native:create-context title) (print "native:create-context") (let*((window (CreateWindowEx WS_EX_APPWINDOW|WS_EX_WINDOWEDGE , # 32770 is system classname for DIALOG #x06cf0000 ; WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN 0 0 WIDTH HEIGHT ; x y width height #false ; no parent window #false ; no menu #false ; instance #false)) (pfd (make-bytevector '( nSize 1 00 ; nVersion dwFlags - PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER 00 ; iPixelType - PFD_TYPE_RGBA 24 ; cColorBits 00 00 00 00 00 00 ; cRedBits, cRedShift, cGreenBits, cGreenShift, cBlueBits, cBlueShift (Not used) 00 00 ; cAlphaBits, cAlphaShift cAccumBits , cAccumRedBits , cAccumGreenBits , cAccumBlueBits , cAccumAlphaBits 32 ; cDepthBits cStencilBits 00 ; cAuxBuffers 00 ; iLayerType - PFD_MAIN_PLANE 00 ; bReserved 00 00 00 00 ; dwLayerMask 00 00 00 00 ; dwVisibleMask 00 00 00 00 ; dwDamageMask ))) (hDC (GetDC window)) (PixelFormat (ChoosePixelFormat hDC pfd))) (SetPixelFormat hDC PixelFormat pfd) ; we must capture WM_SIZE messages to be processed by opengl coroutine supported only by 64 - bit windows (define OldProc (GetWindowLongPtr window -4)) (define WndProc (vm:pin (cons (cons fft-long (list fft-void* fft-unsigned-int fft-void* fft-void*)) (lambda (hWnd Msg wParam lParam) (case Msg (5 ;WM_SIZE (define rect '(0 0 0 0)) (GetWindowRect hWnd rect) (mail 'opengl ['resize (lref rect 2) (lref rect 3)])) (else #false)) ; nothing ; pass trough to the original handler (ffi OldProc (cons fft-void* (list fft-void* fft-unsigned-int fft-void* fft-void*)) (list hWnd Msg wParam lParam)))))) (SetWindowLongPtr window -4 (make-callback WndProc))) (ShowWindow window 5) (let ((hRC (wglCreateContext hDC))) (wglMakeCurrent hDC hRC) (print-to stderr "OpenGL version: " (glGetString GL_VERSION)) (print-to stderr "OpenGL vendor: " (glGetString GL_VENDOR)) (print-to stderr "OpenGL renderer: " (glGetString GL_RENDERER)) [hDC hRC window]))) (define (native:enable-context context) (vector-apply context (lambda (dc glrc window) (wglMakeCurrent dc glrc)))) (define (native:disable-context context) (wglMakeCurrent #f #f)) (define (native:swap-buffers context) (vector-apply context (lambda (dc glrc window) (SwapBuffers dc)))) ; -=( process events )=-------------------------------- (setq PeekMessage (user32 fft-int "PeekMessageA" fft-void* fft-void* fft-int fft-int fft-int)) (setq TranslateMessage (user32 fft-int "TranslateMessage" fft-void*)) (setq GetMessage (user32 fft-int "GetMessageA" fft-void* fft-void* fft-int fft-int)) (setq DispatchMessage (user32 fft-int "DispatchMessageA" fft-void*)) (setq sizeof-MSG (if (eq? (size nullptr) 4) 28 48));sizeof(MSG) (define (native:process-events context handler) (define MSG (make-bytevector sizeof-MSG)) (let loop () (when (= (PeekMessage MSG #false 0 0 1) 1) (let*((w (size nullptr)) (message (bytevector->int32 MSG w))) (define wParam (bytevector->int32 MSG (+ w w))) (cond WM_COMMAND IDCANCEL (handler ['quit])) WM_KEYDOWN (handler ['keyboard wParam])) (else (TranslateMessage MSG) (DispatchMessage MSG) (loop))))))) ; --- (setq SetWindowText (user32 fft-int "SetWindowTextW" fft-void* type-string-wide)) (define (gl:SetWindowTitle context title) (vector-apply context (lambda (dc glrc window) (SetWindowText window title)))) ; --- (setq MoveWindow (user32 fft-int "MoveWindow" fft-void* fft-int fft-int fft-int fft-int fft-int)) (define (gl:SetWindowSize context width height) (vector-apply context (lambda (dc glrc window) (let ((rect '(0 0 0 0))) (GetWindowRect window rect) (MoveWindow window (list-ref rect 0) (list-ref rect 1) width height 0))))) ; --- (setq ShowCursor (user32 fft-int "ShowCursor" fft-int)) (define (gl:HideCursor context) (ShowCursor 0)) ; --- (setq GetCursorPos (user32 fft-int "GetCursorPos" fft-int&)) (setq ScreenToClient (user32 fft-int "ScreenToClient" type-vptr fft-int&)) (define (gl:GetMousePos context) (vector-apply context (lambda (dc glrc window) (let ((pos '(0 0))) (GetCursorPos pos) (ScreenToClient window pos) (cons (car pos) (cadr pos)))))) ;; (setq GDI (load-dynamic-library "gdi32.dll")) ( define gl : CreateContext ( WGL type - vptr " wglCreateContext " fft - void * ) ) ( define gl : MakeCurrent ( WGL fft - int " wglMakeCurrent " fft - void * fft - void * ) ) ( define gl : SwapBuffers ( let ( ( SwapBuffers ( GDI fft - int " SwapBuffers " fft - void * ) ) ) ;; (lambda (context) ;; (if context ( SwapBuffers ( ref context 1 ) ) ) ) ) )
null
https://raw.githubusercontent.com/yuriy-chumak/ol/0f38ec46e80724e468ebc5ed205812065c3adf4a/libraries/lib/gl/Windows.scm
scheme
functions WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN x y width height no parent window no menu instance nVersion iPixelType - PFD_TYPE_RGBA cColorBits cRedBits, cRedShift, cGreenBits, cGreenShift, cBlueBits, cBlueShift (Not used) cAlphaBits, cAlphaShift cDepthBits cAuxBuffers iLayerType - PFD_MAIN_PLANE bReserved dwLayerMask dwVisibleMask dwDamageMask we must capture WM_SIZE messages to be processed by opengl coroutine WM_SIZE nothing pass trough to the original handler -=( process events )=-------------------------------- sizeof(MSG) --- --- --- --- (setq GDI (load-dynamic-library "gdi32.dll")) (lambda (context) (if context
(setq user32 (load-dynamic-library "user32.dll")) (setq gdi32 (load-dynamic-library "gdi32.dll")) (setq opengl32 (load-dynamic-library "opengl32.dll")) (setq CreateWindowEx (user32 fft-void* "CreateWindowExW" fft-int type-string-wide type-string-wide fft-int fft-int fft-int fft-int fft-int fft-void* fft-void* fft-void* fft-void*)) (setq GetDC (user32 fft-void* "GetDC" fft-void*)) (setq ShowWindow (user32 fft-int "ShowWindow" fft-void* fft-int)) (setq ChoosePixelFormat(gdi32 fft-int "ChoosePixelFormat" fft-void* fft-void*)) (setq SetPixelFormat (gdi32 fft-int "SetPixelFormat" fft-void* fft-int fft-void*)) (setq SwapBuffers (gdi32 fft-int "SwapBuffers" fft-void*)) (setq SetWindowLong (user32 fft-void* "SetWindowLongW" fft-void* fft-int type-callable)) (setq GetWindowLongPtr (user32 fft-void* "GetWindowLongPtrW" fft-void* fft-int)) (setq SetWindowLongPtr (user32 fft-void* "SetWindowLongPtrW" fft-void* fft-int type-callable)) (setq DefWindowProc (user32 fft-long "DefWindowProcW" fft-void* fft-unsigned-int fft-void* fft-void*)) (setq GetWindowRect (user32 fft-int "GetWindowRect" fft-void* (fft& fft-int))) (setq wglCreateContext (opengl32 type-vptr "wglCreateContext" fft-void*)) (setq wglMakeCurrent (opengl32 fft-int "wglMakeCurrent" fft-void* fft-void*)) (define (native:create-context title) (print "native:create-context") (let*((window (CreateWindowEx WS_EX_APPWINDOW|WS_EX_WINDOWEDGE , # 32770 is system classname for DIALOG #false)) (pfd (make-bytevector '( nSize dwFlags - PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER cAccumBits , cAccumRedBits , cAccumGreenBits , cAccumBlueBits , cAccumAlphaBits cStencilBits ))) (hDC (GetDC window)) (PixelFormat (ChoosePixelFormat hDC pfd))) (SetPixelFormat hDC PixelFormat pfd) supported only by 64 - bit windows (define OldProc (GetWindowLongPtr window -4)) (define WndProc (vm:pin (cons (cons fft-long (list fft-void* fft-unsigned-int fft-void* fft-void*)) (lambda (hWnd Msg wParam lParam) (case Msg (define rect '(0 0 0 0)) (GetWindowRect hWnd rect) (mail 'opengl ['resize (lref rect 2) (lref rect 3)])) (else (ffi OldProc (cons fft-void* (list fft-void* fft-unsigned-int fft-void* fft-void*)) (list hWnd Msg wParam lParam)))))) (SetWindowLongPtr window -4 (make-callback WndProc))) (ShowWindow window 5) (let ((hRC (wglCreateContext hDC))) (wglMakeCurrent hDC hRC) (print-to stderr "OpenGL version: " (glGetString GL_VERSION)) (print-to stderr "OpenGL vendor: " (glGetString GL_VENDOR)) (print-to stderr "OpenGL renderer: " (glGetString GL_RENDERER)) [hDC hRC window]))) (define (native:enable-context context) (vector-apply context (lambda (dc glrc window) (wglMakeCurrent dc glrc)))) (define (native:disable-context context) (wglMakeCurrent #f #f)) (define (native:swap-buffers context) (vector-apply context (lambda (dc glrc window) (SwapBuffers dc)))) (setq PeekMessage (user32 fft-int "PeekMessageA" fft-void* fft-void* fft-int fft-int fft-int)) (setq TranslateMessage (user32 fft-int "TranslateMessage" fft-void*)) (setq GetMessage (user32 fft-int "GetMessageA" fft-void* fft-void* fft-int fft-int)) (setq DispatchMessage (user32 fft-int "DispatchMessageA" fft-void*)) (define (native:process-events context handler) (define MSG (make-bytevector sizeof-MSG)) (let loop () (when (= (PeekMessage MSG #false 0 0 1) 1) (let*((w (size nullptr)) (message (bytevector->int32 MSG w))) (define wParam (bytevector->int32 MSG (+ w w))) (cond WM_COMMAND IDCANCEL (handler ['quit])) WM_KEYDOWN (handler ['keyboard wParam])) (else (TranslateMessage MSG) (DispatchMessage MSG) (loop))))))) (setq SetWindowText (user32 fft-int "SetWindowTextW" fft-void* type-string-wide)) (define (gl:SetWindowTitle context title) (vector-apply context (lambda (dc glrc window) (SetWindowText window title)))) (setq MoveWindow (user32 fft-int "MoveWindow" fft-void* fft-int fft-int fft-int fft-int fft-int)) (define (gl:SetWindowSize context width height) (vector-apply context (lambda (dc glrc window) (let ((rect '(0 0 0 0))) (GetWindowRect window rect) (MoveWindow window (list-ref rect 0) (list-ref rect 1) width height 0))))) (setq ShowCursor (user32 fft-int "ShowCursor" fft-int)) (define (gl:HideCursor context) (ShowCursor 0)) (setq GetCursorPos (user32 fft-int "GetCursorPos" fft-int&)) (setq ScreenToClient (user32 fft-int "ScreenToClient" type-vptr fft-int&)) (define (gl:GetMousePos context) (vector-apply context (lambda (dc glrc window) (let ((pos '(0 0))) (GetCursorPos pos) (ScreenToClient window pos) (cons (car pos) (cadr pos)))))) ( define gl : CreateContext ( WGL type - vptr " wglCreateContext " fft - void * ) ) ( define gl : MakeCurrent ( WGL fft - int " wglMakeCurrent " fft - void * fft - void * ) ) ( define gl : SwapBuffers ( let ( ( SwapBuffers ( GDI fft - int " SwapBuffers " fft - void * ) ) ) ( SwapBuffers ( ref context 1 ) ) ) ) ) )
c8cc9d800033dcc659c73df4b4544c906d8e0519e394a6857d6e1e692e14ab6c
ocaml-multicore/ocaml-tsan
raise_through_handler.ml
TEST * tsan * * native ocamlopt_flags = " -g " include unix set TSAN_OPTIONS="detect_deadlocks=0 " * tsan ** native ocamlopt_flags = "-g" include unix set TSAN_OPTIONS="detect_deadlocks=0" *) open Printf open Effect open Effect.Deep let g_ref = ref 0 let [@inline never] race () = g_ref := 42 let [@inline never] g () = print_endline "entering g"; ignore @@ raise Exit; print_endline "leaving g"; 12 let [@inline never] f () = print_endline "computation, entering f"; let v = g () in print_endline "computation, leaving f"; v + 1 let effh : type a. a t -> ((a, 'b) continuation -> 'b) option = fun _ -> None let[@inline never] main () = print_endline "Let's work!"; (try ignore ( match_with f () { retc = (fun v -> v + 1); exnc = (fun e -> raise e); effc = effh } ) with Exit -> print_endline "In exception handler"; race (); ); 44 let[@inline never] other_domain () = ignore (Sys.opaque_identity !g_ref); Unix.sleepf 0.66 let () = let d = Domain.spawn other_domain in Unix.sleepf 0.33; let v = main () in printf "result = %d\n" v; Domain.join d
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/594bd94629e59507c643e00408fb4a0f46d2630c/testsuite/tests/tsan/raise_through_handler.ml
ocaml
TEST * tsan * * native ocamlopt_flags = " -g " include unix set TSAN_OPTIONS="detect_deadlocks=0 " * tsan ** native ocamlopt_flags = "-g" include unix set TSAN_OPTIONS="detect_deadlocks=0" *) open Printf open Effect open Effect.Deep let g_ref = ref 0 let [@inline never] race () = g_ref := 42 let [@inline never] g () = print_endline "entering g"; ignore @@ raise Exit; print_endline "leaving g"; 12 let [@inline never] f () = print_endline "computation, entering f"; let v = g () in print_endline "computation, leaving f"; v + 1 let effh : type a. a t -> ((a, 'b) continuation -> 'b) option = fun _ -> None let[@inline never] main () = print_endline "Let's work!"; (try ignore ( match_with f () { retc = (fun v -> v + 1); exnc = (fun e -> raise e); effc = effh } ) with Exit -> print_endline "In exception handler"; race (); ); 44 let[@inline never] other_domain () = ignore (Sys.opaque_identity !g_ref); Unix.sleepf 0.66 let () = let d = Domain.spawn other_domain in Unix.sleepf 0.33; let v = main () in printf "result = %d\n" v; Domain.join d
2d60a0dbf48ecb3a551089ddb63554a25dbf7b372e1df6add869cd3745fad8c2
pjotrp/guix
monad-repl.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2014 , 2015 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix monad-repl) #:use-module (guix store) #:use-module (guix monads) #:use-module (guix utils) #:use-module (guix packages) #:use-module (ice-9 pretty-print) #:use-module (system repl repl) #:use-module (system repl common) #:use-module (system repl command) #:use-module (system base language) #:use-module (system base compile) #:use-module (srfi srfi-26) #:export (run-in-store enter-store-monad)) ;;; Comment: ;;; ;;; This modules provides a couple of REPL meta-commands that make it easier ;;; to work with monadic procedures in the store monad. ;;; ;;; Code: (define* (monad-language monad run #:optional (name 'monad)) "Return a language with a special evaluator that causes monadic values to be \"run\" in MONAD using procedure RUN." (let ((scheme (lookup-language 'scheme))) (define (evaluate-monadic-expression exp env) (let ((mvalue (compile exp #:to 'value #:env env))) (run mvalue))) (make-language #:name name #:title "Monad" #:reader (language-reader scheme) #:compilers (language-compilers scheme) #:decompilers (language-decompilers scheme) #:evaluator evaluate-monadic-expression #:printer (language-printer scheme) #:make-default-environment (language-make-default-environment scheme)))) (define* (default-guile-derivation store #:optional (system (%current-system))) "Return the derivation of the default " (package-derivation store (default-guile) system)) (define (store-monad-language) "Return a compiler language for the store monad." (let* ((store (open-connection)) (guile (or (%guile-for-build) (default-guile-derivation store)))) (monad-language %store-monad (cut run-with-store store <> #:guile-for-build guile) 'store-monad))) (define-meta-command ((run-in-store guix) repl (form)) "run-in-store EXP Run EXP through the store monad." (with-store store (let* ((guile (or (%guile-for-build) (default-guile-derivation store))) (value (run-with-store store (repl-eval repl form) #:guile-for-build guile))) (run-hook before-print-hook value) (pretty-print value)))) (define-meta-command ((enter-store-monad guix) repl) "enter-store-monad Enter a REPL for values in the store monad." (let ((new (make-repl (store-monad-language)))) Force interpretation so that our specially - crafted language evaluator ;; is actually used. (repl-option-set! new 'interp #t) (run-repl new))) ;;; monad-repl.scm ends here
null
https://raw.githubusercontent.com/pjotrp/guix/96250294012c2f1520b67f12ea80bfd6b98075a2/guix/monad-repl.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Comment: This modules provides a couple of REPL meta-commands that make it easier to work with monadic procedures in the store monad. Code: is actually used. monad-repl.scm ends here
Copyright © 2014 , 2015 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix monad-repl) #:use-module (guix store) #:use-module (guix monads) #:use-module (guix utils) #:use-module (guix packages) #:use-module (ice-9 pretty-print) #:use-module (system repl repl) #:use-module (system repl common) #:use-module (system repl command) #:use-module (system base language) #:use-module (system base compile) #:use-module (srfi srfi-26) #:export (run-in-store enter-store-monad)) (define* (monad-language monad run #:optional (name 'monad)) "Return a language with a special evaluator that causes monadic values to be \"run\" in MONAD using procedure RUN." (let ((scheme (lookup-language 'scheme))) (define (evaluate-monadic-expression exp env) (let ((mvalue (compile exp #:to 'value #:env env))) (run mvalue))) (make-language #:name name #:title "Monad" #:reader (language-reader scheme) #:compilers (language-compilers scheme) #:decompilers (language-decompilers scheme) #:evaluator evaluate-monadic-expression #:printer (language-printer scheme) #:make-default-environment (language-make-default-environment scheme)))) (define* (default-guile-derivation store #:optional (system (%current-system))) "Return the derivation of the default " (package-derivation store (default-guile) system)) (define (store-monad-language) "Return a compiler language for the store monad." (let* ((store (open-connection)) (guile (or (%guile-for-build) (default-guile-derivation store)))) (monad-language %store-monad (cut run-with-store store <> #:guile-for-build guile) 'store-monad))) (define-meta-command ((run-in-store guix) repl (form)) "run-in-store EXP Run EXP through the store monad." (with-store store (let* ((guile (or (%guile-for-build) (default-guile-derivation store))) (value (run-with-store store (repl-eval repl form) #:guile-for-build guile))) (run-hook before-print-hook value) (pretty-print value)))) (define-meta-command ((enter-store-monad guix) repl) "enter-store-monad Enter a REPL for values in the store monad." (let ((new (make-repl (store-monad-language)))) Force interpretation so that our specially - crafted language evaluator (repl-option-set! new 'interp #t) (run-repl new)))
9cf6368ec9540be09c0993455ad81c5ad3c1ea940f581a48697cf13565a019eb
avsm/mirage-duniverse
topkg_codec.mli
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) * interprocess communication codec . See { ! . Private . Codec } for documentation . See {!Topkg.Private.Codec} for documentation. *) (** {1 Codec} *) open Topkg_result type error = Corrupted of (string * string) | Version of int * int val pp_error : Format.formatter -> error -> unit exception Error of error val err : kind:string -> string -> 'a type 'a t val v : kind:string -> enc:('a -> string) -> dec:(string -> 'a) -> 'a t val kind : 'a t -> string val enc : 'a t -> 'a -> string val dec : 'a t -> string -> 'a val dec_result : 'a t -> string -> 'a result val with_kind : string -> 'a t -> 'a t val write : Topkg_fpath.t -> 'a t -> 'a -> unit result val read : Topkg_fpath.t -> 'a t -> 'a result val unit : unit t val const : 'a -> 'a t val bool : bool t val int : int t val string : string t val option : 'a t -> 'a option t val result : ok:'a t -> error:'b t -> ('a, 'b) Result.result t val list : 'a t -> 'a list t val pair : 'a t -> 'b t -> ('a * 'b) t val t2 : 'a t -> 'b t -> ('a * 'b) t val t3 : 'a t -> 'b t -> 'c t -> ('a * 'b * 'c) t val t4 : 'a t -> 'b t -> 'c t -> 'd t -> ('a * 'b * 'c * 'd) t val t5 : 'a t -> 'b t -> 'c t -> 'd t -> 'e t -> ('a * 'b * 'c * 'd * 'e) t val alt : kind:string -> ('a -> int) -> 'a t array -> 'a t val version : int -> 'a t -> 'a t val view : ?kind:string -> ('a -> 'b) * ('b -> 'a) -> 'b t -> 'a t val msg : [`Msg of string ] t val result_error_msg : 'a t -> 'a result t val fpath : Topkg_fpath.t t val cmd : Topkg_cmd.t t --------------------------------------------------------------------------- Copyright ( c ) 2016 Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/topkg/src/topkg_codec.mli
ocaml
* {1 Codec}
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) * interprocess communication codec . See { ! . Private . Codec } for documentation . See {!Topkg.Private.Codec} for documentation. *) open Topkg_result type error = Corrupted of (string * string) | Version of int * int val pp_error : Format.formatter -> error -> unit exception Error of error val err : kind:string -> string -> 'a type 'a t val v : kind:string -> enc:('a -> string) -> dec:(string -> 'a) -> 'a t val kind : 'a t -> string val enc : 'a t -> 'a -> string val dec : 'a t -> string -> 'a val dec_result : 'a t -> string -> 'a result val with_kind : string -> 'a t -> 'a t val write : Topkg_fpath.t -> 'a t -> 'a -> unit result val read : Topkg_fpath.t -> 'a t -> 'a result val unit : unit t val const : 'a -> 'a t val bool : bool t val int : int t val string : string t val option : 'a t -> 'a option t val result : ok:'a t -> error:'b t -> ('a, 'b) Result.result t val list : 'a t -> 'a list t val pair : 'a t -> 'b t -> ('a * 'b) t val t2 : 'a t -> 'b t -> ('a * 'b) t val t3 : 'a t -> 'b t -> 'c t -> ('a * 'b * 'c) t val t4 : 'a t -> 'b t -> 'c t -> 'd t -> ('a * 'b * 'c * 'd) t val t5 : 'a t -> 'b t -> 'c t -> 'd t -> 'e t -> ('a * 'b * 'c * 'd * 'e) t val alt : kind:string -> ('a -> int) -> 'a t array -> 'a t val version : int -> 'a t -> 'a t val view : ?kind:string -> ('a -> 'b) * ('b -> 'a) -> 'b t -> 'a t val msg : [`Msg of string ] t val result_error_msg : 'a t -> 'a result t val fpath : Topkg_fpath.t t val cmd : Topkg_cmd.t t --------------------------------------------------------------------------- Copyright ( c ) 2016 Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
4faf2b7da77724a8a089fd59386e14a728146151ac9281d28f0a600a5b4c9220
s-expressionists/Cleavir
packages.lisp
(defpackage #:cleavir-graph-test-utilities (:use #:cl #:cleavir-graph) (:export #:node #:make-node #:name #:successors #:random-flow-chart))
null
https://raw.githubusercontent.com/s-expressionists/Cleavir/e0293780d356a9d563af9abf9317019f608b4e1d/Graph/Test-utilities/packages.lisp
lisp
(defpackage #:cleavir-graph-test-utilities (:use #:cl #:cleavir-graph) (:export #:node #:make-node #:name #:successors #:random-flow-chart))
625ad157b6ca2da58c4e24f9d5a0551239a2079330f1ce5cb08865b6fee88461
janestreet/async
rpc.mli
* This module just re - exports lots of modules from [ Async_rpc_kernel ] and adds some Unix - specific wrappers in [ Connection ] ( for using [ Reader ] , [ Writer ] , and [ ] ) . For documentation , see { { ! Async_rpc_kernel . Rpc}[Rpc ] } and { { ! Async_rpc_kernel__.Connection_intf}[Connection_intf ] } in the { { ! Async_rpc_kernel}[Async_rpc_kernel ] } library . Unix-specific wrappers in [Connection] (for using [Reader], [Writer], and [Tcp]). For documentation, see {{!Async_rpc_kernel.Rpc}[Rpc]} and {{!Async_rpc_kernel__.Connection_intf}[Connection_intf]} in the {{!Async_rpc_kernel}[Async_rpc_kernel]} library. *) open! Core open! Import module Transport = Rpc_transport module Low_latency_transport = Rpc_transport_low_latency module Any = Rpc_kernel.Any module Description = Rpc_kernel.Description module On_exception = Rpc_kernel.On_exception module Implementation = Rpc_kernel.Implementation module Implementations = Rpc_kernel.Implementations module One_way = Rpc_kernel.One_way module Pipe_rpc = Rpc_kernel.Pipe_rpc module Rpc = Rpc_kernel.Rpc module State_rpc = Rpc_kernel.State_rpc module Pipe_close_reason = Rpc_kernel.Pipe_close_reason module Connection : sig include module type of struct include Rpc_kernel.Connection end (** These functions are mostly the same as the ones with the same names in [Async_rpc_kernel.Rpc.Connection]; see [Connection_intf] in that library for documentation. The differences are that: - they take an [Async_unix.Reader.t], [Async_unix.Writer.t] and [max_message_size] instead of a [Transport.t] - they use [Time] instead of [Time_ns] *) val create : ?implementations:'s Implementations.t -> connection_state:(t -> 's) -> ?max_message_size:int -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> Reader.t -> Writer.t -> (t, Exn.t) Result.t Deferred.t * As of Feb 2017 , the RPC protocol started to contain a magic number so that one can identify RPC communication . The bool returned by [ contains_magic_prefix ] says whether this magic number was observed . This operation is a " peek " that does not advance any pointers associated with the reader . In particular , it makes sense to call [ create ] on a reader after calling this function . identify RPC communication. The bool returned by [contains_magic_prefix] says whether this magic number was observed. This operation is a "peek" that does not advance any pointers associated with the reader. In particular, it makes sense to call [create] on a reader after calling this function. *) val contains_magic_prefix : Reader.t -> bool Deferred.t val with_close : ?implementations:'s Implementations.t -> ?max_message_size:int -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> connection_state:(t -> 's) -> Reader.t -> Writer.t -> dispatch_queries:(t -> 'a Deferred.t) -> on_handshake_error:[ `Raise | `Call of Exn.t -> 'a Deferred.t ] -> 'a Deferred.t val server_with_close : ?max_message_size:int -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> Reader.t -> Writer.t -> implementations:'s Implementations.t -> connection_state:(t -> 's) -> on_handshake_error:[ `Raise | `Ignore | `Call of Exn.t -> unit Deferred.t ] -> unit Deferred.t (** A function creating a transport from a file descriptor. It is responsible for setting the low-level parameters of the underlying transport. For instance to set up a transport using [Async.{Reader,Writer}] and set a buffer age limit on the writer, you can pass this to the functions of this module: {[ ~make_transport:(fun fd ~max_message_size -> Rpc.Transport.of_fd fd ~max_message_size ~buffer_age_limit:`Unlimited) ]} *) type transport_maker = Fd.t -> max_message_size:int -> Transport.t (** [serve implementations ~port ?on_handshake_error ()] starts a server with the given implementation on [port]. The optional auth function will be called on all incoming connections with the address info of the client and will disconnect the client immediately if it returns false. This auth mechanism is generic and does nothing other than disconnect the client -- any logging or record of the reasons is the responsibility of the auth function itself. *) val serve : implementations:'s Implementations.t -> initial_connection_state:('address -> t -> 's) -> where_to_listen:('address, 'listening_on) Tcp.Where_to_listen.t -> ?max_connections:int -> ?backlog:int -> ?drop_incoming_connections:bool -> ?time_source:[> read ] Time_source.T1.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?auth:('address -> bool) (** default is [`Ignore] *) -> ?on_handshake_error:[ `Raise | `Ignore | `Call of 'address -> exn -> unit ] (** default is [`Ignore] *) -> ?on_handler_error:[ `Raise | `Ignore | `Call of 'address -> exn -> unit ] -> unit -> ('address, 'listening_on) Tcp.Server.t Deferred.t (** As [serve], but only accepts IP addresses, not Unix sockets; returns server immediately rather than asynchronously. *) val serve_inet : implementations:'s Implementations.t -> initial_connection_state:(Socket.Address.Inet.t -> t -> 's) -> where_to_listen:Tcp.Where_to_listen.inet -> ?max_connections:int -> ?backlog:int -> ?drop_incoming_connections:bool -> ?time_source:[> read ] Time_source.T1.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?auth:(Socket.Address.Inet.t -> bool) (** default is [`Ignore] *) -> ?on_handshake_error: [ `Raise | `Ignore | `Call of Socket.Address.Inet.t -> exn -> unit ] (** default is [`Ignore] *) -> ?on_handler_error: [ `Raise | `Ignore | `Call of Socket.Address.Inet.t -> exn -> unit ] -> unit -> (Socket.Address.Inet.t, int) Tcp.Server.t (** [client where_to_connect ()] connects to the server at [where_to_connect] and returns the connection or an Error if a connection could not be made. It is the responsibility of the caller to eventually call [close]. In [client] and [with_client], the [handshake_timeout] encompasses both the TCP connection timeout and the timeout for this module's own handshake. *) val client : ?implementations:_ Client_implementations.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> _ Tcp.Where_to_connect.t -> (t, Exn.t) Result.t Deferred.t * Similar to [ client ] , but additionally expose the [ Socket . Address.t ] of the RPC server that we connected to . server that we connected to. *) val client' : ?implementations:_ Client_implementations.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> 'address Tcp.Where_to_connect.t -> ('address * t, Exn.t) Result.t Deferred.t (** [with_client where_to_connect f] connects to the server at [where_to_connect] and runs f until an exception is thrown or until the returned Deferred is fulfilled. NOTE: As with [with_close], you should be careful when using this with [Pipe_rpc]. See [with_close] for more information. *) val with_client : ?implementations:_ Client_implementations.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> _ Tcp.Where_to_connect.t -> (t -> 'a Deferred.t) -> ('a, Exn.t) Result.t Deferred.t * Similar to [ with_client ] , but additionally expose the [ Socket . Address.t ] of the RPC server that we connected to . server that we connected to. *) val with_client' : ?implementations:_ Client_implementations.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> 'transport Tcp.Where_to_connect.t -> (remote_server:'transport -> t -> 'a Deferred.t) -> ('a, Exn.t) Result.t Deferred.t end
null
https://raw.githubusercontent.com/janestreet/async/56d8d18f61e010fbb975ce3c6df2ab4cc86f6543/async_rpc/src/rpc.mli
ocaml
* These functions are mostly the same as the ones with the same names in [Async_rpc_kernel.Rpc.Connection]; see [Connection_intf] in that library for documentation. The differences are that: - they take an [Async_unix.Reader.t], [Async_unix.Writer.t] and [max_message_size] instead of a [Transport.t] - they use [Time] instead of [Time_ns] * A function creating a transport from a file descriptor. It is responsible for setting the low-level parameters of the underlying transport. For instance to set up a transport using [Async.{Reader,Writer}] and set a buffer age limit on the writer, you can pass this to the functions of this module: {[ ~make_transport:(fun fd ~max_message_size -> Rpc.Transport.of_fd fd ~max_message_size ~buffer_age_limit:`Unlimited) ]} * [serve implementations ~port ?on_handshake_error ()] starts a server with the given implementation on [port]. The optional auth function will be called on all incoming connections with the address info of the client and will disconnect the client immediately if it returns false. This auth mechanism is generic and does nothing other than disconnect the client -- any logging or record of the reasons is the responsibility of the auth function itself. * default is [`Ignore] * default is [`Ignore] * As [serve], but only accepts IP addresses, not Unix sockets; returns server immediately rather than asynchronously. * default is [`Ignore] * default is [`Ignore] * [client where_to_connect ()] connects to the server at [where_to_connect] and returns the connection or an Error if a connection could not be made. It is the responsibility of the caller to eventually call [close]. In [client] and [with_client], the [handshake_timeout] encompasses both the TCP connection timeout and the timeout for this module's own handshake. * [with_client where_to_connect f] connects to the server at [where_to_connect] and runs f until an exception is thrown or until the returned Deferred is fulfilled. NOTE: As with [with_close], you should be careful when using this with [Pipe_rpc]. See [with_close] for more information.
* This module just re - exports lots of modules from [ Async_rpc_kernel ] and adds some Unix - specific wrappers in [ Connection ] ( for using [ Reader ] , [ Writer ] , and [ ] ) . For documentation , see { { ! Async_rpc_kernel . Rpc}[Rpc ] } and { { ! Async_rpc_kernel__.Connection_intf}[Connection_intf ] } in the { { ! Async_rpc_kernel}[Async_rpc_kernel ] } library . Unix-specific wrappers in [Connection] (for using [Reader], [Writer], and [Tcp]). For documentation, see {{!Async_rpc_kernel.Rpc}[Rpc]} and {{!Async_rpc_kernel__.Connection_intf}[Connection_intf]} in the {{!Async_rpc_kernel}[Async_rpc_kernel]} library. *) open! Core open! Import module Transport = Rpc_transport module Low_latency_transport = Rpc_transport_low_latency module Any = Rpc_kernel.Any module Description = Rpc_kernel.Description module On_exception = Rpc_kernel.On_exception module Implementation = Rpc_kernel.Implementation module Implementations = Rpc_kernel.Implementations module One_way = Rpc_kernel.One_way module Pipe_rpc = Rpc_kernel.Pipe_rpc module Rpc = Rpc_kernel.Rpc module State_rpc = Rpc_kernel.State_rpc module Pipe_close_reason = Rpc_kernel.Pipe_close_reason module Connection : sig include module type of struct include Rpc_kernel.Connection end val create : ?implementations:'s Implementations.t -> connection_state:(t -> 's) -> ?max_message_size:int -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> Reader.t -> Writer.t -> (t, Exn.t) Result.t Deferred.t * As of Feb 2017 , the RPC protocol started to contain a magic number so that one can identify RPC communication . The bool returned by [ contains_magic_prefix ] says whether this magic number was observed . This operation is a " peek " that does not advance any pointers associated with the reader . In particular , it makes sense to call [ create ] on a reader after calling this function . identify RPC communication. The bool returned by [contains_magic_prefix] says whether this magic number was observed. This operation is a "peek" that does not advance any pointers associated with the reader. In particular, it makes sense to call [create] on a reader after calling this function. *) val contains_magic_prefix : Reader.t -> bool Deferred.t val with_close : ?implementations:'s Implementations.t -> ?max_message_size:int -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> connection_state:(t -> 's) -> Reader.t -> Writer.t -> dispatch_queries:(t -> 'a Deferred.t) -> on_handshake_error:[ `Raise | `Call of Exn.t -> 'a Deferred.t ] -> 'a Deferred.t val server_with_close : ?max_message_size:int -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> Reader.t -> Writer.t -> implementations:'s Implementations.t -> connection_state:(t -> 's) -> on_handshake_error:[ `Raise | `Ignore | `Call of Exn.t -> unit Deferred.t ] -> unit Deferred.t type transport_maker = Fd.t -> max_message_size:int -> Transport.t val serve : implementations:'s Implementations.t -> initial_connection_state:('address -> t -> 's) -> where_to_listen:('address, 'listening_on) Tcp.Where_to_listen.t -> ?max_connections:int -> ?backlog:int -> ?drop_incoming_connections:bool -> ?time_source:[> read ] Time_source.T1.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?on_handshake_error:[ `Raise | `Ignore | `Call of 'address -> exn -> unit ] -> ?on_handler_error:[ `Raise | `Ignore | `Call of 'address -> exn -> unit ] -> unit -> ('address, 'listening_on) Tcp.Server.t Deferred.t val serve_inet : implementations:'s Implementations.t -> initial_connection_state:(Socket.Address.Inet.t -> t -> 's) -> where_to_listen:Tcp.Where_to_listen.inet -> ?max_connections:int -> ?backlog:int -> ?drop_incoming_connections:bool -> ?time_source:[> read ] Time_source.T1.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?on_handshake_error: [ `Raise | `Ignore | `Call of Socket.Address.Inet.t -> exn -> unit ] -> ?on_handler_error: [ `Raise | `Ignore | `Call of Socket.Address.Inet.t -> exn -> unit ] -> unit -> (Socket.Address.Inet.t, int) Tcp.Server.t val client : ?implementations:_ Client_implementations.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> _ Tcp.Where_to_connect.t -> (t, Exn.t) Result.t Deferred.t * Similar to [ client ] , but additionally expose the [ Socket . Address.t ] of the RPC server that we connected to . server that we connected to. *) val client' : ?implementations:_ Client_implementations.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> 'address Tcp.Where_to_connect.t -> ('address * t, Exn.t) Result.t Deferred.t val with_client : ?implementations:_ Client_implementations.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> _ Tcp.Where_to_connect.t -> (t -> 'a Deferred.t) -> ('a, Exn.t) Result.t Deferred.t * Similar to [ with_client ] , but additionally expose the [ Socket . Address.t ] of the RPC server that we connected to . server that we connected to. *) val with_client' : ?implementations:_ Client_implementations.t -> ?max_message_size:int -> ?make_transport:transport_maker -> ?handshake_timeout:Time_float.Span.t -> ?heartbeat_config:Heartbeat_config.t -> ?description:Info.t -> 'transport Tcp.Where_to_connect.t -> (remote_server:'transport -> t -> 'a Deferred.t) -> ('a, Exn.t) Result.t Deferred.t end
1cbd46557e9df9920050f25606cd1eaf6fbd27bf5ab4282f643d0427670925fc
ConsumerDataStandardsAustralia/validation-prototype
PayeesTest.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeApplications # module Web.ConsumerData.Au.Api.Types.Banking.PayeesTest where import Control.Lens import Data.Functor.Identity (Identity) import Data.Tagged (Tagged) import Test.Tasty (TestTree) import Text.URI.QQ (uri) import Waargonaut.Decode (Decoder) import Waargonaut.Encode (Encoder) import Waargonaut.Generic (mkDecoder, mkEncoder, untag) import WaargoRoundTrip (roundTripTest) import Web.ConsumerData.Au.Api.Types import Web.ConsumerData.Au.Api.Types.LinkTestHelpers (linkTest, paginatedLinkTest) import Web.ConsumerData.Au.Api.Types.PrismTestHelpers (testEnumPrismTripping) import Web.ConsumerData.Au.Api.Types.Tag test_payeesLinks :: [TestTree] test_payeesLinks = [ paginatedLinkTest "Get Payees no params" ((links^.bankingLinks.bankingPayeesLinks.payeesGet) Nothing) [uri||] , paginatedLinkTest "Get Payees all params" ((links^.bankingLinks.bankingPayeesLinks.payeesGet) (Just PayeeTypeParamInternational)) [uri||] , linkTest "Get Payee Detail" (links^.bankingLinks.bankingPayeesLinks.payeesByIdGet.to ($ PayeeId "123")) [uri||] ] test_roundTripEnum :: [TestTree] test_roundTripEnum = [ testEnumPrismTripping "PayeeType" _PayeeType ] test_roundTripPayees :: TestTree test_roundTripPayees = roundTripTest (untag (mkDecoder :: (Tagged OB (Decoder Identity (PaginatedResponse Payees))))) (untag (mkEncoder :: (Tagged OB (Encoder Identity (PaginatedResponse Payees))))) "PayeesRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/payees.golden.json" test_roundTripPayeeDetail :: TestTree test_roundTripPayeeDetail = roundTripTest (untag (mkDecoder :: (Tagged OB (Decoder Identity (StandardResponse PayeeDetail))))) (untag (mkEncoder :: (Tagged OB (Encoder Identity (StandardResponse PayeeDetail))))) "PayeeDetailRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/payeedetail.golden.json" test_roundSubPayeeDetail :: [TestTree] test_roundSubPayeeDetail = [ roundTripTest domesticPayeeDecoder domesticPayeeEncoder " DomesticPayeeRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/domesticPayee.json" , roundTripTest domesticPayeeAccountDecoder domesticPayeeAccountEncoder " DomesticPayeeAccountRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/domesticPayeeAccount.json" , roundTripTest domesticPayeeCardDecoder domesticPayeeCardEncoder " DomesticPayeeCardRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/domesticPayeeCard.json" , roundTripTest domesticPayeePayIdDecoder domesticPayeePayIdEncoder " DomesticPayeePayIdRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/domesticPayeePayId.json" , roundTripTest internationalPayeeDecoder internationalPayeeEncoder " InternationalPayeeRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/internationalPayee.json" , roundTripTest billerPayeeDecoder billerPayeeEncoder " BillerPayeeRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/billerPayee.json" ]
null
https://raw.githubusercontent.com/ConsumerDataStandardsAustralia/validation-prototype/ff63338b77339ee49fa3e0be5bb9d7f74e50c28b/consumer-data-au-api-types/tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE QuasiQuotes # # LANGUAGE RankNTypes #
# LANGUAGE TypeApplications # module Web.ConsumerData.Au.Api.Types.Banking.PayeesTest where import Control.Lens import Data.Functor.Identity (Identity) import Data.Tagged (Tagged) import Test.Tasty (TestTree) import Text.URI.QQ (uri) import Waargonaut.Decode (Decoder) import Waargonaut.Encode (Encoder) import Waargonaut.Generic (mkDecoder, mkEncoder, untag) import WaargoRoundTrip (roundTripTest) import Web.ConsumerData.Au.Api.Types import Web.ConsumerData.Au.Api.Types.LinkTestHelpers (linkTest, paginatedLinkTest) import Web.ConsumerData.Au.Api.Types.PrismTestHelpers (testEnumPrismTripping) import Web.ConsumerData.Au.Api.Types.Tag test_payeesLinks :: [TestTree] test_payeesLinks = [ paginatedLinkTest "Get Payees no params" ((links^.bankingLinks.bankingPayeesLinks.payeesGet) Nothing) [uri||] , paginatedLinkTest "Get Payees all params" ((links^.bankingLinks.bankingPayeesLinks.payeesGet) (Just PayeeTypeParamInternational)) [uri||] , linkTest "Get Payee Detail" (links^.bankingLinks.bankingPayeesLinks.payeesByIdGet.to ($ PayeeId "123")) [uri||] ] test_roundTripEnum :: [TestTree] test_roundTripEnum = [ testEnumPrismTripping "PayeeType" _PayeeType ] test_roundTripPayees :: TestTree test_roundTripPayees = roundTripTest (untag (mkDecoder :: (Tagged OB (Decoder Identity (PaginatedResponse Payees))))) (untag (mkEncoder :: (Tagged OB (Encoder Identity (PaginatedResponse Payees))))) "PayeesRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/payees.golden.json" test_roundTripPayeeDetail :: TestTree test_roundTripPayeeDetail = roundTripTest (untag (mkDecoder :: (Tagged OB (Decoder Identity (StandardResponse PayeeDetail))))) (untag (mkEncoder :: (Tagged OB (Encoder Identity (StandardResponse PayeeDetail))))) "PayeeDetailRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/payeedetail.golden.json" test_roundSubPayeeDetail :: [TestTree] test_roundSubPayeeDetail = [ roundTripTest domesticPayeeDecoder domesticPayeeEncoder " DomesticPayeeRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/domesticPayee.json" , roundTripTest domesticPayeeAccountDecoder domesticPayeeAccountEncoder " DomesticPayeeAccountRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/domesticPayeeAccount.json" , roundTripTest domesticPayeeCardDecoder domesticPayeeCardEncoder " DomesticPayeeCardRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/domesticPayeeCard.json" , roundTripTest domesticPayeePayIdDecoder domesticPayeePayIdEncoder " DomesticPayeePayIdRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/domesticPayeePayId.json" , roundTripTest internationalPayeeDecoder internationalPayeeEncoder " InternationalPayeeRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/internationalPayee.json" , roundTripTest billerPayeeDecoder billerPayeeEncoder " BillerPayeeRoundTrip" "tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesTest/billerPayee.json" ]
80e8aff2020e6f951b08bd285f18bc505fc9ace866b0bc8b5034d97444a5792c
lisp/de.setf.xml
namespace.lisp
-*- Mode : lisp ; Syntax : ansi - common - lisp ; Base : 10 ; Package : xml - query - data - model ; -*- (in-package :xml-query-data-model) (setq xml-query-data-model:*namespace* (xml-query-data-model:defnamespace "#" (:use) (:nicknames) (:export "AdministrativeBoundary" "AdministrativeDivision" "AdministrativeRegion" "AlbersConicalEqualArea" "Arc" "AstronomicalCoordinateSystem" "Attitude" "Axis" "Azimuth" "AzimuthalEquidistant" "Barrier" "Base" "Bearing" "Big" "Body" "Bottom" "BoundingBox" "Broken" "CartesianCoordinates" "CartesianCoordinateSystem" "Center" "City" "Country" "County" "Declination" "Deep" "DepthCategory" "Direction" "DistanceCategory" "Down" "Downward" "East" "Eastward" "Edge" "EquidistantConic" "Equirectangular" "Floor" "GeneralVerticalNearSidedPespe" "GeodeticCoordinateSystem" "GeographicalCoordinates" "GeographicCoordinateSystem" "Geoid" "GeoReferenceInformation" "Gnomic" "Grid" "Horizon" "HorizontalCoordinate" "HybridHeight" "Inclination" "Incoming" "LambertAzimuthalEqualArea" "LambertConformalConic" "Latitude" "LatitudeInterval" "LatLonBox" "Layer" "Level" "LocalCoordinateSystem" "LocalPlanarCoordinateSystem" "Location" "Longitude" "LongitudeInterval" "Margin" "Mercator" "Meridian" "MillerCylindrical" "ModifiedStereographic" "North" "Northward" "ObliqueMercator" "Obstruction" "Orbit" "Outgoing" "Outside" "Overcast" "Patch" "PolarStereographic" "PoliticalDivision" "Polyconic" "Position" "PressureCoordinate" "Profile" "Projection" "Province" "R-Coordinate" "Radial" "Region" "Relief" "RightAscension" "Robinson" "RotatedLaatitudeLongitude" "S-Coordinate" "SeaLevel" "Shadow" "Shallow" "Sigma" "Sinusoidal" "SizeCategory" "Slope" "Small" "South" "Southward" "SpaceObliqueMercator" "SpatialDistribution" "SpatialExtentCategory" "SpatialObject" "SpatialReferenceSystem" "SpatialScale" "State" "Stereographic" "StratigraphicSequence" "Stratigraphy" "Top" "TransverseMercator" "TraverseMercator" "UniversalTraverseMercator" "UniversalTraverseMercatorCoordinates" "Up" "Upper" "UpperLevel" "Upward" "VanDeGrinten" "VerticalCoordinate" "VerticalProfile" "Vicinity" "West" "Westward" "XCoordinate" "YCoordinate" "ZCoordinate" "ZenithAngle" "Zone" "ZoneCode") (:documentation nil))) (let ((xml-query-data-model::p (or (find-package "#") (make-package "#" :use nil :nicknames 'nil)))) (dolist (xml-query-data-model::s '("AdministrativeBoundary" "AdministrativeDivision" "AdministrativeRegion" "AlbersConicalEqualArea" "Arc" "AstronomicalCoordinateSystem" "Attitude" "Axis" "Azimuth" "AzimuthalEquidistant" "Barrier" "Base" "Bearing" "Big" "Body" "Bottom" "BoundingBox" "Broken" "CartesianCoordinates" "CartesianCoordinateSystem" "Center" "City" "Country" "County" "Declination" "Deep" "DepthCategory" "Direction" "DistanceCategory" "Down" "Downward" "East" "Eastward" "Edge" "EquidistantConic" "Equirectangular" "Floor" "GeneralVerticalNearSidedPespe" "GeodeticCoordinateSystem" "GeographicalCoordinates" "GeographicCoordinateSystem" "Geoid" "GeoReferenceInformation" "Gnomic" "Grid" "Horizon" "HorizontalCoordinate" "HybridHeight" "Inclination" "Incoming" "LambertAzimuthalEqualArea" "LambertConformalConic" "Latitude" "LatitudeInterval" "LatLonBox" "Layer" "Level" "LocalCoordinateSystem" "LocalPlanarCoordinateSystem" "Location" "Longitude" "LongitudeInterval" "Margin" "Mercator" "Meridian" "MillerCylindrical" "ModifiedStereographic" "North" "Northward" "ObliqueMercator" "Obstruction" "Orbit" "Outgoing" "Outside" "Overcast" "Patch" "PolarStereographic" "PoliticalDivision" "Polyconic" "Position" "PressureCoordinate" "Profile" "Projection" "Province" "R-Coordinate" "Radial" "Region" "Relief" "RightAscension" "Robinson" "RotatedLaatitudeLongitude" "S-Coordinate" "SeaLevel" "Shadow" "Shallow" "Sigma" "Sinusoidal" "SizeCategory" "Slope" "Small" "South" "Southward" "SpaceObliqueMercator" "SpatialDistribution" "SpatialExtentCategory" "SpatialObject" "SpatialReferenceSystem" "SpatialScale" "State" "Stereographic" "StratigraphicSequence" "Stratigraphy" "Top" "TransverseMercator" "TraverseMercator" "UniversalTraverseMercator" "UniversalTraverseMercatorCoordinates" "Up" "Upper" "UpperLevel" "Upward" "VanDeGrinten" "VerticalCoordinate" "VerticalProfile" "Vicinity" "West" "Westward" "XCoordinate" "YCoordinate" "ZCoordinate" "ZenithAngle" "Zone" "ZoneCode")) (export (intern xml-query-data-model::s xml-query-data-model::p) xml-query-data-model::p))) ;;; (xqdm:find-namespace "#" :if-does-not-exist :load)
null
https://raw.githubusercontent.com/lisp/de.setf.xml/827681c969342096c3b95735d84b447befa69fa6/namespaces/sweet-jpl-nasa-gov/ontology/space-owl/namespace.lisp
lisp
Syntax : ansi - common - lisp ; Base : 10 ; Package : xml - query - data - model ; -*- (xqdm:find-namespace "#" :if-does-not-exist :load)
(in-package :xml-query-data-model) (setq xml-query-data-model:*namespace* (xml-query-data-model:defnamespace "#" (:use) (:nicknames) (:export "AdministrativeBoundary" "AdministrativeDivision" "AdministrativeRegion" "AlbersConicalEqualArea" "Arc" "AstronomicalCoordinateSystem" "Attitude" "Axis" "Azimuth" "AzimuthalEquidistant" "Barrier" "Base" "Bearing" "Big" "Body" "Bottom" "BoundingBox" "Broken" "CartesianCoordinates" "CartesianCoordinateSystem" "Center" "City" "Country" "County" "Declination" "Deep" "DepthCategory" "Direction" "DistanceCategory" "Down" "Downward" "East" "Eastward" "Edge" "EquidistantConic" "Equirectangular" "Floor" "GeneralVerticalNearSidedPespe" "GeodeticCoordinateSystem" "GeographicalCoordinates" "GeographicCoordinateSystem" "Geoid" "GeoReferenceInformation" "Gnomic" "Grid" "Horizon" "HorizontalCoordinate" "HybridHeight" "Inclination" "Incoming" "LambertAzimuthalEqualArea" "LambertConformalConic" "Latitude" "LatitudeInterval" "LatLonBox" "Layer" "Level" "LocalCoordinateSystem" "LocalPlanarCoordinateSystem" "Location" "Longitude" "LongitudeInterval" "Margin" "Mercator" "Meridian" "MillerCylindrical" "ModifiedStereographic" "North" "Northward" "ObliqueMercator" "Obstruction" "Orbit" "Outgoing" "Outside" "Overcast" "Patch" "PolarStereographic" "PoliticalDivision" "Polyconic" "Position" "PressureCoordinate" "Profile" "Projection" "Province" "R-Coordinate" "Radial" "Region" "Relief" "RightAscension" "Robinson" "RotatedLaatitudeLongitude" "S-Coordinate" "SeaLevel" "Shadow" "Shallow" "Sigma" "Sinusoidal" "SizeCategory" "Slope" "Small" "South" "Southward" "SpaceObliqueMercator" "SpatialDistribution" "SpatialExtentCategory" "SpatialObject" "SpatialReferenceSystem" "SpatialScale" "State" "Stereographic" "StratigraphicSequence" "Stratigraphy" "Top" "TransverseMercator" "TraverseMercator" "UniversalTraverseMercator" "UniversalTraverseMercatorCoordinates" "Up" "Upper" "UpperLevel" "Upward" "VanDeGrinten" "VerticalCoordinate" "VerticalProfile" "Vicinity" "West" "Westward" "XCoordinate" "YCoordinate" "ZCoordinate" "ZenithAngle" "Zone" "ZoneCode") (:documentation nil))) (let ((xml-query-data-model::p (or (find-package "#") (make-package "#" :use nil :nicknames 'nil)))) (dolist (xml-query-data-model::s '("AdministrativeBoundary" "AdministrativeDivision" "AdministrativeRegion" "AlbersConicalEqualArea" "Arc" "AstronomicalCoordinateSystem" "Attitude" "Axis" "Azimuth" "AzimuthalEquidistant" "Barrier" "Base" "Bearing" "Big" "Body" "Bottom" "BoundingBox" "Broken" "CartesianCoordinates" "CartesianCoordinateSystem" "Center" "City" "Country" "County" "Declination" "Deep" "DepthCategory" "Direction" "DistanceCategory" "Down" "Downward" "East" "Eastward" "Edge" "EquidistantConic" "Equirectangular" "Floor" "GeneralVerticalNearSidedPespe" "GeodeticCoordinateSystem" "GeographicalCoordinates" "GeographicCoordinateSystem" "Geoid" "GeoReferenceInformation" "Gnomic" "Grid" "Horizon" "HorizontalCoordinate" "HybridHeight" "Inclination" "Incoming" "LambertAzimuthalEqualArea" "LambertConformalConic" "Latitude" "LatitudeInterval" "LatLonBox" "Layer" "Level" "LocalCoordinateSystem" "LocalPlanarCoordinateSystem" "Location" "Longitude" "LongitudeInterval" "Margin" "Mercator" "Meridian" "MillerCylindrical" "ModifiedStereographic" "North" "Northward" "ObliqueMercator" "Obstruction" "Orbit" "Outgoing" "Outside" "Overcast" "Patch" "PolarStereographic" "PoliticalDivision" "Polyconic" "Position" "PressureCoordinate" "Profile" "Projection" "Province" "R-Coordinate" "Radial" "Region" "Relief" "RightAscension" "Robinson" "RotatedLaatitudeLongitude" "S-Coordinate" "SeaLevel" "Shadow" "Shallow" "Sigma" "Sinusoidal" "SizeCategory" "Slope" "Small" "South" "Southward" "SpaceObliqueMercator" "SpatialDistribution" "SpatialExtentCategory" "SpatialObject" "SpatialReferenceSystem" "SpatialScale" "State" "Stereographic" "StratigraphicSequence" "Stratigraphy" "Top" "TransverseMercator" "TraverseMercator" "UniversalTraverseMercator" "UniversalTraverseMercatorCoordinates" "Up" "Upper" "UpperLevel" "Upward" "VanDeGrinten" "VerticalCoordinate" "VerticalProfile" "Vicinity" "West" "Westward" "XCoordinate" "YCoordinate" "ZCoordinate" "ZenithAngle" "Zone" "ZoneCode")) (export (intern xml-query-data-model::s xml-query-data-model::p) xml-query-data-model::p)))
371ca104154fa4708c10823cb8b679b007fed103971cf18708f3a6ee7a374f6b
newque/newque
http_prot.ml
open Core open Lwt open Cohttp open Cohttp_lwt_unix module Logger = Log.Make (struct let section = "Http" end) type t = { generic: Config_t.config_listener; specific: Config_t.config_http_settings; sock: Lwt_unix.file_descr; stop_w: unit Lwt.u; ctx: Cohttp_lwt_unix_net.ctx; thread: unit Lwt.t; exception_filter: Exception.exn_filter; } let missing_header = "<no header>" let default_filter _ req _ = let path = Uri.path (Request.uri req) in let url_fragments = String.split ~on:'/' path in let result = match url_fragments with | ""::"v1"::"health"::_ -> begin match Request.meth req with | `GET -> Ok (None, `Health) | meth -> Error (405, [sprintf "Invalid HTTP method [%s] for health" (Code.string_of_method meth)]) end | ""::"v1"::chan_name::"health"::_ -> begin match Request.meth req with | `GET -> Ok (Some chan_name, `Health) | meth -> Error (405, [sprintf "Invalid HTTP method [%s] for health" (Code.string_of_method meth)]) end | ""::"v1"::chan_name::"count"::_ -> begin match Request.meth req with | `GET -> Ok (Some chan_name, `Count) | meth -> Error (405, [sprintf "Invalid HTTP method [%s] for count" (Code.string_of_method meth)]) end | ""::"v1"::chan_name::_ -> let mode_opt = Header.get (Request.headers req) Header_names.mode in let mode_string = Option.value ~default:missing_header mode_opt in let mode_value = Result.bind (Result.of_option ~error:missing_header mode_opt) Mode.of_string in begin match ((Request.meth req), mode_value) with | `DELETE, _ -> Ok (Some chan_name, `Delete) | `POST, Ok (`Single as m) | `POST, Ok (`Multiple as m) | `POST, Ok (`Atomic as m) | `GET, Ok (`One as m) | `GET, Ok ((`Many _) as m) | `GET, Ok ((`After_id _) as m) | `GET, Ok ((`After_ts _) as m) -> Ok (Some chan_name, Mode.wrap m) | `POST, Error err when String.(=) err missing_header -> Ok (Some chan_name, Mode.wrap `Single) | meth, Ok m -> Error (400, [sprintf "Invalid {Method, Mode} pair: {%s, %s}" (Code.string_of_method meth) (Mode.to_string (m :> Mode.Any.t))]) | meth, Error _ -> Error (400, [sprintf "Invalid {Method, Mode} pair: {%s, %s}" (Code.string_of_method meth) mode_string]) end | _ -> Error (400, [sprintf "Invalid path [%s] (should begin with /v1/)" path]) in return result let json_response_header = Header.init_with "content-type" "application/json" let handle_errors code errors = let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_errors { code; errors; }) in Server.respond_string ~headers ~status ~body () let handler http routing ((ch, _) as conn) req body = let open Routing in let%lwt http = http in try%lwt begin match%lwt default_filter conn req body with | Error (code, errors) -> handle_errors code errors | Ok (Some chan_name, `Write mode) -> let stream = Cohttp_lwt_body.to_stream body in let id_header = Header.get (Request.headers req) Header_names.id in let%lwt (code, errors, saved) = begin match%lwt routing.write_http ~chan_name ~id_header ~mode stream with | Ok ((Some _) as count) -> return (201, [], count) | Ok None -> return (202, [], None) | Error errors -> return (400, errors, (Some 0)) end in let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_write { code; errors; saved; }) in Server.respond_string ~headers ~status ~body () | Ok (Some chan_name, `Read mode) -> begin match Request.encoding req with | Transfer.Chunked -> begin match%lwt routing.read_stream ~chan_name ~mode with | Error errors -> handle_errors 400 errors | Ok (stream, channel) -> let status = Code.status_of_code 200 in let%lwt headers = match%lwt Lwt_stream.is_empty stream with | false -> return (Header.add_list (Header.init ()) [ ("content-type", "application/octet-stream") ]) | true -> return ( Header.add_list (Header.init ()) [ ("content-type", "application/octet-stream"); (Header_names.length, "0"); ]) in let sep = channel.Channel.conf_channel.Config_t.separator in let body_stream = Lwt_stream.map_list_s (fun raw -> begin match%lwt Lwt_stream.is_empty stream with | true -> return [raw] | false -> return [raw; sep] end ) stream in let encoding = Transfer.Chunked in let response = Response.make ~status ~flush:true ~encoding ~headers () in let body = Cohttp_lwt_body.of_stream body_stream in return (response, body) end | Transfer.Unknown | Transfer.Fixed _ -> let limit = Util.header_name_to_int64_opt (Request.headers req) Header_names.limit in begin match%lwt routing.read_slice ~chan_name ~mode ~limit with | Error errors -> handle_errors 400 errors | Ok (slice, channel) -> let open Persistence in let payloads = slice.payloads in let code = 200 in let status = Code.status_of_code code in let headers = match slice.metadata with | None -> Header.add_list (Header.init ()) [ (Header_names.length, Int.to_string (Collection.length payloads)); ] | Some metadata -> Header.add_list (Header.init ()) [ (Header_names.length, Int.to_string (Collection.length payloads)); (Header_names.last_id, metadata.last_id); (Header_names.last_ts, (Int64.to_string metadata.last_timens)); ] in let open Read_settings in let (body, headers) = match channel.Channel.read with | None -> let err = sprintf "Impossible case: Missing readSettings for channel [%s]" chan_name in async (fun () -> Logger.error err); let headers = Header.add headers "content-type" "application/json" in let body = Json_obj_j.(string_of_read_list { code = 500; errors = [err]; messages = []; }) in (body, headers) | Some { http_format = Http_format.Plaintext } -> let headers = Header.add headers "content-type" "application/octet-stream" in let body = Collection.concat_string ~sep:channel.Channel.conf_channel.Config_t.separator payloads in (body, headers) | Some { http_format = Http_format.Json } -> let headers = Header.add headers "content-type" "application/json" in let body = match Collection.to_list_or_array payloads with | `List messages -> Json_obj_j.(string_of_read_list { code; errors = []; messages; }) | `Array messages -> Json_obj_j.(string_of_read_array { code; errors = []; messages; }) in (body, headers) in let encoding = Transfer.Fixed (Int.to_int64 (String.length body)) in let response = Response.make ~status ~flush:true ~encoding ~headers () in return (response, (Cohttp_lwt_body.of_string body)) end end | Ok (Some chan_name, (`Count as mode)) -> let%lwt (code, errors, count) = begin match%lwt routing.count ~chan_name ~mode with | Ok count -> return (200, [], Some count) | Error errors -> return (400, errors, None) end in let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_count { code; errors; count; }) in Server.respond_string ~headers ~status ~body () | Ok (Some chan_name, (`Delete as mode)) -> let%lwt (code, errors) = begin match%lwt routing.delete ~chan_name ~mode with | Ok () -> return (200, []) | Error errors -> return (400, errors) end in let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_errors { code; errors; }) in Server.respond_string ~headers ~status ~body () | Ok ((Some _) as chan_name, (`Health as mode)) | Ok (None as chan_name, (`Health as mode)) -> let%lwt (code, errors) = begin match%lwt routing.health ~chan_name ~mode with | [] as ll -> return (200, ll) | errors -> return (500, errors) end in let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_errors { code; errors; }) in Server.respond_string ~headers ~status ~body () | Ok (None, _) -> fail_with "Invalid routing" end with | ex -> (* Catch errors that bubbled up from the backend *) match http.exception_filter ex with | errors, true -> handle_errors 400 errors | errors, false -> handle_errors 500 errors let open_sockets = Int.Table.create ~size:5 () let make_socket ~backlog host port = let open Lwt_unix in let%lwt () = Logger.info (sprintf "Creating a new TCP socket on %s:%d" host port) in let%lwt info = Lwt_unix.getaddrinfo host "0" [AI_PASSIVE; AI_SOCKTYPE SOCK_STREAM] in let%lwt (sockaddr, ip) = match List.hd info with | Some {ai_addr = (ADDR_UNIX _)} -> fail_with "Cant listen to TCP on a domain socket" | Some {ai_addr = (ADDR_INET (a,_))} -> return (ADDR_INET (a,port), Ipaddr_unix.of_inet_addr a) | None -> return (ADDR_INET (Unix.Inet_addr.bind_any,port), Ipaddr.(V4 V4.any)) in let sock = Lwt_unix.socket (Unix.domain_of_sockaddr sockaddr) Unix.SOCK_STREAM 0 in Lwt_unix.setsockopt sock SO_REUSEADDR true; let%lwt () = Lwt_unix.bind sock sockaddr in Lwt_unix.listen sock backlog; Lwt_unix.set_close_on_exec sock; return sock let conn_closed name conn = async (fun () -> Logger.debug_lazy (lazy (sprintf "Connection closed on [%s]" name))) let start main_env generic specific routing = let open Config_t in let open Routing in let thunk () = make_socket ~backlog:specific.backlog generic.host generic.port in let%lwt sock = match Int.Table.find_and_remove open_sockets generic.port with | Some s -> begin match%lwt Fs.healthy_fd s with | true -> return s | false -> thunk () end | None -> thunk () in let%lwt ctx = Conduit_lwt_unix.init () in let ctx = Cohttp_lwt_unix_net.init ~ctx () in let mode = `TCP (`Socket sock) in let (instance_t, instance_w) = wait () in let conf = match routing with | Standard routing -> Server.make ~callback:(handler instance_t routing) () | Admin routing -> Server.make ~callback:(Admin.handler routing) () in let (stop_t, stop_w) = wait () in let thread = Server.create ~stop:stop_t ~ctx ~mode conf in let listener_env = Option.map ~f:Environment.create generic.listener_environment in let exception_filter = Exception.create_exception_filter ~section:generic.name ~main_env ~listener_env in let instance = { generic; specific; sock; stop_w; ctx; thread; exception_filter; } in wakeup instance_w instance; return instance let stop http = let open Config_t in wakeup http.stop_w (); let%lwt () = waiter_of_wakener http.stop_w in Int.Table.add_exn open_sockets ~key:http.generic.port ~data:http.sock; return_unit let close http = let open Config_t in let%lwt () = stop http in match Int.Table.find_and_remove open_sockets http.generic.port with | Some s -> Lwt_unix.close s | None -> return_unit
null
https://raw.githubusercontent.com/newque/newque/dee73e2cb7be8700847f9e5cf900731cc20b1b8c/src/server/protocols/http_prot.ml
ocaml
Catch errors that bubbled up from the backend
open Core open Lwt open Cohttp open Cohttp_lwt_unix module Logger = Log.Make (struct let section = "Http" end) type t = { generic: Config_t.config_listener; specific: Config_t.config_http_settings; sock: Lwt_unix.file_descr; stop_w: unit Lwt.u; ctx: Cohttp_lwt_unix_net.ctx; thread: unit Lwt.t; exception_filter: Exception.exn_filter; } let missing_header = "<no header>" let default_filter _ req _ = let path = Uri.path (Request.uri req) in let url_fragments = String.split ~on:'/' path in let result = match url_fragments with | ""::"v1"::"health"::_ -> begin match Request.meth req with | `GET -> Ok (None, `Health) | meth -> Error (405, [sprintf "Invalid HTTP method [%s] for health" (Code.string_of_method meth)]) end | ""::"v1"::chan_name::"health"::_ -> begin match Request.meth req with | `GET -> Ok (Some chan_name, `Health) | meth -> Error (405, [sprintf "Invalid HTTP method [%s] for health" (Code.string_of_method meth)]) end | ""::"v1"::chan_name::"count"::_ -> begin match Request.meth req with | `GET -> Ok (Some chan_name, `Count) | meth -> Error (405, [sprintf "Invalid HTTP method [%s] for count" (Code.string_of_method meth)]) end | ""::"v1"::chan_name::_ -> let mode_opt = Header.get (Request.headers req) Header_names.mode in let mode_string = Option.value ~default:missing_header mode_opt in let mode_value = Result.bind (Result.of_option ~error:missing_header mode_opt) Mode.of_string in begin match ((Request.meth req), mode_value) with | `DELETE, _ -> Ok (Some chan_name, `Delete) | `POST, Ok (`Single as m) | `POST, Ok (`Multiple as m) | `POST, Ok (`Atomic as m) | `GET, Ok (`One as m) | `GET, Ok ((`Many _) as m) | `GET, Ok ((`After_id _) as m) | `GET, Ok ((`After_ts _) as m) -> Ok (Some chan_name, Mode.wrap m) | `POST, Error err when String.(=) err missing_header -> Ok (Some chan_name, Mode.wrap `Single) | meth, Ok m -> Error (400, [sprintf "Invalid {Method, Mode} pair: {%s, %s}" (Code.string_of_method meth) (Mode.to_string (m :> Mode.Any.t))]) | meth, Error _ -> Error (400, [sprintf "Invalid {Method, Mode} pair: {%s, %s}" (Code.string_of_method meth) mode_string]) end | _ -> Error (400, [sprintf "Invalid path [%s] (should begin with /v1/)" path]) in return result let json_response_header = Header.init_with "content-type" "application/json" let handle_errors code errors = let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_errors { code; errors; }) in Server.respond_string ~headers ~status ~body () let handler http routing ((ch, _) as conn) req body = let open Routing in let%lwt http = http in try%lwt begin match%lwt default_filter conn req body with | Error (code, errors) -> handle_errors code errors | Ok (Some chan_name, `Write mode) -> let stream = Cohttp_lwt_body.to_stream body in let id_header = Header.get (Request.headers req) Header_names.id in let%lwt (code, errors, saved) = begin match%lwt routing.write_http ~chan_name ~id_header ~mode stream with | Ok ((Some _) as count) -> return (201, [], count) | Ok None -> return (202, [], None) | Error errors -> return (400, errors, (Some 0)) end in let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_write { code; errors; saved; }) in Server.respond_string ~headers ~status ~body () | Ok (Some chan_name, `Read mode) -> begin match Request.encoding req with | Transfer.Chunked -> begin match%lwt routing.read_stream ~chan_name ~mode with | Error errors -> handle_errors 400 errors | Ok (stream, channel) -> let status = Code.status_of_code 200 in let%lwt headers = match%lwt Lwt_stream.is_empty stream with | false -> return (Header.add_list (Header.init ()) [ ("content-type", "application/octet-stream") ]) | true -> return ( Header.add_list (Header.init ()) [ ("content-type", "application/octet-stream"); (Header_names.length, "0"); ]) in let sep = channel.Channel.conf_channel.Config_t.separator in let body_stream = Lwt_stream.map_list_s (fun raw -> begin match%lwt Lwt_stream.is_empty stream with | true -> return [raw] | false -> return [raw; sep] end ) stream in let encoding = Transfer.Chunked in let response = Response.make ~status ~flush:true ~encoding ~headers () in let body = Cohttp_lwt_body.of_stream body_stream in return (response, body) end | Transfer.Unknown | Transfer.Fixed _ -> let limit = Util.header_name_to_int64_opt (Request.headers req) Header_names.limit in begin match%lwt routing.read_slice ~chan_name ~mode ~limit with | Error errors -> handle_errors 400 errors | Ok (slice, channel) -> let open Persistence in let payloads = slice.payloads in let code = 200 in let status = Code.status_of_code code in let headers = match slice.metadata with | None -> Header.add_list (Header.init ()) [ (Header_names.length, Int.to_string (Collection.length payloads)); ] | Some metadata -> Header.add_list (Header.init ()) [ (Header_names.length, Int.to_string (Collection.length payloads)); (Header_names.last_id, metadata.last_id); (Header_names.last_ts, (Int64.to_string metadata.last_timens)); ] in let open Read_settings in let (body, headers) = match channel.Channel.read with | None -> let err = sprintf "Impossible case: Missing readSettings for channel [%s]" chan_name in async (fun () -> Logger.error err); let headers = Header.add headers "content-type" "application/json" in let body = Json_obj_j.(string_of_read_list { code = 500; errors = [err]; messages = []; }) in (body, headers) | Some { http_format = Http_format.Plaintext } -> let headers = Header.add headers "content-type" "application/octet-stream" in let body = Collection.concat_string ~sep:channel.Channel.conf_channel.Config_t.separator payloads in (body, headers) | Some { http_format = Http_format.Json } -> let headers = Header.add headers "content-type" "application/json" in let body = match Collection.to_list_or_array payloads with | `List messages -> Json_obj_j.(string_of_read_list { code; errors = []; messages; }) | `Array messages -> Json_obj_j.(string_of_read_array { code; errors = []; messages; }) in (body, headers) in let encoding = Transfer.Fixed (Int.to_int64 (String.length body)) in let response = Response.make ~status ~flush:true ~encoding ~headers () in return (response, (Cohttp_lwt_body.of_string body)) end end | Ok (Some chan_name, (`Count as mode)) -> let%lwt (code, errors, count) = begin match%lwt routing.count ~chan_name ~mode with | Ok count -> return (200, [], Some count) | Error errors -> return (400, errors, None) end in let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_count { code; errors; count; }) in Server.respond_string ~headers ~status ~body () | Ok (Some chan_name, (`Delete as mode)) -> let%lwt (code, errors) = begin match%lwt routing.delete ~chan_name ~mode with | Ok () -> return (200, []) | Error errors -> return (400, errors) end in let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_errors { code; errors; }) in Server.respond_string ~headers ~status ~body () | Ok ((Some _) as chan_name, (`Health as mode)) | Ok (None as chan_name, (`Health as mode)) -> let%lwt (code, errors) = begin match%lwt routing.health ~chan_name ~mode with | [] as ll -> return (200, ll) | errors -> return (500, errors) end in let headers = json_response_header in let status = Code.status_of_code code in let body = Json_obj_j.(string_of_errors { code; errors; }) in Server.respond_string ~headers ~status ~body () | Ok (None, _) -> fail_with "Invalid routing" end with | ex -> match http.exception_filter ex with | errors, true -> handle_errors 400 errors | errors, false -> handle_errors 500 errors let open_sockets = Int.Table.create ~size:5 () let make_socket ~backlog host port = let open Lwt_unix in let%lwt () = Logger.info (sprintf "Creating a new TCP socket on %s:%d" host port) in let%lwt info = Lwt_unix.getaddrinfo host "0" [AI_PASSIVE; AI_SOCKTYPE SOCK_STREAM] in let%lwt (sockaddr, ip) = match List.hd info with | Some {ai_addr = (ADDR_UNIX _)} -> fail_with "Cant listen to TCP on a domain socket" | Some {ai_addr = (ADDR_INET (a,_))} -> return (ADDR_INET (a,port), Ipaddr_unix.of_inet_addr a) | None -> return (ADDR_INET (Unix.Inet_addr.bind_any,port), Ipaddr.(V4 V4.any)) in let sock = Lwt_unix.socket (Unix.domain_of_sockaddr sockaddr) Unix.SOCK_STREAM 0 in Lwt_unix.setsockopt sock SO_REUSEADDR true; let%lwt () = Lwt_unix.bind sock sockaddr in Lwt_unix.listen sock backlog; Lwt_unix.set_close_on_exec sock; return sock let conn_closed name conn = async (fun () -> Logger.debug_lazy (lazy (sprintf "Connection closed on [%s]" name))) let start main_env generic specific routing = let open Config_t in let open Routing in let thunk () = make_socket ~backlog:specific.backlog generic.host generic.port in let%lwt sock = match Int.Table.find_and_remove open_sockets generic.port with | Some s -> begin match%lwt Fs.healthy_fd s with | true -> return s | false -> thunk () end | None -> thunk () in let%lwt ctx = Conduit_lwt_unix.init () in let ctx = Cohttp_lwt_unix_net.init ~ctx () in let mode = `TCP (`Socket sock) in let (instance_t, instance_w) = wait () in let conf = match routing with | Standard routing -> Server.make ~callback:(handler instance_t routing) () | Admin routing -> Server.make ~callback:(Admin.handler routing) () in let (stop_t, stop_w) = wait () in let thread = Server.create ~stop:stop_t ~ctx ~mode conf in let listener_env = Option.map ~f:Environment.create generic.listener_environment in let exception_filter = Exception.create_exception_filter ~section:generic.name ~main_env ~listener_env in let instance = { generic; specific; sock; stop_w; ctx; thread; exception_filter; } in wakeup instance_w instance; return instance let stop http = let open Config_t in wakeup http.stop_w (); let%lwt () = waiter_of_wakener http.stop_w in Int.Table.add_exn open_sockets ~key:http.generic.port ~data:http.sock; return_unit let close http = let open Config_t in let%lwt () = stop http in match Int.Table.find_and_remove open_sockets http.generic.port with | Some s -> Lwt_unix.close s | None -> return_unit
025ccd57cc68e8b462d016bc6970345cc137e17d3aab6bc884176530aa9f8b99
statebox/cql
Lib.hs
SPDX - License - Identifier : AGPL-3.0 - only This file is part of ` statebox / cql ` , the categorical query language . Copyright ( C ) 2019 < This program is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with this program . If not , see < / > . SPDX-License-Identifier: AGPL-3.0-only This file is part of `statebox/cql`, the categorical query language. Copyright (C) 2019 Stichting Statebox <> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see </>. -} module Api.Lib where import Api.Api (API, cqlApi) import Api.Config.Config (Config (..)) import Api.Config.Environment (logger) -- servant-server import Servant (Application, Proxy (Proxy), serve) -- warp import Network.Wai.Handler.Warp (defaultSettings, runSettings, setPort) startApp :: Config -> IO () startApp config = runSettings (setPort (apiPort config) defaultSettings) (app config) app :: Config -> Application app config = logger (environment config) $ serve api cqlApi api :: Proxy API api = Proxy
null
https://raw.githubusercontent.com/statebox/cql/b155e737ef4977ec753e44790f236686ff6a4558/http/src/Api/Lib.hs
haskell
servant-server warp
SPDX - License - Identifier : AGPL-3.0 - only This file is part of ` statebox / cql ` , the categorical query language . Copyright ( C ) 2019 < This program is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with this program . If not , see < / > . SPDX-License-Identifier: AGPL-3.0-only This file is part of `statebox/cql`, the categorical query language. Copyright (C) 2019 Stichting Statebox <> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see </>. -} module Api.Lib where import Api.Api (API, cqlApi) import Api.Config.Config (Config (..)) import Api.Config.Environment (logger) import Servant (Application, Proxy (Proxy), serve) import Network.Wai.Handler.Warp (defaultSettings, runSettings, setPort) startApp :: Config -> IO () startApp config = runSettings (setPort (apiPort config) defaultSettings) (app config) app :: Config -> Application app config = logger (environment config) $ serve api cqlApi api :: Proxy API api = Proxy
17da6123e6102feed8341640785d1ff31b45bb78857cfb3a8318accc37414283
alissa-tung/hs-http
Internal.hs
module Z.Data.HTTP.Internal where import Data.Maybe import qualified Z.Data.ASCII as C import qualified Z.Data.Builder as B import qualified Z.Data.Parser as P import qualified Z.Data.Vector as V data HTTPVersion = HTTP1_1 versionToBytes :: HTTPVersion -> V.Bytes versionToBytes = \case HTTP1_1 -> "HTTP/1.1" parseVersion :: P.Parser HTTPVersion parseVersion = do P.skipWhile (/= C.LETTER_P) >> P.skipWord8 c0 <- P.peek P.skipWord8 c1 <- P.peekMaybe let c1' = fromMaybe (error "todo") c1 return (if c0 == C.DIGIT_1 && c1' == C.DIGIT_1 then HTTP1_1 else error "todo") type Headers :: * type Headers = (V.Vector (HeaderHeader, HeaderValue)) headersToBytes' :: Headers -> V.Bytes headersToBytes' hs = case V.unpack hs of [] -> V.empty h : hs -> headerToBytes h <> headersToBytes' hs where headersToBytes' :: [(HeaderHeader, HeaderValue)] -> V.Bytes = \case [] -> V.empty h : hs -> headerToBytes h <> headersToBytes' hs headersToBytes :: Headers -> V.Bytes headersToBytes hs = let hs' = V.unpack hs in mconcat (map headerToBytes hs') type Header = (HeaderHeader, HeaderValue) data HeaderPayload = HTransferEncoding [TransferCoding] | Content - Length = 1*DIGIT readExactly : : HasCallStack = > Int - > BufferedInput - > IO V.Bytes data MessageBodyHeader = TransferEncoding | ContentLength Int type MessageBody = -- | message-body = *OCTET V.Bytes data TransferCoding = Chunked | Compress | Deflate | GZIP | TransferExtension data TransferParameter headerToBytes :: Header -> V.Bytes headerToBytes (header, value) = header <> ": " <> value <> CRLF type HeaderHeader = V.Bytes type HeaderValue = V.Bytes joinHeaders :: Headers -> V.Bytes joinHeaders hs = (V.concat . V.unpack) (fmap (\(header, value) -> header <> ": " <> value) hs) emptyHeaders :: Headers emptyHeaders = V.empty type Body = V.Bytes emptyBody :: Body emptyBody = V.empty data LinearWhitespace = OWS | RWS | BWS data TokenChar pattern CRLF :: V.Bytes pattern CRLF = "\r\n" pSkipCRLF :: P.Parser () pSkipCRLF = P.word8 C.CARRIAGE_RETURN >> P.word8 C.NEWLINE pattern SPACE :: V.Bytes pattern SPACE = " "
null
https://raw.githubusercontent.com/alissa-tung/hs-http/d2871b730b00ad6671aa18bbef24312eaf67844c/Z/Data/HTTP/Internal.hs
haskell
| message-body = *OCTET
module Z.Data.HTTP.Internal where import Data.Maybe import qualified Z.Data.ASCII as C import qualified Z.Data.Builder as B import qualified Z.Data.Parser as P import qualified Z.Data.Vector as V data HTTPVersion = HTTP1_1 versionToBytes :: HTTPVersion -> V.Bytes versionToBytes = \case HTTP1_1 -> "HTTP/1.1" parseVersion :: P.Parser HTTPVersion parseVersion = do P.skipWhile (/= C.LETTER_P) >> P.skipWord8 c0 <- P.peek P.skipWord8 c1 <- P.peekMaybe let c1' = fromMaybe (error "todo") c1 return (if c0 == C.DIGIT_1 && c1' == C.DIGIT_1 then HTTP1_1 else error "todo") type Headers :: * type Headers = (V.Vector (HeaderHeader, HeaderValue)) headersToBytes' :: Headers -> V.Bytes headersToBytes' hs = case V.unpack hs of [] -> V.empty h : hs -> headerToBytes h <> headersToBytes' hs where headersToBytes' :: [(HeaderHeader, HeaderValue)] -> V.Bytes = \case [] -> V.empty h : hs -> headerToBytes h <> headersToBytes' hs headersToBytes :: Headers -> V.Bytes headersToBytes hs = let hs' = V.unpack hs in mconcat (map headerToBytes hs') type Header = (HeaderHeader, HeaderValue) data HeaderPayload = HTransferEncoding [TransferCoding] | Content - Length = 1*DIGIT readExactly : : HasCallStack = > Int - > BufferedInput - > IO V.Bytes data MessageBodyHeader = TransferEncoding | ContentLength Int type MessageBody = V.Bytes data TransferCoding = Chunked | Compress | Deflate | GZIP | TransferExtension data TransferParameter headerToBytes :: Header -> V.Bytes headerToBytes (header, value) = header <> ": " <> value <> CRLF type HeaderHeader = V.Bytes type HeaderValue = V.Bytes joinHeaders :: Headers -> V.Bytes joinHeaders hs = (V.concat . V.unpack) (fmap (\(header, value) -> header <> ": " <> value) hs) emptyHeaders :: Headers emptyHeaders = V.empty type Body = V.Bytes emptyBody :: Body emptyBody = V.empty data LinearWhitespace = OWS | RWS | BWS data TokenChar pattern CRLF :: V.Bytes pattern CRLF = "\r\n" pSkipCRLF :: P.Parser () pSkipCRLF = P.word8 C.CARRIAGE_RETURN >> P.word8 C.NEWLINE pattern SPACE :: V.Bytes pattern SPACE = " "