_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
497b5f9cfde4f01c9ddecd856380a08ec43e1fc427d93d8f6717a6ff358d236c
dparis/gen-phzr
line.cljs
(ns phzr.impl.accessors.line) (def line-get-properties {:angle "angle" :bottom "bottom" :end "end" :height "height" :left "left" :length "length" :normal-angle "normalAngle" :normal-x "normalX" :normal-y "normalY" :perp-slope "perpSlope" :right "right" :slope "slope" :start "start" :top "top" :type "type" :width "width" :x "x" :y "y"}) (def line-set-properties {:end "end" :start "start"})
null
https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/impl/accessors/line.cljs
clojure
(ns phzr.impl.accessors.line) (def line-get-properties {:angle "angle" :bottom "bottom" :end "end" :height "height" :left "left" :length "length" :normal-angle "normalAngle" :normal-x "normalX" :normal-y "normalY" :perp-slope "perpSlope" :right "right" :slope "slope" :start "start" :top "top" :type "type" :width "width" :x "x" :y "y"}) (def line-set-properties {:end "end" :start "start"})
096d13108ecaf27cdca905d12ad5bab2d9c4ecb11c889701800680b311ef185d
DKurilo/hackerrank
testgenerator.hs
# LANGUAGE FlexibleInstances , UndecidableInstances , DuplicateRecordFields # module Main where import Control.Monad import qualified Data.List as DL import Data.List.Split import qualified Data.Set as DS import System.Environment import System.IO import qualified Data.Map.Strict as DM import System.Random import Debug.Trace main :: IO() main = do stdout <- getEnv "OUTPUT_PATH" fptr <- openFile stdout WriteMode d <- getStdRandom $ randomR (1,100000) :: IO Int hPutStrLn fptr $ show d arr <- mapM (\_ -> getStdRandom $ randomR (1,1000000) :: IO Int) [1..d] hPutStrLn fptr $ DL.intercalate " " $ map show $ arr hFlush fptr hClose fptr
null
https://raw.githubusercontent.com/DKurilo/hackerrank/37063170567b397b25a2b7123bc9c1299d34814a/largest-rectangle/testgenerator.hs
haskell
# LANGUAGE FlexibleInstances , UndecidableInstances , DuplicateRecordFields # module Main where import Control.Monad import qualified Data.List as DL import Data.List.Split import qualified Data.Set as DS import System.Environment import System.IO import qualified Data.Map.Strict as DM import System.Random import Debug.Trace main :: IO() main = do stdout <- getEnv "OUTPUT_PATH" fptr <- openFile stdout WriteMode d <- getStdRandom $ randomR (1,100000) :: IO Int hPutStrLn fptr $ show d arr <- mapM (\_ -> getStdRandom $ randomR (1,1000000) :: IO Int) [1..d] hPutStrLn fptr $ DL.intercalate " " $ map show $ arr hFlush fptr hClose fptr
c060cfbf4f5032f7f1e3bd4c02f17d5ccd5d862d51db667694501c2cdd83a8ce
well-typed/large-records
R080.hs
#if PROFILE_CORESIZE {-# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #-} #endif #if PROFILE_TIMING {-# OPTIONS_GHC -ddump-to-file -ddump-timings #-} #endif # OPTIONS_GHC -fplugin = TypeLet # module Experiment.HListLetAsCase.Sized.R080 where import TypeLet import Bench.HList import Bench.Types import Common.HListOfSize.HL080 hlist :: HList Fields hlist = 79 .. 70 case letAs (MkT 79 :* Nil) of { LetAs (xs79 :: HList t79) -> case letAs (MkT 78 :* xs79) of { LetAs (xs78 :: HList t78) -> case letAs (MkT 77 :* xs78) of { LetAs (xs77 :: HList t77) -> case letAs (MkT 76 :* xs77) of { LetAs (xs76 :: HList t76) -> case letAs (MkT 75 :* xs76) of { LetAs (xs75 :: HList t75) -> case letAs (MkT 74 :* xs75) of { LetAs (xs74 :: HList t74) -> case letAs (MkT 73 :* xs74) of { LetAs (xs73 :: HList t73) -> case letAs (MkT 72 :* xs73) of { LetAs (xs72 :: HList t72) -> case letAs (MkT 71 :* xs72) of { LetAs (xs71 :: HList t71) -> case letAs (MkT 70 :* xs71) of { LetAs (xs70 :: HList t70) -> 69 .. 60 case letAs (MkT 69 :* xs70) of { LetAs (xs69 :: HList t69) -> case letAs (MkT 68 :* xs69) of { LetAs (xs68 :: HList t68) -> case letAs (MkT 67 :* xs68) of { LetAs (xs67 :: HList t67) -> case letAs (MkT 66 :* xs67) of { LetAs (xs66 :: HList t66) -> case letAs (MkT 65 :* xs66) of { LetAs (xs65 :: HList t65) -> case letAs (MkT 64 :* xs65) of { LetAs (xs64 :: HList t64) -> case letAs (MkT 63 :* xs64) of { LetAs (xs63 :: HList t63) -> case letAs (MkT 62 :* xs63) of { LetAs (xs62 :: HList t62) -> case letAs (MkT 61 :* xs62) of { LetAs (xs61 :: HList t61) -> case letAs (MkT 60 :* xs61) of { LetAs (xs60 :: HList t60) -> 59 .. 50 case letAs (MkT 59 :* xs60) of { LetAs (xs59 :: HList t59) -> case letAs (MkT 58 :* xs59) of { LetAs (xs58 :: HList t58) -> case letAs (MkT 57 :* xs58) of { LetAs (xs57 :: HList t57) -> case letAs (MkT 56 :* xs57) of { LetAs (xs56 :: HList t56) -> case letAs (MkT 55 :* xs56) of { LetAs (xs55 :: HList t55) -> case letAs (MkT 54 :* xs55) of { LetAs (xs54 :: HList t54) -> case letAs (MkT 53 :* xs54) of { LetAs (xs53 :: HList t53) -> case letAs (MkT 52 :* xs53) of { LetAs (xs52 :: HList t52) -> case letAs (MkT 51 :* xs52) of { LetAs (xs51 :: HList t51) -> case letAs (MkT 50 :* xs51) of { LetAs (xs50 :: HList t50) -> 49 .. 40 case letAs (MkT 49 :* xs50) of { LetAs (xs49 :: HList t49) -> case letAs (MkT 48 :* xs49) of { LetAs (xs48 :: HList t48) -> case letAs (MkT 47 :* xs48) of { LetAs (xs47 :: HList t47) -> case letAs (MkT 46 :* xs47) of { LetAs (xs46 :: HList t46) -> case letAs (MkT 45 :* xs46) of { LetAs (xs45 :: HList t45) -> case letAs (MkT 44 :* xs45) of { LetAs (xs44 :: HList t44) -> case letAs (MkT 43 :* xs44) of { LetAs (xs43 :: HList t43) -> case letAs (MkT 42 :* xs43) of { LetAs (xs42 :: HList t42) -> case letAs (MkT 41 :* xs42) of { LetAs (xs41 :: HList t41) -> case letAs (MkT 40 :* xs41) of { LetAs (xs40 :: HList t40) -> 39 .. 30 case letAs (MkT 39 :* xs40) of { LetAs (xs39 :: HList t39) -> case letAs (MkT 38 :* xs39) of { LetAs (xs38 :: HList t38) -> case letAs (MkT 37 :* xs38) of { LetAs (xs37 :: HList t37) -> case letAs (MkT 36 :* xs37) of { LetAs (xs36 :: HList t36) -> case letAs (MkT 35 :* xs36) of { LetAs (xs35 :: HList t35) -> case letAs (MkT 34 :* xs35) of { LetAs (xs34 :: HList t34) -> case letAs (MkT 33 :* xs34) of { LetAs (xs33 :: HList t33) -> case letAs (MkT 32 :* xs33) of { LetAs (xs32 :: HList t32) -> case letAs (MkT 31 :* xs32) of { LetAs (xs31 :: HList t31) -> case letAs (MkT 30 :* xs31) of { LetAs (xs30 :: HList t30) -> 29 .. 20 case letAs (MkT 29 :* xs30) of { LetAs (xs29 :: HList t29) -> case letAs (MkT 28 :* xs29) of { LetAs (xs28 :: HList t28) -> case letAs (MkT 27 :* xs28) of { LetAs (xs27 :: HList t27) -> case letAs (MkT 26 :* xs27) of { LetAs (xs26 :: HList t26) -> case letAs (MkT 25 :* xs26) of { LetAs (xs25 :: HList t25) -> case letAs (MkT 24 :* xs25) of { LetAs (xs24 :: HList t24) -> case letAs (MkT 23 :* xs24) of { LetAs (xs23 :: HList t23) -> case letAs (MkT 22 :* xs23) of { LetAs (xs22 :: HList t22) -> case letAs (MkT 21 :* xs22) of { LetAs (xs21 :: HList t21) -> case letAs (MkT 20 :* xs21) of { LetAs (xs20 :: HList t20) -> 19 .. 10 case letAs (MkT 19 :* xs20) of { LetAs (xs19 :: HList t19) -> case letAs (MkT 18 :* xs19) of { LetAs (xs18 :: HList t18) -> case letAs (MkT 17 :* xs18) of { LetAs (xs17 :: HList t17) -> case letAs (MkT 16 :* xs17) of { LetAs (xs16 :: HList t16) -> case letAs (MkT 15 :* xs16) of { LetAs (xs15 :: HList t15) -> case letAs (MkT 14 :* xs15) of { LetAs (xs14 :: HList t14) -> case letAs (MkT 13 :* xs14) of { LetAs (xs13 :: HList t13) -> case letAs (MkT 12 :* xs13) of { LetAs (xs12 :: HList t12) -> case letAs (MkT 11 :* xs12) of { LetAs (xs11 :: HList t11) -> case letAs (MkT 10 :* xs11) of { LetAs (xs10 :: HList t10) -> 09 .. 00 case letAs (MkT 09 :* xs10) of { LetAs (xs09 :: HList t09) -> case letAs (MkT 08 :* xs09) of { LetAs (xs08 :: HList t08) -> case letAs (MkT 07 :* xs08) of { LetAs (xs07 :: HList t07) -> case letAs (MkT 06 :* xs07) of { LetAs (xs06 :: HList t06) -> case letAs (MkT 05 :* xs06) of { LetAs (xs05 :: HList t05) -> case letAs (MkT 04 :* xs05) of { LetAs (xs04 :: HList t04) -> case letAs (MkT 03 :* xs04) of { LetAs (xs03 :: HList t03) -> case letAs (MkT 02 :* xs03) of { LetAs (xs02 :: HList t02) -> case letAs (MkT 01 :* xs02) of { LetAs (xs01 :: HList t01) -> case letAs (MkT 00 :* xs01) of { LetAs (xs00 :: HList t00) -> castEqual xs00 }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}}
null
https://raw.githubusercontent.com/well-typed/large-records/551f265845fbe56346988a6b484dca40ef380609/large-records-benchmarks/bench/typelet/Experiment/HListLetAsCase/Sized/R080.hs
haskell
# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl # # OPTIONS_GHC -ddump-to-file -ddump-timings #
#if PROFILE_CORESIZE #endif #if PROFILE_TIMING #endif # OPTIONS_GHC -fplugin = TypeLet # module Experiment.HListLetAsCase.Sized.R080 where import TypeLet import Bench.HList import Bench.Types import Common.HListOfSize.HL080 hlist :: HList Fields hlist = 79 .. 70 case letAs (MkT 79 :* Nil) of { LetAs (xs79 :: HList t79) -> case letAs (MkT 78 :* xs79) of { LetAs (xs78 :: HList t78) -> case letAs (MkT 77 :* xs78) of { LetAs (xs77 :: HList t77) -> case letAs (MkT 76 :* xs77) of { LetAs (xs76 :: HList t76) -> case letAs (MkT 75 :* xs76) of { LetAs (xs75 :: HList t75) -> case letAs (MkT 74 :* xs75) of { LetAs (xs74 :: HList t74) -> case letAs (MkT 73 :* xs74) of { LetAs (xs73 :: HList t73) -> case letAs (MkT 72 :* xs73) of { LetAs (xs72 :: HList t72) -> case letAs (MkT 71 :* xs72) of { LetAs (xs71 :: HList t71) -> case letAs (MkT 70 :* xs71) of { LetAs (xs70 :: HList t70) -> 69 .. 60 case letAs (MkT 69 :* xs70) of { LetAs (xs69 :: HList t69) -> case letAs (MkT 68 :* xs69) of { LetAs (xs68 :: HList t68) -> case letAs (MkT 67 :* xs68) of { LetAs (xs67 :: HList t67) -> case letAs (MkT 66 :* xs67) of { LetAs (xs66 :: HList t66) -> case letAs (MkT 65 :* xs66) of { LetAs (xs65 :: HList t65) -> case letAs (MkT 64 :* xs65) of { LetAs (xs64 :: HList t64) -> case letAs (MkT 63 :* xs64) of { LetAs (xs63 :: HList t63) -> case letAs (MkT 62 :* xs63) of { LetAs (xs62 :: HList t62) -> case letAs (MkT 61 :* xs62) of { LetAs (xs61 :: HList t61) -> case letAs (MkT 60 :* xs61) of { LetAs (xs60 :: HList t60) -> 59 .. 50 case letAs (MkT 59 :* xs60) of { LetAs (xs59 :: HList t59) -> case letAs (MkT 58 :* xs59) of { LetAs (xs58 :: HList t58) -> case letAs (MkT 57 :* xs58) of { LetAs (xs57 :: HList t57) -> case letAs (MkT 56 :* xs57) of { LetAs (xs56 :: HList t56) -> case letAs (MkT 55 :* xs56) of { LetAs (xs55 :: HList t55) -> case letAs (MkT 54 :* xs55) of { LetAs (xs54 :: HList t54) -> case letAs (MkT 53 :* xs54) of { LetAs (xs53 :: HList t53) -> case letAs (MkT 52 :* xs53) of { LetAs (xs52 :: HList t52) -> case letAs (MkT 51 :* xs52) of { LetAs (xs51 :: HList t51) -> case letAs (MkT 50 :* xs51) of { LetAs (xs50 :: HList t50) -> 49 .. 40 case letAs (MkT 49 :* xs50) of { LetAs (xs49 :: HList t49) -> case letAs (MkT 48 :* xs49) of { LetAs (xs48 :: HList t48) -> case letAs (MkT 47 :* xs48) of { LetAs (xs47 :: HList t47) -> case letAs (MkT 46 :* xs47) of { LetAs (xs46 :: HList t46) -> case letAs (MkT 45 :* xs46) of { LetAs (xs45 :: HList t45) -> case letAs (MkT 44 :* xs45) of { LetAs (xs44 :: HList t44) -> case letAs (MkT 43 :* xs44) of { LetAs (xs43 :: HList t43) -> case letAs (MkT 42 :* xs43) of { LetAs (xs42 :: HList t42) -> case letAs (MkT 41 :* xs42) of { LetAs (xs41 :: HList t41) -> case letAs (MkT 40 :* xs41) of { LetAs (xs40 :: HList t40) -> 39 .. 30 case letAs (MkT 39 :* xs40) of { LetAs (xs39 :: HList t39) -> case letAs (MkT 38 :* xs39) of { LetAs (xs38 :: HList t38) -> case letAs (MkT 37 :* xs38) of { LetAs (xs37 :: HList t37) -> case letAs (MkT 36 :* xs37) of { LetAs (xs36 :: HList t36) -> case letAs (MkT 35 :* xs36) of { LetAs (xs35 :: HList t35) -> case letAs (MkT 34 :* xs35) of { LetAs (xs34 :: HList t34) -> case letAs (MkT 33 :* xs34) of { LetAs (xs33 :: HList t33) -> case letAs (MkT 32 :* xs33) of { LetAs (xs32 :: HList t32) -> case letAs (MkT 31 :* xs32) of { LetAs (xs31 :: HList t31) -> case letAs (MkT 30 :* xs31) of { LetAs (xs30 :: HList t30) -> 29 .. 20 case letAs (MkT 29 :* xs30) of { LetAs (xs29 :: HList t29) -> case letAs (MkT 28 :* xs29) of { LetAs (xs28 :: HList t28) -> case letAs (MkT 27 :* xs28) of { LetAs (xs27 :: HList t27) -> case letAs (MkT 26 :* xs27) of { LetAs (xs26 :: HList t26) -> case letAs (MkT 25 :* xs26) of { LetAs (xs25 :: HList t25) -> case letAs (MkT 24 :* xs25) of { LetAs (xs24 :: HList t24) -> case letAs (MkT 23 :* xs24) of { LetAs (xs23 :: HList t23) -> case letAs (MkT 22 :* xs23) of { LetAs (xs22 :: HList t22) -> case letAs (MkT 21 :* xs22) of { LetAs (xs21 :: HList t21) -> case letAs (MkT 20 :* xs21) of { LetAs (xs20 :: HList t20) -> 19 .. 10 case letAs (MkT 19 :* xs20) of { LetAs (xs19 :: HList t19) -> case letAs (MkT 18 :* xs19) of { LetAs (xs18 :: HList t18) -> case letAs (MkT 17 :* xs18) of { LetAs (xs17 :: HList t17) -> case letAs (MkT 16 :* xs17) of { LetAs (xs16 :: HList t16) -> case letAs (MkT 15 :* xs16) of { LetAs (xs15 :: HList t15) -> case letAs (MkT 14 :* xs15) of { LetAs (xs14 :: HList t14) -> case letAs (MkT 13 :* xs14) of { LetAs (xs13 :: HList t13) -> case letAs (MkT 12 :* xs13) of { LetAs (xs12 :: HList t12) -> case letAs (MkT 11 :* xs12) of { LetAs (xs11 :: HList t11) -> case letAs (MkT 10 :* xs11) of { LetAs (xs10 :: HList t10) -> 09 .. 00 case letAs (MkT 09 :* xs10) of { LetAs (xs09 :: HList t09) -> case letAs (MkT 08 :* xs09) of { LetAs (xs08 :: HList t08) -> case letAs (MkT 07 :* xs08) of { LetAs (xs07 :: HList t07) -> case letAs (MkT 06 :* xs07) of { LetAs (xs06 :: HList t06) -> case letAs (MkT 05 :* xs06) of { LetAs (xs05 :: HList t05) -> case letAs (MkT 04 :* xs05) of { LetAs (xs04 :: HList t04) -> case letAs (MkT 03 :* xs04) of { LetAs (xs03 :: HList t03) -> case letAs (MkT 02 :* xs03) of { LetAs (xs02 :: HList t02) -> case letAs (MkT 01 :* xs02) of { LetAs (xs01 :: HList t01) -> case letAs (MkT 00 :* xs01) of { LetAs (xs00 :: HList t00) -> castEqual xs00 }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}} }}}}}}}}}}
362ea6c0f550b7e208ffddcd7ec0ca017bf70f45b15070e604b707fbc82c1323
tomoyuki28jp/web4r
user.lisp
(in-package :web4r-tests) (in-suite web4r) (test user* (defpclass test-user1 (user) ((email :format :email :unique t))) (setf *user* (make-instance 'user* :class 'test-user1 :id-label "ID1" :pass-label "Password1" :login-page 'login1 :logout-page 'logout1 :regist-page 'regist1)) (is (eq (user-class) 'test-user1)) (is (eq (user-id-slot) 'id)) (is (eq (user-pass-slot) 'pass)) (is (equal (user-id-label) "ID1")) (is (equal (user-pass-label) "Password1")) (drop-instances-by-class 'test-user1) (let ((i (make-instance 'test-user1 :id "id1" :pass "pass1"))) (let ((user-id (user-id i)) (user-pass (user-pass i))) (is (equal user-id "id1")) (is (equal user-pass "pass1")) (is (eq i (get-user user-id))) (is (eq i (get-user user-id user-pass))) (is (eq nil (get-user user-id "pass123"))) (is (eq (get-user-oid user-id) (oid i)))))) (test login (drop-instances-by-class 'test-user2) (defpclass test-user2 (user) ((email :format :email :unique t))) (setf *user* (make-instance 'user* :class 'test-user2)) (let ((i (make-instance 'test-user2 :id "user1" :pass :pass1))) (defpage login-test1 () (login (oid i) (user-id i))) (defpage logout-test1 () (logout)) (defpage login-user-id-test () (p (login-user-id))) (defpage login-user-oid-test () (p (login-user-oid))) (let ((c (make-instance 'cookie-jar))) (http-request (page-uri "login-test1") :cookie-jar c) (is (equal (user-id i) (http-request (page-uri "login-user-id-test") :cookie-jar c))) (is (equal (->string (oid i)) (http-request (page-uri "login-user-oid-test") :cookie-jar c))) (http-request (page-uri "logout") :cookie-jar c) (is (eq nil (http-request (page-uri "login-user-id-test") :cookie-jar c))) (is (eq nil (http-request (page-uri "login-user-oid-test") :cookie-jar c))))))
null
https://raw.githubusercontent.com/tomoyuki28jp/web4r/c0ebe1f8d29994af20bdece8e9ad8b356b136ae9/tests/user.lisp
lisp
(in-package :web4r-tests) (in-suite web4r) (test user* (defpclass test-user1 (user) ((email :format :email :unique t))) (setf *user* (make-instance 'user* :class 'test-user1 :id-label "ID1" :pass-label "Password1" :login-page 'login1 :logout-page 'logout1 :regist-page 'regist1)) (is (eq (user-class) 'test-user1)) (is (eq (user-id-slot) 'id)) (is (eq (user-pass-slot) 'pass)) (is (equal (user-id-label) "ID1")) (is (equal (user-pass-label) "Password1")) (drop-instances-by-class 'test-user1) (let ((i (make-instance 'test-user1 :id "id1" :pass "pass1"))) (let ((user-id (user-id i)) (user-pass (user-pass i))) (is (equal user-id "id1")) (is (equal user-pass "pass1")) (is (eq i (get-user user-id))) (is (eq i (get-user user-id user-pass))) (is (eq nil (get-user user-id "pass123"))) (is (eq (get-user-oid user-id) (oid i)))))) (test login (drop-instances-by-class 'test-user2) (defpclass test-user2 (user) ((email :format :email :unique t))) (setf *user* (make-instance 'user* :class 'test-user2)) (let ((i (make-instance 'test-user2 :id "user1" :pass :pass1))) (defpage login-test1 () (login (oid i) (user-id i))) (defpage logout-test1 () (logout)) (defpage login-user-id-test () (p (login-user-id))) (defpage login-user-oid-test () (p (login-user-oid))) (let ((c (make-instance 'cookie-jar))) (http-request (page-uri "login-test1") :cookie-jar c) (is (equal (user-id i) (http-request (page-uri "login-user-id-test") :cookie-jar c))) (is (equal (->string (oid i)) (http-request (page-uri "login-user-oid-test") :cookie-jar c))) (http-request (page-uri "logout") :cookie-jar c) (is (eq nil (http-request (page-uri "login-user-id-test") :cookie-jar c))) (is (eq nil (http-request (page-uri "login-user-oid-test") :cookie-jar c))))))
3d12e3bce8efea71156edfe4b899faa438a848863b674acf8d901b91ccdd6987
mput/sicp-solutions
1_31.rkt
#lang racket Solution for exercise 1_31 . (provide product product-reqursive) (define (product term a next b) (define (product-iter next-a acc) (if (> next-a b) acc (product-iter (next next-a) (* (term next-a) acc)))) (product-iter a 1)) (define (product-reqursive term a next b) (if (> a b) 1 (* (term a) (product-reqursive term (next a) next b))))
null
https://raw.githubusercontent.com/mput/sicp-solutions/fe12ad2b6f17c99978c8fe04b2495005986b8496/solutions/1_31.rkt
racket
#lang racket Solution for exercise 1_31 . (provide product product-reqursive) (define (product term a next b) (define (product-iter next-a acc) (if (> next-a b) acc (product-iter (next next-a) (* (term next-a) acc)))) (product-iter a 1)) (define (product-reqursive term a next b) (if (> a b) 1 (* (term a) (product-reqursive term (next a) next b))))
56639d8f7d700b1fc867ba0b0a8a357ec9894dfb65f919da46b7b4c0bb75d950
GaloisInc/macaw
Shared.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE RankNTypes #-} module Shared ( withELF , withMemory , findEntryPoint , ElfException(..) ) where import qualified Control.Monad.Catch as C import Data.Binary.Get (ByteOffset) import qualified Data.ByteString as B import qualified Data.ElfEdit as E import Data.List (intercalate) import qualified Data.Macaw.Memory as MM import qualified Data.Macaw.Memory.ElfLoader as MM import Data.Typeable ( Typeable ) | Given an Elf object and the corresponding Memory object , find the -- address of the correct entry point to the program findEntryPoint :: (MM.MemWidth w, Integral (E.ElfWordType w)) => E.Elf w -> MM.Memory w -> MM.MemAddr w findEntryPoint elf mem = let startEntry = E.elfEntry elf absEntry = MM.absoluteAddr $ MM.memWord $ fromIntegral $ startEntry endian = case E.elfData elf of E.ELFDATA2LSB -> MM.LittleEndian E.ELFDATA2MSB -> MM.BigEndian derefEntry = case MM.readAddr mem endian absEntry of Left memErr -> error $ "findEntryPoint: " ++ show memErr Right derefEntry' -> derefEntry' in case E.elfMachine elf of E.EM_PPC -> derefEntry -- PPC entrypoint is a table reference _ -> absEntry | Invokes the continuation with the parsed results of reading the specified file , or generates an error exception of type ElfException . withELF :: FilePath -> (forall w. E.Elf w -> E.ElfHeaderInfo w -> IO ()) -> IO () withELF fp k = do bytes <- B.readFile fp case E.decodeElfHeaderInfo bytes of Left (offset, msg) -> C.throwM $ ElfHeaderParseError fp offset msg Right (E.SomeElf elfHeaderInfo) -> case E.getElf elfHeaderInfo of ([], elf) -> k elf elfHeaderInfo (errs, _) -> C.throwM $ ElfParseError fp $ intercalate "; " $ map show errs | Invokes the callback with a Macaw Memory representation of the -- indicated Elf object. withMemory :: forall w m a . (C.MonadThrow m, MM.MemWidth w, Integral (E.ElfWordType w)) => MM.AddrWidthRepr w -> E.ElfHeaderInfo w -> (MM.Memory w -> m a) -> m a withMemory _ e k = let options = MM.LoadOptions { MM.loadOffset = Just 0 } in case MM.memoryForElf options e of Left err -> C.throwM (MemoryLoadError err) Right (mem, _sym, _warn, _err) -> k mem data ElfException = MemoryLoadError String | ElfParseError FilePath String | ElfHeaderParseError FilePath ByteOffset String deriving (Typeable, Show) instance C.Exception ElfException
null
https://raw.githubusercontent.com/GaloisInc/macaw/9d2e1d4b9f163c8947a284c2031000c54a3a9330/macaw-riscv/tests/Shared.hs
haskell
# LANGUAGE RankNTypes # address of the correct entry point to the program PPC entrypoint is a table reference indicated Elf object.
# LANGUAGE FlexibleContexts # module Shared ( withELF , withMemory , findEntryPoint , ElfException(..) ) where import qualified Control.Monad.Catch as C import Data.Binary.Get (ByteOffset) import qualified Data.ByteString as B import qualified Data.ElfEdit as E import Data.List (intercalate) import qualified Data.Macaw.Memory as MM import qualified Data.Macaw.Memory.ElfLoader as MM import Data.Typeable ( Typeable ) | Given an Elf object and the corresponding Memory object , find the findEntryPoint :: (MM.MemWidth w, Integral (E.ElfWordType w)) => E.Elf w -> MM.Memory w -> MM.MemAddr w findEntryPoint elf mem = let startEntry = E.elfEntry elf absEntry = MM.absoluteAddr $ MM.memWord $ fromIntegral $ startEntry endian = case E.elfData elf of E.ELFDATA2LSB -> MM.LittleEndian E.ELFDATA2MSB -> MM.BigEndian derefEntry = case MM.readAddr mem endian absEntry of Left memErr -> error $ "findEntryPoint: " ++ show memErr Right derefEntry' -> derefEntry' in case E.elfMachine elf of _ -> absEntry | Invokes the continuation with the parsed results of reading the specified file , or generates an error exception of type ElfException . withELF :: FilePath -> (forall w. E.Elf w -> E.ElfHeaderInfo w -> IO ()) -> IO () withELF fp k = do bytes <- B.readFile fp case E.decodeElfHeaderInfo bytes of Left (offset, msg) -> C.throwM $ ElfHeaderParseError fp offset msg Right (E.SomeElf elfHeaderInfo) -> case E.getElf elfHeaderInfo of ([], elf) -> k elf elfHeaderInfo (errs, _) -> C.throwM $ ElfParseError fp $ intercalate "; " $ map show errs | Invokes the callback with a Macaw Memory representation of the withMemory :: forall w m a . (C.MonadThrow m, MM.MemWidth w, Integral (E.ElfWordType w)) => MM.AddrWidthRepr w -> E.ElfHeaderInfo w -> (MM.Memory w -> m a) -> m a withMemory _ e k = let options = MM.LoadOptions { MM.loadOffset = Just 0 } in case MM.memoryForElf options e of Left err -> C.throwM (MemoryLoadError err) Right (mem, _sym, _warn, _err) -> k mem data ElfException = MemoryLoadError String | ElfParseError FilePath String | ElfHeaderParseError FilePath ByteOffset String deriving (Typeable, Show) instance C.Exception ElfException
4825d029f2d430cbe8e3bbe5b494dd63066dfa7ebf1d95b76013622cd3a022a9
ocaml/odoc
odoc_loader.ml
open Result module Error = Odoc_model.Error let read_string parent_definition filename text = let location = let pos = Lexing.{ pos_fname = filename; pos_lnum = 1; pos_cnum = 0; pos_bol = 0 } in Location.{ loc_start = pos; loc_end = pos; loc_ghost = true } in Error.catch_errors_and_warnings (fun () -> Doc_attr.page parent_definition location text) let corrupted file = Error.raise_exception (Error.filename_only "corrupted" file) let not_a_typedtree file = Error.raise_exception (Error.filename_only "not a Typedtree" file) let not_an_implementation file = Error.raise_exception (Error.filename_only "not an implementation" file) let not_an_interface file = Error.raise_exception (Error.filename_only "not an interface" file) let wrong_version file = Error.raise_exception (Error.filename_only "wrong OCaml version" file) let error_msg file (msg : string) = Error.raise_exception (Error.filename_only "%s" msg file) exception Corrupted exception Not_an_implementation exception Not_an_interface exception Make_root_error of string let make_compilation_unit ~make_root ~imports ~interface ?sourcefile ~name ~id ?canonical content = let open Odoc_model.Lang.Compilation_unit in let interface, digest = match interface with | Some digest -> (true, digest) | None -> ( match List.assoc name imports with | Some digest -> (false, digest) | None -> raise Corrupted | exception Not_found -> raise Corrupted) in let root = match make_root ~module_name:name ~digest with | Ok root -> root | Error (`Msg m) -> raise (Make_root_error m) in let imports = List.filter (fun (name', _) -> name <> name') imports in let imports = List.map (fun (s, d) -> Import.Unresolved (s, d)) imports in let source = match sourcefile with | Some (Some file, Some digest, build_dir) -> Some { Source.file; digest; build_dir } | _ -> None in { id; root; digest; imports; source; interface; hidden = Odoc_model.Root.contains_double_underscore name; content; expansion = None; linked = false; canonical; } let compilation_unit_of_sig ~make_root ~imports ~interface ?sourcefile ~name ~id ?canonical sg = let content = Odoc_model.Lang.Compilation_unit.Module sg in make_compilation_unit ~make_root ~imports ~interface ?sourcefile ~name ~id ?canonical content let read_cmti ~make_root ~parent ~filename () = let cmt_info = Cmt_format.read_cmt filename in match cmt_info.cmt_annots with | Interface intf -> ( match cmt_info.cmt_interface_digest with | None -> raise Corrupted | Some _ as interface -> let name = cmt_info.cmt_modname in let sourcefile = ( cmt_info.cmt_sourcefile, cmt_info.cmt_source_digest, cmt_info.cmt_builddir ) in let id, sg, canonical = Cmti.read_interface parent name intf in compilation_unit_of_sig ~make_root ~imports:cmt_info.cmt_imports ~interface ~sourcefile ~name ~id ?canonical sg) | _ -> raise Not_an_interface let read_cmt ~make_root ~parent ~filename () = match Cmt_format.read_cmt filename with | exception Cmi_format.Error (Not_an_interface _) -> raise Not_an_implementation | cmt_info -> ( let name = cmt_info.cmt_modname in let sourcefile = ( cmt_info.cmt_sourcefile, cmt_info.cmt_source_digest, cmt_info.cmt_builddir ) in let interface = cmt_info.cmt_interface_digest in let imports = cmt_info.cmt_imports in match cmt_info.cmt_annots with | Packed (_, files) -> let id = Odoc_model.Paths.Identifier.Mk.root (parent, Odoc_model.Names.ModuleName.make_std name) in let items = List.map (fun file -> let pref = Misc.chop_extensions file in Astring.String.Ascii.capitalize (Filename.basename pref)) files in let items = List.sort String.compare items in let items = List.map (fun name -> let id = Odoc_model.Paths.Identifier.Mk.module_ (id, Odoc_model.Names.ModuleName.make_std name) in let path = `Root name in { Odoc_model.Lang.Compilation_unit.Packed.id; path }) items in let content = Odoc_model.Lang.Compilation_unit.Pack items in make_compilation_unit ~make_root ~imports ~interface ~sourcefile ~name ~id content | Implementation impl -> let id, sg, canonical = Cmt.read_implementation parent name impl in compilation_unit_of_sig ~make_root ~imports ~interface ~sourcefile ~name ~id ?canonical sg | _ -> raise Not_an_implementation) let read_cmi ~make_root ~parent ~filename () = let cmi_info = Cmi_format.read_cmi filename in match cmi_info.cmi_crcs with | (name, (Some _ as interface)) :: imports when name = cmi_info.cmi_name -> let id, sg = Cmi.read_interface parent name (Odoc_model.Compat.signature cmi_info.cmi_sign) in compilation_unit_of_sig ~make_root ~imports ~interface ~name ~id sg | _ -> raise Corrupted (** Catch errors from reading the object files and some internal errors *) let wrap_errors ~filename f = Odoc_model.Error.catch_errors_and_warnings (fun () -> try f () with | Cmi_format.Error (Not_an_interface _) -> not_an_interface filename | Cmt_format.Error (Not_a_typedtree _) -> not_a_typedtree filename | Cmi_format.Error (Wrong_version_interface _) -> wrong_version filename | Cmi_format.Error (Corrupted_interface _) -> corrupted filename | Corrupted -> corrupted filename | Not_an_implementation -> not_an_implementation filename | Not_an_interface -> not_an_interface filename | Make_root_error m -> error_msg filename m) let read_cmti ~make_root ~parent ~filename = wrap_errors ~filename (read_cmti ~make_root ~parent ~filename) let read_cmt ~make_root ~parent ~filename = wrap_errors ~filename (read_cmt ~make_root ~parent ~filename) let read_cmi ~make_root ~parent ~filename = wrap_errors ~filename (read_cmi ~make_root ~parent ~filename)
null
https://raw.githubusercontent.com/ocaml/odoc/704ce161a32b6830c824ec4b9cc87b113b9228bd/src/loader/odoc_loader.ml
ocaml
* Catch errors from reading the object files and some internal errors
open Result module Error = Odoc_model.Error let read_string parent_definition filename text = let location = let pos = Lexing.{ pos_fname = filename; pos_lnum = 1; pos_cnum = 0; pos_bol = 0 } in Location.{ loc_start = pos; loc_end = pos; loc_ghost = true } in Error.catch_errors_and_warnings (fun () -> Doc_attr.page parent_definition location text) let corrupted file = Error.raise_exception (Error.filename_only "corrupted" file) let not_a_typedtree file = Error.raise_exception (Error.filename_only "not a Typedtree" file) let not_an_implementation file = Error.raise_exception (Error.filename_only "not an implementation" file) let not_an_interface file = Error.raise_exception (Error.filename_only "not an interface" file) let wrong_version file = Error.raise_exception (Error.filename_only "wrong OCaml version" file) let error_msg file (msg : string) = Error.raise_exception (Error.filename_only "%s" msg file) exception Corrupted exception Not_an_implementation exception Not_an_interface exception Make_root_error of string let make_compilation_unit ~make_root ~imports ~interface ?sourcefile ~name ~id ?canonical content = let open Odoc_model.Lang.Compilation_unit in let interface, digest = match interface with | Some digest -> (true, digest) | None -> ( match List.assoc name imports with | Some digest -> (false, digest) | None -> raise Corrupted | exception Not_found -> raise Corrupted) in let root = match make_root ~module_name:name ~digest with | Ok root -> root | Error (`Msg m) -> raise (Make_root_error m) in let imports = List.filter (fun (name', _) -> name <> name') imports in let imports = List.map (fun (s, d) -> Import.Unresolved (s, d)) imports in let source = match sourcefile with | Some (Some file, Some digest, build_dir) -> Some { Source.file; digest; build_dir } | _ -> None in { id; root; digest; imports; source; interface; hidden = Odoc_model.Root.contains_double_underscore name; content; expansion = None; linked = false; canonical; } let compilation_unit_of_sig ~make_root ~imports ~interface ?sourcefile ~name ~id ?canonical sg = let content = Odoc_model.Lang.Compilation_unit.Module sg in make_compilation_unit ~make_root ~imports ~interface ?sourcefile ~name ~id ?canonical content let read_cmti ~make_root ~parent ~filename () = let cmt_info = Cmt_format.read_cmt filename in match cmt_info.cmt_annots with | Interface intf -> ( match cmt_info.cmt_interface_digest with | None -> raise Corrupted | Some _ as interface -> let name = cmt_info.cmt_modname in let sourcefile = ( cmt_info.cmt_sourcefile, cmt_info.cmt_source_digest, cmt_info.cmt_builddir ) in let id, sg, canonical = Cmti.read_interface parent name intf in compilation_unit_of_sig ~make_root ~imports:cmt_info.cmt_imports ~interface ~sourcefile ~name ~id ?canonical sg) | _ -> raise Not_an_interface let read_cmt ~make_root ~parent ~filename () = match Cmt_format.read_cmt filename with | exception Cmi_format.Error (Not_an_interface _) -> raise Not_an_implementation | cmt_info -> ( let name = cmt_info.cmt_modname in let sourcefile = ( cmt_info.cmt_sourcefile, cmt_info.cmt_source_digest, cmt_info.cmt_builddir ) in let interface = cmt_info.cmt_interface_digest in let imports = cmt_info.cmt_imports in match cmt_info.cmt_annots with | Packed (_, files) -> let id = Odoc_model.Paths.Identifier.Mk.root (parent, Odoc_model.Names.ModuleName.make_std name) in let items = List.map (fun file -> let pref = Misc.chop_extensions file in Astring.String.Ascii.capitalize (Filename.basename pref)) files in let items = List.sort String.compare items in let items = List.map (fun name -> let id = Odoc_model.Paths.Identifier.Mk.module_ (id, Odoc_model.Names.ModuleName.make_std name) in let path = `Root name in { Odoc_model.Lang.Compilation_unit.Packed.id; path }) items in let content = Odoc_model.Lang.Compilation_unit.Pack items in make_compilation_unit ~make_root ~imports ~interface ~sourcefile ~name ~id content | Implementation impl -> let id, sg, canonical = Cmt.read_implementation parent name impl in compilation_unit_of_sig ~make_root ~imports ~interface ~sourcefile ~name ~id ?canonical sg | _ -> raise Not_an_implementation) let read_cmi ~make_root ~parent ~filename () = let cmi_info = Cmi_format.read_cmi filename in match cmi_info.cmi_crcs with | (name, (Some _ as interface)) :: imports when name = cmi_info.cmi_name -> let id, sg = Cmi.read_interface parent name (Odoc_model.Compat.signature cmi_info.cmi_sign) in compilation_unit_of_sig ~make_root ~imports ~interface ~name ~id sg | _ -> raise Corrupted let wrap_errors ~filename f = Odoc_model.Error.catch_errors_and_warnings (fun () -> try f () with | Cmi_format.Error (Not_an_interface _) -> not_an_interface filename | Cmt_format.Error (Not_a_typedtree _) -> not_a_typedtree filename | Cmi_format.Error (Wrong_version_interface _) -> wrong_version filename | Cmi_format.Error (Corrupted_interface _) -> corrupted filename | Corrupted -> corrupted filename | Not_an_implementation -> not_an_implementation filename | Not_an_interface -> not_an_interface filename | Make_root_error m -> error_msg filename m) let read_cmti ~make_root ~parent ~filename = wrap_errors ~filename (read_cmti ~make_root ~parent ~filename) let read_cmt ~make_root ~parent ~filename = wrap_errors ~filename (read_cmt ~make_root ~parent ~filename) let read_cmi ~make_root ~parent ~filename = wrap_errors ~filename (read_cmi ~make_root ~parent ~filename)
ec6617932c01fecf4059e7cb453182b875f7bd59f4003d083d072a092805de82
ekmett/succinct
huTuckerBench.hs
module Main (main) where import Criterion.Main import Data.Bits import qualified Data.Vector.Primitive as P import Data.Word import Succinct.Sequence import System.Random sampleVec :: Int -> [((Int, String), Int)] sampleVec elements = zip [(i, "v" ++ show i) | i <- [0..]] $ take elements $ randomRs (1, 10000) (mkStdGen 42) benchSized :: String -> Int -> Benchmark benchSized tag bytes = v `seq` bgroup tag [ bench "Hu-Tucker" $ whnf (show . huTucker) v ] where v = sampleVec bytes benchmarks :: [Benchmark] benchmarks = [ benchSized ("2^" ++ show i) (2^i) | i <- [4,8,12,16,20::Int]] main :: IO () main = defaultMain benchmarks
null
https://raw.githubusercontent.com/ekmett/succinct/7e884138c2e943f5ca08f56b58b409d08b870ab9/benchmarks/huTuckerBench.hs
haskell
module Main (main) where import Criterion.Main import Data.Bits import qualified Data.Vector.Primitive as P import Data.Word import Succinct.Sequence import System.Random sampleVec :: Int -> [((Int, String), Int)] sampleVec elements = zip [(i, "v" ++ show i) | i <- [0..]] $ take elements $ randomRs (1, 10000) (mkStdGen 42) benchSized :: String -> Int -> Benchmark benchSized tag bytes = v `seq` bgroup tag [ bench "Hu-Tucker" $ whnf (show . huTucker) v ] where v = sampleVec bytes benchmarks :: [Benchmark] benchmarks = [ benchSized ("2^" ++ show i) (2^i) | i <- [4,8,12,16,20::Int]] main :: IO () main = defaultMain benchmarks
51c9e00834dd8dc04fbf88c5e65b0b6cd0ee16a19c8be39449d522f72e0787a3
basho/riak_kv
riak_kv_index_fsm.erl
%% ------------------------------------------------------------------- %% %% riak_index_fsm: Manage secondary index queries. %% Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -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. %% %% ------------------------------------------------------------------- @doc The index fsm manages the execution of secondary index queries . %% The index fsm creates a plan to achieve coverage %% of the cluster using the minimum %% possible number of VNodes, sends index query %% commands to each of those VNodes, and compiles the %% responses. %% %% The number of VNodes required for full %% coverage is based on the number %% of partitions, the number of available physical %% nodes, and the bucket n_val. -module(riak_kv_index_fsm). -behaviour(riak_core_coverage_fsm). -include_lib("riak_kv_vnode.hrl"). -define(SLOW_TIME, application:get_env(riak_kv, index_fsm_slow_timems, 200)). -define(FAST_TIME, application:get_env(riak_kv, index_fsm_fast_timems, 10)). -export([init/2, plan/2, process_results/3, process_results/2, finish/2]). -export([use_ack_backpressure/0, req/3]). -type from() :: {atom(), req_id(), pid()}. -type req_id() :: non_neg_integer(). -ifdef(namespaced_types). -type riak_kv_index_fsm_dict() :: dict:dict(). -else. -type riak_kv_index_fsm_dict() :: dict(). -endif. -record(timings, {start_time = os:timestamp() :: os:timestamp(), max = 0 :: non_neg_integer(), min = infinity :: non_neg_integer()|infinity, count = 0 :: non_neg_integer(), sum = 0 :: non_neg_integer(), slow_count = 0 :: non_neg_integer(), fast_count = 0 :: non_neg_integer(), slow_time = ?SLOW_TIME, fast_time = ?FAST_TIME}). -type timings() :: #timings{}. -record(state, {from :: from(), pagination_sort :: boolean(), merge_sort_buffer = undefined :: sms:sms() | undefined, max_results :: all | pos_integer(), results_per_vnode = dict:new() :: riak_kv_index_fsm_dict(), timings = #timings{} :: timings(), bucket :: riak_object:buckey() | undefined, results_sent = 0 :: non_neg_integer()}). %% @doc Returns `true' if the new ack-based backpressure index %% protocol should be used. This decision is based on the %% `index_backpressure' setting in `riak_kv''s application %% environment. -spec use_ack_backpressure() -> boolean(). use_ack_backpressure() -> riak_core_capability:get({riak_kv, index_backpressure}, false) == true. @doc Construct the correct index command record . -spec req(binary(), term(), term()) -> term(). req(Bucket, ItemFilter, Query) -> riak_kv_requests:new_index_request(Bucket, ItemFilter, Query, use_ack_backpressure()). @doc Return a tuple containing the ModFun to call per vnode , %% the number of primary preflist vnodes the operation %% should cover, the service to use to check for available nodes, %% and the registered name to use to access the vnode master process. init(From={_, _, _}, [Bucket, ItemFilter, Query, Timeout]) -> %% #id77404 %% atom() > number() init(From, [Bucket, ItemFilter, Query, Timeout, all]); init(From={_, _, _}, [Bucket, ItemFilter, Query, Timeout, MaxResults]) -> init(From, [Bucket, ItemFilter, Query, Timeout, MaxResults, undefined]); init(From={_, _, _}, [Bucket, ItemFilter, Query, Timeout, MaxResults0, PgSort0]) -> %% Get the bucket n_val for use in creating a coverage plan BucketProps = riak_core_bucket:get_bucket(Bucket), NVal = proplists:get_value(n_val, BucketProps), MaxResults = case is_integer(MaxResults0) of true -> MaxResults0; false -> all end, % Force MaxResults to only be the expected all/integer() - and not % undefined Paginating = is_integer(MaxResults) andalso MaxResults > 0, PgSort = case {Paginating, PgSort0} of {true, _} -> true; {_, undefined} -> app_helper:get_env(riak_kv, secondary_index_sort_default, false); _ -> PgSort0 end, Construct the key listing request Req = req(Bucket, ItemFilter, Query), {Req, all, NVal, 1, riak_kv, riak_kv_vnode_master, Timeout, #state{from=From, max_results=MaxResults, pagination_sort=PgSort, bucket=Bucket}}. plan(CoverageVNodes, State = #state{pagination_sort=true}) -> {ok, State#state{merge_sort_buffer=sms:new(CoverageVNodes)}}; plan(_CoverageVNodes, State) -> {ok, State}. process_results(_VNode, {error, Reason}, _State) -> {error, Reason}; process_results(_VNode, {From, _Bucket, _Results}, State=#state{max_results=X, results_sent=Y}) when Y >= X -> riak_kv_vnode:stop_fold(From), {done, State}; process_results(VNode, {From, Bucket, Results}, State) -> case process_results(VNode, {Bucket, Results}, State) of {ok, State2 = #state{pagination_sort=true}} -> #state{results_per_vnode=PerNode, max_results=MaxResults} = State2, case {dict:fetch(VNode, PerNode), MaxResults} of {VnodeCount, MR} when is_integer(MR), VnodeCount >= MR -> riak_kv_vnode:stop_fold(From), {done, State2}; _ -> _ = riak_kv_vnode:ack_keys(From), {ok, State2} end; {ok, State2} -> _ = riak_kv_vnode:ack_keys(From), {ok, State2}; {done, State2} -> riak_kv_vnode:stop_fold(From), {done, State2} end; process_results(VNode, {_Bucket, Results}, State = #state{pagination_sort=true}) -> #state{merge_sort_buffer=MergeSortBuffer, results_per_vnode=PerNode, from={raw, ReqId, ClientPid}, results_sent=ResultsSent, max_results=MaxResults} = State, %% add new results to buffer {ToSend, NewBuff} = update_buffer(VNode, Results, MergeSortBuffer), NumResults = length(Results), NewPerNode = dict:update(VNode, fun(C) -> C + NumResults end, NumResults, PerNode), LenToSend = length(ToSend), {Response, ResultsLen, ResultsToSend} = get_results_to_send(LenToSend, ToSend, ResultsSent, MaxResults), send_results(ClientPid, ReqId, ResultsToSend), {Response, State#state{merge_sort_buffer=NewBuff, results_per_vnode=NewPerNode, results_sent=ResultsSent+ResultsLen}}; process_results(VNode, done, State = #state{pagination_sort=true}) -> %% tell the sms buffer about the done vnode #state{merge_sort_buffer=MergeSortBuffer} = State, BufferWithNewResults = sms:add_results(VNode, done, MergeSortBuffer), UpdTimings = update_timings(State#state.timings), {done, State#state{merge_sort_buffer=BufferWithNewResults, timings=UpdTimings}}; process_results(_VNode, {_Bucket, Results}, State) -> #state{from={raw, ReqId, ClientPid}} = State, send_results(ClientPid, ReqId, Results), ResultsSent = length(Results) + State#state.results_sent, UpdTimings = update_timings(State#state.timings), {ok, State#state{timings = UpdTimings, results_sent = ResultsSent}}; process_results(_VNode, done, State) -> {done, State}. %% @private Update the buffer with results and process it update_buffer(VNode, Results, Buffer) -> BufferWithNewResults = sms:add_results(VNode, lists:reverse(Results), Buffer), sms:sms(BufferWithNewResults). @private Get the subset of ` ToSend ' that we can send without violating ` MaxResults ' get_results_to_send(LenToSend, ToSend, ResultsSent, MaxResults) when (ResultsSent + LenToSend) >= MaxResults -> ResultsLen = MaxResults - ResultsSent, ResultsToSend = lists:sublist(ToSend, ResultsLen), {done, ResultsLen, ResultsToSend}; get_results_to_send(LenToSend, ToSend, _, _) -> {ok, LenToSend, ToSend}. @private send results , but only if there are some send_results(_ClientPid, _ReqId, []) -> ok; send_results(ClientPid, ReqId, ResultsToSend) -> ClientPid ! {ReqId, {results, ResultsToSend}}. Legacy , unsorted 2i , should remove ? process_results({error, Reason}, _State) -> {error, Reason}; process_results({From, Bucket, Results}, StateData=#state{from={raw, ReqId, ClientPid}}) -> process_query_results(Bucket, Results, ReqId, ClientPid), _ = riak_kv_vnode:ack_keys(From), % tell that vnode we're ready for more {ok, StateData}; process_results({Bucket, Results}, StateData=#state{from={raw, ReqId, ClientPid}}) -> process_query_results(Bucket, Results, ReqId, ClientPid), {ok, StateData}; process_results(done, StateData) -> {done, StateData}. finish({error, Error}, State=#state{from={raw, ReqId, ClientPid}}) -> %% Notify the requesting client that an error %% occurred or the timeout has elapsed. ClientPid ! {ReqId, {error, Error}}, {stop, normal, State}; finish(clean, State=#state{from={raw, ReqId, ClientPid}, merge_sort_buffer=undefined}) -> ClientPid ! {ReqId, done}, log_timings(State#state.timings, State#state.bucket, State#state.results_sent), {stop, normal, State}; finish(clean, State=#state{from={raw, ReqId, ClientPid}, merge_sort_buffer=MergeSortBuffer, results_sent=ResultsSent, max_results=MaxResults}) -> LastResults = sms:done(MergeSortBuffer), DownTheWire = case MaxResults of all -> LastResults; _ -> lists:sublist(LastResults, MaxResults - ResultsSent) end, ClientPid ! {ReqId, {results, DownTheWire}}, ClientPid ! {ReqId, done}, log_timings(State#state.timings, State#state.bucket, ResultsSent + length(DownTheWire)), {stop, normal, State}. %% =================================================================== Internal functions %% =================================================================== process_query_results(_Bucket, Results, ReqId, ClientPid) -> ClientPid ! {ReqId, {results, Results}}. -spec update_timings(timings()) -> timings(). update_timings(Timings) -> MS = timer:now_diff(os:timestamp(), Timings#timings.start_time) div 1000, SlowCount = case MS > Timings#timings.slow_time of true -> Timings#timings.slow_count + 1; false -> Timings#timings.slow_count end, FastCount = case MS < Timings#timings.fast_time of true -> Timings#timings.fast_count + 1; false -> Timings#timings.fast_count end, Timings#timings{ max = max(Timings#timings.max, MS), min = min(Timings#timings.min, MS), count = Timings#timings.count + 1, sum = Timings#timings.sum + MS, slow_count = SlowCount, fast_count = FastCount }. -spec log_timings(timings(), riak_object:bucket(), non_neg_integer()) -> ok. log_timings(Timings, Bucket, ResultCount) -> Duration = timer:now_diff(os:timestamp(), Timings#timings.start_time), ok = riak_kv_stat:update({index_fsm_time, Duration, ResultCount}), log_timings(Timings, Bucket, ResultCount, application:get_env(riak_kv, log_index_fsm, false)). log_timings(_Timings, _Bucket, _ResultCount, false) -> ok; log_timings(Timings, Bucket, ResultCount, true) -> lager:info("Index query on bucket=~p " ++ "max_vnodeq=~w min_vnodeq=~w sum_vnodeq=~w count_vnodeq=~w " ++ "slow_count_vnodeq=~w fast_count_vnodeq=~w result_count=~w", [Bucket, Timings#timings.max, Timings#timings.min, Timings#timings.sum, Timings#timings.count, Timings#timings.slow_count, Timings#timings.fast_count, ResultCount]).
null
https://raw.githubusercontent.com/basho/riak_kv/44849c1bee170804d68df7ad9d244dc89236db7b/src/riak_kv_index_fsm.erl
erlang
------------------------------------------------------------------- riak_index_fsm: Manage secondary index queries. Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- of the cluster using the minimum possible number of VNodes, sends index query commands to each of those VNodes, and compiles the responses. The number of VNodes required for full coverage is based on the number of partitions, the number of available physical nodes, and the bucket n_val. @doc Returns `true' if the new ack-based backpressure index protocol should be used. This decision is based on the `index_backpressure' setting in `riak_kv''s application environment. the number of primary preflist vnodes the operation should cover, the service to use to check for available nodes, and the registered name to use to access the vnode master process. #id77404 atom() > number() Get the bucket n_val for use in creating a coverage plan Force MaxResults to only be the expected all/integer() - and not undefined add new results to buffer tell the sms buffer about the done vnode @private Update the buffer with results and process it tell that vnode we're ready for more Notify the requesting client that an error occurred or the timeout has elapsed. =================================================================== ===================================================================
Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY @doc The index fsm manages the execution of secondary index queries . The index fsm creates a plan to achieve coverage -module(riak_kv_index_fsm). -behaviour(riak_core_coverage_fsm). -include_lib("riak_kv_vnode.hrl"). -define(SLOW_TIME, application:get_env(riak_kv, index_fsm_slow_timems, 200)). -define(FAST_TIME, application:get_env(riak_kv, index_fsm_fast_timems, 10)). -export([init/2, plan/2, process_results/3, process_results/2, finish/2]). -export([use_ack_backpressure/0, req/3]). -type from() :: {atom(), req_id(), pid()}. -type req_id() :: non_neg_integer(). -ifdef(namespaced_types). -type riak_kv_index_fsm_dict() :: dict:dict(). -else. -type riak_kv_index_fsm_dict() :: dict(). -endif. -record(timings, {start_time = os:timestamp() :: os:timestamp(), max = 0 :: non_neg_integer(), min = infinity :: non_neg_integer()|infinity, count = 0 :: non_neg_integer(), sum = 0 :: non_neg_integer(), slow_count = 0 :: non_neg_integer(), fast_count = 0 :: non_neg_integer(), slow_time = ?SLOW_TIME, fast_time = ?FAST_TIME}). -type timings() :: #timings{}. -record(state, {from :: from(), pagination_sort :: boolean(), merge_sort_buffer = undefined :: sms:sms() | undefined, max_results :: all | pos_integer(), results_per_vnode = dict:new() :: riak_kv_index_fsm_dict(), timings = #timings{} :: timings(), bucket :: riak_object:buckey() | undefined, results_sent = 0 :: non_neg_integer()}). -spec use_ack_backpressure() -> boolean(). use_ack_backpressure() -> riak_core_capability:get({riak_kv, index_backpressure}, false) == true. @doc Construct the correct index command record . -spec req(binary(), term(), term()) -> term(). req(Bucket, ItemFilter, Query) -> riak_kv_requests:new_index_request(Bucket, ItemFilter, Query, use_ack_backpressure()). @doc Return a tuple containing the ModFun to call per vnode , init(From={_, _, _}, [Bucket, ItemFilter, Query, Timeout]) -> init(From, [Bucket, ItemFilter, Query, Timeout, all]); init(From={_, _, _}, [Bucket, ItemFilter, Query, Timeout, MaxResults]) -> init(From, [Bucket, ItemFilter, Query, Timeout, MaxResults, undefined]); init(From={_, _, _}, [Bucket, ItemFilter, Query, Timeout, MaxResults0, PgSort0]) -> BucketProps = riak_core_bucket:get_bucket(Bucket), NVal = proplists:get_value(n_val, BucketProps), MaxResults = case is_integer(MaxResults0) of true -> MaxResults0; false -> all end, Paginating = is_integer(MaxResults) andalso MaxResults > 0, PgSort = case {Paginating, PgSort0} of {true, _} -> true; {_, undefined} -> app_helper:get_env(riak_kv, secondary_index_sort_default, false); _ -> PgSort0 end, Construct the key listing request Req = req(Bucket, ItemFilter, Query), {Req, all, NVal, 1, riak_kv, riak_kv_vnode_master, Timeout, #state{from=From, max_results=MaxResults, pagination_sort=PgSort, bucket=Bucket}}. plan(CoverageVNodes, State = #state{pagination_sort=true}) -> {ok, State#state{merge_sort_buffer=sms:new(CoverageVNodes)}}; plan(_CoverageVNodes, State) -> {ok, State}. process_results(_VNode, {error, Reason}, _State) -> {error, Reason}; process_results(_VNode, {From, _Bucket, _Results}, State=#state{max_results=X, results_sent=Y}) when Y >= X -> riak_kv_vnode:stop_fold(From), {done, State}; process_results(VNode, {From, Bucket, Results}, State) -> case process_results(VNode, {Bucket, Results}, State) of {ok, State2 = #state{pagination_sort=true}} -> #state{results_per_vnode=PerNode, max_results=MaxResults} = State2, case {dict:fetch(VNode, PerNode), MaxResults} of {VnodeCount, MR} when is_integer(MR), VnodeCount >= MR -> riak_kv_vnode:stop_fold(From), {done, State2}; _ -> _ = riak_kv_vnode:ack_keys(From), {ok, State2} end; {ok, State2} -> _ = riak_kv_vnode:ack_keys(From), {ok, State2}; {done, State2} -> riak_kv_vnode:stop_fold(From), {done, State2} end; process_results(VNode, {_Bucket, Results}, State = #state{pagination_sort=true}) -> #state{merge_sort_buffer=MergeSortBuffer, results_per_vnode=PerNode, from={raw, ReqId, ClientPid}, results_sent=ResultsSent, max_results=MaxResults} = State, {ToSend, NewBuff} = update_buffer(VNode, Results, MergeSortBuffer), NumResults = length(Results), NewPerNode = dict:update(VNode, fun(C) -> C + NumResults end, NumResults, PerNode), LenToSend = length(ToSend), {Response, ResultsLen, ResultsToSend} = get_results_to_send(LenToSend, ToSend, ResultsSent, MaxResults), send_results(ClientPid, ReqId, ResultsToSend), {Response, State#state{merge_sort_buffer=NewBuff, results_per_vnode=NewPerNode, results_sent=ResultsSent+ResultsLen}}; process_results(VNode, done, State = #state{pagination_sort=true}) -> #state{merge_sort_buffer=MergeSortBuffer} = State, BufferWithNewResults = sms:add_results(VNode, done, MergeSortBuffer), UpdTimings = update_timings(State#state.timings), {done, State#state{merge_sort_buffer=BufferWithNewResults, timings=UpdTimings}}; process_results(_VNode, {_Bucket, Results}, State) -> #state{from={raw, ReqId, ClientPid}} = State, send_results(ClientPid, ReqId, Results), ResultsSent = length(Results) + State#state.results_sent, UpdTimings = update_timings(State#state.timings), {ok, State#state{timings = UpdTimings, results_sent = ResultsSent}}; process_results(_VNode, done, State) -> {done, State}. update_buffer(VNode, Results, Buffer) -> BufferWithNewResults = sms:add_results(VNode, lists:reverse(Results), Buffer), sms:sms(BufferWithNewResults). @private Get the subset of ` ToSend ' that we can send without violating ` MaxResults ' get_results_to_send(LenToSend, ToSend, ResultsSent, MaxResults) when (ResultsSent + LenToSend) >= MaxResults -> ResultsLen = MaxResults - ResultsSent, ResultsToSend = lists:sublist(ToSend, ResultsLen), {done, ResultsLen, ResultsToSend}; get_results_to_send(LenToSend, ToSend, _, _) -> {ok, LenToSend, ToSend}. @private send results , but only if there are some send_results(_ClientPid, _ReqId, []) -> ok; send_results(ClientPid, ReqId, ResultsToSend) -> ClientPid ! {ReqId, {results, ResultsToSend}}. Legacy , unsorted 2i , should remove ? process_results({error, Reason}, _State) -> {error, Reason}; process_results({From, Bucket, Results}, StateData=#state{from={raw, ReqId, ClientPid}}) -> process_query_results(Bucket, Results, ReqId, ClientPid), {ok, StateData}; process_results({Bucket, Results}, StateData=#state{from={raw, ReqId, ClientPid}}) -> process_query_results(Bucket, Results, ReqId, ClientPid), {ok, StateData}; process_results(done, StateData) -> {done, StateData}. finish({error, Error}, State=#state{from={raw, ReqId, ClientPid}}) -> ClientPid ! {ReqId, {error, Error}}, {stop, normal, State}; finish(clean, State=#state{from={raw, ReqId, ClientPid}, merge_sort_buffer=undefined}) -> ClientPid ! {ReqId, done}, log_timings(State#state.timings, State#state.bucket, State#state.results_sent), {stop, normal, State}; finish(clean, State=#state{from={raw, ReqId, ClientPid}, merge_sort_buffer=MergeSortBuffer, results_sent=ResultsSent, max_results=MaxResults}) -> LastResults = sms:done(MergeSortBuffer), DownTheWire = case MaxResults of all -> LastResults; _ -> lists:sublist(LastResults, MaxResults - ResultsSent) end, ClientPid ! {ReqId, {results, DownTheWire}}, ClientPid ! {ReqId, done}, log_timings(State#state.timings, State#state.bucket, ResultsSent + length(DownTheWire)), {stop, normal, State}. Internal functions process_query_results(_Bucket, Results, ReqId, ClientPid) -> ClientPid ! {ReqId, {results, Results}}. -spec update_timings(timings()) -> timings(). update_timings(Timings) -> MS = timer:now_diff(os:timestamp(), Timings#timings.start_time) div 1000, SlowCount = case MS > Timings#timings.slow_time of true -> Timings#timings.slow_count + 1; false -> Timings#timings.slow_count end, FastCount = case MS < Timings#timings.fast_time of true -> Timings#timings.fast_count + 1; false -> Timings#timings.fast_count end, Timings#timings{ max = max(Timings#timings.max, MS), min = min(Timings#timings.min, MS), count = Timings#timings.count + 1, sum = Timings#timings.sum + MS, slow_count = SlowCount, fast_count = FastCount }. -spec log_timings(timings(), riak_object:bucket(), non_neg_integer()) -> ok. log_timings(Timings, Bucket, ResultCount) -> Duration = timer:now_diff(os:timestamp(), Timings#timings.start_time), ok = riak_kv_stat:update({index_fsm_time, Duration, ResultCount}), log_timings(Timings, Bucket, ResultCount, application:get_env(riak_kv, log_index_fsm, false)). log_timings(_Timings, _Bucket, _ResultCount, false) -> ok; log_timings(Timings, Bucket, ResultCount, true) -> lager:info("Index query on bucket=~p " ++ "max_vnodeq=~w min_vnodeq=~w sum_vnodeq=~w count_vnodeq=~w " ++ "slow_count_vnodeq=~w fast_count_vnodeq=~w result_count=~w", [Bucket, Timings#timings.max, Timings#timings.min, Timings#timings.sum, Timings#timings.count, Timings#timings.slow_count, Timings#timings.fast_count, ResultCount]).
dce75c3a9de8cf264c26b34e019179d36f3ee370ad044ee59dfb90d830ef8773
hasktorch/hasktorch
NN.hs
module Torch.GraduallyTyped.NN ( module Torch.GraduallyTyped.NN.Class, module Torch.GraduallyTyped.NN.Initialization, module Torch.GraduallyTyped.NN.Linear, module Torch.GraduallyTyped.NN.Transformer, module Torch.GraduallyTyped.NN.Dropout, module Torch.GraduallyTyped.NN.Activation, module Torch.GraduallyTyped.NN.Functional, module Torch.GraduallyTyped.NN.Normalization, module Torch.GraduallyTyped.NN.Sparse, module Torch.GraduallyTyped.NN.Type, module Torch.GraduallyTyped.NN.Training, module Torch.GraduallyTyped.NN.Loss, ) where import Torch.GraduallyTyped.NN.Activation import Torch.GraduallyTyped.NN.Class import Torch.GraduallyTyped.NN.Dropout import Torch.GraduallyTyped.NN.Functional import Torch.GraduallyTyped.NN.Initialization import Torch.GraduallyTyped.NN.Linear import Torch.GraduallyTyped.NN.Loss import Torch.GraduallyTyped.NN.Normalization import Torch.GraduallyTyped.NN.Sparse import Torch.GraduallyTyped.NN.Training import Torch.GraduallyTyped.NN.Transformer import Torch.GraduallyTyped.NN.Type
null
https://raw.githubusercontent.com/hasktorch/hasktorch/c34996b0a401a5b1b98b5774e892fde88adaa079/experimental/gradually-typed/src/Torch/GraduallyTyped/NN.hs
haskell
module Torch.GraduallyTyped.NN ( module Torch.GraduallyTyped.NN.Class, module Torch.GraduallyTyped.NN.Initialization, module Torch.GraduallyTyped.NN.Linear, module Torch.GraduallyTyped.NN.Transformer, module Torch.GraduallyTyped.NN.Dropout, module Torch.GraduallyTyped.NN.Activation, module Torch.GraduallyTyped.NN.Functional, module Torch.GraduallyTyped.NN.Normalization, module Torch.GraduallyTyped.NN.Sparse, module Torch.GraduallyTyped.NN.Type, module Torch.GraduallyTyped.NN.Training, module Torch.GraduallyTyped.NN.Loss, ) where import Torch.GraduallyTyped.NN.Activation import Torch.GraduallyTyped.NN.Class import Torch.GraduallyTyped.NN.Dropout import Torch.GraduallyTyped.NN.Functional import Torch.GraduallyTyped.NN.Initialization import Torch.GraduallyTyped.NN.Linear import Torch.GraduallyTyped.NN.Loss import Torch.GraduallyTyped.NN.Normalization import Torch.GraduallyTyped.NN.Sparse import Torch.GraduallyTyped.NN.Training import Torch.GraduallyTyped.NN.Transformer import Torch.GraduallyTyped.NN.Type
37962604d82b302f1a7ac6085b9a40a1f7bfe317cb9a2ca60bbd31a8a68f84ec
wilkerlucio/pathom
demo_parallel_reader.cljs
(ns com.wsscode.pathom.book.tracing.demo-parallel-reader (:require [clojure.core.async :as async] [com.wsscode.common.async-cljs :refer [go-catch <?]] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p])) (pc/defresolver movie-details [env {:movie/keys [id]}] {::pc/input #{:movie/id} ::pc/output [:movie/id :movie/title :movie/release-date]} (go-catch (<? (async/timeout 100)) {:movie/id id :movie/title "Title" :movie/release-date #inst "2018-10-30"})) (pc/defresolver movie-rating [env input] {::pc/input #{:movie/id} ::pc/output [:movie/rating]} (go-catch (<? (async/timeout 100)) {:movie/rating "PG"})) (pc/defresolver movie-title-prefixed [env {:movie/keys [title]}] {::pc/input #{:movie/title} ::pc/output [:movie/title-prefixed]} (go-catch (<? (async/timeout 100)) {:movie/title-prefixed (str "Prefix " title)})) (def app-registry [movie-details movie-rating movie-title-prefixed]) (def parser (p/parallel-parser {::p/env {::p/reader [p/map-reader pc/parallel-reader pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/mutate pc/mutate-async ::p/plugins [(pc/connect-plugin {::pc/register app-registry}) p/error-handler-plugin p/trace-plugin]}))
null
https://raw.githubusercontent.com/wilkerlucio/pathom/4ec25055d3d156241e9174d68ec438c93c971b9b/docs-src/modules/ROOT/examples/com/wsscode/pathom/book/tracing/demo_parallel_reader.cljs
clojure
(ns com.wsscode.pathom.book.tracing.demo-parallel-reader (:require [clojure.core.async :as async] [com.wsscode.common.async-cljs :refer [go-catch <?]] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p])) (pc/defresolver movie-details [env {:movie/keys [id]}] {::pc/input #{:movie/id} ::pc/output [:movie/id :movie/title :movie/release-date]} (go-catch (<? (async/timeout 100)) {:movie/id id :movie/title "Title" :movie/release-date #inst "2018-10-30"})) (pc/defresolver movie-rating [env input] {::pc/input #{:movie/id} ::pc/output [:movie/rating]} (go-catch (<? (async/timeout 100)) {:movie/rating "PG"})) (pc/defresolver movie-title-prefixed [env {:movie/keys [title]}] {::pc/input #{:movie/title} ::pc/output [:movie/title-prefixed]} (go-catch (<? (async/timeout 100)) {:movie/title-prefixed (str "Prefix " title)})) (def app-registry [movie-details movie-rating movie-title-prefixed]) (def parser (p/parallel-parser {::p/env {::p/reader [p/map-reader pc/parallel-reader pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/mutate pc/mutate-async ::p/plugins [(pc/connect-plugin {::pc/register app-registry}) p/error-handler-plugin p/trace-plugin]}))
799c6b9e3f0e1b32d210d815f030e6b83391f56ae2bff0810465b3834b27243b
ocaml-batteries-team/batteries-included
batISet.mli
Copyright 2003 . distributed with LGPL (** DIET : Discrete Interval Encoding Trees Sets of integers represented as ranges This data structure is efficient for large sets of integers where many adjacent integers are all part of the set. This will have higher overhead for sets with lots of point elements, but will be much more efficient for sets containing mostly ranges. *) type t = (int * int) BatAvlTree.tree (** the underlying representation is a balanced tree of ranges *) type elt = int (** This kind of set only holds ints *) val empty : t (** The empty set *) val is_empty : t -> bool (** Test whether a set is empty, returns [true] if the set is empty. *) val mem : int -> t -> bool (** test whether a given int is a member of the set *) val add : int -> t -> t (** Add the given int to the set, returning a new set *) val add_range : int -> int -> t -> t (** [add_range lo hi t] adds the range of integers [lo, hi] (including both endpoints) to the given set, returning a new set @raise Invalid_argument if [lo] > [hi] *) val singleton : int -> t (** Return the singleton set containing only the given element *) val remove : int -> t -> t (** Remove an element from the given set, returning a new set *) val remove_range : int -> int -> t -> t (** [remove_range lo hi t] removes a range of elements from the given set, returning a new set @raise Invalid_argument if [lo] > [hi] *) val union : t -> t -> t * Compute the union of two sets . This is the set whose elements are those elements in either input set . those elements in either input set. *) val inter : t -> t -> t * Compute the intersection of two sets . This is the set whose elements are those in * both * of the input sets . elements are those in *both* of the input sets. *) val diff : t -> t -> t * Compute the difference between two sets . This is the set of elements that are in the first but not in the second . Unlike [ union ] and [ inter ] , order matters here . elements that are in the first but not in the second. Unlike [union] and [inter], order matters here.*) val compl : t -> t (** Create the complement of the given set - i.e. the set of all values not in the input set. *) val compare : t -> t -> int * Compare two sets . It is not safe to use the polymorphic ( < ) and related functions to compare these sets , as the tree representation used can balance in multiple ways . related functions to compare these sets, as the tree representation used can balance in multiple ways. *) val equal : t -> t -> bool * Test whether two sets are equal . It is not safe to use the polymorphic ( =) on these sets , as the same set can have multiple representations depending on how it was built . polymorphic (=) on these sets, as the same set can have multiple representations depending on how it was built. *) val ord : t -> t -> BatOrd.order * Same as [ compare ] but returns [ BatOrd . Lt | BatOrd . . Gt ] instead of an int . instead of an int. *) val subset : t -> t -> bool (** [subset t u] returns [true] if [t] is a subset of [u] *) val from : int -> t -> t (** [from x t] returns the portion of [t] in the range [x, max_int] *) val after : int -> t -> t (** [after x t] returns the portion of [t] in the range [x+1, max_int] *) val until : int -> t -> t (** [until x t] returns the portion of [t] in the range [min_int, x] *) val before : int -> t -> t (** [before x t] returns the portion of [t] in the range [min_int, x-1] *) val iter : (int -> unit) -> t -> unit (** [iter f t] calls [f] once for each element of [t] *) val iter_range : (int -> int -> unit) -> t -> unit (** [iter_range f t] calls [f] once for each contiguous range of [t]. The contiguous ranges of a set are sequences of adjacent integers all part of the set. *) val fold : (int -> 'a -> 'a) -> t -> 'a -> 'a (** [fold f t x0] returns the final result of merging each element of [t] into [x0] using merge function [f] *) val fold_range : (int -> int -> 'a -> 'a) -> t -> 'a -> 'a (** As fold, but operates on contiguous ranges *) val for_all : (int -> bool) -> t -> bool (** Tests whether a predicate applies to all elements of the set *) val exists : (int -> bool) -> t -> bool (** Test whether some element of a set satisfies a predicate *) val filter : (int -> bool) -> t -> t (** Builds the subset of those elements that satisfy the predicate *) val partition : (int -> bool) -> t -> t * t * partitions the input set into two sets with elements that satisfy the predicate and those that do n't the predicate and those that don't *) val cardinal : t -> int (** Returns the number of elements in the set *) val elements : t -> int list (** Returns a list of all elements in the set *) val ranges : t -> (int * int) list (** Returns a list of all contiguous ranges in the set *) val min_elt : t -> int (** Returns the minimum element in the set *) val max_elt : t -> int (** Returns the maximum element in the set *) val choose : t -> int (** Returns some element in the set *) val enum : t -> (int * int) BatEnum.t (** Enumerates all contiguous ranges in the set *) val of_enum : (int*int) BatEnum.t -> t val of_list : (int*int) list -> t (** Build a ISet.t out of a list or enum of ranges *) val print : _ BatIO.output -> t -> unit
null
https://raw.githubusercontent.com/ocaml-batteries-team/batteries-included/59f8946a0220fa59775f6205a17080df9ab3c1cf/src/batISet.mli
ocaml
* DIET : Discrete Interval Encoding Trees Sets of integers represented as ranges This data structure is efficient for large sets of integers where many adjacent integers are all part of the set. This will have higher overhead for sets with lots of point elements, but will be much more efficient for sets containing mostly ranges. * the underlying representation is a balanced tree of ranges * This kind of set only holds ints * The empty set * Test whether a set is empty, returns [true] if the set is empty. * test whether a given int is a member of the set * Add the given int to the set, returning a new set * [add_range lo hi t] adds the range of integers [lo, hi] (including both endpoints) to the given set, returning a new set @raise Invalid_argument if [lo] > [hi] * Return the singleton set containing only the given element * Remove an element from the given set, returning a new set * [remove_range lo hi t] removes a range of elements from the given set, returning a new set @raise Invalid_argument if [lo] > [hi] * Create the complement of the given set - i.e. the set of all values not in the input set. * [subset t u] returns [true] if [t] is a subset of [u] * [from x t] returns the portion of [t] in the range [x, max_int] * [after x t] returns the portion of [t] in the range [x+1, max_int] * [until x t] returns the portion of [t] in the range [min_int, x] * [before x t] returns the portion of [t] in the range [min_int, x-1] * [iter f t] calls [f] once for each element of [t] * [iter_range f t] calls [f] once for each contiguous range of [t]. The contiguous ranges of a set are sequences of adjacent integers all part of the set. * [fold f t x0] returns the final result of merging each element of [t] into [x0] using merge function [f] * As fold, but operates on contiguous ranges * Tests whether a predicate applies to all elements of the set * Test whether some element of a set satisfies a predicate * Builds the subset of those elements that satisfy the predicate * Returns the number of elements in the set * Returns a list of all elements in the set * Returns a list of all contiguous ranges in the set * Returns the minimum element in the set * Returns the maximum element in the set * Returns some element in the set * Enumerates all contiguous ranges in the set * Build a ISet.t out of a list or enum of ranges
Copyright 2003 . distributed with LGPL type t = (int * int) BatAvlTree.tree type elt = int val empty : t val is_empty : t -> bool val mem : int -> t -> bool val add : int -> t -> t val add_range : int -> int -> t -> t val singleton : int -> t val remove : int -> t -> t val remove_range : int -> int -> t -> t val union : t -> t -> t * Compute the union of two sets . This is the set whose elements are those elements in either input set . those elements in either input set. *) val inter : t -> t -> t * Compute the intersection of two sets . This is the set whose elements are those in * both * of the input sets . elements are those in *both* of the input sets. *) val diff : t -> t -> t * Compute the difference between two sets . This is the set of elements that are in the first but not in the second . Unlike [ union ] and [ inter ] , order matters here . elements that are in the first but not in the second. Unlike [union] and [inter], order matters here.*) val compl : t -> t val compare : t -> t -> int * Compare two sets . It is not safe to use the polymorphic ( < ) and related functions to compare these sets , as the tree representation used can balance in multiple ways . related functions to compare these sets, as the tree representation used can balance in multiple ways. *) val equal : t -> t -> bool * Test whether two sets are equal . It is not safe to use the polymorphic ( =) on these sets , as the same set can have multiple representations depending on how it was built . polymorphic (=) on these sets, as the same set can have multiple representations depending on how it was built. *) val ord : t -> t -> BatOrd.order * Same as [ compare ] but returns [ BatOrd . Lt | BatOrd . . Gt ] instead of an int . instead of an int. *) val subset : t -> t -> bool val from : int -> t -> t val after : int -> t -> t val until : int -> t -> t val before : int -> t -> t val iter : (int -> unit) -> t -> unit val iter_range : (int -> int -> unit) -> t -> unit val fold : (int -> 'a -> 'a) -> t -> 'a -> 'a val fold_range : (int -> int -> 'a -> 'a) -> t -> 'a -> 'a val for_all : (int -> bool) -> t -> bool val exists : (int -> bool) -> t -> bool val filter : (int -> bool) -> t -> t val partition : (int -> bool) -> t -> t * t * partitions the input set into two sets with elements that satisfy the predicate and those that do n't the predicate and those that don't *) val cardinal : t -> int val elements : t -> int list val ranges : t -> (int * int) list val min_elt : t -> int val max_elt : t -> int val choose : t -> int val enum : t -> (int * int) BatEnum.t val of_enum : (int*int) BatEnum.t -> t val of_list : (int*int) list -> t val print : _ BatIO.output -> t -> unit
d78d87f0c6a9d03460835ab7848706923a181468bbdf3d482acfcdcf03c04b8e
ros/roslisp_common
ros-messages.lisp
Copyright ( c ) 2013 , < > ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. * Neither the name of the Institute for Artificial Intelligence/ Universitaet Bremen nor the names of its contributors may be used to ;;; endorse or promote products derived from this software without specific ;;; prior written permission. ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " ;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN ;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ;;; POSSIBILITY OF SUCH DAMAGE. (in-package :cl-transforms-stamped) (defgeneric to-msg (data) (:documentation "Transforms `data' into an equivalent ROS message")) (defgeneric from-msg (msg) (:documentation "Transforms `msg' into their corresponding Lisp data structures.")) (defgeneric restamp-msg (msg stamp) (:documentation "Update all stamp fields of `msg' with new value `stamp'.")) (defmethod to-msg ((data list)) (coerce (mapcar #'to-msg data) 'vector)) (defmethod to-msg ((data cl-transforms:transform)) (make-msg "geometry_msgs/Transform" :translation (to-msg (cl-transforms:translation data)) :rotation (to-msg (cl-transforms:rotation data)))) (defmethod to-msg ((data cl-transforms:quaternion)) (make-msg "geometry_msgs/Quaternion" :x (cl-transforms:x data) :y (cl-transforms:y data) :z (cl-transforms:z data) :w (cl-transforms:w data))) (defmethod to-msg ((data cl-transforms:3d-vector)) "cl-transforms represents 3d points as objects of class 3D-VECTOR. They are automatically converted to geometry_msgs/Vector3. If you need a geometry_msgs/Point use the MAKE-POINT-MSG function." (make-msg "geometry_msgs/Vector3" :x (cl-transforms:x data) :y (cl-transforms:y data) :z (cl-transforms:z data))) (defmethod to-msg ((data cl-transforms:pose)) (make-msg "geometry_msgs/Pose" :position (make-point-msg (cl-transforms:origin data)) :orientation (to-msg (cl-transforms:orientation data)))) (defmethod to-msg ((data transform-stamped)) (make-msg "geometry_msgs/TransformStamped" :header (make-header-msg (stamp data) (frame-id data)) :child_frame_id (child-frame-id data) :transform (to-msg (cl-transforms:make-transform (cl-transforms:translation data) (cl-transforms:rotation data))))) (defmethod to-msg ((data pose-stamped)) (make-msg "geometry_msgs/PoseStamped" :header (make-header-msg (stamp data) (frame-id data)) :pose (to-msg (cl-transforms:make-pose (cl-transforms:origin data) (cl-transforms:orientation data))))) (defmethod to-msg ((data point-stamped)) (make-msg "geometry_msgs/PointStamped" (stamp header) (stamp data) (frame_id header) (frame-id data) (x point) (x data) (y point) (y data) (z point) (z data))) (defun make-header-msg (stamp frame-id) (make-msg "std_msgs/Header" :stamp stamp :frame_id frame-id)) (defun make-point-msg (data) (declare (type cl-transforms:3d-vector data)) (make-msg "geometry_msgs/Point" :x (cl-transforms:x data) :y (cl-transforms:y data) :z (cl-transforms:z data))) (defun make-pose-stamped-msg (pose frame-id stamp) (declare (type cl-transforms:pose pose)) (to-msg (make-pose-stamped frame-id stamp (origin pose) (orientation pose)))) (defmethod from-msg ((msg geometry_msgs-msg:TransformStamped)) (with-fields ((frame-id (frame_id header)) (stamp (stamp header)) child_frame_id (translation-msg (translation transform)) (rotation-msg (rotation transform))) msg (make-transform-stamped frame-id child_frame_id stamp (from-msg translation-msg) (from-msg rotation-msg)))) (defmethod from-msg ((msg geometry_msgs-msg:Transform)) (with-fields (translation rotation) msg (make-transform (from-msg translation) (from-msg rotation) :validate-args nil))) (defmethod from-msg ((msg geometry_msgs-msg:Vector3)) (with-fields (x y z) msg (make-3d-vector x y z))) (defmethod from-msg ((msg geometry_msgs-msg:Quaternion)) (with-fields (x y z w) msg (make-quaternion x y z w))) (defmethod from-msg ((msg geometry_msgs-msg:Point)) (with-fields (x y z) msg (make-3d-vector x y z))) (defmethod from-msg ((msg geometry_msgs-msg:Pose)) (with-fields (orientation position) msg (make-pose (from-msg position) (from-msg orientation)))) (defmethod from-msg ((msg geometry_msgs-msg:PoseStamped)) (with-fields ((frame-id (frame_id header)) (stamp (stamp header)) (position-msg (position pose)) (orientation-msg (orientation pose))) msg (make-pose-stamped frame-id stamp (from-msg position-msg) (from-msg orientation-msg)))) (defmethod from-msg ((msg geometry_msgs-msg:PointStamped)) (with-fields ((frame-id (frame_id header)) (stamp (stamp header)) (x (x point)) (y (y point)) (z (z point))) msg (make-point-stamped frame-id stamp (make-3d-vector x y z)))) (defmethod restamp-msg ((msg geometry_msgs-msg:TransformStamped) new-stamp) (with-slots ((header geometry_msgs-msg:header)) msg (with-slots ((stamp std_msgs-msg:stamp)) header (setf stamp new-stamp) msg))) ;;; misc conversions (defun pose-stamped->point-stamped-msg (pose) (make-msg "geometry_msgs/PointStamped" (stamp header) (stamp pose) (frame_id header) (frame-id pose) (x point) (cl-transforms:x (cl-transforms:origin pose)) (y point) (cl-transforms:y (cl-transforms:origin pose)) (z point) (cl-transforms:z (cl-transforms:origin pose))))
null
https://raw.githubusercontent.com/ros/roslisp_common/4db311da26497d84a147f190200e50c7a5b4106e/cl_transforms_stamped/src/ros-messages.lisp
lisp
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. endorse or promote products derived from this software without specific prior written permission. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. misc conversions
Copyright ( c ) 2013 , < > * Neither the name of the Institute for Artificial Intelligence/ Universitaet Bremen nor the names of its contributors may be used to THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN (in-package :cl-transforms-stamped) (defgeneric to-msg (data) (:documentation "Transforms `data' into an equivalent ROS message")) (defgeneric from-msg (msg) (:documentation "Transforms `msg' into their corresponding Lisp data structures.")) (defgeneric restamp-msg (msg stamp) (:documentation "Update all stamp fields of `msg' with new value `stamp'.")) (defmethod to-msg ((data list)) (coerce (mapcar #'to-msg data) 'vector)) (defmethod to-msg ((data cl-transforms:transform)) (make-msg "geometry_msgs/Transform" :translation (to-msg (cl-transforms:translation data)) :rotation (to-msg (cl-transforms:rotation data)))) (defmethod to-msg ((data cl-transforms:quaternion)) (make-msg "geometry_msgs/Quaternion" :x (cl-transforms:x data) :y (cl-transforms:y data) :z (cl-transforms:z data) :w (cl-transforms:w data))) (defmethod to-msg ((data cl-transforms:3d-vector)) "cl-transforms represents 3d points as objects of class 3D-VECTOR. They are automatically converted to geometry_msgs/Vector3. If you need a geometry_msgs/Point use the MAKE-POINT-MSG function." (make-msg "geometry_msgs/Vector3" :x (cl-transforms:x data) :y (cl-transforms:y data) :z (cl-transforms:z data))) (defmethod to-msg ((data cl-transforms:pose)) (make-msg "geometry_msgs/Pose" :position (make-point-msg (cl-transforms:origin data)) :orientation (to-msg (cl-transforms:orientation data)))) (defmethod to-msg ((data transform-stamped)) (make-msg "geometry_msgs/TransformStamped" :header (make-header-msg (stamp data) (frame-id data)) :child_frame_id (child-frame-id data) :transform (to-msg (cl-transforms:make-transform (cl-transforms:translation data) (cl-transforms:rotation data))))) (defmethod to-msg ((data pose-stamped)) (make-msg "geometry_msgs/PoseStamped" :header (make-header-msg (stamp data) (frame-id data)) :pose (to-msg (cl-transforms:make-pose (cl-transforms:origin data) (cl-transforms:orientation data))))) (defmethod to-msg ((data point-stamped)) (make-msg "geometry_msgs/PointStamped" (stamp header) (stamp data) (frame_id header) (frame-id data) (x point) (x data) (y point) (y data) (z point) (z data))) (defun make-header-msg (stamp frame-id) (make-msg "std_msgs/Header" :stamp stamp :frame_id frame-id)) (defun make-point-msg (data) (declare (type cl-transforms:3d-vector data)) (make-msg "geometry_msgs/Point" :x (cl-transforms:x data) :y (cl-transforms:y data) :z (cl-transforms:z data))) (defun make-pose-stamped-msg (pose frame-id stamp) (declare (type cl-transforms:pose pose)) (to-msg (make-pose-stamped frame-id stamp (origin pose) (orientation pose)))) (defmethod from-msg ((msg geometry_msgs-msg:TransformStamped)) (with-fields ((frame-id (frame_id header)) (stamp (stamp header)) child_frame_id (translation-msg (translation transform)) (rotation-msg (rotation transform))) msg (make-transform-stamped frame-id child_frame_id stamp (from-msg translation-msg) (from-msg rotation-msg)))) (defmethod from-msg ((msg geometry_msgs-msg:Transform)) (with-fields (translation rotation) msg (make-transform (from-msg translation) (from-msg rotation) :validate-args nil))) (defmethod from-msg ((msg geometry_msgs-msg:Vector3)) (with-fields (x y z) msg (make-3d-vector x y z))) (defmethod from-msg ((msg geometry_msgs-msg:Quaternion)) (with-fields (x y z w) msg (make-quaternion x y z w))) (defmethod from-msg ((msg geometry_msgs-msg:Point)) (with-fields (x y z) msg (make-3d-vector x y z))) (defmethod from-msg ((msg geometry_msgs-msg:Pose)) (with-fields (orientation position) msg (make-pose (from-msg position) (from-msg orientation)))) (defmethod from-msg ((msg geometry_msgs-msg:PoseStamped)) (with-fields ((frame-id (frame_id header)) (stamp (stamp header)) (position-msg (position pose)) (orientation-msg (orientation pose))) msg (make-pose-stamped frame-id stamp (from-msg position-msg) (from-msg orientation-msg)))) (defmethod from-msg ((msg geometry_msgs-msg:PointStamped)) (with-fields ((frame-id (frame_id header)) (stamp (stamp header)) (x (x point)) (y (y point)) (z (z point))) msg (make-point-stamped frame-id stamp (make-3d-vector x y z)))) (defmethod restamp-msg ((msg geometry_msgs-msg:TransformStamped) new-stamp) (with-slots ((header geometry_msgs-msg:header)) msg (with-slots ((stamp std_msgs-msg:stamp)) header (setf stamp new-stamp) msg))) (defun pose-stamped->point-stamped-msg (pose) (make-msg "geometry_msgs/PointStamped" (stamp header) (stamp pose) (frame_id header) (frame-id pose) (x point) (cl-transforms:x (cl-transforms:origin pose)) (y point) (cl-transforms:y (cl-transforms:origin pose)) (z point) (cl-transforms:z (cl-transforms:origin pose))))
6f3d2a73d2f6499911f7ebc31c2cb3b2a440c8f5e9b50afdb38311bd64691c34
wwezhuimeng/kazoo
stress_test_app.erl
@author < > 2012 %% 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. -module(stress_test_app). -author('Kirill Trofimov <>'). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %% =================================================================== %% Application callbacks %% =================================================================== start(_StartType, _StartArgs) -> stress_test_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/wwezhuimeng/kazoo/06a15811dbf123ae1601dc7a4ced956a7e04f58a/deps/socketio-0.1.0/stress/src/stress_test_app.erl
erlang
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. Application callbacks =================================================================== Application callbacks ===================================================================
@author < > 2012 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(stress_test_app). -author('Kirill Trofimov <>'). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> stress_test_sup:start_link(). stop(_State) -> ok.
6ab7d22f2d2a2413c72426f7720430ad20c6b6f9d3c526f72f5433c3841ad3ba
ryanpbrewster/haskell
P087.hs
module Problems.P087 ( solve ) where import Data.Set (fromList, size) - The smallest number expressible as the sum of a prime square , prime cube , - and prime fourth power is 28 . In fact , there are exactly four numbers below - fifty that can be expressed in such a way : - - 28 = 2 ^ 2 + 2 ^ 3 + 2 ^ 4 - 33 = 3 ^ 2 + 2 ^ 3 + 2 ^ 4 - 49 = 5 ^ 2 + 2 ^ 3 + 2 ^ 4 - 47 = 2 ^ 2 + 3 ^ 3 + 2 ^ 4 - - How many numbers below fifty million can be expressed as the sum of a prime - square , prime cube , and prime fourth power ? - The smallest number expressible as the sum of a prime square, prime cube, - and prime fourth power is 28. In fact, there are exactly four numbers below - fifty that can be expressed in such a way: - - 28 = 2^2 + 2^3 + 2^4 - 33 = 3^2 + 2^3 + 2^4 - 49 = 5^2 + 2^3 + 2^4 - 47 = 2^2 + 3^3 + 2^4 - - How many numbers below fifty million can be expressed as the sum of a prime - square, prime cube, and prime fourth power? -} import Util.Prime (primes) solve :: String solve = show $ solveProblem 50e6 solveProblem bound = size $ fromList [ p2 + p3 + p4 | p4 <- takeWhile (< bound) $ map (^ 4) primes , p3 <- takeWhile (< bound - p4) $ map (^ 3) primes , p2 <- takeWhile (< bound - p4 - p3) $ map (^ 2) primes ]
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/src/Problems/P087.hs
haskell
module Problems.P087 ( solve ) where import Data.Set (fromList, size) - The smallest number expressible as the sum of a prime square , prime cube , - and prime fourth power is 28 . In fact , there are exactly four numbers below - fifty that can be expressed in such a way : - - 28 = 2 ^ 2 + 2 ^ 3 + 2 ^ 4 - 33 = 3 ^ 2 + 2 ^ 3 + 2 ^ 4 - 49 = 5 ^ 2 + 2 ^ 3 + 2 ^ 4 - 47 = 2 ^ 2 + 3 ^ 3 + 2 ^ 4 - - How many numbers below fifty million can be expressed as the sum of a prime - square , prime cube , and prime fourth power ? - The smallest number expressible as the sum of a prime square, prime cube, - and prime fourth power is 28. In fact, there are exactly four numbers below - fifty that can be expressed in such a way: - - 28 = 2^2 + 2^3 + 2^4 - 33 = 3^2 + 2^3 + 2^4 - 49 = 5^2 + 2^3 + 2^4 - 47 = 2^2 + 3^3 + 2^4 - - How many numbers below fifty million can be expressed as the sum of a prime - square, prime cube, and prime fourth power? -} import Util.Prime (primes) solve :: String solve = show $ solveProblem 50e6 solveProblem bound = size $ fromList [ p2 + p3 + p4 | p4 <- takeWhile (< bound) $ map (^ 4) primes , p3 <- takeWhile (< bound - p4) $ map (^ 3) primes , p2 <- takeWhile (< bound - p4 - p3) $ map (^ 2) primes ]
b3992e1f43ab22782fb32b0811c5ded32401d6cd39ad51834da1fbb9970e6ecd
nuprl/website
frog.rkt
#lang frog/config ;; Called early when Frog launches. Use this to set parameters defined ;; in frog/params. (define/contract (init) (-> any) (current-scheme/host "") (current-uri-prefix "/blog") (current-title "PRL Blog") (current-author "PRL") (current-editor "$EDITOR") (current-editor-command "{editor} {filename}") (current-show-tag-counts? #t) (current-permalink "/{year}/{month}/{day}/{title}/index.html") (current-index-full? #f) (current-feed-full? #t) (current-max-feed-items 20) (current-decorate-feed-uris? #t) (current-feed-image-bugs? #t) (current-posts-per-page 10) (current-index-newest-first? #t) (current-posts-index-uri "/index.html") (current-source-dir "_src") (current-output-dir ".")) ;; Called once per post and non-post page, on the contents. (define/contract (enhance-body xs) (-> (listof xexpr/c) (listof xexpr/c)) ;; Here we pass the xexprs through a series of functions. (~> xs (syntax-highlight #:python-executable "python" #:line-numbers? #t #:css-class "source") (auto-embed-tweets #:parents? #t) (add-racket-doc-links #:code? #t #:prose? #t))) ;; Called from `raco frog --clean`. (define/contract (clean) (-> any) (void))
null
https://raw.githubusercontent.com/nuprl/website/6952d0572094feae39e515e6b421de81af5a5be9/blog/frog.rkt
racket
Called early when Frog launches. Use this to set parameters defined in frog/params. Called once per post and non-post page, on the contents. Here we pass the xexprs through a series of functions. Called from `raco frog --clean`.
#lang frog/config (define/contract (init) (-> any) (current-scheme/host "") (current-uri-prefix "/blog") (current-title "PRL Blog") (current-author "PRL") (current-editor "$EDITOR") (current-editor-command "{editor} {filename}") (current-show-tag-counts? #t) (current-permalink "/{year}/{month}/{day}/{title}/index.html") (current-index-full? #f) (current-feed-full? #t) (current-max-feed-items 20) (current-decorate-feed-uris? #t) (current-feed-image-bugs? #t) (current-posts-per-page 10) (current-index-newest-first? #t) (current-posts-index-uri "/index.html") (current-source-dir "_src") (current-output-dir ".")) (define/contract (enhance-body xs) (-> (listof xexpr/c) (listof xexpr/c)) (~> xs (syntax-highlight #:python-executable "python" #:line-numbers? #t #:css-class "source") (auto-embed-tweets #:parents? #t) (add-racket-doc-links #:code? #t #:prose? #t))) (define/contract (clean) (-> any) (void))
16c7e13ffc195b722c6f07a3788ee949300e9492d03b2648842391becba50197
rowangithub/DOrder
monniaux.ml
let rec loop i = if i < 1000 then ( loop (i+1)) else (assert (i <= 10000);) let main () = loop 0 let _ = main ()
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/folprograms/mcmc/monniaux.ml
ocaml
let rec loop i = if i < 1000 then ( loop (i+1)) else (assert (i <= 10000);) let main () = loop 0 let _ = main ()
50ffe2a5bfb1486978fbf8a940e93ed93d7b0227809057e60859dbb81bff213a
Tavistock/lseq-tree
triple.cljc
(ns lseq-tree.triple) (defrecord Triple [path site counter]) (defn sorted "compare two triples prioritizing the path, then site, then counter it either returns -1, 0, or 1" ([xs] (sort-by (juxt :path :site :counter) xs)) ([k xs] (sort-by #((juxt :path :site :counter) (k %)) xs ))) (defn triple ([] (triple 0 0 0)) ([path site counter] (Triple. path site counter)))
null
https://raw.githubusercontent.com/Tavistock/lseq-tree/4b75e43477fdeb421c5bf56f65be71c108378673/src/lseq_tree/triple.cljc
clojure
(ns lseq-tree.triple) (defrecord Triple [path site counter]) (defn sorted "compare two triples prioritizing the path, then site, then counter it either returns -1, 0, or 1" ([xs] (sort-by (juxt :path :site :counter) xs)) ([k xs] (sort-by #((juxt :path :site :counter) (k %)) xs ))) (defn triple ([] (triple 0 0 0)) ([path site counter] (Triple. path site counter)))
8ab60a4dfec592d8a3d100002c59b3d7bedf1d5cbdc88872b66cf09a2318b953
Octachron/codept
findlib.ml
type query = { pkgs: Name.t list; predicates: string list; syntaxes: Name.t list; ppxopts: string list Name.map; ppopt: string list } type result = { libs: string list; ppxs: string list; pp: string option } let pp ppf r = Pp.fp ppf "libs={%a};@; ppxs={%a};@; pp = %a " Pp.(list estring) r.libs Pp.(list estring) r.ppxs Pp.(opt estring) r.pp let run cmd = let cin = Unix.open_process_in cmd in let rec read l = try match input_line cin with | "" -> read l | s -> read (s::l) with End_of_file -> List.rev l in read [] let run_word cmd = match run cmd with | [a] -> Some a | _ -> None let query q = run@@ String.concat " " ("ocamlfind query -r " :: q) let printppx q = let s = run_word @@ String.concat " " ("ocamlfind printppx " :: q) in Option.fmap (fun s -> String.sub s 4 @@ String.length s - 4) s let archive q = run @@ String.concat " " ("ocamlfind query -format %a":: q) let find_pred info = let p = String.concat "," info.predicates in if p = "" then [] else ["-predicates"; p ] let camlp4 = "camlp4" let filter predicates syntax pkg = archive @@ (pkg :: predicates) @ ["-pp"; "-predicates"; syntax] <> [] let find_pp info syntax pkgs = let predicates = find_pred info in let g = List.filter (filter predicates syntax) pkgs in let main_pp = camlp4 in let includes l i = List.fold_left (fun acc x -> "-I" :: x :: acc ) l @@ query (i::predicates) in let i = List.fold_left includes [] g in main_pp :: i @ archive ( main_pp :: predicates @ ["-pp"; "-predicates"; syntax] @ g ) @ List.rev info.ppopt let process_pkg info name = let predicates = find_pred info in let dirs = query @@ predicates @ [name] in let ppxopt = Option.default [] @@ Name.Map.find_opt name info.ppxopts in let ppx = Option.fmap (fun s -> String.concat " " @@ s :: ppxopt) @@ printppx @@ predicates @ [name] in dirs, ppx let pkg info pkg = { info with pkgs = pkg :: info.pkgs } let syntax info syntax = { info with syntaxes = syntax :: info.syntaxes } let ppxopt info opt = match Support.split_on_char ',' opt with | [] | [_] -> info | a :: q -> let q = String.concat "," q in let m = info.ppxopts in let q = Option.( Name.Map.find_opt a m >>| (List.cons q) >< [q] ) in let m = Name.Map.add a q m in { info with ppxopts = m } let ppopt info opt = { info with ppopt = opt :: info.ppopt } let predicates info s = let l = List.map String.trim @@ Support.split_on_char ',' s in { info with predicates = l @ info.predicates } let empty = { pkgs = []; syntaxes =[]; ppopt = []; ppxopts = Name.Map.empty; predicates = [] } let process_pp info name pp = try let s = find_pp info name info.pkgs in let s = String.concat " " s in Some s with Not_found -> pp let ( |:: ) x l = Option.( x >>| (fun x -> x :: l) >< l) let process info = let syntaxes = Name.Set.of_list (info.syntaxes) in let pp = Name.Set.fold (process_pp info) syntaxes None in let libs, ppxs = List.fold_left (fun (libs,ppxs) pkg -> let lib, ppx = process_pkg info pkg in (lib @ libs, ppx |:: ppxs)) ([],[]) info.pkgs in {ppxs;libs;pp}
null
https://raw.githubusercontent.com/Octachron/codept/66fb4b2caac8e9757eefb3f4e605b392a0fa457f/core/findlib.ml
ocaml
type query = { pkgs: Name.t list; predicates: string list; syntaxes: Name.t list; ppxopts: string list Name.map; ppopt: string list } type result = { libs: string list; ppxs: string list; pp: string option } let pp ppf r = Pp.fp ppf "libs={%a};@; ppxs={%a};@; pp = %a " Pp.(list estring) r.libs Pp.(list estring) r.ppxs Pp.(opt estring) r.pp let run cmd = let cin = Unix.open_process_in cmd in let rec read l = try match input_line cin with | "" -> read l | s -> read (s::l) with End_of_file -> List.rev l in read [] let run_word cmd = match run cmd with | [a] -> Some a | _ -> None let query q = run@@ String.concat " " ("ocamlfind query -r " :: q) let printppx q = let s = run_word @@ String.concat " " ("ocamlfind printppx " :: q) in Option.fmap (fun s -> String.sub s 4 @@ String.length s - 4) s let archive q = run @@ String.concat " " ("ocamlfind query -format %a":: q) let find_pred info = let p = String.concat "," info.predicates in if p = "" then [] else ["-predicates"; p ] let camlp4 = "camlp4" let filter predicates syntax pkg = archive @@ (pkg :: predicates) @ ["-pp"; "-predicates"; syntax] <> [] let find_pp info syntax pkgs = let predicates = find_pred info in let g = List.filter (filter predicates syntax) pkgs in let main_pp = camlp4 in let includes l i = List.fold_left (fun acc x -> "-I" :: x :: acc ) l @@ query (i::predicates) in let i = List.fold_left includes [] g in main_pp :: i @ archive ( main_pp :: predicates @ ["-pp"; "-predicates"; syntax] @ g ) @ List.rev info.ppopt let process_pkg info name = let predicates = find_pred info in let dirs = query @@ predicates @ [name] in let ppxopt = Option.default [] @@ Name.Map.find_opt name info.ppxopts in let ppx = Option.fmap (fun s -> String.concat " " @@ s :: ppxopt) @@ printppx @@ predicates @ [name] in dirs, ppx let pkg info pkg = { info with pkgs = pkg :: info.pkgs } let syntax info syntax = { info with syntaxes = syntax :: info.syntaxes } let ppxopt info opt = match Support.split_on_char ',' opt with | [] | [_] -> info | a :: q -> let q = String.concat "," q in let m = info.ppxopts in let q = Option.( Name.Map.find_opt a m >>| (List.cons q) >< [q] ) in let m = Name.Map.add a q m in { info with ppxopts = m } let ppopt info opt = { info with ppopt = opt :: info.ppopt } let predicates info s = let l = List.map String.trim @@ Support.split_on_char ',' s in { info with predicates = l @ info.predicates } let empty = { pkgs = []; syntaxes =[]; ppopt = []; ppxopts = Name.Map.empty; predicates = [] } let process_pp info name pp = try let s = find_pp info name info.pkgs in let s = String.concat " " s in Some s with Not_found -> pp let ( |:: ) x l = Option.( x >>| (fun x -> x :: l) >< l) let process info = let syntaxes = Name.Set.of_list (info.syntaxes) in let pp = Name.Set.fold (process_pp info) syntaxes None in let libs, ppxs = List.fold_left (fun (libs,ppxs) pkg -> let lib, ppx = process_pkg info pkg in (lib @ libs, ppx |:: ppxs)) ([],[]) info.pkgs in {ppxs;libs;pp}
20463b103cad858afef2e1fa02394e7c12f99075a225ba66def3b5f603e5cbed
dinosaure/contruno
unikernel.ml
open Rresult open Lwt.Infix let ( <.> ) f g = fun x -> f (g x) module Make (Random : Mirage_random.S) (Time : Mirage_time.S) (Mclock : Mirage_clock.MCLOCK) (Pclock : Mirage_clock.PCLOCK) (Stack : Tcpip.Stack.V4V6) (ALPN : Http_mirage_client.S) (_ : sig end) = struct include Contruno.Make (Random) (Time) (Mclock) (Pclock) (Stack) module Log = (val (Logs.src_log (Logs.Src.create "contruno.main"))) (* XXX(dinosaure): [add_hook] fills a stream with what it's upgraded from the Git * repository. If the user adds a new certificate, it will appear into the stream. * So we must consume it and check if a new domain appeared according to our [hashset]. * * Then, a job waiting a new thread to renegociate a certificate and launch it with * [Lwt.async]. This thread is an infinite thread (until an error), So it's an expected * behavior to let it go without a control of us. *) let launch_reneg_ths ~stop:https ~upgrader reneg_ths stream = let mutex = Lwt_mutex.create () in let condition = Lwt_condition.create () in let stop, waker = Lwt.wait () in let set = Hashset.create (List.length reneg_ths) in let rec launch_jobs () = Lwt.pick [ Lwt_condition.wait ~mutex condition ; stop ] >>= function | `Stop -> Lwt.return_unit | `Launch th -> Log.debug (fun m -> m "Launch a new thread."); begin Lwt.async @@ fun () -> th `Ready end ; launch_jobs () in let fill_jobs () = Log.debug (fun m -> m "Waiting for a new certificate."); Lwt_stream.get stream >>= function | Some (hostname, v) -> Log.debug (fun m -> m "Launch a renegociation thread for %a." Domain_name.pp hostname); Lwt_mutex.with_lock mutex @@ fun () -> if Hashset.mem set hostname then ( Log.debug (fun m -> m "A renegociation thread already exists for %a." Domain_name.pp hostname) ; Lwt.return_unit ) else ( Hashset.add set hostname ; upgrader (Art.unsafe_key (Domain_name.to_string hostname)) v >>= fun th -> Lwt_condition.signal condition (`Launch th) ; Lwt.return_unit ) | None -> (* XXX(dinosaure): the stream is infinite, we should never stop. *) Log.err (fun m -> m "The stream of new certificates was done."); Lwt.wakeup_later waker `Stop ; Lwt.return_unit in let first_fill reneg_ths = Lwt_list.iter_s begin fun (hostname, tth) -> Lwt_mutex.with_lock mutex @@ fun () -> Hashset.add set hostname ; tth >>= fun th -> Lwt_condition.signal condition (`Launch th) ; Lwt.return_unit end reneg_ths >|= fun () -> Log.debug (fun m -> m "Threads for valid certificates are launched!"); in Lwt.join [ first_fill reneg_ths; launch_jobs (); fill_jobs () ] >>= fun () -> Lwt_switch.turn_off https let start _random _time () () stackv4v6 alpn ctx = let http = Lwt_mutex.create () in let cfg = { Contruno.production= Key_gen.production () ; email= Option.bind (Key_gen.email ()) (R.to_option <.> Emile.of_string) ; account_seed= Key_gen.account_seed () ; certificate_seed= Key_gen.certificate_seed () } in let remote = Key_gen.remote () in let stream, push = Lwt_stream.create () in initialize http ~ctx ~remote cfg alpn stackv4v6 >>= fun (conns, tree, reneg_ths, `Upgrader upgrader) -> let service = serve conns tree (Stack.tcp stackv4v6) in add_hook ~pass:(Key_gen.pass ()) ~ctx ~remote tree push stackv4v6 ; init ~port:443 stackv4v6 >>= fun stack -> let stop = Lwt_switch.create () in let `Initialized th = Paf.serve ~stop service stack in Lwt.both (launch_reneg_ths ~stop ~upgrader reneg_ths stream) (Lwt.both th (Stack.listen stackv4v6)) >>= fun ((), ((), ())) -> Lwt.return_unit end
null
https://raw.githubusercontent.com/dinosaure/contruno/7e6ce1fbe23ddc47911690277eec6c0ef9c09627/unikernel/unikernel.ml
ocaml
XXX(dinosaure): [add_hook] fills a stream with what it's upgraded from the Git * repository. If the user adds a new certificate, it will appear into the stream. * So we must consume it and check if a new domain appeared according to our [hashset]. * * Then, a job waiting a new thread to renegociate a certificate and launch it with * [Lwt.async]. This thread is an infinite thread (until an error), So it's an expected * behavior to let it go without a control of us. XXX(dinosaure): the stream is infinite, we should never stop.
open Rresult open Lwt.Infix let ( <.> ) f g = fun x -> f (g x) module Make (Random : Mirage_random.S) (Time : Mirage_time.S) (Mclock : Mirage_clock.MCLOCK) (Pclock : Mirage_clock.PCLOCK) (Stack : Tcpip.Stack.V4V6) (ALPN : Http_mirage_client.S) (_ : sig end) = struct include Contruno.Make (Random) (Time) (Mclock) (Pclock) (Stack) module Log = (val (Logs.src_log (Logs.Src.create "contruno.main"))) let launch_reneg_ths ~stop:https ~upgrader reneg_ths stream = let mutex = Lwt_mutex.create () in let condition = Lwt_condition.create () in let stop, waker = Lwt.wait () in let set = Hashset.create (List.length reneg_ths) in let rec launch_jobs () = Lwt.pick [ Lwt_condition.wait ~mutex condition ; stop ] >>= function | `Stop -> Lwt.return_unit | `Launch th -> Log.debug (fun m -> m "Launch a new thread."); begin Lwt.async @@ fun () -> th `Ready end ; launch_jobs () in let fill_jobs () = Log.debug (fun m -> m "Waiting for a new certificate."); Lwt_stream.get stream >>= function | Some (hostname, v) -> Log.debug (fun m -> m "Launch a renegociation thread for %a." Domain_name.pp hostname); Lwt_mutex.with_lock mutex @@ fun () -> if Hashset.mem set hostname then ( Log.debug (fun m -> m "A renegociation thread already exists for %a." Domain_name.pp hostname) ; Lwt.return_unit ) else ( Hashset.add set hostname ; upgrader (Art.unsafe_key (Domain_name.to_string hostname)) v >>= fun th -> Lwt_condition.signal condition (`Launch th) ; Lwt.return_unit ) Log.err (fun m -> m "The stream of new certificates was done."); Lwt.wakeup_later waker `Stop ; Lwt.return_unit in let first_fill reneg_ths = Lwt_list.iter_s begin fun (hostname, tth) -> Lwt_mutex.with_lock mutex @@ fun () -> Hashset.add set hostname ; tth >>= fun th -> Lwt_condition.signal condition (`Launch th) ; Lwt.return_unit end reneg_ths >|= fun () -> Log.debug (fun m -> m "Threads for valid certificates are launched!"); in Lwt.join [ first_fill reneg_ths; launch_jobs (); fill_jobs () ] >>= fun () -> Lwt_switch.turn_off https let start _random _time () () stackv4v6 alpn ctx = let http = Lwt_mutex.create () in let cfg = { Contruno.production= Key_gen.production () ; email= Option.bind (Key_gen.email ()) (R.to_option <.> Emile.of_string) ; account_seed= Key_gen.account_seed () ; certificate_seed= Key_gen.certificate_seed () } in let remote = Key_gen.remote () in let stream, push = Lwt_stream.create () in initialize http ~ctx ~remote cfg alpn stackv4v6 >>= fun (conns, tree, reneg_ths, `Upgrader upgrader) -> let service = serve conns tree (Stack.tcp stackv4v6) in add_hook ~pass:(Key_gen.pass ()) ~ctx ~remote tree push stackv4v6 ; init ~port:443 stackv4v6 >>= fun stack -> let stop = Lwt_switch.create () in let `Initialized th = Paf.serve ~stop service stack in Lwt.both (launch_reneg_ths ~stop ~upgrader reneg_ths stream) (Lwt.both th (Stack.listen stackv4v6)) >>= fun ((), ((), ())) -> Lwt.return_unit end
481b62b8aa04485a8f9e3274971da89530b724e087376bc218754999875d621c
caribou/caribou-core
validation.clj
(ns caribou.validation (:require [caribou.field :as field])) (defn recursive-merge [a b] (merge-with recursive-merge a b)) (defn beams [slug opts] "verify that the given options make sense for the model given by the slug" (let [model (field/models (keyword slug))] (when-not model (throw (new Exception (format "no such model: %s" slug)))) (doseq [include (recursive-merge (get opts :where) (get opts :include))] (let [[included payload] include included-field (get (:fields model) included) new-opts (and payload {:where payload})] (when-not included-field (throw (new Exception (str "field '" included "' not found in model " (:slug model))))) (and new-opts (field/validate included-field new-opts)) true)))) (defn throw-not-link [field-type opts] (throw (new Exception (str "field of type " field-type " is not a link type so cannot be included." " As requested in opts: " opts)))) (defn for-type [this opts predicate type-string] (when (seq (:include opts)) (throw-not-link type-string opts)) (let [condition (:where opts)] (when (not (some identity (map apply [predicate (fn [s] (and (string? s) (predicate (read-string s))))] (repeat [condition])))) (if (map? (:where opts)) (throw-not-link type-string opts) (throw (new Exception (str "cannot make a " type-string " from " condition)))))) true) (defn for-asset [this opts] true) (defn for-address [this opts] true) (defn for-associated-id [this id-field opts] (let [slug (-> this :row id-field (field/models) :slug)] (beams slug opts))) ( defn for - part ;; [this opts models] ;; (for-associated-id this :model-id opts models)) (defn for-assoc [this opts] (for-associated-id this :target-id opts))
null
https://raw.githubusercontent.com/caribou/caribou-core/6ebd9db4e14cddb1d6b4e152e771e016fa9c55f6/src/caribou/validation.clj
clojure
[this opts models] (for-associated-id this :model-id opts models))
(ns caribou.validation (:require [caribou.field :as field])) (defn recursive-merge [a b] (merge-with recursive-merge a b)) (defn beams [slug opts] "verify that the given options make sense for the model given by the slug" (let [model (field/models (keyword slug))] (when-not model (throw (new Exception (format "no such model: %s" slug)))) (doseq [include (recursive-merge (get opts :where) (get opts :include))] (let [[included payload] include included-field (get (:fields model) included) new-opts (and payload {:where payload})] (when-not included-field (throw (new Exception (str "field '" included "' not found in model " (:slug model))))) (and new-opts (field/validate included-field new-opts)) true)))) (defn throw-not-link [field-type opts] (throw (new Exception (str "field of type " field-type " is not a link type so cannot be included." " As requested in opts: " opts)))) (defn for-type [this opts predicate type-string] (when (seq (:include opts)) (throw-not-link type-string opts)) (let [condition (:where opts)] (when (not (some identity (map apply [predicate (fn [s] (and (string? s) (predicate (read-string s))))] (repeat [condition])))) (if (map? (:where opts)) (throw-not-link type-string opts) (throw (new Exception (str "cannot make a " type-string " from " condition)))))) true) (defn for-asset [this opts] true) (defn for-address [this opts] true) (defn for-associated-id [this id-field opts] (let [slug (-> this :row id-field (field/models) :slug)] (beams slug opts))) ( defn for - part (defn for-assoc [this opts] (for-associated-id this :target-id opts))
85282efb9fd17dca14debaa5971aa25f99f899e1dc372148c7ff628423fa14ee
facebook/infer
Utils.ml
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * 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) 2009-2013, Monoidics ltd. * 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 PolyVariantEqual module F = Format module Hashtbl = Caml.Hashtbl module L = Die let fold_file_tree ~init ~f_dir ~f_reg ~path = let rec traverse_dir_aux acc dir_path = let aux base_path acc' rel_path = let full_path = base_path ^/ rel_path in match (Unix.stat full_path).st_kind with | S_DIR -> traverse_dir_aux (f_dir acc' full_path) full_path | S_REG -> f_reg acc' full_path | _ -> acc' | exception Unix.Unix_error (ENOENT, _, _) -> acc' in Sys.fold_dir ~init:acc ~f:(aux dir_path) dir_path in traverse_dir_aux init path let fold_folders ~init ~f ~path = let f_reg acc _ignore_reg = acc in fold_file_tree ~init ~f_dir:f ~f_reg ~path let fold_files ~init ~f ~path = let f_dir acc _ignore_dir = acc in fold_file_tree ~init ~f_dir ~f_reg:f ~path (** recursively find all files in [path] with names ending in [extension] *) let find_files ~path ~extension = let f_dir acc _ignore_dir = acc in let f_reg acc path = if Filename.check_suffix path extension then path :: acc else acc in fold_file_tree ~init:[] ~f_dir ~f_reg ~path (** read a source file and return a list of lines, or None in case of error *) let read_file fname = let res = ref [] in let cin_ref = ref None in let cleanup () = match !cin_ref with None -> () | Some cin -> In_channel.close cin in try let cin = In_channel.create fname in cin_ref := Some cin ; while true do let line = In_channel.input_line_exn cin in res := line :: !res done ; assert false with | End_of_file -> cleanup () ; Ok (List.rev !res) | Sys_error error -> cleanup () ; Error error (** type for files used for printing *) type outfile = { fname: string (** name of the file *) ; out_c: Out_channel.t (** output channel *) ; fmt: F.formatter (** formatter for printing *) } (** create an outfile for the command line *) let create_outfile fname = try let out_c = Out_channel.create fname in let fmt = F.formatter_of_out_channel out_c in Some {fname; out_c; fmt} with Sys_error _ -> F.fprintf F.err_formatter "error: cannot create file %s@." fname ; None (** close an outfile *) let close_outf outf = Out_channel.close outf.out_c let normalize_path_from ~root fname = let add_entry (rev_done, rev_root) entry = match (entry, rev_done, rev_root) with | ".", _, _ -> (* path/. --> path *) (rev_done, rev_root) | "..", [], ["/"] | "..", ["/"], _ -> (* /.. -> / *) (rev_done, rev_root) | "..", [], ("." | "..") :: _ | "..", ("." | "..") :: _, _ -> (* id on {.,..}/.. *) (entry :: rev_done, rev_root) | "..", [], _ :: rev_root_parent -> (* eat from the root part if it's not / *) ([], rev_root_parent) | "..", _ :: rev_done_parent, _ -> (* path/dir/.. --> path *) (rev_done_parent, rev_root) | _ -> (entry :: rev_done, rev_root) in let rev_root = (* Remove the leading "." inserted by [Filename.parts] on relative paths. We don't need to do that for [Filename.parts fname] because the "." will go away during normalization in [add_entry]. *) let root_without_leading_dot = match Filename.parts root with "." :: (_ :: _ as rest) -> rest | parts -> parts in List.rev root_without_leading_dot in let rev_result, rev_root = Filename.parts fname |> List.fold ~init:([], rev_root) ~f:add_entry in do n't use [ Filename.of_parts ] because it does n't like empty lists and produces relative paths " ./like / this " instead of " like / this " "./like/this" instead of "like/this" *) let filename_of_rev_parts = function | [] -> "." | _ :: _ as rev_parts -> let parts = List.rev rev_parts in if String.equal (List.hd_exn parts) "/" then "/" ^ String.concat ~sep:Filename.dir_sep (List.tl_exn parts) else String.concat ~sep:Filename.dir_sep parts in (filename_of_rev_parts rev_result, filename_of_rev_parts rev_root) let normalize_path fname = fname |> normalize_path_from ~root:"." |> fst (** Convert a filename to an absolute one if it is relative, and normalize "." and ".." *) let filename_to_absolute ~root fname = let abs_fname = if Filename.is_absolute fname then fname else root ^/ fname in normalize_path_from ~root:"/" abs_fname |> fst * Convert an absolute filename to one relative to the given directory . let filename_to_relative ?(force_full_backtrack = false) ?(backtrack = 0) ~root fname = let rec relativize_if_under origin target = match (origin, target) with | x :: xs, y :: ys when String.equal x y -> relativize_if_under xs ys | _ :: _, _ when force_full_backtrack || backtrack >= List.length origin -> let parent_dir = List.init (List.length origin) ~f:(fun _ -> Filename.parent_dir_name) in Some (Filename.of_parts (parent_dir @ target)) | [], [] -> Some "." | [], ys -> Some (Filename.of_parts ys) | _ -> None in relativize_if_under (Filename.parts root) (Filename.parts fname) let directory_fold f init path = let collect current_dir (accu, dirs) path = let full_path = current_dir ^/ path in try if Sys.is_directory full_path = `Yes then (accu, full_path :: dirs) else (f accu full_path, dirs) with Sys_error _ -> (accu, dirs) in let rec loop accu dirs = match dirs with | [] -> accu | d :: tl -> let new_accu, new_dirs = Array.fold ~f:(collect d) ~init:(accu, tl) (Sys.readdir d) in loop new_accu new_dirs in if Sys.is_directory path = `Yes then loop init [path] else f init path let directory_iter f path = let apply current_dir dirs path = let full_path = current_dir ^/ path in try if Sys.is_directory full_path = `Yes then full_path :: dirs else let () = f full_path in dirs with Sys_error _ -> dirs in let rec loop dirs = match dirs with | [] -> () | d :: tl -> let new_dirs = Array.fold ~f:(apply d) ~init:tl (Sys.readdir d) in loop new_dirs in if Sys.is_directory path = `Yes then loop [path] else f path let directory_is_empty path = Sys.readdir path |> Array.is_empty let string_crc_hex32 s = Caml.Digest.to_hex (Caml.Digest.string s) let read_json_file path = try Ok (Yojson.Basic.from_file path) with Sys_error msg | Yojson.Json_error msg -> Error msg let read_safe_json_file path = try Ok (Yojson.Safe.from_file path) with Sys_error msg | Yojson.Json_error msg -> Error msg let do_finally_swallow_timeout ~f ~finally = let res_finally = ref None in let finally () = res_finally := Some (finally ()) in let res = Exception.try_finally ~f ~finally in (res, Option.value_exn !res_finally) let with_file_in file ~f = let ic = In_channel.create file in let f () = f ic in let finally () = In_channel.close ic in Exception.try_finally ~f ~finally let with_file_out ?append file ~f = let oc = Out_channel.create ?append file in let f () = f oc in let finally () = Out_channel.close oc in Exception.try_finally ~f ~finally let with_intermediate_temp_file_out file ~f = let temp_filename, temp_oc = Filename.open_temp_file ~in_dir:(Filename.dirname file) "infer" "" in let f () = f temp_oc in let finally () = Out_channel.close temp_oc ; Unix.rename ~src:temp_filename ~dst:file in Exception.try_finally ~f ~finally let write_json_to_file destfile json = with_file_out destfile ~f:(fun oc -> Yojson.Basic.pretty_to_channel oc json) let with_channel_in ~f chan_in = try while true do f @@ In_channel.input_line_exn chan_in done with End_of_file -> () let consume_in chan_in = with_channel_in ~f:ignore chan_in let echo_in chan_in = with_channel_in ~f:print_endline chan_in let with_process_in command read = let chan = Unix.open_process_in command in let f () = read chan in let finally () = consume_in chan ; Unix.close_process_in chan in do_finally_swallow_timeout ~f ~finally let is_dir_kind (kind : Unix.file_kind) = match kind with S_DIR -> true | _ -> false (** Recursively create a directory if it does not exist already. *) let create_dir dir = try if not (is_dir_kind (Unix.stat dir).Unix.st_kind) then L.(die ExternalError) "file '%s' already exists and is not a directory" dir with Unix.Unix_error _ -> ( try Unix.mkdir_p dir ~perm:0o700 with Unix.Unix_error _ -> let created_concurrently = (* check if another process created it meanwhile *) try Poly.equal (Unix.stat dir).Unix.st_kind Unix.S_DIR with Unix.Unix_error _ -> false in if not created_concurrently then L.(die ExternalError) "cannot create directory '%s'" dir ) let out_channel_create_with_dir fname = try Out_channel.create fname with Sys_error _ -> Unix.mkdir_p ~perm:0o700 (Filename.dirname fname) ; Out_channel.create fname let realpath_cache = Hashtbl.create 1023 let realpath ?(warn_on_error = true) path = match Hashtbl.find realpath_cache path with | exception Caml.Not_found -> ( match Filename.realpath path with | realpath -> Hashtbl.add realpath_cache path (Ok realpath) ; realpath | exception (Unix.Unix_error (code, _, arg) as exn) -> IExn.reraise_after exn ~f:(fun () -> if warn_on_error then F.eprintf "WARNING: Failed to resolve file %s with \"%s\" @\n@." arg (Unix.Error.message code) ; (* cache failures as well *) Hashtbl.add realpath_cache path (Error exn) ) ) | Ok path -> path | Error exn -> raise exn (* never closed *) let devnull = lazy (Unix.openfile "/dev/null" ~mode:[O_WRONLY]) let suppress_stderr2 f2 x1 x2 = let restore_stderr src = Unix.dup2 ~src ~dst:Unix.stderr () ; Unix.close src in let orig_stderr = Unix.dup Unix.stderr in Unix.dup2 ~src:(Lazy.force devnull) ~dst:Unix.stderr () ; let f () = f2 x1 x2 in let finally () = restore_stderr orig_stderr in protect ~f ~finally let rec rmtree name = match Unix.((lstat name).st_kind) with | S_DIR -> let dir = Unix.opendir name in let rec rmdir dir = match Unix.readdir_opt dir with | Some entry -> if not ( String.equal entry Filename.current_dir_name || String.equal entry Filename.parent_dir_name ) then rmtree (name ^/ entry) ; rmdir dir | None -> Unix.closedir dir ; Unix.rmdir name in rmdir dir | _ -> Unix.unlink name | exception Unix.Unix_error (ENOENT, _, _) -> () let better_hash x = Marshal.to_string x [Marshal.No_sharing] |> Caml.Digest.string let unlink_file_on_exit temp_file = let description = "Cleaning temporary file " ^ temp_file in Epilogues.register ~description ~f:(fun () -> try Unix.unlink temp_file with _ -> ()) * drop at most one layer of well - balanced first and last characters satisfying [ drop ] from the string ; for instance , [ strip_balanced ~drop:(function | ' a ' | ' x ' - > true | _ - > false ) " xaabax " ] returns " aaba " string; for instance, [strip_balanced ~drop:(function | 'a' | 'x' -> true | _ -> false) "xaabax"] returns "aaba" *) let strip_balanced_once ~drop s = let n = String.length s in if n < 2 then s else let first = String.unsafe_get s 0 in if Char.equal first (String.unsafe_get s (n - 1)) && drop first then String.slice s 1 (n - 1) else s let die_expected_yojson_type expected yojson_obj ~src ~example = let eg = if String.equal example "" then "" else " (e.g. '" ^ example ^ "')" in Die.die UserError "in %s expected json %s%s not %s" src expected eg (Yojson.Basic.to_string yojson_obj) let assoc_of_yojson yojson_obj ~src = match yojson_obj with | `Assoc assoc -> assoc | `List [] -> (* missing entries in config reported as empty list *) [] | _ -> die_expected_yojson_type "object" yojson_obj ~example:"{ \"foo\": \"bar\" }" ~src let string_of_yojson yojson_obj ~src = match yojson_obj with | `String str -> str | _ -> die_expected_yojson_type "string" yojson_obj ~example:"\"foo\"" ~src let list_of_yojson yojson_obj ~src = match yojson_obj with | `List list -> list | _ -> die_expected_yojson_type "list" yojson_obj ~example:"[ \"foo\", \"bar\" ]" ~src let string_list_of_yojson yojson_obj ~src = List.map ~f:(string_of_yojson ~src) (list_of_yojson yojson_obj ~src) let yojson_lookup yojson_assoc elt_name ~src ~f ~default = let src = src ^ " -> " ^ elt_name in Option.value_map ~default ~f:(fun res -> f res ~src) (List.Assoc.find ~equal:String.equal yojson_assoc elt_name) let timeit ~f = let start_time = Mtime_clock.counter () in let ret_val = f () in let duration_ms = Mtime_clock.count start_time |> IMtime.span_to_ms_int in (ret_val, duration_ms) let do_in_dir ~dir ~f = let cwd = Unix.getcwd () in Unix.chdir dir ; Exception.try_finally ~f ~finally:(fun () -> Unix.chdir cwd) let get_available_memory_MB () = let proc_meminfo = "/proc/meminfo" in let rec scan_for_expected_output in_channel = match In_channel.input_line in_channel with | None -> None | Some line -> ( try Scanf.sscanf line "MemAvailable: %u kB" (fun mem_kB -> Some (mem_kB / 1024)) with Scanf.Scan_failure _ -> scan_for_expected_output in_channel ) in if not (ISys.file_exists proc_meminfo) then None else with_file_in proc_meminfo ~f:scan_for_expected_output let iter_infer_deps ~root ~f infer_deps_file = let one_line line = match String.split ~on:'\t' line with | [_; _; target_results_dir] -> let infer_out_src = if Filename.is_relative target_results_dir then Filename.dirname (root ^/ target_results_dir) else target_results_dir in f infer_out_src | _ -> Die.die InternalError "Couldn't parse deps file '%s', line: %s" infer_deps_file line in match read_file infer_deps_file with | Ok lines -> List.iter ~f:one_line lines | Error error -> Die.die InternalError "Couldn't read deps file '%s': %s" infer_deps_file error let inline_argument_files args = let expand_arg arg = if String.is_prefix ~prefix:"@" arg then let file_name = String.chop_prefix_exn ~prefix:"@" arg in if not (ISys.file_exists file_name) then [arg] (* Arguments that start with @ could mean something different than an arguments file *) else let expanded_args = try with_file_in file_name ~f:In_channel.input_lines with exn -> Die.die UserError "Could not read from file '%s': %a@\n" file_name Exn.pp exn in expanded_args else [arg] in List.concat_map ~f:expand_arg args let physical_cores () = with_file_in "/proc/cpuinfo" ~f:(fun ic -> let physical_or_core_regxp = Re.Str.regexp "\\(physical id\\|core id\\)[^0-9]+\\([0-9]+\\).*" in let rec loop sockets cores = match In_channel.input_line ~fix_win_eol:true ic with | None -> let physical_cores = Int.Set.length sockets * Int.Set.length cores in if physical_cores <= 0 then None else Some physical_cores | Some line when Re.Str.string_match physical_or_core_regxp line 0 -> ( let value = Re.Str.matched_group 2 line |> int_of_string in match Re.Str.matched_group 1 line with | "physical id" -> loop (Int.Set.add sockets value) cores | "core id" -> loop sockets (Int.Set.add cores value) | _ -> (* cannot happen thanks to the regexp *) L.die InternalError "Couldn't parse line '%s' from /proc/cpuinfo." line ) | Some _ -> loop sockets cores in loop Int.Set.empty Int.Set.empty ) let cpus = Setcore.numcores () let numcores = let default = cpus / 2 in match Version.build_platform with | Darwin | Windows -> default | Linux -> physical_cores () |> Option.value ~default let zip_fold_filenames ~init ~f ~zip_filename = let file_in = Zip.open_in zip_filename in let collect acc (entry : Zip.entry) = f acc entry.filename in let result = List.fold ~f:collect ~init (Zip.entries file_in) in Zip.close_in file_in ; result let is_term_dumb () = match Sys.getenv "TERM" with | Some kind when String.(equal "dumb" (lowercase kind)) -> true | _ -> false
null
https://raw.githubusercontent.com/facebook/infer/6386e1383f0a95e369f58ff07626f367fcbaad5e/infer/src/base/Utils.ml
ocaml
* recursively find all files in [path] with names ending in [extension] * read a source file and return a list of lines, or None in case of error * type for files used for printing * name of the file * output channel * formatter for printing * create an outfile for the command line * close an outfile path/. --> path /.. -> / id on {.,..}/.. eat from the root part if it's not / path/dir/.. --> path Remove the leading "." inserted by [Filename.parts] on relative paths. We don't need to do that for [Filename.parts fname] because the "." will go away during normalization in [add_entry]. * Convert a filename to an absolute one if it is relative, and normalize "." and ".." * Recursively create a directory if it does not exist already. check if another process created it meanwhile cache failures as well never closed missing entries in config reported as empty list Arguments that start with @ could mean something different than an arguments file cannot happen thanks to the regexp
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * 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) 2009-2013, Monoidics ltd. * 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 PolyVariantEqual module F = Format module Hashtbl = Caml.Hashtbl module L = Die let fold_file_tree ~init ~f_dir ~f_reg ~path = let rec traverse_dir_aux acc dir_path = let aux base_path acc' rel_path = let full_path = base_path ^/ rel_path in match (Unix.stat full_path).st_kind with | S_DIR -> traverse_dir_aux (f_dir acc' full_path) full_path | S_REG -> f_reg acc' full_path | _ -> acc' | exception Unix.Unix_error (ENOENT, _, _) -> acc' in Sys.fold_dir ~init:acc ~f:(aux dir_path) dir_path in traverse_dir_aux init path let fold_folders ~init ~f ~path = let f_reg acc _ignore_reg = acc in fold_file_tree ~init ~f_dir:f ~f_reg ~path let fold_files ~init ~f ~path = let f_dir acc _ignore_dir = acc in fold_file_tree ~init ~f_dir ~f_reg:f ~path let find_files ~path ~extension = let f_dir acc _ignore_dir = acc in let f_reg acc path = if Filename.check_suffix path extension then path :: acc else acc in fold_file_tree ~init:[] ~f_dir ~f_reg ~path let read_file fname = let res = ref [] in let cin_ref = ref None in let cleanup () = match !cin_ref with None -> () | Some cin -> In_channel.close cin in try let cin = In_channel.create fname in cin_ref := Some cin ; while true do let line = In_channel.input_line_exn cin in res := line :: !res done ; assert false with | End_of_file -> cleanup () ; Ok (List.rev !res) | Sys_error error -> cleanup () ; Error error type outfile = let create_outfile fname = try let out_c = Out_channel.create fname in let fmt = F.formatter_of_out_channel out_c in Some {fname; out_c; fmt} with Sys_error _ -> F.fprintf F.err_formatter "error: cannot create file %s@." fname ; None let close_outf outf = Out_channel.close outf.out_c let normalize_path_from ~root fname = let add_entry (rev_done, rev_root) entry = match (entry, rev_done, rev_root) with | ".", _, _ -> (rev_done, rev_root) | "..", [], ["/"] | "..", ["/"], _ -> (rev_done, rev_root) | "..", [], ("." | "..") :: _ | "..", ("." | "..") :: _, _ -> (entry :: rev_done, rev_root) | "..", [], _ :: rev_root_parent -> ([], rev_root_parent) | "..", _ :: rev_done_parent, _ -> (rev_done_parent, rev_root) | _ -> (entry :: rev_done, rev_root) in let rev_root = let root_without_leading_dot = match Filename.parts root with "." :: (_ :: _ as rest) -> rest | parts -> parts in List.rev root_without_leading_dot in let rev_result, rev_root = Filename.parts fname |> List.fold ~init:([], rev_root) ~f:add_entry in do n't use [ Filename.of_parts ] because it does n't like empty lists and produces relative paths " ./like / this " instead of " like / this " "./like/this" instead of "like/this" *) let filename_of_rev_parts = function | [] -> "." | _ :: _ as rev_parts -> let parts = List.rev rev_parts in if String.equal (List.hd_exn parts) "/" then "/" ^ String.concat ~sep:Filename.dir_sep (List.tl_exn parts) else String.concat ~sep:Filename.dir_sep parts in (filename_of_rev_parts rev_result, filename_of_rev_parts rev_root) let normalize_path fname = fname |> normalize_path_from ~root:"." |> fst let filename_to_absolute ~root fname = let abs_fname = if Filename.is_absolute fname then fname else root ^/ fname in normalize_path_from ~root:"/" abs_fname |> fst * Convert an absolute filename to one relative to the given directory . let filename_to_relative ?(force_full_backtrack = false) ?(backtrack = 0) ~root fname = let rec relativize_if_under origin target = match (origin, target) with | x :: xs, y :: ys when String.equal x y -> relativize_if_under xs ys | _ :: _, _ when force_full_backtrack || backtrack >= List.length origin -> let parent_dir = List.init (List.length origin) ~f:(fun _ -> Filename.parent_dir_name) in Some (Filename.of_parts (parent_dir @ target)) | [], [] -> Some "." | [], ys -> Some (Filename.of_parts ys) | _ -> None in relativize_if_under (Filename.parts root) (Filename.parts fname) let directory_fold f init path = let collect current_dir (accu, dirs) path = let full_path = current_dir ^/ path in try if Sys.is_directory full_path = `Yes then (accu, full_path :: dirs) else (f accu full_path, dirs) with Sys_error _ -> (accu, dirs) in let rec loop accu dirs = match dirs with | [] -> accu | d :: tl -> let new_accu, new_dirs = Array.fold ~f:(collect d) ~init:(accu, tl) (Sys.readdir d) in loop new_accu new_dirs in if Sys.is_directory path = `Yes then loop init [path] else f init path let directory_iter f path = let apply current_dir dirs path = let full_path = current_dir ^/ path in try if Sys.is_directory full_path = `Yes then full_path :: dirs else let () = f full_path in dirs with Sys_error _ -> dirs in let rec loop dirs = match dirs with | [] -> () | d :: tl -> let new_dirs = Array.fold ~f:(apply d) ~init:tl (Sys.readdir d) in loop new_dirs in if Sys.is_directory path = `Yes then loop [path] else f path let directory_is_empty path = Sys.readdir path |> Array.is_empty let string_crc_hex32 s = Caml.Digest.to_hex (Caml.Digest.string s) let read_json_file path = try Ok (Yojson.Basic.from_file path) with Sys_error msg | Yojson.Json_error msg -> Error msg let read_safe_json_file path = try Ok (Yojson.Safe.from_file path) with Sys_error msg | Yojson.Json_error msg -> Error msg let do_finally_swallow_timeout ~f ~finally = let res_finally = ref None in let finally () = res_finally := Some (finally ()) in let res = Exception.try_finally ~f ~finally in (res, Option.value_exn !res_finally) let with_file_in file ~f = let ic = In_channel.create file in let f () = f ic in let finally () = In_channel.close ic in Exception.try_finally ~f ~finally let with_file_out ?append file ~f = let oc = Out_channel.create ?append file in let f () = f oc in let finally () = Out_channel.close oc in Exception.try_finally ~f ~finally let with_intermediate_temp_file_out file ~f = let temp_filename, temp_oc = Filename.open_temp_file ~in_dir:(Filename.dirname file) "infer" "" in let f () = f temp_oc in let finally () = Out_channel.close temp_oc ; Unix.rename ~src:temp_filename ~dst:file in Exception.try_finally ~f ~finally let write_json_to_file destfile json = with_file_out destfile ~f:(fun oc -> Yojson.Basic.pretty_to_channel oc json) let with_channel_in ~f chan_in = try while true do f @@ In_channel.input_line_exn chan_in done with End_of_file -> () let consume_in chan_in = with_channel_in ~f:ignore chan_in let echo_in chan_in = with_channel_in ~f:print_endline chan_in let with_process_in command read = let chan = Unix.open_process_in command in let f () = read chan in let finally () = consume_in chan ; Unix.close_process_in chan in do_finally_swallow_timeout ~f ~finally let is_dir_kind (kind : Unix.file_kind) = match kind with S_DIR -> true | _ -> false let create_dir dir = try if not (is_dir_kind (Unix.stat dir).Unix.st_kind) then L.(die ExternalError) "file '%s' already exists and is not a directory" dir with Unix.Unix_error _ -> ( try Unix.mkdir_p dir ~perm:0o700 with Unix.Unix_error _ -> let created_concurrently = try Poly.equal (Unix.stat dir).Unix.st_kind Unix.S_DIR with Unix.Unix_error _ -> false in if not created_concurrently then L.(die ExternalError) "cannot create directory '%s'" dir ) let out_channel_create_with_dir fname = try Out_channel.create fname with Sys_error _ -> Unix.mkdir_p ~perm:0o700 (Filename.dirname fname) ; Out_channel.create fname let realpath_cache = Hashtbl.create 1023 let realpath ?(warn_on_error = true) path = match Hashtbl.find realpath_cache path with | exception Caml.Not_found -> ( match Filename.realpath path with | realpath -> Hashtbl.add realpath_cache path (Ok realpath) ; realpath | exception (Unix.Unix_error (code, _, arg) as exn) -> IExn.reraise_after exn ~f:(fun () -> if warn_on_error then F.eprintf "WARNING: Failed to resolve file %s with \"%s\" @\n@." arg (Unix.Error.message code) ; Hashtbl.add realpath_cache path (Error exn) ) ) | Ok path -> path | Error exn -> raise exn let devnull = lazy (Unix.openfile "/dev/null" ~mode:[O_WRONLY]) let suppress_stderr2 f2 x1 x2 = let restore_stderr src = Unix.dup2 ~src ~dst:Unix.stderr () ; Unix.close src in let orig_stderr = Unix.dup Unix.stderr in Unix.dup2 ~src:(Lazy.force devnull) ~dst:Unix.stderr () ; let f () = f2 x1 x2 in let finally () = restore_stderr orig_stderr in protect ~f ~finally let rec rmtree name = match Unix.((lstat name).st_kind) with | S_DIR -> let dir = Unix.opendir name in let rec rmdir dir = match Unix.readdir_opt dir with | Some entry -> if not ( String.equal entry Filename.current_dir_name || String.equal entry Filename.parent_dir_name ) then rmtree (name ^/ entry) ; rmdir dir | None -> Unix.closedir dir ; Unix.rmdir name in rmdir dir | _ -> Unix.unlink name | exception Unix.Unix_error (ENOENT, _, _) -> () let better_hash x = Marshal.to_string x [Marshal.No_sharing] |> Caml.Digest.string let unlink_file_on_exit temp_file = let description = "Cleaning temporary file " ^ temp_file in Epilogues.register ~description ~f:(fun () -> try Unix.unlink temp_file with _ -> ()) * drop at most one layer of well - balanced first and last characters satisfying [ drop ] from the string ; for instance , [ strip_balanced ~drop:(function | ' a ' | ' x ' - > true | _ - > false ) " xaabax " ] returns " aaba " string; for instance, [strip_balanced ~drop:(function | 'a' | 'x' -> true | _ -> false) "xaabax"] returns "aaba" *) let strip_balanced_once ~drop s = let n = String.length s in if n < 2 then s else let first = String.unsafe_get s 0 in if Char.equal first (String.unsafe_get s (n - 1)) && drop first then String.slice s 1 (n - 1) else s let die_expected_yojson_type expected yojson_obj ~src ~example = let eg = if String.equal example "" then "" else " (e.g. '" ^ example ^ "')" in Die.die UserError "in %s expected json %s%s not %s" src expected eg (Yojson.Basic.to_string yojson_obj) let assoc_of_yojson yojson_obj ~src = match yojson_obj with | `Assoc assoc -> assoc | `List [] -> [] | _ -> die_expected_yojson_type "object" yojson_obj ~example:"{ \"foo\": \"bar\" }" ~src let string_of_yojson yojson_obj ~src = match yojson_obj with | `String str -> str | _ -> die_expected_yojson_type "string" yojson_obj ~example:"\"foo\"" ~src let list_of_yojson yojson_obj ~src = match yojson_obj with | `List list -> list | _ -> die_expected_yojson_type "list" yojson_obj ~example:"[ \"foo\", \"bar\" ]" ~src let string_list_of_yojson yojson_obj ~src = List.map ~f:(string_of_yojson ~src) (list_of_yojson yojson_obj ~src) let yojson_lookup yojson_assoc elt_name ~src ~f ~default = let src = src ^ " -> " ^ elt_name in Option.value_map ~default ~f:(fun res -> f res ~src) (List.Assoc.find ~equal:String.equal yojson_assoc elt_name) let timeit ~f = let start_time = Mtime_clock.counter () in let ret_val = f () in let duration_ms = Mtime_clock.count start_time |> IMtime.span_to_ms_int in (ret_val, duration_ms) let do_in_dir ~dir ~f = let cwd = Unix.getcwd () in Unix.chdir dir ; Exception.try_finally ~f ~finally:(fun () -> Unix.chdir cwd) let get_available_memory_MB () = let proc_meminfo = "/proc/meminfo" in let rec scan_for_expected_output in_channel = match In_channel.input_line in_channel with | None -> None | Some line -> ( try Scanf.sscanf line "MemAvailable: %u kB" (fun mem_kB -> Some (mem_kB / 1024)) with Scanf.Scan_failure _ -> scan_for_expected_output in_channel ) in if not (ISys.file_exists proc_meminfo) then None else with_file_in proc_meminfo ~f:scan_for_expected_output let iter_infer_deps ~root ~f infer_deps_file = let one_line line = match String.split ~on:'\t' line with | [_; _; target_results_dir] -> let infer_out_src = if Filename.is_relative target_results_dir then Filename.dirname (root ^/ target_results_dir) else target_results_dir in f infer_out_src | _ -> Die.die InternalError "Couldn't parse deps file '%s', line: %s" infer_deps_file line in match read_file infer_deps_file with | Ok lines -> List.iter ~f:one_line lines | Error error -> Die.die InternalError "Couldn't read deps file '%s': %s" infer_deps_file error let inline_argument_files args = let expand_arg arg = if String.is_prefix ~prefix:"@" arg then let file_name = String.chop_prefix_exn ~prefix:"@" arg in if not (ISys.file_exists file_name) then [arg] else let expanded_args = try with_file_in file_name ~f:In_channel.input_lines with exn -> Die.die UserError "Could not read from file '%s': %a@\n" file_name Exn.pp exn in expanded_args else [arg] in List.concat_map ~f:expand_arg args let physical_cores () = with_file_in "/proc/cpuinfo" ~f:(fun ic -> let physical_or_core_regxp = Re.Str.regexp "\\(physical id\\|core id\\)[^0-9]+\\([0-9]+\\).*" in let rec loop sockets cores = match In_channel.input_line ~fix_win_eol:true ic with | None -> let physical_cores = Int.Set.length sockets * Int.Set.length cores in if physical_cores <= 0 then None else Some physical_cores | Some line when Re.Str.string_match physical_or_core_regxp line 0 -> ( let value = Re.Str.matched_group 2 line |> int_of_string in match Re.Str.matched_group 1 line with | "physical id" -> loop (Int.Set.add sockets value) cores | "core id" -> loop sockets (Int.Set.add cores value) | _ -> L.die InternalError "Couldn't parse line '%s' from /proc/cpuinfo." line ) | Some _ -> loop sockets cores in loop Int.Set.empty Int.Set.empty ) let cpus = Setcore.numcores () let numcores = let default = cpus / 2 in match Version.build_platform with | Darwin | Windows -> default | Linux -> physical_cores () |> Option.value ~default let zip_fold_filenames ~init ~f ~zip_filename = let file_in = Zip.open_in zip_filename in let collect acc (entry : Zip.entry) = f acc entry.filename in let result = List.fold ~f:collect ~init (Zip.entries file_in) in Zip.close_in file_in ; result let is_term_dumb () = match Sys.getenv "TERM" with | Some kind when String.(equal "dumb" (lowercase kind)) -> true | _ -> false
999c615c619c917036a3f7a1c57b9df165134aada5324d4568c7432b9de446db
opencog/opencog
demand.scm
; ; demand.scm ; Methods to define and work with demands. ; Copyright ( C ) 2015 - 2016 OpenCog Foundation Copyright ( C ) 2017 MindCloud ; ; Design Notes: Demands are associated with demand values . There are two different , ; conflicting ways in which this is done in the code below: in some ; cases, the value is stored as the mean of the TV; in other cases, the value is a NumberNode attached to the ConceptNode . Having two places ; to store this info is just asking for hard-to-find bugs to pop up. ; The long-term solution is probably to associate the value to the ; demand using a protoatom[now renamed value]. (use-modules (rnrs sorting)) ; For sorting demands by their values. (use-modules (srfi srfi-1)) ; for `lset-difference` (use-modules (opencog) (opencog exec) (opencog ure)) (load "utilities.scm") ; -------------------------------------------------------------- (define psi-demand-node (ConceptNode (string-append psi-prefix-str "demand"))) ; -------------------------------------------------------------- ; A cache of the demands, used to improve performance. (define psi-demand-cache '()) ; -------------------------------------------------------------- ; reset the cache (define (clear-demand-cache) (set! psi-demand-cache '()) ) (define (make-demand-cache) ; Get the set of demands that are currently disabled. (define skip-set (cog-execute! (GetLink (TypedVariableLink (VariableNode "demand") (TypeNode "ConceptNode")) (AndLink (InheritanceLink (VariableNode "demand") psi-demand-node) (MemberLink (VariableNode "demand") psi-label-skip))) )) ; Compute the list of enabled demands, and cache it. (set! psi-demand-cache (lset-difference! equal? (psi-get-all-demands) (cog-outgoing-set skip-set)) ) Delete the SetLink , so it does not pollute the atomspace . (cog-extract! skip-set) ) ; -------------------------------------------------------------- (define (psi-get-all-demands) " psi-get-all-demands - Return a list of all demand-nodes. " (filter (lambda (x) (not (equal? x psi-demand-node))) (cog-chase-link 'InheritanceLink 'ConceptNode psi-demand-node)) ) ; -------------------------------------------------------------- (define (psi-get-all-enabled-demands) " psi-get-all-enabled-demands - Return list of all demands that are enabled. " (if (nil? psi-demand-cache) (make-demand-cache)) psi-demand-cache ) ; Backwards-compat wrapper (define (psi-get-all-valid-demands) " Do not use this, use psi-get-all-enabled-demands instead " (psi-get-all-enabled-demands)) ; -------------------------------------------------------------- (define (psi-demand NAME) " psi-demand NAME VALUE Create and return a ConceptNode that represents an OpenPsi demand. The NAME should be a string. " (let* ((demand-node (ConceptNode NAME))) (InheritanceLink demand-node psi-demand-node) demand-node ) ) ; -------------------------------------------------------------- (define (psi-demand? node) " psi-demand? NODE - Return #t if NODE is a demand, else return #f. The NODE is a demand only if it was previously added to the set of demands. " (let ((candidates (cog-chase-link 'InheritanceLink 'ConceptNode node))) ; A filter is used to account for empty list as well as ; cog-chase-link returning multiple results, just in case. (not (nil? (filter (lambda (x) (equal? x psi-demand-node)) candidates))) ) ) ; -------------------------------------------------------------- (define (psi-set-demand-value demand-node demand-value) " psi-set-demand-value DEMAND VALUE - Set the DEMAND to VALUE. The DEMAND must be a demand node that was previously declared to the system. The VALUE must be a floating-point number between [0, 1]. " (cog-set-tv! demand-node (stv demand-value (cog-confidence demand-node))) ) ; -------------------------------------------------------------- ; Functions to help define standard action-rules ; -------------------------------------------------------------- (define (psi-demand-value-increase demand-node rate-node) " psi-demand-value-increase DEMAND RATE Increases the strength of DEMAND by the given percentage RATE. RATE must be a NumberNode, holding the percentage change by which the demand-value will be updated with, on each step. " (let* ((strength (cog-mean demand-node)) (rate (/ (cog-number rate-node) 100)) (demand-value (+ strength (* strength rate)))) (psi-set-demand-value demand-node demand-value) (stv 1 1) ) ) ; -------------------------------------------------------------- (define (psi-demand-value-decrease demand-node rate-node) " psi-demand-value-decrease DEMAND RATE Decreases the strength of the demand by the given percentage rate. RATE must be a NumberNode holding the percentage change by which the demand-value will be updated with, on each step. " (let* ((strength (cog-mean demand-node)) (rate (/ (cog-number rate-node) 100)) (demand-value (- strength (* strength rate)))) (psi-set-demand-value demand-node demand-value) (stv 1 1) ) ) ; -------------------------------------------------------------- ; This is used to label a demand for skipping. During actions-selection. (define psi-label-skip (ConceptNode (string-append psi-prefix-str "skip"))) ; -------------------------------------------------------------- (define (psi-demand-skip demand) " psi-demand-skip DEMAND - Disable DEMAND. Use this to disable the DEMAND from being considered during action selection. The DEMAND should be a valid demand node. " ; Check arguments (if (not (psi-demand? demand)) (error (string-append "In procedure psi-demand-skip, expected " "argument to be a node representing a demand, got:") demand)) (MemberLink demand psi-label-skip) (clear-demand-cache) ) ; -------------------------------------------------------------- (define (psi-demand-skip? demand) " psi-demand-skip? DEMAND - return #t if DEMAND should be skipped. " ; Check arguments (if (not (psi-demand? demand)) (error (string-append "In procedure psi-demand-skip?, expected " "argument to be a node representing a demand, got:") demand)) (not (member demand (psi-get-all-enabled-demands))) )
null
https://raw.githubusercontent.com/opencog/opencog/53f2c2c8e26160e3321b399250afb0e3dbc64d4c/opencog/openpsi/demand.scm
scheme
demand.scm Methods to define and work with demands. Design Notes: conflicting ways in which this is done in the code below: in some cases, the value is stored as the mean of the TV; in other cases, the to store this info is just asking for hard-to-find bugs to pop up. The long-term solution is probably to associate the value to the demand using a protoatom[now renamed value]. For sorting demands by their values. for `lset-difference` -------------------------------------------------------------- -------------------------------------------------------------- A cache of the demands, used to improve performance. -------------------------------------------------------------- reset the cache Get the set of demands that are currently disabled. Compute the list of enabled demands, and cache it. -------------------------------------------------------------- -------------------------------------------------------------- Backwards-compat wrapper -------------------------------------------------------------- -------------------------------------------------------------- A filter is used to account for empty list as well as cog-chase-link returning multiple results, just in case. -------------------------------------------------------------- -------------------------------------------------------------- Functions to help define standard action-rules -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- This is used to label a demand for skipping. During actions-selection. -------------------------------------------------------------- Check arguments -------------------------------------------------------------- Check arguments
Copyright ( C ) 2015 - 2016 OpenCog Foundation Copyright ( C ) 2017 MindCloud Demands are associated with demand values . There are two different , value is a NumberNode attached to the ConceptNode . Having two places (use-modules (opencog) (opencog exec) (opencog ure)) (load "utilities.scm") (define psi-demand-node (ConceptNode (string-append psi-prefix-str "demand"))) (define psi-demand-cache '()) (define (clear-demand-cache) (set! psi-demand-cache '()) ) (define (make-demand-cache) (define skip-set (cog-execute! (GetLink (TypedVariableLink (VariableNode "demand") (TypeNode "ConceptNode")) (AndLink (InheritanceLink (VariableNode "demand") psi-demand-node) (MemberLink (VariableNode "demand") psi-label-skip))) )) (set! psi-demand-cache (lset-difference! equal? (psi-get-all-demands) (cog-outgoing-set skip-set)) ) Delete the SetLink , so it does not pollute the atomspace . (cog-extract! skip-set) ) (define (psi-get-all-demands) " psi-get-all-demands - Return a list of all demand-nodes. " (filter (lambda (x) (not (equal? x psi-demand-node))) (cog-chase-link 'InheritanceLink 'ConceptNode psi-demand-node)) ) (define (psi-get-all-enabled-demands) " psi-get-all-enabled-demands - Return list of all demands that are enabled. " (if (nil? psi-demand-cache) (make-demand-cache)) psi-demand-cache ) (define (psi-get-all-valid-demands) " Do not use this, use psi-get-all-enabled-demands instead " (psi-get-all-enabled-demands)) (define (psi-demand NAME) " psi-demand NAME VALUE Create and return a ConceptNode that represents an OpenPsi demand. The NAME should be a string. " (let* ((demand-node (ConceptNode NAME))) (InheritanceLink demand-node psi-demand-node) demand-node ) ) (define (psi-demand? node) " psi-demand? NODE - Return #t if NODE is a demand, else return #f. The NODE is a demand only if it was previously added to the set of demands. " (let ((candidates (cog-chase-link 'InheritanceLink 'ConceptNode node))) (not (nil? (filter (lambda (x) (equal? x psi-demand-node)) candidates))) ) ) (define (psi-set-demand-value demand-node demand-value) " psi-set-demand-value DEMAND VALUE - Set the DEMAND to VALUE. The DEMAND must be a demand node that was previously declared to the system. The VALUE must be a floating-point number between [0, 1]. " (cog-set-tv! demand-node (stv demand-value (cog-confidence demand-node))) ) (define (psi-demand-value-increase demand-node rate-node) " psi-demand-value-increase DEMAND RATE Increases the strength of DEMAND by the given percentage RATE. RATE must be a NumberNode, holding the percentage change by which the demand-value will be updated with, on each step. " (let* ((strength (cog-mean demand-node)) (rate (/ (cog-number rate-node) 100)) (demand-value (+ strength (* strength rate)))) (psi-set-demand-value demand-node demand-value) (stv 1 1) ) ) (define (psi-demand-value-decrease demand-node rate-node) " psi-demand-value-decrease DEMAND RATE Decreases the strength of the demand by the given percentage rate. RATE must be a NumberNode holding the percentage change by which the demand-value will be updated with, on each step. " (let* ((strength (cog-mean demand-node)) (rate (/ (cog-number rate-node) 100)) (demand-value (- strength (* strength rate)))) (psi-set-demand-value demand-node demand-value) (stv 1 1) ) ) (define psi-label-skip (ConceptNode (string-append psi-prefix-str "skip"))) (define (psi-demand-skip demand) " psi-demand-skip DEMAND - Disable DEMAND. Use this to disable the DEMAND from being considered during action selection. The DEMAND should be a valid demand node. " (if (not (psi-demand? demand)) (error (string-append "In procedure psi-demand-skip, expected " "argument to be a node representing a demand, got:") demand)) (MemberLink demand psi-label-skip) (clear-demand-cache) ) (define (psi-demand-skip? demand) " psi-demand-skip? DEMAND - return #t if DEMAND should be skipped. " (if (not (psi-demand? demand)) (error (string-append "In procedure psi-demand-skip?, expected " "argument to be a node representing a demand, got:") demand)) (not (member demand (psi-get-all-enabled-demands))) )
a97819570687eaba1103537095aaacd476fb5ddff3e287a73c5475e49b84feb4
bragful/ephp
ephp_lib_test.erl
-module(ephp_lib_test). -author(''). -compile([warnings_as_errors]). -include("ephp.hrl"). -behaviour(ephp_lib). -export([init_func/0, init_config/0, init_const/0]). -spec init_config() -> ephp_func:php_config_results(). init_config() -> [{<<"test">>, <<"true">>}]. -spec init_const() -> ephp_func:php_const_results(). init_const() -> []. -spec init_func() -> ephp_func:php_function_results(). init_func() -> [].
null
https://raw.githubusercontent.com/bragful/ephp/119f1760a5cdf4c8b6a01739e852c7183af7acff/test/ephp_lib_test.erl
erlang
-module(ephp_lib_test). -author(''). -compile([warnings_as_errors]). -include("ephp.hrl"). -behaviour(ephp_lib). -export([init_func/0, init_config/0, init_const/0]). -spec init_config() -> ephp_func:php_config_results(). init_config() -> [{<<"test">>, <<"true">>}]. -spec init_const() -> ephp_func:php_const_results(). init_const() -> []. -spec init_func() -> ephp_func:php_function_results(). init_func() -> [].
bdf70924c76b9878cca1bb256b553cc7754501016ce16be621e130103960d085
pgujjula/hilbert
Modular.hs
# LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # | Module : Math . . Modular -- Description : Functions to perform modular arithmetic. Copyright : ( c ) , 2016 - 2020 -- License : BSD-3-Clause -- Maintainer : -- Stability : experimental -- -- Functions to perform modular arithmetic. module Math.NumberTheory.Modular ( egcd, chineseRemainder, chineseRemainderF, ) where import Control.Arrow ((>>>)) import Control.Monad (foldM, (>=>)) import Data.Foldable (foldl') import Data.List.Duplicate (groupBy) import Data.Maybe (fromJust) import Data.Mod (Mod, invertMod, unMod) import Data.Ord (comparing) import Data.Type.Natural (SNat, withSNat) import Math.NumberTheory.Prime.Factor (Factorization, factor) | @egcd m n@ is the extended GCD of @m@ and @n@. It is a tuple @(g , ( a , b))@ such that @gcd m n = = g@ and @a*m + b*n = = g@. -- > > > egcd 3 5 ( 1 , ( 2 , -1 ) ) > > > egcd 10 4 ( 2 , ( 1 , -2 ) ) > > > ( -4 ) 7 ( 1 , ( -2 , -1 ) ) -- >>> egcd 4 0 ( 4 , ( 1 , 0 ) ) -- >>> egcd 0 0 -- (0, (0, 0)) egcd :: (Integral a) => a -> a -> (a, (a, a)) egcd m n | m < n = (g', (signa * a', signb * b')) | otherwise = (g', (signb * b', signa * a')) where (g', (a', b')) = egcdLowLevel (abs lower) (abs upper) signa = signum lower signb = signum upper lower = min m n upper = max m n {- Here, we are guaranteed n > m > 0 -} egcdLowLevel :: (Integral a) => a -> a -> (a, (a, a)) egcdLowLevel m n = egcdRecursive m n (1, 0) (0, 1) egcdRecursive :: (Integral a) => a -> a -> (a, a) -> (a, a) -> (a, (a, a)) egcdRecursive m n m_coeffs n_coeffs | m == 0 = (n, n_coeffs) | otherwise = egcdRecursive r m (n0 - q * m0, n1 - q * m1) m_coeffs where (q, r) = quotRem n m (m0, m1) = m_coeffs (n0, n1) = n_coeffs -- | Solve a system of modular congruences. The input list is a list of pairs , mi)@ , representing a system -- \[\forall i \quad x \equiv a_{i } \mod m_{i } \ ] -- -- The result @(x, m)@ is the solution @x@ and its modulus @m@, if a -- solution exists. -- -- >>> EXAMPLE HERE chineseRemainder :: Integral a => [(a, a)] -> Maybe (a, a) chineseRemainder = traverse (\(x, m) -> (x,) <$> factor (abs m)) >=> chineseRemainderF -- | Like 'chineseRemainder', but takes in the factorizations of the moduli to -- speed up computation. -- -- >>> EXAMPLE HERE chineseRemainderF :: Integral a => [(a, Factorization a)] -> Maybe (a, a) chineseRemainderF = breakUp >>> massage >>> fmap (uncurry solveAllPrime) >>> sequence >>> fmap solveAll breakUp :: [(a, Factorization a)] -> [(a, (a, Int))] breakUp = concatMap (\(x, fact) -> fmap (x,) fact) massage :: Ord b => [(a, (b, c))] -> [(b, [(a, c)])] massage = fmap (\(a, (b, c)) -> (b, (a, c))) >>> groupBy (comparing fst) >>> fmap (\xs -> (fst (head xs), fmap snd xs)) solveAll :: Integral a => [(a, a)] -> (a, a) solveAll = foldl' solve (0, 1) solve :: Integral a => (a, a) -> (a, a) -> (a, a) solve (a, m) (b, n) = (x, s) where s = m * n x = ( (a * (fromJust $ modInv n m)) * n + (b * (fromJust $ modInv m n)) * m ) `rem` s modInv :: Integral a => a -> a -> Maybe a modInv a m = withSNat (fromIntegral m) $ \(_ :: SNat n) -> fmap (fromIntegral . unMod) (invertMod (fromIntegral a :: Mod n)) Given a prime p and a list of ( xi , ) representing a system of congruences -- x == xi (mod p^ki) -- solve for x, k such that x (mod p^k) is a solution to the system. solveAllPrime :: Integral a => a -> [(a, Int)] -> Maybe (a, a) solveAllPrime p = fmap (\(x, k) -> (x, p ^ k)) . foldM (solvePrime p) (0, 0) solvePrime :: Integral a => a -> (a, Int) -> (a, Int) -> Maybe (a, Int) solvePrime p (x1, k1) (x2, k2) | k1 > k2 = solvePrime p (x2, k2) (x1, k1) | (x2 - x1) `mod` (p ^ k1) /= 0 = Nothing | otherwise = Just (x2, k2)
null
https://raw.githubusercontent.com/pgujjula/hilbert/ea64f2d06ceeb96da11fe6f2b868cef1cd817e28/src/Math/NumberTheory/Modular.hs
haskell
Description : Functions to perform modular arithmetic. License : BSD-3-Clause Maintainer : Stability : experimental Functions to perform modular arithmetic. >>> egcd 4 0 >>> egcd 0 0 (0, (0, 0)) Here, we are guaranteed n > m > 0 | Solve a system of modular congruences. The input list is a list of pairs The result @(x, m)@ is the solution @x@ and its modulus @m@, if a solution exists. >>> EXAMPLE HERE | Like 'chineseRemainder', but takes in the factorizations of the moduli to speed up computation. >>> EXAMPLE HERE x == xi (mod p^ki) solve for x, k such that x (mod p^k) is a solution to the system.
# LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # | Module : Math . . Modular Copyright : ( c ) , 2016 - 2020 module Math.NumberTheory.Modular ( egcd, chineseRemainder, chineseRemainderF, ) where import Control.Arrow ((>>>)) import Control.Monad (foldM, (>=>)) import Data.Foldable (foldl') import Data.List.Duplicate (groupBy) import Data.Maybe (fromJust) import Data.Mod (Mod, invertMod, unMod) import Data.Ord (comparing) import Data.Type.Natural (SNat, withSNat) import Math.NumberTheory.Prime.Factor (Factorization, factor) | @egcd m n@ is the extended GCD of @m@ and @n@. It is a tuple @(g , ( a , b))@ such that @gcd m n = = g@ and @a*m + b*n = = g@. > > > egcd 3 5 ( 1 , ( 2 , -1 ) ) > > > egcd 10 4 ( 2 , ( 1 , -2 ) ) > > > ( -4 ) 7 ( 1 , ( -2 , -1 ) ) ( 4 , ( 1 , 0 ) ) egcd :: (Integral a) => a -> a -> (a, (a, a)) egcd m n | m < n = (g', (signa * a', signb * b')) | otherwise = (g', (signb * b', signa * a')) where (g', (a', b')) = egcdLowLevel (abs lower) (abs upper) signa = signum lower signb = signum upper lower = min m n upper = max m n egcdLowLevel :: (Integral a) => a -> a -> (a, (a, a)) egcdLowLevel m n = egcdRecursive m n (1, 0) (0, 1) egcdRecursive :: (Integral a) => a -> a -> (a, a) -> (a, a) -> (a, (a, a)) egcdRecursive m n m_coeffs n_coeffs | m == 0 = (n, n_coeffs) | otherwise = egcdRecursive r m (n0 - q * m0, n1 - q * m1) m_coeffs where (q, r) = quotRem n m (m0, m1) = m_coeffs (n0, n1) = n_coeffs , mi)@ , representing a system \[\forall i \quad x \equiv a_{i } \mod m_{i } \ ] chineseRemainder :: Integral a => [(a, a)] -> Maybe (a, a) chineseRemainder = traverse (\(x, m) -> (x,) <$> factor (abs m)) >=> chineseRemainderF chineseRemainderF :: Integral a => [(a, Factorization a)] -> Maybe (a, a) chineseRemainderF = breakUp >>> massage >>> fmap (uncurry solveAllPrime) >>> sequence >>> fmap solveAll breakUp :: [(a, Factorization a)] -> [(a, (a, Int))] breakUp = concatMap (\(x, fact) -> fmap (x,) fact) massage :: Ord b => [(a, (b, c))] -> [(b, [(a, c)])] massage = fmap (\(a, (b, c)) -> (b, (a, c))) >>> groupBy (comparing fst) >>> fmap (\xs -> (fst (head xs), fmap snd xs)) solveAll :: Integral a => [(a, a)] -> (a, a) solveAll = foldl' solve (0, 1) solve :: Integral a => (a, a) -> (a, a) -> (a, a) solve (a, m) (b, n) = (x, s) where s = m * n x = ( (a * (fromJust $ modInv n m)) * n + (b * (fromJust $ modInv m n)) * m ) `rem` s modInv :: Integral a => a -> a -> Maybe a modInv a m = withSNat (fromIntegral m) $ \(_ :: SNat n) -> fmap (fromIntegral . unMod) (invertMod (fromIntegral a :: Mod n)) Given a prime p and a list of ( xi , ) representing a system of congruences solveAllPrime :: Integral a => a -> [(a, Int)] -> Maybe (a, a) solveAllPrime p = fmap (\(x, k) -> (x, p ^ k)) . foldM (solvePrime p) (0, 0) solvePrime :: Integral a => a -> (a, Int) -> (a, Int) -> Maybe (a, Int) solvePrime p (x1, k1) (x2, k2) | k1 > k2 = solvePrime p (x2, k2) (x1, k1) | (x2 - x1) `mod` (p ^ k1) /= 0 = Nothing | otherwise = Just (x2, k2)
d713e81caa61125a274cdce4ac01b58b38b05375348c93ead8b82dfd5e35f750
futurice/haskell-mega-repo
Eval.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # module PlanMill.Eval (evalPlanMill) where import PlanMill.Internal.Prelude import Control.Monad.Http (MonadHttp (..), httpLbs) import Data.Aeson.Compat (eitherDecode) import Data.IORef (IORef, atomicModifyIORef', newIORef) import Futurice.Metrics.RateMeter (mark) import Network.HTTP.Client (Request, RequestBody (..), method, parseRequest, path, queryString, requestBody, requestHeaders, responseBody, responseStatus, responseTimeout, responseTimeoutMicro, setQueryString) import Network.HTTP.Types (Header, Status (..), statusIsSuccessful) import System.IO.Unsafe (unsafePerformIO) import Text.Printf (printf) -- Qualified imports import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Char8 as BS8 import qualified Data.ByteString.Lazy as LBS import qualified Data.Map as Map import qualified Data.Text as T import qualified Data.Vector as V -- PlanMill import import PlanMill.Auth (Auth (..), getAuth) import PlanMill.Classes import PlanMill.Types ------------------------------------------------------------------------------- -- Counter ------------------------------------------------------------------------------- counter :: IORef Int counter = unsafePerformIO $ newIORef 0 # NOINLINE counter # ------------------------------------------------------------------------------- -- Evaluate ------------------------------------------------------------------------------- getModifiedTimeout :: ByteString -> Int getModifiedTimeout path | BS8.isSuffixOf "Earned%20vacations%20(Custom)" path = 6 * 60 * 1000000 | otherwise = 3 * 60 * 1000000 evalPlanMill :: forall m env e a. MonadTime m implied by MonadLog , MonadReader env m, HasPlanMillCfg env , MonadCRandom e m, ContainsCryptoGenError e , MonadIO m -- counter, mark , MonadClock m -- clocked , FromJSON a ) => PlanMill a -> m a evalPlanMill pm = do baseReq <- mkBaseReq pm case pm of PlanMillGet qs _ -> singleReq baseReq qs Nothing PlanMillPagedGet qs _ -> pagedReq baseReq qs PlanMillPost e body _ -> do let req = addHeader ("Content-Type", "application/json;charset=UTF-8") $ baseReq { method = "POST", requestBody = RequestBodyLBS body } singleReq req mempty $ case e of Nothing -> Nothing Just Refl -> pure () PlanMillDelete _ -> do let req = baseReq { method = "DELETE" } singleReq req mempty (pure ()) where mkBaseReq :: forall b. PlanMill b -> m Request mkBaseReq planmill = do baseUrl <- view planmillCfgBaseUrl parseRequest $ baseUrl <> fromUrlParts (requestUrlParts planmill) singleReq :: forall b. FromJSON b => Request -> QueryString -> Maybe b -- ^ Possibly return when empty response -> m b singleReq req qs d = do let req' = setQueryString' qs req let m = BS8.unpack (method req') let url = BS8.unpack (path req') <> BS8.unpack (queryString req') uniqId <- liftIO $ textShow <$> atomicModifyIORef' counter (\c -> (succ c, c)) logLocalDomain ("req-" <> uniqId) $ do logTrace_ $ T.pack $ "req " <> m <> " " <> url We need to generate auth ( nonce ) at each req auth <- getAuth let req'' = (addHeader (authHeader auth) req') BEGIN HACK : 2018 - 12 - 17 , PlanMill is sad so we do this { responseTimeout = if BS8.isSuffixOf "tasks/28532" (path req) HACK : 2019 - 09 - 19 , we are yet again sad HACK : 2019 - 11 - 07 , -;;- HACK : 2020 - 01 - 23 the sadness continues || BS8.isSuffixOf "absences" (path req) || BS8.isSuffixOf "projects" (path req) || BS8.isSuffixOf "Value%20creation%20per%20month%20by%20employee" (path req) || BS8.isSuffixOf "Earned%20vacations%20(Custom)" (path req) then responseTimeoutMicro $ getModifiedTimeout (path req) else responseTimeout req' -- otherwise do nothing } -- END HACK (dur, res) <- clocked $ httpLbs req'' let status@Status {..} = responseStatus res let body = responseBody res let dur' = timeSpecToSecondsD dur let dur'' = printf "%.06fs" dur' logTrace_ $ "res " <> textShow statusCode <> " " <> textShow statusMessage <> "; took " <> dur'' ^. packed liftIO $ mark "PlanMill request" if isn't _Empty body then logTrace _ $ " response body : " < > decodeUtf8Lenient ( responseBody res ^. strict ) if statusIsSuccessful status then parseResult url body else do -- if we have "default" response, we return it in case of error let exc = parseError url body case d of Nothing -> throwM exc Just d' -> do logAttention "Recoverable error" $ object [ "exc" .= textShow exc ] return d' else do logTrace_ "empty response" case d of Just d' -> pure d' Nothing -> throwM (emptyError url) setQueryString' :: QueryString -> Request -> Request setQueryString' qs = setQueryString (f <$> Map.toList qs) where f (a, b) = (encodeUtf8 a, Just $ encodeUtf8 b) parseResult :: forall b .(FromJSON b) => String -> LBS.ByteString -> m b parseResult url body = case eitherDecode body of Right x -> pure x Left err -> throwM $ DecodeError url err parseError :: String -> LBS.ByteString -> PlanMillError parseError url body = case eitherDecode body of Right exc -> ErrorResponse url exc Left err -> DecodeError url err emptyError url = DecodeError url "empty input" -- See #projects_get -- for explanation of paged response query string parameters -- -- We actually need the type equality constraint -- to use vector's length pagedReq :: forall b b'. (b ~ V.Vector b', FromJSON b) => Request -> QueryString -> m b pagedReq req qs = go mempty where go :: V.Vector b' -> m b go acc = do -- We are for one too much, because if `nextrows` is over amount -- the collection from beginning is returned let qs' = Map.fromList [ ("rowcount", T.pack $ show $ rowCount + 1) , ("nextrows", T.pack $ show $ V.length acc + 1) ] res <- singleReq req (qs <> qs') (pure V.empty) if V.length res <= rowCount then pure (acc <> res) else go (acc <> V.take rowCount res) -- The PlanMill documentation doesn't specify the maximum rows we -- can ask for, so we empirically found this limit works rowCount :: Int rowCount = 1000 authHeader :: Auth -> Header authHeader (Auth (Ident uid) (Nonce nonce) ts sig) = ("x-PlanMill-Auth", "user:" <> bsShow uid <> ";" <> "nonce:" <> nonce <> ";" <> "timestamp:" <> bsShow (utcTimeToInteger ts) <> ";" <> "signature:" <> Base64.encode sig) addHeader :: Header -> Request -> Request addHeader header req = req { requestHeaders = header : requestHeaders req }
null
https://raw.githubusercontent.com/futurice/haskell-mega-repo/8cb82bb0656c4a7e62a88b19f17ddbec1b037f4f/planmill-client/src/PlanMill/Eval.hs
haskell
# LANGUAGE GADTs # # LANGUAGE OverloadedStrings # Qualified imports PlanMill import ----------------------------------------------------------------------------- Counter ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Evaluate ----------------------------------------------------------------------------- counter, mark clocked ^ Possibly return when empty response otherwise do nothing END HACK if we have "default" response, we return it in case of error See #projects_get for explanation of paged response query string parameters We actually need the type equality constraint to use vector's length We are for one too much, because if `nextrows` is over amount the collection from beginning is returned The PlanMill documentation doesn't specify the maximum rows we can ask for, so we empirically found this limit works
# LANGUAGE FlexibleContexts # # LANGUAGE RecordWildCards # module PlanMill.Eval (evalPlanMill) where import PlanMill.Internal.Prelude import Control.Monad.Http (MonadHttp (..), httpLbs) import Data.Aeson.Compat (eitherDecode) import Data.IORef (IORef, atomicModifyIORef', newIORef) import Futurice.Metrics.RateMeter (mark) import Network.HTTP.Client (Request, RequestBody (..), method, parseRequest, path, queryString, requestBody, requestHeaders, responseBody, responseStatus, responseTimeout, responseTimeoutMicro, setQueryString) import Network.HTTP.Types (Header, Status (..), statusIsSuccessful) import System.IO.Unsafe (unsafePerformIO) import Text.Printf (printf) import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Char8 as BS8 import qualified Data.ByteString.Lazy as LBS import qualified Data.Map as Map import qualified Data.Text as T import qualified Data.Vector as V import PlanMill.Auth (Auth (..), getAuth) import PlanMill.Classes import PlanMill.Types counter :: IORef Int counter = unsafePerformIO $ newIORef 0 # NOINLINE counter # getModifiedTimeout :: ByteString -> Int getModifiedTimeout path | BS8.isSuffixOf "Earned%20vacations%20(Custom)" path = 6 * 60 * 1000000 | otherwise = 3 * 60 * 1000000 evalPlanMill :: forall m env e a. MonadTime m implied by MonadLog , MonadReader env m, HasPlanMillCfg env , MonadCRandom e m, ContainsCryptoGenError e , FromJSON a ) => PlanMill a -> m a evalPlanMill pm = do baseReq <- mkBaseReq pm case pm of PlanMillGet qs _ -> singleReq baseReq qs Nothing PlanMillPagedGet qs _ -> pagedReq baseReq qs PlanMillPost e body _ -> do let req = addHeader ("Content-Type", "application/json;charset=UTF-8") $ baseReq { method = "POST", requestBody = RequestBodyLBS body } singleReq req mempty $ case e of Nothing -> Nothing Just Refl -> pure () PlanMillDelete _ -> do let req = baseReq { method = "DELETE" } singleReq req mempty (pure ()) where mkBaseReq :: forall b. PlanMill b -> m Request mkBaseReq planmill = do baseUrl <- view planmillCfgBaseUrl parseRequest $ baseUrl <> fromUrlParts (requestUrlParts planmill) singleReq :: forall b. FromJSON b => Request -> QueryString -> m b singleReq req qs d = do let req' = setQueryString' qs req let m = BS8.unpack (method req') let url = BS8.unpack (path req') <> BS8.unpack (queryString req') uniqId <- liftIO $ textShow <$> atomicModifyIORef' counter (\c -> (succ c, c)) logLocalDomain ("req-" <> uniqId) $ do logTrace_ $ T.pack $ "req " <> m <> " " <> url We need to generate auth ( nonce ) at each req auth <- getAuth let req'' = (addHeader (authHeader auth) req') BEGIN HACK : 2018 - 12 - 17 , PlanMill is sad so we do this { responseTimeout = if BS8.isSuffixOf "tasks/28532" (path req) HACK : 2019 - 09 - 19 , we are yet again sad HACK : 2019 - 11 - 07 , -;;- HACK : 2020 - 01 - 23 the sadness continues || BS8.isSuffixOf "absences" (path req) || BS8.isSuffixOf "projects" (path req) || BS8.isSuffixOf "Value%20creation%20per%20month%20by%20employee" (path req) || BS8.isSuffixOf "Earned%20vacations%20(Custom)" (path req) then responseTimeoutMicro $ getModifiedTimeout (path req) } (dur, res) <- clocked $ httpLbs req'' let status@Status {..} = responseStatus res let body = responseBody res let dur' = timeSpecToSecondsD dur let dur'' = printf "%.06fs" dur' logTrace_ $ "res " <> textShow statusCode <> " " <> textShow statusMessage <> "; took " <> dur'' ^. packed liftIO $ mark "PlanMill request" if isn't _Empty body then logTrace _ $ " response body : " < > decodeUtf8Lenient ( responseBody res ^. strict ) if statusIsSuccessful status then parseResult url body else do let exc = parseError url body case d of Nothing -> throwM exc Just d' -> do logAttention "Recoverable error" $ object [ "exc" .= textShow exc ] return d' else do logTrace_ "empty response" case d of Just d' -> pure d' Nothing -> throwM (emptyError url) setQueryString' :: QueryString -> Request -> Request setQueryString' qs = setQueryString (f <$> Map.toList qs) where f (a, b) = (encodeUtf8 a, Just $ encodeUtf8 b) parseResult :: forall b .(FromJSON b) => String -> LBS.ByteString -> m b parseResult url body = case eitherDecode body of Right x -> pure x Left err -> throwM $ DecodeError url err parseError :: String -> LBS.ByteString -> PlanMillError parseError url body = case eitherDecode body of Right exc -> ErrorResponse url exc Left err -> DecodeError url err emptyError url = DecodeError url "empty input" pagedReq :: forall b b'. (b ~ V.Vector b', FromJSON b) => Request -> QueryString -> m b pagedReq req qs = go mempty where go :: V.Vector b' -> m b go acc = do let qs' = Map.fromList [ ("rowcount", T.pack $ show $ rowCount + 1) , ("nextrows", T.pack $ show $ V.length acc + 1) ] res <- singleReq req (qs <> qs') (pure V.empty) if V.length res <= rowCount then pure (acc <> res) else go (acc <> V.take rowCount res) rowCount :: Int rowCount = 1000 authHeader :: Auth -> Header authHeader (Auth (Ident uid) (Nonce nonce) ts sig) = ("x-PlanMill-Auth", "user:" <> bsShow uid <> ";" <> "nonce:" <> nonce <> ";" <> "timestamp:" <> bsShow (utcTimeToInteger ts) <> ";" <> "signature:" <> Base64.encode sig) addHeader :: Header -> Request -> Request addHeader header req = req { requestHeaders = header : requestHeaders req }
fd65d418d998aeffd90e64b7565ab247eba18e8cd1a9b68104733d916b4f66cd
haskell-game/tiny-games-hs
Import.hs
module Import ( module Graphics.Gloss.Interface.Pure.Game , module Data.Bits , module Control.Applicative , module Control.Monad , module Data.List , module Data.Bool , module GHC.Float ) where import Graphics.Gloss.Interface.Pure.Game hiding (shift, rotate) import Data.Bits import Control.Applicative import Control.Monad(guard, mzero) import Data.List(partition) import Data.Bool import GHC.Float (int2Float)
null
https://raw.githubusercontent.com/haskell-game/tiny-games-hs/9dcd6f220d265966bf1f1ca259b5aa956a4cc8a6/hackage/vaders/Import.hs
haskell
module Import ( module Graphics.Gloss.Interface.Pure.Game , module Data.Bits , module Control.Applicative , module Control.Monad , module Data.List , module Data.Bool , module GHC.Float ) where import Graphics.Gloss.Interface.Pure.Game hiding (shift, rotate) import Data.Bits import Control.Applicative import Control.Monad(guard, mzero) import Data.List(partition) import Data.Bool import GHC.Float (int2Float)
d8e1b8af9bc047a6f753cec733cf36eb1c7c2b765e39c4392b3a06bd9c7e8509
xvw/ocamlectron
Signal.mli
* Linux supports both [ POSIX ] reliable signals ( hereinafter " standard signals " ) and POSIX real - time signals . You can find more information on this page : - { { : #process_signal_events } NodeJS : documentation for [ Signals ] } - { { : -pages/man7/signal.7.html } Linux Programmer 's Manual on [ Signals ] } signals") and POSIX real-time signals. You can find more information on this page : - {{: #process_signal_events } NodeJS : documentation for [Signals] } - {{: -pages/man7/signal.7.html } Linux Programmer's Manual on [Signals] } *) * { 2 Internals types } (** POSIX Signals *) type t = | SIGHUP | SIGINT | SIGQUIT | SIGILL | SIGABRT | SIGFPE | SIGKILL | SIGSEGV | SIGPIPE | SIGALRM | SIGTERM | SIGUSR1 | SIGUSR2 | SIGCHLD | SIGSTOP | SIGSTP | SIGTTIN | SIGTTOU | SIGVTALRM | SIGXCPU | SIGXFSZ | SIGWINCH | SIGBREAK | SIGBUS * { 2 Functions } val to_string : t -> string (** Converts signal to string *)
null
https://raw.githubusercontent.com/xvw/ocamlectron/3e0cb9575975e69ab34cb7e0e3549d31c07141c2/lib/electron_api/Signal.mli
ocaml
* POSIX Signals * Converts signal to string
* Linux supports both [ POSIX ] reliable signals ( hereinafter " standard signals " ) and POSIX real - time signals . You can find more information on this page : - { { : #process_signal_events } NodeJS : documentation for [ Signals ] } - { { : -pages/man7/signal.7.html } Linux Programmer 's Manual on [ Signals ] } signals") and POSIX real-time signals. You can find more information on this page : - {{: #process_signal_events } NodeJS : documentation for [Signals] } - {{: -pages/man7/signal.7.html } Linux Programmer's Manual on [Signals] } *) * { 2 Internals types } type t = | SIGHUP | SIGINT | SIGQUIT | SIGILL | SIGABRT | SIGFPE | SIGKILL | SIGSEGV | SIGPIPE | SIGALRM | SIGTERM | SIGUSR1 | SIGUSR2 | SIGCHLD | SIGSTOP | SIGSTP | SIGTTIN | SIGTTOU | SIGVTALRM | SIGXCPU | SIGXFSZ | SIGWINCH | SIGBREAK | SIGBUS * { 2 Functions } val to_string : t -> string
b99537b1b649bb2ad278c3dcab2d420836b0f374f02dc2430ba8734621402200
softwarelanguageslab/maf
R5RS_icp_icp_3_leval-3.scm
; Changes: * removed : 2 * added : 3 * swaps : 2 * negated predicates : 2 * swapped branches : 1 * calls to i d fun : 11 (letrec ((true #t) (false #f) (delay-it (lambda (exp env) (list 'thunk exp env))) (thunk? (lambda (obj) (tagged-list? obj 'thunk))) (thunk-exp (lambda (thunk) (cadr thunk))) (thunk-env (lambda (thunk) (<change> () caddr) (caddr thunk))) (force-it (lambda (obj) (if (thunk? obj) (actual-value (thunk-exp obj) (thunk-env obj)) obj))) (nonmemo-force-it force-it) (evaluated-thunk? (lambda (obj) (tagged-list? obj 'evaluated-thunk))) (thunk-value (lambda (evaluated-thunk) (cadr evaluated-thunk))) (force-it2 (lambda (obj) (if (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) (if (evaluated-thunk? obj) (thunk-value obj) obj)))) (memo-force-it force-it2) (apply-in-underlying-scheme (lambda (proc args) (if (null? args) (proc) (if (null? (cdr args)) (proc (car args)) (if (null? (cddr args)) (proc (car args) (cadr args)) (error "Unsupported call")))))) (eval (lambda (exp env) (if (self-evaluating? exp) exp (if (variable? exp) (lookup-variable-value exp env) (if (let ((__or_res (quoted? exp))) (if __or_res __or_res (quasiquoted? exp))) (eval-quotation-args (text-of-quotation exp) env) (if (assignment? exp) (eval-assignment exp env) (if (definition? exp) (eval-definition exp env) (if (if? exp) (eval-if exp env) (if (<change> (lambda? exp) (not (lambda? exp))) (make-procedure (lambda-parameters exp) (lambda-body exp) env) (if (begin? exp) (eval-sequence (begin-actions exp) env) (if (<change> (cond? exp) (not (cond? exp))) (eval (cond->if exp) env) (if (application? exp) (leval-apply (actual-value (operator exp) env) (operands exp) env) (error "Unknown expression type -- EVAL"))))))))))))) (actual-value (lambda (exp env) (force-it (eval exp env)))) (leval-apply (lambda (procedure arguments env) (if (primitive-procedure? procedure) (apply-primitive-procedure procedure (list-of-arg-values arguments env)) (if (compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) (list-of-delayed-args arguments env) (procedure-environment procedure))) (error "Unknown procedure type -- APPLY"))))) (list-of-arg-values (lambda (exps env) (if (no-operands? exps) () (cons (actual-value (first-operand exps) env) (list-of-arg-values (rest-operands exps) env))))) (list-of-delayed-args (lambda (exps env) (if (no-operands? exps) () (cons (delay-it (first-operand exps) env) (list-of-delayed-args (rest-operands exps) env))))) (eval-assignment (lambda (exp env) (set-variable-value! (assignment-variable exp) (eval (assignment-value exp) env) env) 'ok)) (eval-definition (lambda (exp env) (define-variable! (definition-variable exp) (eval (definition-value exp) env) env) 'ok)) (true? (lambda (x) (not (eq? x false)))) (false? (lambda (x) (eq? x false))) (eval-if (lambda (exp env) (if (true? (actual-value (if-predicate exp) env)) (eval (if-consequent exp) env) (eval (if-alternative exp) env)))) (eval-sequence (lambda (exps env) (<change> (if (last-exp? exps) (eval (first-exp exps) env) (begin (eval (first-exp exps) env) (eval-sequence (rest-exps exps) env))) ((lambda (x) x) (if (last-exp? exps) (eval (first-exp exps) env) (begin (eval (first-exp exps) env) (eval-sequence (rest-exps exps) env))))))) (self-evaluating? (lambda (exp) (if (number? exp) (<change> true (if (string? exp) true false)) (<change> (if (string? exp) true false) true)))) (tagged-list? (lambda (exp tag) (if (pair? exp) (eq? (car exp) tag) false))) (quoted? (lambda (exp) (<change> (tagged-list? exp 'quote) ((lambda (x) x) (tagged-list? exp 'quote))))) (text-of-quotation (lambda (exp) (<change> (cadr exp) ((lambda (x) x) (cadr exp))))) (quasiquoted? (lambda (exp) (<change> (tagged-list? exp 'quasiquote) ((lambda (x) x) (tagged-list? exp 'quasiquote))))) (unquote? (lambda (exp) (tagged-list? exp 'unquote))) (variable? (lambda (exp) (symbol? exp))) (assignment? (lambda (exp) (tagged-list? exp 'set!))) (assignment-variable (lambda (exp) (cadr exp))) (assignment-value (lambda (exp) (caddr exp))) (definition? (lambda (exp) (tagged-list? exp 'define))) (definition-variable (lambda (exp) (if (symbol? (cadr exp)) (cadr exp) (caadr exp)))) (definition-value (lambda (exp) (if (symbol? (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp))))) (if? (lambda (exp) (tagged-list? exp 'if))) (if-predicate (lambda (exp) (cadr exp))) (if-consequent (lambda (exp) (caddr exp))) (if-alternative (lambda (exp) (if (not (null? (cdddr exp))) (cadddr exp) 'false))) (make-if (lambda (predicate consequent alternative) (list 'if predicate consequent alternative))) (lambda? (lambda (exp) (tagged-list? exp 'lambda))) (lambda-parameters (lambda (exp) (cadr exp))) (lambda-body (lambda (exp) (cddr exp))) (make-lambda (lambda (parameters body) (cons 'lambda (cons parameters body)))) (cond? (lambda (exp) (<change> (tagged-list? exp 'cond) ((lambda (x) x) (tagged-list? exp 'cond))))) (cond-clauses (lambda (exp) (cdr exp))) (cond-else-clause? (lambda (clause) (eq? (cond-predicate clause) 'else))) (cond-predicate (lambda (clause) (car clause))) (cond-actions (lambda (clause) (cdr clause))) (cond->if (lambda (exp) (<change> (expand-clauses (cond-clauses exp)) ((lambda (x) x) (expand-clauses (cond-clauses exp)))))) (expand-clauses (lambda (clauses) (if (null? clauses) 'false (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF")) (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest))))))) (begin? (lambda (exp) (tagged-list? exp 'begin))) (begin-actions (lambda (exp) (cdr exp))) (last-exp? (lambda (seq) (null? (cdr seq)))) (first-exp (lambda (seq) (car seq))) (rest-exps (lambda (seq) (<change> (cdr seq) ((lambda (x) x) (cdr seq))))) (sequence->exp (lambda (seq) (if (null? seq) seq (if (last-exp? seq) (first-exp seq) (make-begin seq))))) (make-begin (lambda (seq) (cons 'begin seq))) (application? (lambda (exp) (pair? exp))) (operator (lambda (exp) (car exp))) (operands (lambda (exp) (cdr exp))) (no-operands? (lambda (ops) (<change> () (display null?)) (<change> (null? ops) ((lambda (x) x) (null? ops))))) (first-operand (lambda (ops) (car ops))) (rest-operands (lambda (ops) (<change> (cdr ops) ((lambda (x) x) (cdr ops))))) (make-procedure (lambda (parameters body env) (list 'procedure parameters body env))) (compound-procedure? (lambda (p) (tagged-list? p 'procedure))) (procedure-parameters (lambda (p) (cadr p))) (procedure-body (lambda (p) (caddr p))) (procedure-environment (lambda (p) (cadddr p))) (enclosing-environment (lambda (env) (cdr env))) (first-frame (lambda (env) (car env))) (the-empty-environment ()) (extend-environment (lambda (vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied") (error "Too few arguments supplied"))))) (make-frame (lambda (variables values) (cons variables values))) (frame-variables (lambda (frame) (car frame))) (frame-values (lambda (frame) (cdr frame))) (add-binding-to-frame! (lambda (var val frame) (<change> (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame)))) (<change> (set-cdr! frame (cons val (cdr frame))) (set-car! frame (cons var (car frame)))))) (lookup-variable-value (lambda (var env) (letrec ((env-loop (lambda (env) (letrec ((scan (lambda (vars vals) (if (null? vars) (env-loop (enclosing-environment env)) (if (eq? var (car vars)) (car vals) (scan (cdr vars) (cdr vals))))))) (if (eq? env the-empty-environment) (error "Unbound variable") (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame)))))))) (<change> (env-loop env) ((lambda (x) x) (env-loop env)))))) (set-variable-value! (lambda (var val env) (letrec ((env-loop (lambda (env) (letrec ((scan (lambda (vars vals) (<change> () (display car)) (if (null? vars) (env-loop (enclosing-environment env)) (if (eq? var (car vars)) (set-car! vals val) (scan (cdr vars) (cdr vals))))))) (if (eq? env the-empty-environment) (error "Unbound variable -- SET!") (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame)))))))) (env-loop env)))) (define-variable! (lambda (var val env) (let ((frame (first-frame env))) (letrec ((scan (lambda (vars vals) (if (null? vars) (add-binding-to-frame! var val frame) (if (eq? var (car vars)) (set-car! vals val) (scan (cdr vars) (cdr vals))))))) (scan (frame-variables frame) (frame-values frame)))))) (setup-environment (lambda () (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true true initial-env) (<change> (define-variable! 'false false initial-env) ()) initial-env))) (primitive-procedure? (lambda (proc) (tagged-list? proc 'primitive))) (primitive-implementation (lambda (proc) (cadr proc))) (primitive-procedures (list (list 'null? null?) (list '+ +) (list '- -) (list '* *) (list '/ /) (list '= =) (list '<= <=) (list '>= >=) (list '< <) (list '> >) (list 'newline newline) (list 'display display))) (primitive-procedure-names (lambda () (map car primitive-procedures))) (primitive-procedure-objects (lambda () (<change> (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures) ((lambda (x) x) (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures))))) (apply-primitive-procedure (lambda (proc args) (apply-in-underlying-scheme (primitive-implementation proc) args))) (input-prompt ";;; L-Eval input:") (output-prompt ";;; L-Eval value:") (prompt-for-input (lambda (string) (<change> (newline) (newline)) (<change> (newline) (newline)) (display string) (newline))) (announce-output (lambda (string) (newline) (display string) (newline))) (user-print (lambda (object) (if (compound-procedure? object) (display (list 'compound-procedure (procedure-parameters object) (procedure-body object) '<procedure-env>)) (display object)))) (the-global-environment (setup-environment)) (make-list (lambda (xs) (if (null? xs) () (let ((x (car xs))) (list 'cons (if (unquote? x) (cadr x) (list 'quote x)) (make-list (cdr xs))))))) (unaware-eval-quotation-args (lambda (qargs env) qargs)) (aware-eval-quotation-args (lambda (qargs env) (if (pair? qargs) (eval (make-list qargs) env) qargs))) (eval-quotation-args unaware-eval-quotation-args)) (<change> (display "Loading definitions of cons, car, cdr as compound procedures. ") ()) (eval (__toplevel_cons 'begin (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'cons (__toplevel_cons 'x (__toplevel_cons 'y ()))) (__toplevel_cons (__toplevel_cons 'lambda (__toplevel_cons (__toplevel_cons 'm ()) (__toplevel_cons (__toplevel_cons 'm (__toplevel_cons 'x (__toplevel_cons 'y ()))) ()))) ()))) (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'car (__toplevel_cons 'z ())) (__toplevel_cons (__toplevel_cons 'z (__toplevel_cons (__toplevel_cons 'lambda (__toplevel_cons (__toplevel_cons 'p (__toplevel_cons 'q ())) (__toplevel_cons 'p ()))) ())) ()))) (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'cdr (__toplevel_cons 'z ())) (__toplevel_cons (__toplevel_cons 'z (__toplevel_cons (__toplevel_cons 'lambda (__toplevel_cons (__toplevel_cons 'p (__toplevel_cons 'q ())) (__toplevel_cons 'q ()))) ())) ()))) (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'list-ref (__toplevel_cons 'items (__toplevel_cons 'n ()))) (__toplevel_cons (__toplevel_cons 'if (__toplevel_cons (__toplevel_cons '= (__toplevel_cons 'n (__toplevel_cons 0 ()))) (__toplevel_cons (__toplevel_cons 'car (__toplevel_cons 'items ())) (__toplevel_cons (__toplevel_cons 'list-ref (__toplevel_cons (__toplevel_cons 'cdr (__toplevel_cons 'items ())) (__toplevel_cons (__toplevel_cons '- (__toplevel_cons 'n (__toplevel_cons 1 ()))) ()))) ())))) ()))) (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'map (__toplevel_cons 'proc (__toplevel_cons 'items ()))) (__toplevel_cons (__toplevel_cons 'if (__toplevel_cons (__toplevel_cons 'null? (__toplevel_cons 'items ())) (__toplevel_cons (__toplevel_cons 'quote (__toplevel_cons () ())) (__toplevel_cons (__toplevel_cons 'cons (__toplevel_cons (__toplevel_cons 'proc (__toplevel_cons (__toplevel_cons 'car (__toplevel_cons 'items ())) ())) (__toplevel_cons (__toplevel_cons 'map (__toplevel_cons 'proc (__toplevel_cons (__toplevel_cons 'cdr (__toplevel_cons 'items ())) ()))) ()))) ())))) ()))) ())))))) the-global-environment))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_icp_icp_3_leval-3.scm
scheme
Changes:
* removed : 2 * added : 3 * swaps : 2 * negated predicates : 2 * swapped branches : 1 * calls to i d fun : 11 (letrec ((true #t) (false #f) (delay-it (lambda (exp env) (list 'thunk exp env))) (thunk? (lambda (obj) (tagged-list? obj 'thunk))) (thunk-exp (lambda (thunk) (cadr thunk))) (thunk-env (lambda (thunk) (<change> () caddr) (caddr thunk))) (force-it (lambda (obj) (if (thunk? obj) (actual-value (thunk-exp obj) (thunk-env obj)) obj))) (nonmemo-force-it force-it) (evaluated-thunk? (lambda (obj) (tagged-list? obj 'evaluated-thunk))) (thunk-value (lambda (evaluated-thunk) (cadr evaluated-thunk))) (force-it2 (lambda (obj) (if (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) (if (evaluated-thunk? obj) (thunk-value obj) obj)))) (memo-force-it force-it2) (apply-in-underlying-scheme (lambda (proc args) (if (null? args) (proc) (if (null? (cdr args)) (proc (car args)) (if (null? (cddr args)) (proc (car args) (cadr args)) (error "Unsupported call")))))) (eval (lambda (exp env) (if (self-evaluating? exp) exp (if (variable? exp) (lookup-variable-value exp env) (if (let ((__or_res (quoted? exp))) (if __or_res __or_res (quasiquoted? exp))) (eval-quotation-args (text-of-quotation exp) env) (if (assignment? exp) (eval-assignment exp env) (if (definition? exp) (eval-definition exp env) (if (if? exp) (eval-if exp env) (if (<change> (lambda? exp) (not (lambda? exp))) (make-procedure (lambda-parameters exp) (lambda-body exp) env) (if (begin? exp) (eval-sequence (begin-actions exp) env) (if (<change> (cond? exp) (not (cond? exp))) (eval (cond->if exp) env) (if (application? exp) (leval-apply (actual-value (operator exp) env) (operands exp) env) (error "Unknown expression type -- EVAL"))))))))))))) (actual-value (lambda (exp env) (force-it (eval exp env)))) (leval-apply (lambda (procedure arguments env) (if (primitive-procedure? procedure) (apply-primitive-procedure procedure (list-of-arg-values arguments env)) (if (compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) (list-of-delayed-args arguments env) (procedure-environment procedure))) (error "Unknown procedure type -- APPLY"))))) (list-of-arg-values (lambda (exps env) (if (no-operands? exps) () (cons (actual-value (first-operand exps) env) (list-of-arg-values (rest-operands exps) env))))) (list-of-delayed-args (lambda (exps env) (if (no-operands? exps) () (cons (delay-it (first-operand exps) env) (list-of-delayed-args (rest-operands exps) env))))) (eval-assignment (lambda (exp env) (set-variable-value! (assignment-variable exp) (eval (assignment-value exp) env) env) 'ok)) (eval-definition (lambda (exp env) (define-variable! (definition-variable exp) (eval (definition-value exp) env) env) 'ok)) (true? (lambda (x) (not (eq? x false)))) (false? (lambda (x) (eq? x false))) (eval-if (lambda (exp env) (if (true? (actual-value (if-predicate exp) env)) (eval (if-consequent exp) env) (eval (if-alternative exp) env)))) (eval-sequence (lambda (exps env) (<change> (if (last-exp? exps) (eval (first-exp exps) env) (begin (eval (first-exp exps) env) (eval-sequence (rest-exps exps) env))) ((lambda (x) x) (if (last-exp? exps) (eval (first-exp exps) env) (begin (eval (first-exp exps) env) (eval-sequence (rest-exps exps) env))))))) (self-evaluating? (lambda (exp) (if (number? exp) (<change> true (if (string? exp) true false)) (<change> (if (string? exp) true false) true)))) (tagged-list? (lambda (exp tag) (if (pair? exp) (eq? (car exp) tag) false))) (quoted? (lambda (exp) (<change> (tagged-list? exp 'quote) ((lambda (x) x) (tagged-list? exp 'quote))))) (text-of-quotation (lambda (exp) (<change> (cadr exp) ((lambda (x) x) (cadr exp))))) (quasiquoted? (lambda (exp) (<change> (tagged-list? exp 'quasiquote) ((lambda (x) x) (tagged-list? exp 'quasiquote))))) (unquote? (lambda (exp) (tagged-list? exp 'unquote))) (variable? (lambda (exp) (symbol? exp))) (assignment? (lambda (exp) (tagged-list? exp 'set!))) (assignment-variable (lambda (exp) (cadr exp))) (assignment-value (lambda (exp) (caddr exp))) (definition? (lambda (exp) (tagged-list? exp 'define))) (definition-variable (lambda (exp) (if (symbol? (cadr exp)) (cadr exp) (caadr exp)))) (definition-value (lambda (exp) (if (symbol? (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp))))) (if? (lambda (exp) (tagged-list? exp 'if))) (if-predicate (lambda (exp) (cadr exp))) (if-consequent (lambda (exp) (caddr exp))) (if-alternative (lambda (exp) (if (not (null? (cdddr exp))) (cadddr exp) 'false))) (make-if (lambda (predicate consequent alternative) (list 'if predicate consequent alternative))) (lambda? (lambda (exp) (tagged-list? exp 'lambda))) (lambda-parameters (lambda (exp) (cadr exp))) (lambda-body (lambda (exp) (cddr exp))) (make-lambda (lambda (parameters body) (cons 'lambda (cons parameters body)))) (cond? (lambda (exp) (<change> (tagged-list? exp 'cond) ((lambda (x) x) (tagged-list? exp 'cond))))) (cond-clauses (lambda (exp) (cdr exp))) (cond-else-clause? (lambda (clause) (eq? (cond-predicate clause) 'else))) (cond-predicate (lambda (clause) (car clause))) (cond-actions (lambda (clause) (cdr clause))) (cond->if (lambda (exp) (<change> (expand-clauses (cond-clauses exp)) ((lambda (x) x) (expand-clauses (cond-clauses exp)))))) (expand-clauses (lambda (clauses) (if (null? clauses) 'false (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF")) (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest))))))) (begin? (lambda (exp) (tagged-list? exp 'begin))) (begin-actions (lambda (exp) (cdr exp))) (last-exp? (lambda (seq) (null? (cdr seq)))) (first-exp (lambda (seq) (car seq))) (rest-exps (lambda (seq) (<change> (cdr seq) ((lambda (x) x) (cdr seq))))) (sequence->exp (lambda (seq) (if (null? seq) seq (if (last-exp? seq) (first-exp seq) (make-begin seq))))) (make-begin (lambda (seq) (cons 'begin seq))) (application? (lambda (exp) (pair? exp))) (operator (lambda (exp) (car exp))) (operands (lambda (exp) (cdr exp))) (no-operands? (lambda (ops) (<change> () (display null?)) (<change> (null? ops) ((lambda (x) x) (null? ops))))) (first-operand (lambda (ops) (car ops))) (rest-operands (lambda (ops) (<change> (cdr ops) ((lambda (x) x) (cdr ops))))) (make-procedure (lambda (parameters body env) (list 'procedure parameters body env))) (compound-procedure? (lambda (p) (tagged-list? p 'procedure))) (procedure-parameters (lambda (p) (cadr p))) (procedure-body (lambda (p) (caddr p))) (procedure-environment (lambda (p) (cadddr p))) (enclosing-environment (lambda (env) (cdr env))) (first-frame (lambda (env) (car env))) (the-empty-environment ()) (extend-environment (lambda (vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied") (error "Too few arguments supplied"))))) (make-frame (lambda (variables values) (cons variables values))) (frame-variables (lambda (frame) (car frame))) (frame-values (lambda (frame) (cdr frame))) (add-binding-to-frame! (lambda (var val frame) (<change> (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame)))) (<change> (set-cdr! frame (cons val (cdr frame))) (set-car! frame (cons var (car frame)))))) (lookup-variable-value (lambda (var env) (letrec ((env-loop (lambda (env) (letrec ((scan (lambda (vars vals) (if (null? vars) (env-loop (enclosing-environment env)) (if (eq? var (car vars)) (car vals) (scan (cdr vars) (cdr vals))))))) (if (eq? env the-empty-environment) (error "Unbound variable") (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame)))))))) (<change> (env-loop env) ((lambda (x) x) (env-loop env)))))) (set-variable-value! (lambda (var val env) (letrec ((env-loop (lambda (env) (letrec ((scan (lambda (vars vals) (<change> () (display car)) (if (null? vars) (env-loop (enclosing-environment env)) (if (eq? var (car vars)) (set-car! vals val) (scan (cdr vars) (cdr vals))))))) (if (eq? env the-empty-environment) (error "Unbound variable -- SET!") (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame)))))))) (env-loop env)))) (define-variable! (lambda (var val env) (let ((frame (first-frame env))) (letrec ((scan (lambda (vars vals) (if (null? vars) (add-binding-to-frame! var val frame) (if (eq? var (car vars)) (set-car! vals val) (scan (cdr vars) (cdr vals))))))) (scan (frame-variables frame) (frame-values frame)))))) (setup-environment (lambda () (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true true initial-env) (<change> (define-variable! 'false false initial-env) ()) initial-env))) (primitive-procedure? (lambda (proc) (tagged-list? proc 'primitive))) (primitive-implementation (lambda (proc) (cadr proc))) (primitive-procedures (list (list 'null? null?) (list '+ +) (list '- -) (list '* *) (list '/ /) (list '= =) (list '<= <=) (list '>= >=) (list '< <) (list '> >) (list 'newline newline) (list 'display display))) (primitive-procedure-names (lambda () (map car primitive-procedures))) (primitive-procedure-objects (lambda () (<change> (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures) ((lambda (x) x) (map (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures))))) (apply-primitive-procedure (lambda (proc args) (apply-in-underlying-scheme (primitive-implementation proc) args))) (input-prompt ";;; L-Eval input:") (output-prompt ";;; L-Eval value:") (prompt-for-input (lambda (string) (<change> (newline) (newline)) (<change> (newline) (newline)) (display string) (newline))) (announce-output (lambda (string) (newline) (display string) (newline))) (user-print (lambda (object) (if (compound-procedure? object) (display (list 'compound-procedure (procedure-parameters object) (procedure-body object) '<procedure-env>)) (display object)))) (the-global-environment (setup-environment)) (make-list (lambda (xs) (if (null? xs) () (let ((x (car xs))) (list 'cons (if (unquote? x) (cadr x) (list 'quote x)) (make-list (cdr xs))))))) (unaware-eval-quotation-args (lambda (qargs env) qargs)) (aware-eval-quotation-args (lambda (qargs env) (if (pair? qargs) (eval (make-list qargs) env) qargs))) (eval-quotation-args unaware-eval-quotation-args)) (<change> (display "Loading definitions of cons, car, cdr as compound procedures. ") ()) (eval (__toplevel_cons 'begin (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'cons (__toplevel_cons 'x (__toplevel_cons 'y ()))) (__toplevel_cons (__toplevel_cons 'lambda (__toplevel_cons (__toplevel_cons 'm ()) (__toplevel_cons (__toplevel_cons 'm (__toplevel_cons 'x (__toplevel_cons 'y ()))) ()))) ()))) (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'car (__toplevel_cons 'z ())) (__toplevel_cons (__toplevel_cons 'z (__toplevel_cons (__toplevel_cons 'lambda (__toplevel_cons (__toplevel_cons 'p (__toplevel_cons 'q ())) (__toplevel_cons 'p ()))) ())) ()))) (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'cdr (__toplevel_cons 'z ())) (__toplevel_cons (__toplevel_cons 'z (__toplevel_cons (__toplevel_cons 'lambda (__toplevel_cons (__toplevel_cons 'p (__toplevel_cons 'q ())) (__toplevel_cons 'q ()))) ())) ()))) (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'list-ref (__toplevel_cons 'items (__toplevel_cons 'n ()))) (__toplevel_cons (__toplevel_cons 'if (__toplevel_cons (__toplevel_cons '= (__toplevel_cons 'n (__toplevel_cons 0 ()))) (__toplevel_cons (__toplevel_cons 'car (__toplevel_cons 'items ())) (__toplevel_cons (__toplevel_cons 'list-ref (__toplevel_cons (__toplevel_cons 'cdr (__toplevel_cons 'items ())) (__toplevel_cons (__toplevel_cons '- (__toplevel_cons 'n (__toplevel_cons 1 ()))) ()))) ())))) ()))) (__toplevel_cons (__toplevel_cons 'define (__toplevel_cons (__toplevel_cons 'map (__toplevel_cons 'proc (__toplevel_cons 'items ()))) (__toplevel_cons (__toplevel_cons 'if (__toplevel_cons (__toplevel_cons 'null? (__toplevel_cons 'items ())) (__toplevel_cons (__toplevel_cons 'quote (__toplevel_cons () ())) (__toplevel_cons (__toplevel_cons 'cons (__toplevel_cons (__toplevel_cons 'proc (__toplevel_cons (__toplevel_cons 'car (__toplevel_cons 'items ())) ())) (__toplevel_cons (__toplevel_cons 'map (__toplevel_cons 'proc (__toplevel_cons (__toplevel_cons 'cdr (__toplevel_cons 'items ())) ()))) ()))) ())))) ()))) ())))))) the-global-environment))
a9f50e66858d2eb03ac5ca21077b37dabb06e1c594e109dd965ef6333a6b9719
jeromesimeon/Galax
xquery_core_ast_util.mli
(***********************************************************************) (* *) (* GALAX *) (* XQuery Engine *) (* *) Copyright 2001 - 2007 . (* Distributed only by permission. *) (* *) (***********************************************************************) $ I d : , v 1.30 2007/10/16 01:25:34 Module : Xquery_core_ast_util Description : This module implements some useful operations the XQuery core AST . Description: This module implements some useful operations the XQuery core AST. *) open Xquery_common_ast open Xquery_core_ast open Xquery_core_ast_annotation (*********************) Core AST creation (*********************) Core typeswitch patterns val mkcpattern : cpattern_desc -> cpattern val fmkcpattern : cpattern_desc -> Finfo.finfo -> cpattern Core sequence types val mkcsequencetype : csequencetype_desc -> csequencetype val fmkcsequencetype : csequencetype_desc -> Finfo.finfo -> csequencetype Core expressions val fmkcexpr : acexpr_desc -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val fmkacexpr : acexpr_desc -> ast_annot -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val fmkcfunction_def : acfunction_def_desc -> Finfo.finfo -> acfunction_def val fmkcvar_decl : acvar_decl_desc -> Finfo.finfo -> acvar_decl (***********************************************************************) (* *) (* GALAX *) (* XQuery Engine *) (* *) Copyright 2001 - 2007 . (* Distributed only by permission. *) (* *) (***********************************************************************) $ I d : , v 1.30 2007/10/16 01:25:34 Module : Xquery_core_ast_util Description : This module implements some useful operations the XQuery core AST . Description: This module implements some useful operations the XQuery core AST. *) open Xquery_common_ast open Xquery_core_ast open Xquery_core_ast_annotation (*********************) Core AST creation (*********************) Core typeswitch patterns val mkcpattern : cpattern_desc -> cpattern val fmkcpattern : cpattern_desc -> Finfo.finfo -> cpattern Core sequence types val mkcsequencetype : csequencetype_desc -> csequencetype val fmkcsequencetype : csequencetype_desc -> Finfo.finfo -> csequencetype Core expressions val fmkcexpr : acexpr_desc -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val fmkacexpr : acexpr_desc -> ast_annot -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val fmkcfunction_def : acfunction_def_desc -> Finfo.finfo -> acfunction_def val fmkcvar_decl : acvar_decl_desc -> Finfo.finfo -> acvar_decl val fmkcserver_decl : acserver_decl_desc -> Finfo.finfo -> acserver_decl val fmkcindex_def : acindex_def_desc -> Finfo.finfo -> acindex_def Core prolog AST creation val fmkcprolog : acfunction_def list -> acvar_decl list -> acindex_def list -> acprolog Core module AST creation val fmkcmodule_from_library_module : acxmodule -> acstatement list -> acxmodule (************************************) (* Returns the core expression kind *) (************************************) (* Note: This is used for monitoring - Jerome *) type cexpr_kind = | CEKUnordered | CEKOrdered | CEKFLWOR | CEKOrderBy (* "Temporary" OrderBy core expression -- Never exposed between processing phases *) | CEKIf | CEKWhile | CEKTypeswitch | CEKVar | CEKScalar | CEKProtoValue | CEKDocument | CEKPI | CEKPIComputed | CEKComment | CEKCommentComputed | CEKText | CEKCharRef | CEKTextComputed | CEKCall | CEKOverloadedCall | CEKSeq | CEKEmpty | CEKElem | CEKAnyElem | CEKAttr | CEKAnyAttr | CEKError | CEKTreat | CEKValidate | CEKCast | CEKCastable | CEKAxis | CEKSome | CEKEvery | CEKLetServerImplement | CEKExecute | CEKForServerClose | CEKEvalClosure | CEKCopy | CEKDelete | CEKDetach | CEKInsert | CEKRename | CEKReplace | CEKSnap | CEKLetvar | CEKSet | CEKImperativeSeq val get_cexpr_kind : acexpr -> cexpr_kind (*****************************) (* Module related operations *) (*****************************) val merge_cmodules : acxmodule -> acxmodule -> acxmodule (*****************************************) (* Some macros used during normalization *) (*****************************************) (* Builds a variable expression from its name *) val mkcvar : cvname -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr (* Generate a fresh variable name and a corresponding variable expression in the 'fs:' namespace *) val cexpr_fs_dot : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val cexpr_fs_sequence : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val cexpr_fs_position : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val cexpr_fs_last : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr Core expression for ( ) val cexpr_empty : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr Adding ' parenthesises right associatively : l = [ e1 ; e2 ; e3 ... ; en ] - > ( e1 ( e2 ( e3 ( ... en ) ... ) -> (e1 (e2 (e3 (... en)...) *) val map_to_sequence : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr list -> acexpr val map_to_imperative_sequence : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr list -> acexpr Extract all variable bindings from a expressions Note : This is used to build the tuple in a with order by clause . - Jerome - Jerome *) val all_cflwr_bindings : acfl_expr list -> cvname list (* Creates a FLWOR expression only with let bindings. This is used at different places in the code, notably when doing rewriting and factorization. If the list of input let bindings is empty, returns the return expression 'as is' - Jerome *) val make_let_flwor : acfl_expr list -> acexpr -> ast_annot -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val make_for_flwor : acfl_expr list -> acexpr -> ast_annot -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr (* Remove empty text nodes at head and tail of expression list *) val remove_empty_textnodes : acexpr list -> acexpr list (* Some operations on core FLWOR expressions *) val get_first_fl_clause : acexpr -> acfl_expr option * acexpr val add_first_fl_clause : acfl_expr -> acexpr -> acexpr val build_flwor_from_fl_clauses : acfl_expr list -> acexpr -> acexpr (*************************) (* Access to annotations *) (*************************) val set_annotation_for_cexpr : acexpr -> ast_annot -> unit val get_type_annotation_from_cexpr : acexpr -> Xquery_type_core_ast.cxtype val set_type_annotation_for_cexpr : acexpr -> Xquery_type_core_ast.cxtype -> unit val get_expr_from_insert_location : acinsert_location -> acexpr added by for determining max_one property val has_max_one : acexpr -> bool
null
https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/ast/xquery_core_ast_util.mli
ocaml
********************************************************************* GALAX XQuery Engine Distributed only by permission. ********************************************************************* ******************* ******************* ********************************************************************* GALAX XQuery Engine Distributed only by permission. ********************************************************************* ******************* ******************* ********************************** Returns the core expression kind ********************************** Note: This is used for monitoring - Jerome "Temporary" OrderBy core expression -- Never exposed between processing phases *************************** Module related operations *************************** *************************************** Some macros used during normalization *************************************** Builds a variable expression from its name Generate a fresh variable name and a corresponding variable expression in the 'fs:' namespace Creates a FLWOR expression only with let bindings. This is used at different places in the code, notably when doing rewriting and factorization. If the list of input let bindings is empty, returns the return expression 'as is' - Jerome Remove empty text nodes at head and tail of expression list Some operations on core FLWOR expressions *********************** Access to annotations ***********************
Copyright 2001 - 2007 . $ I d : , v 1.30 2007/10/16 01:25:34 Module : Xquery_core_ast_util Description : This module implements some useful operations the XQuery core AST . Description: This module implements some useful operations the XQuery core AST. *) open Xquery_common_ast open Xquery_core_ast open Xquery_core_ast_annotation Core AST creation Core typeswitch patterns val mkcpattern : cpattern_desc -> cpattern val fmkcpattern : cpattern_desc -> Finfo.finfo -> cpattern Core sequence types val mkcsequencetype : csequencetype_desc -> csequencetype val fmkcsequencetype : csequencetype_desc -> Finfo.finfo -> csequencetype Core expressions val fmkcexpr : acexpr_desc -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val fmkacexpr : acexpr_desc -> ast_annot -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val fmkcfunction_def : acfunction_def_desc -> Finfo.finfo -> acfunction_def val fmkcvar_decl : acvar_decl_desc -> Finfo.finfo -> acvar_decl Copyright 2001 - 2007 . $ I d : , v 1.30 2007/10/16 01:25:34 Module : Xquery_core_ast_util Description : This module implements some useful operations the XQuery core AST . Description: This module implements some useful operations the XQuery core AST. *) open Xquery_common_ast open Xquery_core_ast open Xquery_core_ast_annotation Core AST creation Core typeswitch patterns val mkcpattern : cpattern_desc -> cpattern val fmkcpattern : cpattern_desc -> Finfo.finfo -> cpattern Core sequence types val mkcsequencetype : csequencetype_desc -> csequencetype val fmkcsequencetype : csequencetype_desc -> Finfo.finfo -> csequencetype Core expressions val fmkcexpr : acexpr_desc -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val fmkacexpr : acexpr_desc -> ast_annot -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val fmkcfunction_def : acfunction_def_desc -> Finfo.finfo -> acfunction_def val fmkcvar_decl : acvar_decl_desc -> Finfo.finfo -> acvar_decl val fmkcserver_decl : acserver_decl_desc -> Finfo.finfo -> acserver_decl val fmkcindex_def : acindex_def_desc -> Finfo.finfo -> acindex_def Core prolog AST creation val fmkcprolog : acfunction_def list -> acvar_decl list -> acindex_def list -> acprolog Core module AST creation val fmkcmodule_from_library_module : acxmodule -> acstatement list -> acxmodule type cexpr_kind = | CEKUnordered | CEKOrdered | CEKFLWOR | CEKIf | CEKWhile | CEKTypeswitch | CEKVar | CEKScalar | CEKProtoValue | CEKDocument | CEKPI | CEKPIComputed | CEKComment | CEKCommentComputed | CEKText | CEKCharRef | CEKTextComputed | CEKCall | CEKOverloadedCall | CEKSeq | CEKEmpty | CEKElem | CEKAnyElem | CEKAttr | CEKAnyAttr | CEKError | CEKTreat | CEKValidate | CEKCast | CEKCastable | CEKAxis | CEKSome | CEKEvery | CEKLetServerImplement | CEKExecute | CEKForServerClose | CEKEvalClosure | CEKCopy | CEKDelete | CEKDetach | CEKInsert | CEKRename | CEKReplace | CEKSnap | CEKLetvar | CEKSet | CEKImperativeSeq val get_cexpr_kind : acexpr -> cexpr_kind val merge_cmodules : acxmodule -> acxmodule -> acxmodule val mkcvar : cvname -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val cexpr_fs_dot : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val cexpr_fs_sequence : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val cexpr_fs_position : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val cexpr_fs_last : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr Core expression for ( ) val cexpr_empty : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr Adding ' parenthesises right associatively : l = [ e1 ; e2 ; e3 ... ; en ] - > ( e1 ( e2 ( e3 ( ... en ) ... ) -> (e1 (e2 (e3 (... en)...) *) val map_to_sequence : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr list -> acexpr val map_to_imperative_sequence : Xquery_ast.expr_handle -> Finfo.finfo -> acexpr list -> acexpr Extract all variable bindings from a expressions Note : This is used to build the tuple in a with order by clause . - Jerome - Jerome *) val all_cflwr_bindings : acfl_expr list -> cvname list val make_let_flwor : acfl_expr list -> acexpr -> ast_annot -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val make_for_flwor : acfl_expr list -> acexpr -> ast_annot -> Xquery_ast.expr_handle -> Finfo.finfo -> acexpr val remove_empty_textnodes : acexpr list -> acexpr list val get_first_fl_clause : acexpr -> acfl_expr option * acexpr val add_first_fl_clause : acfl_expr -> acexpr -> acexpr val build_flwor_from_fl_clauses : acfl_expr list -> acexpr -> acexpr val set_annotation_for_cexpr : acexpr -> ast_annot -> unit val get_type_annotation_from_cexpr : acexpr -> Xquery_type_core_ast.cxtype val set_type_annotation_for_cexpr : acexpr -> Xquery_type_core_ast.cxtype -> unit val get_expr_from_insert_location : acinsert_location -> acexpr added by for determining max_one property val has_max_one : acexpr -> bool
a274b84014847da71a22caea4e04a24d3ed2420d94c701b8efdb116ddaf9f6d3
chebert/schemeish
bundle.lisp
(in-package #:schemeish.backend) (install-syntax!) (defvar *get-bundle-type-predicate* (gensym)) (defvar *get-bundle-predicate-symbol* (gensym)) (define (make-bundle-predicate name) "Returns a predicate which, only evaluates to true when given a bundle with this type-predicate" (define (dispatch arg) (cond ((eq? *get-bundle-predicate-symbol* arg) name) ((procedure? arg) (eq? dispatch [arg *get-bundle-type-predicate*])) (t nil))) dispatch) (export 'make-bundle-predicate) (export (define (bundle-predicate-symbol predicate) "Returns the debug symbol associated with predicate." [predicate *get-bundle-predicate-symbol*])) (defvar *name?* (make-bundle-predicate :bundle)) (assert [*name?* (lambda (arg) (cond ((eq *get-bundle-type-predicate* arg) *name?*)))]) (defvar *get-bundle-permissions* (gensym "GET-BUNDLE-PERMISSIONS")) (define (get-fn-identifier? fn-identifier) (and (eql (first fn-identifier) :get) (symbol? (second fn-identifier)) (empty? (rest (rest fn-identifier))))) (define (set-fn-identifier? fn-identifier) (and (eql (first fn-identifier) :set!) (symbol? (second fn-identifier)) (or (empty? (rest (rest fn-identifier))) (and (symbol? (third fn-identifier)) (empty? (rest (rest (rest fn-identifier)))))))) (define (set-fn-identifier-setter-keyword fn-identifier) (make-keyword (make-symbol (or (and-let* ((name (third fn-identifier))) (symbol->string name)) (concatenate 'string "SET-" (symbol->string (second fn-identifier)) "!"))))) (define (fn-identifier->permission-name fn-identifier) (cond ((symbol? fn-identifier) (make-keyword fn-identifier)) ((get-fn-identifier? fn-identifier) (make-keyword (second fn-identifier))) ((set-fn-identifier? fn-identifier) (make-keyword (set-fn-identifier-setter-keyword fn-identifier))))) ;; TODO: switch to a case statement (define (bundle-fn-identifier->permission-form arg-name fn-identifier) (let* ((permission-name (fn-identifier->permission-name fn-identifier)) (test-permission-form `(eq ,permission-name ,arg-name))) (cond ((symbol? fn-identifier) `(,test-permission-form ,fn-identifier)) ((get-fn-identifier? fn-identifier) `(,test-permission-form (lambda () ,(second fn-identifier)))) ((set-fn-identifier? fn-identifier) (let ((value-name (unique-symbol 'value))) `(,test-permission-form (lambda (,value-name) (set! ,(second fn-identifier) ,value-name)))))))) (assert (equal? (bundle-fn-identifier->permission-form 'arg 'fn-name) '((EQ :FN-NAME ARG) FN-NAME))) (assert (equal? (bundle-fn-identifier->permission-form 'arg '(:get variable-name)) '((EQ :VARIABLE-NAME ARG) (LAMBDA NIL VARIABLE-NAME)))) (assert (equal? (with-readable-symbols (bundle-fn-identifier->permission-form 'arg '(:set! variable-name))) '((EQ :SET-VARIABLE-NAME! ARG) (LAMBDA (VALUE) (SET! VARIABLE-NAME VALUE))))) (assert (equal? (with-readable-symbols (bundle-fn-identifier->permission-form 'arg '(:set! variable-name setter-name!))) '((EQ :setter-name! ARG) (LAMBDA (VALUE) (SET! VARIABLE-NAME VALUE))))) (for-macros (defvar *bundles* (make-hash-table :weakness :key)) (define (register-bundle! bundle) (setf (gethash bundle *bundles*) t) bundle)) (export (define (bundle? bundle) (gethash bundle *bundles*))) (defmacro bundle (type-predicate &rest fn-identifiers) "Create a bundle of permissions for closure objects. A bundle is a function (bundle-proc msg) => permission, where each permission is meant to be a locally defined function described by fn-identifiers. Each fn-identifier is one of: fn-name => a symbolic name which maps to a function value. Produces a :fn-name permission. (:get variable-name) => variable-name is a symbolic name which maps to a value. Produces a :variable-name permission which returns a function of zero arguments. (:set! variable-name <setter-name>) => variable-name is a symbolic name which maps to a value. Produces a :setter-name permission which returns a function of one argument. If setter-name defaults to :set-variable-name! if not provided. Type-predicate is nil or a predicate created by make-bundle-predicate. Example: (defparameter *point?* (make-bundle-predicate :point)) (define (make-point x y) (define (get-x) x) (define (get-y) y) (define (set-x! new-x) (setq x new-x)) (define (set-y! new-y) (setq y new-y)) (bundle *point?* get-x get-y set-x! set-y!)) (let ((point (make-point 3 4))) = > closure of 0 arguments (assert (= 3 [[point :get-x]])) = > closure of 1 argument [[point :set-x!] 32] (assert (= 32 [[point :get-x]])) (assert [*point?* point]) (bundle-permissions bundle) ; => '(:get-x :get-y :set-x! :set-y!))" (let* ((arg-name (unique-symbol 'arg)) (permission-forms (map (lcurry #'bundle-fn-identifier->permission-form arg-name) fn-identifiers)) (permission-names (map #'fn-identifier->permission-name fn-identifiers))) (assert (every #'identity permission-forms)) `(register-bundle! (lambda (,arg-name) (cond ((eq *get-bundle-type-predicate* ,arg-name) ,(cond ((null? type-predicate) '(constantly nil)) ((symbolp type-predicate) `(function ,type-predicate)) (t type-predicate))) ((eq *get-bundle-permissions* ,arg-name) ',permission-names) ;; TODO: switch to a case statement ,@permission-forms (t (error "Unrecognized permission ~S for bundle. Expected one of: ~S" ,arg-name ',permission-names))))))) (export 'bundle) (defvar *bundle-print-object-table* (make-hash-table :weakness :key)) (export (define (define-bundle-print-object bundle print-object-proc) "Defines the print-object-proc for the given bundle. [print-object-proc stream] will be called when print-object is called on the bundle." (setf (gethash bundle *bundle-print-object-table*) print-object-proc) bundle)) (export (define (undefine-bundle-print-object bundle) "Removes the print-object-proc for the given bundle." (remhash bundle *bundle-print-object-table*) bundle)) (define (bundle-print-object-proc bundle) (gethash bundle *bundle-print-object-table*)) (export (define (bundle-documentation bundle) "Generates documentation for bundle and all of its permissions." (with-output-to-string (s) (format s "~%A bundle of type ~S with permissions:" (bundle-predicate-symbol [bundle *get-bundle-type-predicate*])) (for-each (lambda (permission) (let ((fn [bundle permission])) (format s "~& ~S: ~A" (cons (list 'bundle permission) (arg:arglist fn)) (documentation fn 'function)))) (bundle-permissions bundle))))) (export (define (bundle-permissions bundle) "Return a list of permissions to the bundle." [bundle *get-bundle-permissions*])) (define point? (make-bundle-predicate :point)) (define (make-bundle-point x y) (define (get-x) "x-coord" x) (define (get-y) "y-coord" y) (define (set-x! new-x) "set x-coord to new-x" (setq x new-x)) (define (set-y! new-y) "set y-coord to new-y" (setq y new-y)) (bundle #'point? get-x get-y set-x! set-y!)) (defmethod print-object :around ((object function) stream) (if (bundle? object) (let ((proc (bundle-print-object-proc object))) (if proc [proc stream] (print-unreadable-object (object stream :identity t) (format stream "BUNDLE ~S" (bundle-predicate-symbol [object *get-bundle-type-predicate*]))))) (call-next-method))) (make-bundle-point 3 4) (bundle-documentation (make-bundle-point 3 4)) "(MAKE-BUNDLE-POINT 3 4) A bundle of type :POINT with permissions: ((BUNDLE :GET-X)): x-coord ((BUNDLE :GET-Y)): y-coord ((BUNDLE :SET-X!) NEW-X): set x-coord to new-x ((BUNDLE :SET-Y!) NEW-Y): set y-coord to new-y" (let ((point (make-bundle-point 3 4))) (assert (bundle? point)) (assert (= 3 [[point :get-x]])) [[point :set-x!] 32] (assert (= 32 [[point :get-x]])) (assert (point? point))) #+nil (sb-introspect:function-lambda-list [(make-bundle-point 3 4) :set-x!]) ;; => (NEW-X) (uninstall-syntax!)
null
https://raw.githubusercontent.com/chebert/schemeish/93ea08b17e6d8876f086e1a34a21b538174b2c39/src/bundle.lisp
lisp
TODO: switch to a case statement => '(:get-x :get-y :set-x! :set-y!))" TODO: switch to a case statement => (NEW-X)
(in-package #:schemeish.backend) (install-syntax!) (defvar *get-bundle-type-predicate* (gensym)) (defvar *get-bundle-predicate-symbol* (gensym)) (define (make-bundle-predicate name) "Returns a predicate which, only evaluates to true when given a bundle with this type-predicate" (define (dispatch arg) (cond ((eq? *get-bundle-predicate-symbol* arg) name) ((procedure? arg) (eq? dispatch [arg *get-bundle-type-predicate*])) (t nil))) dispatch) (export 'make-bundle-predicate) (export (define (bundle-predicate-symbol predicate) "Returns the debug symbol associated with predicate." [predicate *get-bundle-predicate-symbol*])) (defvar *name?* (make-bundle-predicate :bundle)) (assert [*name?* (lambda (arg) (cond ((eq *get-bundle-type-predicate* arg) *name?*)))]) (defvar *get-bundle-permissions* (gensym "GET-BUNDLE-PERMISSIONS")) (define (get-fn-identifier? fn-identifier) (and (eql (first fn-identifier) :get) (symbol? (second fn-identifier)) (empty? (rest (rest fn-identifier))))) (define (set-fn-identifier? fn-identifier) (and (eql (first fn-identifier) :set!) (symbol? (second fn-identifier)) (or (empty? (rest (rest fn-identifier))) (and (symbol? (third fn-identifier)) (empty? (rest (rest (rest fn-identifier)))))))) (define (set-fn-identifier-setter-keyword fn-identifier) (make-keyword (make-symbol (or (and-let* ((name (third fn-identifier))) (symbol->string name)) (concatenate 'string "SET-" (symbol->string (second fn-identifier)) "!"))))) (define (fn-identifier->permission-name fn-identifier) (cond ((symbol? fn-identifier) (make-keyword fn-identifier)) ((get-fn-identifier? fn-identifier) (make-keyword (second fn-identifier))) ((set-fn-identifier? fn-identifier) (make-keyword (set-fn-identifier-setter-keyword fn-identifier))))) (define (bundle-fn-identifier->permission-form arg-name fn-identifier) (let* ((permission-name (fn-identifier->permission-name fn-identifier)) (test-permission-form `(eq ,permission-name ,arg-name))) (cond ((symbol? fn-identifier) `(,test-permission-form ,fn-identifier)) ((get-fn-identifier? fn-identifier) `(,test-permission-form (lambda () ,(second fn-identifier)))) ((set-fn-identifier? fn-identifier) (let ((value-name (unique-symbol 'value))) `(,test-permission-form (lambda (,value-name) (set! ,(second fn-identifier) ,value-name)))))))) (assert (equal? (bundle-fn-identifier->permission-form 'arg 'fn-name) '((EQ :FN-NAME ARG) FN-NAME))) (assert (equal? (bundle-fn-identifier->permission-form 'arg '(:get variable-name)) '((EQ :VARIABLE-NAME ARG) (LAMBDA NIL VARIABLE-NAME)))) (assert (equal? (with-readable-symbols (bundle-fn-identifier->permission-form 'arg '(:set! variable-name))) '((EQ :SET-VARIABLE-NAME! ARG) (LAMBDA (VALUE) (SET! VARIABLE-NAME VALUE))))) (assert (equal? (with-readable-symbols (bundle-fn-identifier->permission-form 'arg '(:set! variable-name setter-name!))) '((EQ :setter-name! ARG) (LAMBDA (VALUE) (SET! VARIABLE-NAME VALUE))))) (for-macros (defvar *bundles* (make-hash-table :weakness :key)) (define (register-bundle! bundle) (setf (gethash bundle *bundles*) t) bundle)) (export (define (bundle? bundle) (gethash bundle *bundles*))) (defmacro bundle (type-predicate &rest fn-identifiers) "Create a bundle of permissions for closure objects. A bundle is a function (bundle-proc msg) => permission, where each permission is meant to be a locally defined function described by fn-identifiers. Each fn-identifier is one of: fn-name => a symbolic name which maps to a function value. Produces a :fn-name permission. (:get variable-name) => variable-name is a symbolic name which maps to a value. Produces a :variable-name permission which returns a function of zero arguments. (:set! variable-name <setter-name>) => variable-name is a symbolic name which maps to a value. Produces a :setter-name permission which returns a function of one argument. If setter-name defaults to :set-variable-name! if not provided. Type-predicate is nil or a predicate created by make-bundle-predicate. Example: (defparameter *point?* (make-bundle-predicate :point)) (define (make-point x y) (define (get-x) x) (define (get-y) y) (define (set-x! new-x) (setq x new-x)) (define (set-y! new-y) (setq y new-y)) (bundle *point?* get-x get-y set-x! set-y!)) (let ((point (make-point 3 4))) = > closure of 0 arguments (assert (= 3 [[point :get-x]])) = > closure of 1 argument [[point :set-x!] 32] (assert (= 32 [[point :get-x]])) (assert [*point?* point]) (let* ((arg-name (unique-symbol 'arg)) (permission-forms (map (lcurry #'bundle-fn-identifier->permission-form arg-name) fn-identifiers)) (permission-names (map #'fn-identifier->permission-name fn-identifiers))) (assert (every #'identity permission-forms)) `(register-bundle! (lambda (,arg-name) (cond ((eq *get-bundle-type-predicate* ,arg-name) ,(cond ((null? type-predicate) '(constantly nil)) ((symbolp type-predicate) `(function ,type-predicate)) (t type-predicate))) ((eq *get-bundle-permissions* ,arg-name) ',permission-names) ,@permission-forms (t (error "Unrecognized permission ~S for bundle. Expected one of: ~S" ,arg-name ',permission-names))))))) (export 'bundle) (defvar *bundle-print-object-table* (make-hash-table :weakness :key)) (export (define (define-bundle-print-object bundle print-object-proc) "Defines the print-object-proc for the given bundle. [print-object-proc stream] will be called when print-object is called on the bundle." (setf (gethash bundle *bundle-print-object-table*) print-object-proc) bundle)) (export (define (undefine-bundle-print-object bundle) "Removes the print-object-proc for the given bundle." (remhash bundle *bundle-print-object-table*) bundle)) (define (bundle-print-object-proc bundle) (gethash bundle *bundle-print-object-table*)) (export (define (bundle-documentation bundle) "Generates documentation for bundle and all of its permissions." (with-output-to-string (s) (format s "~%A bundle of type ~S with permissions:" (bundle-predicate-symbol [bundle *get-bundle-type-predicate*])) (for-each (lambda (permission) (let ((fn [bundle permission])) (format s "~& ~S: ~A" (cons (list 'bundle permission) (arg:arglist fn)) (documentation fn 'function)))) (bundle-permissions bundle))))) (export (define (bundle-permissions bundle) "Return a list of permissions to the bundle." [bundle *get-bundle-permissions*])) (define point? (make-bundle-predicate :point)) (define (make-bundle-point x y) (define (get-x) "x-coord" x) (define (get-y) "y-coord" y) (define (set-x! new-x) "set x-coord to new-x" (setq x new-x)) (define (set-y! new-y) "set y-coord to new-y" (setq y new-y)) (bundle #'point? get-x get-y set-x! set-y!)) (defmethod print-object :around ((object function) stream) (if (bundle? object) (let ((proc (bundle-print-object-proc object))) (if proc [proc stream] (print-unreadable-object (object stream :identity t) (format stream "BUNDLE ~S" (bundle-predicate-symbol [object *get-bundle-type-predicate*]))))) (call-next-method))) (make-bundle-point 3 4) (bundle-documentation (make-bundle-point 3 4)) "(MAKE-BUNDLE-POINT 3 4) A bundle of type :POINT with permissions: ((BUNDLE :GET-X)): x-coord ((BUNDLE :GET-Y)): y-coord ((BUNDLE :SET-X!) NEW-X): set x-coord to new-x ((BUNDLE :SET-Y!) NEW-Y): set y-coord to new-y" (let ((point (make-bundle-point 3 4))) (assert (bundle? point)) (assert (= 3 [[point :get-x]])) [[point :set-x!] 32] (assert (= 32 [[point :get-x]])) (assert (point? point))) #+nil (sb-introspect:function-lambda-list [(make-bundle-point 3 4) :set-x!]) (uninstall-syntax!)
c44a773feca79d82211be8db5b64b28efcd4321db3df804030c898f840be82ca
reanimate/reanimate
Magick.hs
module Reanimate.Driver.Magick ( magickCmd ) where import System.IO.Unsafe (unsafePerformIO) import System.Directory (findExecutable) # NOINLINE magickCmd # |The name of the ImageMagick command . On Unix - like operating systems , the -- command \'convert\' does not conflict with the name of other commands. On Windows , ImageMagick version 7 is readily available , the command \'magick\ ' -- should be present, and is preferred over \'convert\'. If it is not present, -- \'convert\' is assumed to be the relevant command. magickCmd :: String The use of ' ' is justified on the basis that if \'magick\ ' is -- found once, it will always be present. magickCmd = unsafePerformIO $ do mPath <- findExecutable "magick" pure $ maybe "convert" (const "magick") mPath
null
https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/src/Reanimate/Driver/Magick.hs
haskell
command \'convert\' does not conflict with the name of other commands. On should be present, and is preferred over \'convert\'. If it is not present, \'convert\' is assumed to be the relevant command. found once, it will always be present.
module Reanimate.Driver.Magick ( magickCmd ) where import System.IO.Unsafe (unsafePerformIO) import System.Directory (findExecutable) # NOINLINE magickCmd # |The name of the ImageMagick command . On Unix - like operating systems , the Windows , ImageMagick version 7 is readily available , the command \'magick\ ' magickCmd :: String The use of ' ' is justified on the basis that if \'magick\ ' is magickCmd = unsafePerformIO $ do mPath <- findExecutable "magick" pure $ maybe "convert" (const "magick") mPath
e26d611429373cc8d1e1fa074f5a6b576170426939b0ac18110b02fe9736f053
Lambda-X/cljs-repl-web
brepl.clj
(require '[cljs.build.api :as b] '[cljs.repl :as repl] '[cljs.repl.browser :as browser]) (b/build "src" {:main 'cljs-browser-repl.core :output-to "target/cljs-browser-repl.js" :output-dir "target" :verbose true}) (repl/repl (browser/repl-env) :output-dir "target")
null
https://raw.githubusercontent.com/Lambda-X/cljs-repl-web/0dabe8ff18d8c0f4ae6c9f052dc23eb1f5ad262c/scripts/brepl.clj
clojure
(require '[cljs.build.api :as b] '[cljs.repl :as repl] '[cljs.repl.browser :as browser]) (b/build "src" {:main 'cljs-browser-repl.core :output-to "target/cljs-browser-repl.js" :output-dir "target" :verbose true}) (repl/repl (browser/repl-env) :output-dir "target")
35446d0b4a39e888fd3f48cea29f7d353faa7944ddeadc0f2e21e84c2e0baf16
webnf/webnf
datomic.clj
(ns webnf.datomic "# Datomic connection helpers This namespace contains schema helpers, connection and transaction routines" (:import datomic.db.Db (java.util.concurrent BlockingQueue TimeUnit)) (:require [clojure.core.async :as async :refer [go go-loop <! <!! >! >!! close! chan mult tap untap alt! put!]] #_[clojure.core.async.impl.protocols :refer [closed?]] [clojure.core.match :refer [match]] [clojure.core.typed :as typed :refer [ann Any All Keyword List defalias Map HMap HVec I U Seqable]] [clojure.repl] [clojure.string :as str] [clojure.tools.logging :as log] [datomic.api :as dtm :refer [tempid]] [webnf.base :refer [forcat]] [webnf.kv :refer [treduce-kv assoc-when]])) # # Schema generation helpers (defn field "Shortcut syntax for defining datomic schema fields. Parameters: - doc, an optional docstring - id, a namespaced keyword for the field id - type, a keyword getting auto-namespaced to db.type, if it hasn't a namespace - flags, zero or more of #{:many :index :unique :identity :fulltext :no-history :component} Example: (field \"Optional docstring\" :schema.field/id :string :index)" {:arglists '([doc id type & flags] [id type & flags])} [& args] (let [[doc id type & flags] (if (string? (first args)) args (cons nil args)) flags (into #{} flags)] (cond-> {:db/id (tempid :db.part/db) :db.install/_attribute :db.part/db :db/ident id :db/valueType (if (namespace type) type (keyword "db.type" (name type))) :db/cardinality (if (:many flags) :db.cardinality/many :db.cardinality/one)} doc (assoc :db/doc doc) (:index flags) (assoc :db/index true) (:unique flags) (assoc :db/unique (if (:identity flags) :db.unique/identity :db.unique/value)) (:fulltext flags) (assoc :db/fulltext true) (:component flags) (assoc :db/isComponent true) (:no-history flags) (assoc :db/noHistory true)))) (defn enum "Shortcut syntax for an enum value schema field" {:arglists '([doc id] [id])} [& args] (let [[doc id] (if (string? (first args)) args (cons nil args))] (assoc-when {:db/id (tempid :db.part/user) :db/ident id} :db/doc doc))) (defn- parse-fn-body [name args] (let [[typ args] (if (= :- (first args)) [(second args) (nnext args)] [nil args]) [doc args] (if (string? (first args)) [(first args) (next args)] [nil args]) [flags [params & body]] (if (map? (first args)) [(first args) (next args)] [nil args]) known-flags #{:imports :requires :part :db-requires} _ (assert (every? known-flags (keys flags)) (str "Flags can be of " known-flags)) [params' lets] (reduce (fn [[params lets] param] (if (symbol? param) [(conj params param) lets] (let [s (gensym "param-")] [(conj params s) (into lets [param s])]))) [[] []] params) {:keys [imports requires part db-requires] :or {part :db.part/user}} flags] {:name name :doc doc :params params' :imports imports :requires requires :db-requires db-requires :part part :lets lets :body body :typ typ})) (defn- resolve-db-require [r] (let [[local-name var-name] (match [r] [[var-name]] [nil var-name] [[local-name var-name]] [local-name var-name]) var-sym (if (namespace var-name) (symbol (namespace var-name) (name var-name)) (symbol (str (ns-name *ns*)) (name var-name))) the-var (find-var var-sym) varm (meta the-var)] (assert varm (str "No var " var-sym)) [(or local-name (symbol (name var-name))) (:dbfn/name varm) (:dbfn/type varm)])) (ann extract-fn (All [f] [Db Keyword -> f])) (defn ^:no-check extract-fn [db fname] (:db/fn (datomic.api/entity db fname))) (defn- dbfn-source [{:keys [name doc params body imports requires part db-requires lets]} version] (let [db-sym (first params)] `(let ~(into lets (forcat [r db-requires] (let [[local-name fn-name typ] (resolve-db-require r)] [local-name (if (and typ (= version :local)) `(clojure.core.typed/ann-form (extract-fn ~db-sym ~fn-name) ~typ) `(:db/fn (datomic.api/entity ~db-sym ~fn-name)))]))) (try ~@body (catch Exception e# (if (instance? clojure.lang.ExceptionInfo e#) (throw (ex-info (.getMessage e#) (assoc (ex-data e#) :name ~(pr-str name) :args (pr-str ~params)))) (throw (ex-info "Wrapped native exception" {:name ~(pr-str name) :args (pr-str ~params)} e#)))))))) (defn- make-db-fn [{:keys [name doc params body imports requires part db-requires lets] :as desc}] `(assoc-when {:db/id (tempid ~part) :db/ident ~(keyword name) :db/fn (dtm/function (assoc-when {:lang :clojure :params '~params :code '~(dbfn-source desc :transactor)} :imports '~imports :requires (into '~requires '[[clojure.repl] [clojure.pprint]])))} :db/doc ~doc)) (defmacro function "Define a database function to be transacted. Syntax similar to clojure.core/fn, attributes can hold: :part the db partition for the tempid :imports for the db function :requires for the db function :db-requires generates a wrapping let that binds another database function (assumes db as first parameter)" {:arglists (list '[name doc? [& params] & body] '[name doc? attributes [& params] & body])} [name & args] (make-db-fn (parse-fn-body name args))) (defmacro defn-db "Defines a database function in regular clojure, for it to be accessible to type checking, direct calling, ... Has the :db/fn entity in :dbfn/entity of var metadata." {:arglists (list '[name doc? [& params] & body] '[name doc? {:imports [& imports] :requires [& requires] :part db-part} [& params] & body])} [fname & args] (let [{:keys [doc params requires typ imports] :as desc} (parse-fn-body fname args) fnsym (symbol (name fname))] `(do ~@(when (seq requires) [`(require ~@(map (partial list 'quote) requires))]) ~@(when (seq imports) [`(import ~@imports)]) ~@(when typ [`(ann ~fnsym ~typ)]) (defn ~(with-meta fnsym (assoc (meta fname) :dbfn/name (keyword fname) :dbfn/entity (make-db-fn desc) :dbfn/type (list 'quote typ))) ~@(when doc [doc]) ~params ~(dbfn-source desc :local))))) (defn dbfn-tx "Get transaction for installing a db function Example usage ------------- (transact conn (dbfn-tx #'webnf.datomic/compose-tx))" [& fn-vars] (map (comp :dbfn/entity meta) fn-vars)) (defalias DbId (U datomic.db.DbId Long Keyword (HVec [Keyword Any]))) (defalias TxItem (U (HVec [Keyword Any *]) (I (Map Keyword Any) (HMap :mandatory {:db/id DbId})))) (defalias Tx (Seqable TxItem)) (ann compose-tx [Db (Seqable Tx) -> Tx]) (defn-db webnf.datomic/compose-tx "Composes multiple transactions, into one, as if they got transacted in order Example usage ------------- [:webnf.datomic/compose-tx [ [[:db/add (tempid :db.part/user) :db/ident :test/entity]] [[:db/add :test/entity :db/doc \"Cool\"] [:db/add (tempid :db.part/user) :db/lang :test/entity]] ]]" {:requires [[datomic.api :as d]]} [db* txs] (letfn [(tx-map-items [tm] (let [id (or (:db/id tm) (throw (ex-info "Need :db/id" {:t tm})))] (for [[k v] (dissoc tm :db/id)] (if (.startsWith (name k) "_") [:db/add v (keyword (namespace k) (subs (name k) 1)) id] [:db/add id k v])))) (tx-tuple-items [db [op & args :as tt]] (case op (:db/add :db/retract) [tt] (tx-items db (apply (:db/fn (d/entity db op)) db args)))) (tx-items [db tx] (mapcat #(cond (vector? %) (tx-tuple-items db %) (map? %) (tx-map-items %) :else (throw (ex-info "Not a tx element" {:t %}))) tx)) (update-tx-ids [db tx-ids tempids] (reduce-kv (fn [res tid id] (if (res id) res (assoc res id tid))) tx-ids tempids)) (update-id [db tempids tx-ids id] (let [tx-id (or (d/resolve-tempid db tempids id) (d/entid db id) (assert false (str "No id: " id)))] (get tx-ids tx-id tx-id))) (rewrite-tx [db tx tempids tx-ids] (for [[op e a v :as tx-item] (tx-items db tx)] (case op :db/add [op (update-id db tempids tx-ids e) a (if (= :db.type/ref (:db/valueType (d/entity db a))) (update-id db tempids tx-ids v) v)] :db/retract tx-item))) (into-tx [tx-base tx] (persistent! (reduce (fn [res [_ e a :as item]] (assoc! res [e a] item)) (transient tx-base) tx)))] (loop [txs' txs db' db* tx-ids {} tx' {}] (if-let [[tx & rst] (seq txs')] (let [{:keys [db-after tempids]} (d/with db' tx) tx-ids' (update-tx-ids db' tx-ids tempids)] (recur rst db-after tx-ids' (into-tx tx' (rewrite-tx db' tx tempids tx-ids')))) (vals tx'))))) # # Connection routines (defn connect "Create and connect to database. If created, transact schema. Return connection." ([db-uri] (dtm/create-database db-uri) (dtm/connect db-uri)) ([db-uri schema & init-data] (let [created (dtm/create-database db-uri) conn (dtm/connect db-uri)] (when created (log/info "Creating schema on" db-uri) @(dtm/transact conn schema) (doseq [d init-data] @(dtm/transact conn d))) conn))) (defn recreate!! "Drop database and recreate, returning connection." [db-uri schema & init-data] (dtm/delete-database db-uri) (apply connect db-uri schema init-data)) # # # core.async base transaction executor ;; - `tx-executor` executes and waits on transactions, then putting the result into returned channel. ;; - `accumulate-tx-results` is an example implementation of what to do with result channel ;; with reasonable default behavior (defn tx-executor "Take transactions from channel and execute them on conn. Returns an output channel that yields: {:tx transaction :result dereferenced-tx} or {:error exception} Up to concurrent-tx transactions are executed in parallel." ([conn tx-in-channel] (tx-executor conn tx-in-channel 8)) ([conn tx-in-channel concurrent-tx] (let [running-tx (async/pipe (async/map< #(try {:tx (dtm/transact conn %)} (catch Exception e {:error e})) tx-in-channel) (async/chan concurrent-tx))] (async/map< (fn [{:keys [tx error] :as in}] (if error in (try (assoc in :result @tx) (catch Exception e (assoc in :error e))))) running-tx)))) (defn accumulate-tx-results "A simple sink for the return channel of tx-executor. Returns channel, that delivers a single, reduced result, once input channel closes: {:success success-count :errors [list of exceptions]}" [tx-result-channel] (async/reduce (fn [out {:keys [error rx result] :as in}] (if error (do (log/error error "Failed transaction") (update-in out [:errors] conj in)) (do (log/debug "Finishing transaction" result) (update-in out [:success] inc)))) {:success 0 :errors []} tx-result-channel)) # # # Middleware for proper request database access (defn wrap-connection "Ring Middleware connecting to a database on creation, gets database at begin of every request. Associates :datomic/conn and :datomic/db to the request." [h uri] (fn [req] (let [conn (dtm/connect uri)] (h (assoc req :datomic/conn conn :datomic/db (dtm/db conn)))))) # # # Race - free report queue (defn listen-reports "Connect to db and open a tx report queue. Listener channels can be added and removed by put!-ing tap and untap messages to ctl-chan: (put! ctl-chan [:tap listener-channel]) (put! ctl-chan [:untap listener-channel]) The first message on a freshly tapped listener channel will always be {:db most-current-db} Then, datomic transaction reports will arrive as they are received from the report queue." [db-uri ctl-chan] (let [conn (connect db-uri) q (dtm/tx-report-queue conn) report-chan (chan) out-chan (chan) out-mult (mult out-chan) closed (volatile! false)] Set up loop to pull tx updates from the report queue and put them on report - chan (go (try (loop [] (log/trace "TX Q step") (when-not @closed (when-let [report (.poll ^BlockingQueue q 10 TimeUnit/SECONDS)] (log/trace "Received TX report from Q" report) (>! report-chan report)) (recur))) (finally (log/trace "Closing TX Q") (dtm/remove-tx-report-queue conn) (close! report-chan)))) ;; Loop to transfer from report-chan to the out mult, ;; + handling taps and untaps (go-loop [db (let [db (dtm/db conn) {qdb :db-after} (.poll ^BlockingQueue q)] (if (and qdb (> (dtm/basis-t qdb) (dtm/basis-t db))) qdb db))] (log/trace "Delivery step") (alt! :priority true ctl-chan ([ctl-msg] (log/trace "Receiving CTL message" ctl-msg) (match [ctl-msg] [nil] (do (close! out-chan) (vreset! closed true) {:success :shutdown}) [{:control :tap :channel ch}] (do (put! ch {:db db}) (tap out-mult ch) (recur db)) [{:control :untap :channel ch}] (do (untap out-mult ch) (recur db)) :else (do (log/error "Unknown control message" ctl-msg) (log/info "Resuming control loop") (recur db)))) report-chan ([{:as report :keys [db-after]}] (cond (nil? report) (do (log/error "Report chan closed, closing control-chan") (close! ctl-chan) {:error :report-chan-died}) (> (dtm/basis-t db-after) (dtm/basis-t db)) (do (log/trace "Delivering TX report" report) (>! out-chan report) (recur db-after)) :else (recur db)))))))
null
https://raw.githubusercontent.com/webnf/webnf/6a2ccaa755e6e40528eb13a5c36bae16ba4947e7/datomic/src/webnf/datomic.clj
clojure
- `tx-executor` executes and waits on transactions, then putting the result into returned channel. - `accumulate-tx-results` is an example implementation of what to do with result channel with reasonable default behavior Loop to transfer from report-chan to the out mult, + handling taps and untaps
(ns webnf.datomic "# Datomic connection helpers This namespace contains schema helpers, connection and transaction routines" (:import datomic.db.Db (java.util.concurrent BlockingQueue TimeUnit)) (:require [clojure.core.async :as async :refer [go go-loop <! <!! >! >!! close! chan mult tap untap alt! put!]] #_[clojure.core.async.impl.protocols :refer [closed?]] [clojure.core.match :refer [match]] [clojure.core.typed :as typed :refer [ann Any All Keyword List defalias Map HMap HVec I U Seqable]] [clojure.repl] [clojure.string :as str] [clojure.tools.logging :as log] [datomic.api :as dtm :refer [tempid]] [webnf.base :refer [forcat]] [webnf.kv :refer [treduce-kv assoc-when]])) # # Schema generation helpers (defn field "Shortcut syntax for defining datomic schema fields. Parameters: - doc, an optional docstring - id, a namespaced keyword for the field id - type, a keyword getting auto-namespaced to db.type, if it hasn't a namespace - flags, zero or more of #{:many :index :unique :identity :fulltext :no-history :component} Example: (field \"Optional docstring\" :schema.field/id :string :index)" {:arglists '([doc id type & flags] [id type & flags])} [& args] (let [[doc id type & flags] (if (string? (first args)) args (cons nil args)) flags (into #{} flags)] (cond-> {:db/id (tempid :db.part/db) :db.install/_attribute :db.part/db :db/ident id :db/valueType (if (namespace type) type (keyword "db.type" (name type))) :db/cardinality (if (:many flags) :db.cardinality/many :db.cardinality/one)} doc (assoc :db/doc doc) (:index flags) (assoc :db/index true) (:unique flags) (assoc :db/unique (if (:identity flags) :db.unique/identity :db.unique/value)) (:fulltext flags) (assoc :db/fulltext true) (:component flags) (assoc :db/isComponent true) (:no-history flags) (assoc :db/noHistory true)))) (defn enum "Shortcut syntax for an enum value schema field" {:arglists '([doc id] [id])} [& args] (let [[doc id] (if (string? (first args)) args (cons nil args))] (assoc-when {:db/id (tempid :db.part/user) :db/ident id} :db/doc doc))) (defn- parse-fn-body [name args] (let [[typ args] (if (= :- (first args)) [(second args) (nnext args)] [nil args]) [doc args] (if (string? (first args)) [(first args) (next args)] [nil args]) [flags [params & body]] (if (map? (first args)) [(first args) (next args)] [nil args]) known-flags #{:imports :requires :part :db-requires} _ (assert (every? known-flags (keys flags)) (str "Flags can be of " known-flags)) [params' lets] (reduce (fn [[params lets] param] (if (symbol? param) [(conj params param) lets] (let [s (gensym "param-")] [(conj params s) (into lets [param s])]))) [[] []] params) {:keys [imports requires part db-requires] :or {part :db.part/user}} flags] {:name name :doc doc :params params' :imports imports :requires requires :db-requires db-requires :part part :lets lets :body body :typ typ})) (defn- resolve-db-require [r] (let [[local-name var-name] (match [r] [[var-name]] [nil var-name] [[local-name var-name]] [local-name var-name]) var-sym (if (namespace var-name) (symbol (namespace var-name) (name var-name)) (symbol (str (ns-name *ns*)) (name var-name))) the-var (find-var var-sym) varm (meta the-var)] (assert varm (str "No var " var-sym)) [(or local-name (symbol (name var-name))) (:dbfn/name varm) (:dbfn/type varm)])) (ann extract-fn (All [f] [Db Keyword -> f])) (defn ^:no-check extract-fn [db fname] (:db/fn (datomic.api/entity db fname))) (defn- dbfn-source [{:keys [name doc params body imports requires part db-requires lets]} version] (let [db-sym (first params)] `(let ~(into lets (forcat [r db-requires] (let [[local-name fn-name typ] (resolve-db-require r)] [local-name (if (and typ (= version :local)) `(clojure.core.typed/ann-form (extract-fn ~db-sym ~fn-name) ~typ) `(:db/fn (datomic.api/entity ~db-sym ~fn-name)))]))) (try ~@body (catch Exception e# (if (instance? clojure.lang.ExceptionInfo e#) (throw (ex-info (.getMessage e#) (assoc (ex-data e#) :name ~(pr-str name) :args (pr-str ~params)))) (throw (ex-info "Wrapped native exception" {:name ~(pr-str name) :args (pr-str ~params)} e#)))))))) (defn- make-db-fn [{:keys [name doc params body imports requires part db-requires lets] :as desc}] `(assoc-when {:db/id (tempid ~part) :db/ident ~(keyword name) :db/fn (dtm/function (assoc-when {:lang :clojure :params '~params :code '~(dbfn-source desc :transactor)} :imports '~imports :requires (into '~requires '[[clojure.repl] [clojure.pprint]])))} :db/doc ~doc)) (defmacro function "Define a database function to be transacted. Syntax similar to clojure.core/fn, attributes can hold: :part the db partition for the tempid :imports for the db function :requires for the db function :db-requires generates a wrapping let that binds another database function (assumes db as first parameter)" {:arglists (list '[name doc? [& params] & body] '[name doc? attributes [& params] & body])} [name & args] (make-db-fn (parse-fn-body name args))) (defmacro defn-db "Defines a database function in regular clojure, for it to be accessible to type checking, direct calling, ... Has the :db/fn entity in :dbfn/entity of var metadata." {:arglists (list '[name doc? [& params] & body] '[name doc? {:imports [& imports] :requires [& requires] :part db-part} [& params] & body])} [fname & args] (let [{:keys [doc params requires typ imports] :as desc} (parse-fn-body fname args) fnsym (symbol (name fname))] `(do ~@(when (seq requires) [`(require ~@(map (partial list 'quote) requires))]) ~@(when (seq imports) [`(import ~@imports)]) ~@(when typ [`(ann ~fnsym ~typ)]) (defn ~(with-meta fnsym (assoc (meta fname) :dbfn/name (keyword fname) :dbfn/entity (make-db-fn desc) :dbfn/type (list 'quote typ))) ~@(when doc [doc]) ~params ~(dbfn-source desc :local))))) (defn dbfn-tx "Get transaction for installing a db function Example usage ------------- (transact conn (dbfn-tx #'webnf.datomic/compose-tx))" [& fn-vars] (map (comp :dbfn/entity meta) fn-vars)) (defalias DbId (U datomic.db.DbId Long Keyword (HVec [Keyword Any]))) (defalias TxItem (U (HVec [Keyword Any *]) (I (Map Keyword Any) (HMap :mandatory {:db/id DbId})))) (defalias Tx (Seqable TxItem)) (ann compose-tx [Db (Seqable Tx) -> Tx]) (defn-db webnf.datomic/compose-tx "Composes multiple transactions, into one, as if they got transacted in order Example usage ------------- [:webnf.datomic/compose-tx [ [[:db/add (tempid :db.part/user) :db/ident :test/entity]] [[:db/add :test/entity :db/doc \"Cool\"] [:db/add (tempid :db.part/user) :db/lang :test/entity]] ]]" {:requires [[datomic.api :as d]]} [db* txs] (letfn [(tx-map-items [tm] (let [id (or (:db/id tm) (throw (ex-info "Need :db/id" {:t tm})))] (for [[k v] (dissoc tm :db/id)] (if (.startsWith (name k) "_") [:db/add v (keyword (namespace k) (subs (name k) 1)) id] [:db/add id k v])))) (tx-tuple-items [db [op & args :as tt]] (case op (:db/add :db/retract) [tt] (tx-items db (apply (:db/fn (d/entity db op)) db args)))) (tx-items [db tx] (mapcat #(cond (vector? %) (tx-tuple-items db %) (map? %) (tx-map-items %) :else (throw (ex-info "Not a tx element" {:t %}))) tx)) (update-tx-ids [db tx-ids tempids] (reduce-kv (fn [res tid id] (if (res id) res (assoc res id tid))) tx-ids tempids)) (update-id [db tempids tx-ids id] (let [tx-id (or (d/resolve-tempid db tempids id) (d/entid db id) (assert false (str "No id: " id)))] (get tx-ids tx-id tx-id))) (rewrite-tx [db tx tempids tx-ids] (for [[op e a v :as tx-item] (tx-items db tx)] (case op :db/add [op (update-id db tempids tx-ids e) a (if (= :db.type/ref (:db/valueType (d/entity db a))) (update-id db tempids tx-ids v) v)] :db/retract tx-item))) (into-tx [tx-base tx] (persistent! (reduce (fn [res [_ e a :as item]] (assoc! res [e a] item)) (transient tx-base) tx)))] (loop [txs' txs db' db* tx-ids {} tx' {}] (if-let [[tx & rst] (seq txs')] (let [{:keys [db-after tempids]} (d/with db' tx) tx-ids' (update-tx-ids db' tx-ids tempids)] (recur rst db-after tx-ids' (into-tx tx' (rewrite-tx db' tx tempids tx-ids')))) (vals tx'))))) # # Connection routines (defn connect "Create and connect to database. If created, transact schema. Return connection." ([db-uri] (dtm/create-database db-uri) (dtm/connect db-uri)) ([db-uri schema & init-data] (let [created (dtm/create-database db-uri) conn (dtm/connect db-uri)] (when created (log/info "Creating schema on" db-uri) @(dtm/transact conn schema) (doseq [d init-data] @(dtm/transact conn d))) conn))) (defn recreate!! "Drop database and recreate, returning connection." [db-uri schema & init-data] (dtm/delete-database db-uri) (apply connect db-uri schema init-data)) # # # core.async base transaction executor (defn tx-executor "Take transactions from channel and execute them on conn. Returns an output channel that yields: {:tx transaction :result dereferenced-tx} or {:error exception} Up to concurrent-tx transactions are executed in parallel." ([conn tx-in-channel] (tx-executor conn tx-in-channel 8)) ([conn tx-in-channel concurrent-tx] (let [running-tx (async/pipe (async/map< #(try {:tx (dtm/transact conn %)} (catch Exception e {:error e})) tx-in-channel) (async/chan concurrent-tx))] (async/map< (fn [{:keys [tx error] :as in}] (if error in (try (assoc in :result @tx) (catch Exception e (assoc in :error e))))) running-tx)))) (defn accumulate-tx-results "A simple sink for the return channel of tx-executor. Returns channel, that delivers a single, reduced result, once input channel closes: {:success success-count :errors [list of exceptions]}" [tx-result-channel] (async/reduce (fn [out {:keys [error rx result] :as in}] (if error (do (log/error error "Failed transaction") (update-in out [:errors] conj in)) (do (log/debug "Finishing transaction" result) (update-in out [:success] inc)))) {:success 0 :errors []} tx-result-channel)) # # # Middleware for proper request database access (defn wrap-connection "Ring Middleware connecting to a database on creation, gets database at begin of every request. Associates :datomic/conn and :datomic/db to the request." [h uri] (fn [req] (let [conn (dtm/connect uri)] (h (assoc req :datomic/conn conn :datomic/db (dtm/db conn)))))) # # # Race - free report queue (defn listen-reports "Connect to db and open a tx report queue. Listener channels can be added and removed by put!-ing tap and untap messages to ctl-chan: (put! ctl-chan [:tap listener-channel]) (put! ctl-chan [:untap listener-channel]) The first message on a freshly tapped listener channel will always be {:db most-current-db} Then, datomic transaction reports will arrive as they are received from the report queue." [db-uri ctl-chan] (let [conn (connect db-uri) q (dtm/tx-report-queue conn) report-chan (chan) out-chan (chan) out-mult (mult out-chan) closed (volatile! false)] Set up loop to pull tx updates from the report queue and put them on report - chan (go (try (loop [] (log/trace "TX Q step") (when-not @closed (when-let [report (.poll ^BlockingQueue q 10 TimeUnit/SECONDS)] (log/trace "Received TX report from Q" report) (>! report-chan report)) (recur))) (finally (log/trace "Closing TX Q") (dtm/remove-tx-report-queue conn) (close! report-chan)))) (go-loop [db (let [db (dtm/db conn) {qdb :db-after} (.poll ^BlockingQueue q)] (if (and qdb (> (dtm/basis-t qdb) (dtm/basis-t db))) qdb db))] (log/trace "Delivery step") (alt! :priority true ctl-chan ([ctl-msg] (log/trace "Receiving CTL message" ctl-msg) (match [ctl-msg] [nil] (do (close! out-chan) (vreset! closed true) {:success :shutdown}) [{:control :tap :channel ch}] (do (put! ch {:db db}) (tap out-mult ch) (recur db)) [{:control :untap :channel ch}] (do (untap out-mult ch) (recur db)) :else (do (log/error "Unknown control message" ctl-msg) (log/info "Resuming control loop") (recur db)))) report-chan ([{:as report :keys [db-after]}] (cond (nil? report) (do (log/error "Report chan closed, closing control-chan") (close! ctl-chan) {:error :report-chan-died}) (> (dtm/basis-t db-after) (dtm/basis-t db)) (do (log/trace "Delivering TX report" report) (>! out-chan report) (recur db-after)) :else (recur db)))))))
75d0b2b5a65107e9b195d83935aac9f1e8cddab08eacffa11a94ae4c9834235e
CodyReichert/qi
asdf.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; asdf.lisp --- ASDF components for cffi-grovel. ;;; Copyright ( C ) 2005 - 2006 , < > Copyright ( C ) 2005 - 2006 , < > Copyright ( C ) 2007 , < > Copyright ( C ) 2007 , ;;; ;;; 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. ;;; (in-package #:cffi-grovel) (defun ensure-pathname (thing) (if (typep thing 'logical-pathname) (translate-logical-pathname thing) (pathname thing))) (defclass cc-flags-mixin () ((cc-flags :initform nil :accessor cc-flags-of :initarg :cc-flags))) (defmethod asdf:perform :around ((op asdf:compile-op) (file cc-flags-mixin)) (declare (ignorable op)) (let ((*cc-flags* (append (ensure-list (cc-flags-of file)) *cc-flags*))) (call-next-method))) (eval-when (:compile-toplevel :load-toplevel :execute) (defclass process-op (#-asdf3 asdf:operation #+asdf3 asdf:downward-operation) () (:documentation "This ASDF operation performs the steps necessary to generate a compilable and loadable lisp file from a PROCESS-OP-INPUT component.")) (defclass process-op-input (asdf:cl-source-file) ((generated-lisp-file-type :initarg :generated-lisp-file-type :accessor generated-lisp-file-type :documentation "The :TYPE argument to use for the generated lisp file.")) (:default-initargs :generated-lisp-file-type "generated-lisp-file") (:documentation "This ASDF component represents a file that is used as input to a function that generates lisp source file. This component acts as if it is a CL-SOURCE-FILE by applying the COMPILE-OP and LOAD-SOURCE-OP operations to the file generated by PROCESS-OP."))) (defmethod asdf:input-files ((op process-op) (c process-op-input)) (list (asdf:component-pathname c))) (defmethod asdf:component-depends-on ((op process-op) (c process-op-input)) `(#-asdf3 (asdf:load-op ,@(asdf::component-load-dependencies c)) #+asdf3 (asdf:prepare-op ,c) ,@(call-next-method))) (defmethod asdf:component-depends-on ((op asdf:compile-op) (c process-op-input)) (declare (ignorable op)) `((process-op ,(asdf:component-name c)) ,@(call-next-method))) (defmethod asdf:component-depends-on ((op asdf:load-source-op) (c process-op-input)) (declare (ignorable op)) `((process-op ,(asdf:component-name c)) ,@(call-next-method))) (defmethod asdf:perform ((op asdf:compile-op) (c process-op-input)) (let ((generated-lisp-file (first (asdf:output-files (make-instance 'process-op) c)))) (asdf:perform op (make-instance 'asdf:cl-source-file :name (asdf:component-name c) :parent (asdf:component-parent c) :pathname generated-lisp-file)))) (defmethod asdf:perform ((op asdf:load-source-op) (c process-op-input)) (let ((generated-lisp-file (first (asdf:output-files (make-instance 'process-op) c)))) (asdf:perform op (make-instance 'asdf:cl-source-file :name (asdf:component-name c) :parent (asdf:component-parent c) :pathname generated-lisp-file)))) # ASDF component : GROVEL - FILE (eval-when (:compile-toplevel :load-toplevel :execute) (defclass grovel-file (process-op-input cc-flags-mixin) () (:default-initargs :generated-lisp-file-type "processed-grovel-file") (:documentation "This ASDF component represents an input file that is processed by PROCESS-GROVEL-FILE."))) (defmethod asdf:output-files ((op process-op) (c grovel-file)) (let* ((input-file (asdf:component-pathname c)) (output-file (make-pathname :type (generated-lisp-file-type c) :defaults input-file)) (c-file (make-c-file-name output-file))) (list output-file c-file (exe-filename c-file)))) (defmethod asdf:perform ((op process-op) (c grovel-file)) (let ((output-file (first (asdf:output-files op c))) (input-file (asdf:component-pathname c))) (ensure-directories-exist (directory-namestring output-file)) (let ((tmp-file (process-grovel-file input-file output-file))) (unwind-protect (alexandria:copy-file tmp-file output-file :if-to-exists :supersede) (delete-file tmp-file))))) ;;;# ASDF component: WRAPPER-FILE (eval-when (:compile-toplevel :load-toplevel :execute) (defclass wrapper-file (process-op-input cc-flags-mixin) ((soname :initform nil :initarg :soname :accessor soname-of)) (:default-initargs :generated-lisp-file-type "processed-wrapper-file") (:documentation "This ASDF component represents an input file that is processed by PROCESS-WRAPPER-FILE. This generates a foreign library and matching CFFI bindings that are subsequently compiled and loaded."))) (defun wrapper-soname (c) (or (soname-of c) (asdf:component-name c))) (defmethod asdf:output-files ((op process-op) (c wrapper-file)) (let* ((input-file (asdf:component-pathname c)) (output-file (make-pathname :type (generated-lisp-file-type c) :defaults input-file)) (c-file (make-c-file-name output-file)) (lib-soname (wrapper-soname c))) (list output-file c-file (lib-filename (make-soname lib-soname output-file))))) (defmethod asdf:perform ((op process-op) (c wrapper-file)) (let ((output-file (first (asdf:output-files op c))) (input-file (asdf:component-pathname c))) (ensure-directories-exist (directory-namestring output-file)) (let ((tmp-file (process-wrapper-file input-file output-file (wrapper-soname c)))) (unwind-protect (alexandria:copy-file tmp-file output-file :if-to-exists :supersede) (delete-file tmp-file))))) ;; Allow for naked :grovel-file and :wrapper-file in asdf definitions. (eval-when (:compile-toplevel :load-toplevel :execute) (setf (find-class 'asdf::cffi-grovel-file) (find-class 'grovel-file)) (setf (find-class 'asdf::cffi-wrapper-file) (find-class 'wrapper-file)))
null
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/cffi-master/grovel/asdf.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- asdf.lisp --- ASDF components for cffi-grovel. 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. # ASDF component: WRAPPER-FILE Allow for naked :grovel-file and :wrapper-file in asdf definitions.
Copyright ( C ) 2005 - 2006 , < > Copyright ( C ) 2005 - 2006 , < > Copyright ( C ) 2007 , < > Copyright ( C ) 2007 , 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 , (in-package #:cffi-grovel) (defun ensure-pathname (thing) (if (typep thing 'logical-pathname) (translate-logical-pathname thing) (pathname thing))) (defclass cc-flags-mixin () ((cc-flags :initform nil :accessor cc-flags-of :initarg :cc-flags))) (defmethod asdf:perform :around ((op asdf:compile-op) (file cc-flags-mixin)) (declare (ignorable op)) (let ((*cc-flags* (append (ensure-list (cc-flags-of file)) *cc-flags*))) (call-next-method))) (eval-when (:compile-toplevel :load-toplevel :execute) (defclass process-op (#-asdf3 asdf:operation #+asdf3 asdf:downward-operation) () (:documentation "This ASDF operation performs the steps necessary to generate a compilable and loadable lisp file from a PROCESS-OP-INPUT component.")) (defclass process-op-input (asdf:cl-source-file) ((generated-lisp-file-type :initarg :generated-lisp-file-type :accessor generated-lisp-file-type :documentation "The :TYPE argument to use for the generated lisp file.")) (:default-initargs :generated-lisp-file-type "generated-lisp-file") (:documentation "This ASDF component represents a file that is used as input to a function that generates lisp source file. This component acts as if it is a CL-SOURCE-FILE by applying the COMPILE-OP and LOAD-SOURCE-OP operations to the file generated by PROCESS-OP."))) (defmethod asdf:input-files ((op process-op) (c process-op-input)) (list (asdf:component-pathname c))) (defmethod asdf:component-depends-on ((op process-op) (c process-op-input)) `(#-asdf3 (asdf:load-op ,@(asdf::component-load-dependencies c)) #+asdf3 (asdf:prepare-op ,c) ,@(call-next-method))) (defmethod asdf:component-depends-on ((op asdf:compile-op) (c process-op-input)) (declare (ignorable op)) `((process-op ,(asdf:component-name c)) ,@(call-next-method))) (defmethod asdf:component-depends-on ((op asdf:load-source-op) (c process-op-input)) (declare (ignorable op)) `((process-op ,(asdf:component-name c)) ,@(call-next-method))) (defmethod asdf:perform ((op asdf:compile-op) (c process-op-input)) (let ((generated-lisp-file (first (asdf:output-files (make-instance 'process-op) c)))) (asdf:perform op (make-instance 'asdf:cl-source-file :name (asdf:component-name c) :parent (asdf:component-parent c) :pathname generated-lisp-file)))) (defmethod asdf:perform ((op asdf:load-source-op) (c process-op-input)) (let ((generated-lisp-file (first (asdf:output-files (make-instance 'process-op) c)))) (asdf:perform op (make-instance 'asdf:cl-source-file :name (asdf:component-name c) :parent (asdf:component-parent c) :pathname generated-lisp-file)))) # ASDF component : GROVEL - FILE (eval-when (:compile-toplevel :load-toplevel :execute) (defclass grovel-file (process-op-input cc-flags-mixin) () (:default-initargs :generated-lisp-file-type "processed-grovel-file") (:documentation "This ASDF component represents an input file that is processed by PROCESS-GROVEL-FILE."))) (defmethod asdf:output-files ((op process-op) (c grovel-file)) (let* ((input-file (asdf:component-pathname c)) (output-file (make-pathname :type (generated-lisp-file-type c) :defaults input-file)) (c-file (make-c-file-name output-file))) (list output-file c-file (exe-filename c-file)))) (defmethod asdf:perform ((op process-op) (c grovel-file)) (let ((output-file (first (asdf:output-files op c))) (input-file (asdf:component-pathname c))) (ensure-directories-exist (directory-namestring output-file)) (let ((tmp-file (process-grovel-file input-file output-file))) (unwind-protect (alexandria:copy-file tmp-file output-file :if-to-exists :supersede) (delete-file tmp-file))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defclass wrapper-file (process-op-input cc-flags-mixin) ((soname :initform nil :initarg :soname :accessor soname-of)) (:default-initargs :generated-lisp-file-type "processed-wrapper-file") (:documentation "This ASDF component represents an input file that is processed by PROCESS-WRAPPER-FILE. This generates a foreign library and matching CFFI bindings that are subsequently compiled and loaded."))) (defun wrapper-soname (c) (or (soname-of c) (asdf:component-name c))) (defmethod asdf:output-files ((op process-op) (c wrapper-file)) (let* ((input-file (asdf:component-pathname c)) (output-file (make-pathname :type (generated-lisp-file-type c) :defaults input-file)) (c-file (make-c-file-name output-file)) (lib-soname (wrapper-soname c))) (list output-file c-file (lib-filename (make-soname lib-soname output-file))))) (defmethod asdf:perform ((op process-op) (c wrapper-file)) (let ((output-file (first (asdf:output-files op c))) (input-file (asdf:component-pathname c))) (ensure-directories-exist (directory-namestring output-file)) (let ((tmp-file (process-wrapper-file input-file output-file (wrapper-soname c)))) (unwind-protect (alexandria:copy-file tmp-file output-file :if-to-exists :supersede) (delete-file tmp-file))))) (eval-when (:compile-toplevel :load-toplevel :execute) (setf (find-class 'asdf::cffi-grovel-file) (find-class 'grovel-file)) (setf (find-class 'asdf::cffi-wrapper-file) (find-class 'wrapper-file)))
423700c2395901b56c7c5560b3c84086a7a7e2661df739b2addf16fb28c17f30
braidchat/braid
conf.clj
(ns braid.test.fixtures.conf (:require [braid.core.modules :as modules] [braid.base.conf :as conf] [mount.core :as mount])) (defn start-config [t] (modules/init! modules/default) (-> (mount/only #{#'conf/config}) (mount/with-args {:port 0}) (mount/start)) (t) (mount/stop))
null
https://raw.githubusercontent.com/braidchat/braid/2e44eb6e77f1d203115f9b9c529bd865fa3d7302/test/braid/test/fixtures/conf.clj
clojure
(ns braid.test.fixtures.conf (:require [braid.core.modules :as modules] [braid.base.conf :as conf] [mount.core :as mount])) (defn start-config [t] (modules/init! modules/default) (-> (mount/only #{#'conf/config}) (mount/with-args {:port 0}) (mount/start)) (t) (mount/stop))
1b7dcc1de743b938ce5c05c394e9dcdd6d00435faed4997a466dc6bee8e3b664
ghcjs/jsaddle-dom
Document.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.Document (getAnimations, getAnimations_, newDocument, getElementsByTagName, getElementsByTagName_, getElementsByTagNameNS, getElementsByTagNameNS_, getElementsByClassName, getElementsByClassName_, createElement, createElement_, createElementNS, createElementNS_, createDocumentFragment, createDocumentFragment_, createTextNode, createTextNode_, createCDATASection, createCDATASection_, createComment, createComment_, createProcessingInstruction, createProcessingInstruction_, importNode, importNode_, adoptNode, adoptNode_, createAttribute, createAttribute_, createAttributeNS, createAttributeNS_, createEvent, createEvent_, createRange, createRange_, createNodeIterator, createNodeIterator_, createTreeWalker, createTreeWalker_, getElementsByName, getElementsByName_, hasFocus, hasFocus_, execCommand, execCommand_, queryCommandEnabled, queryCommandEnabled_, queryCommandIndeterm, queryCommandIndeterm_, queryCommandState, queryCommandState_, queryCommandSupported, queryCommandSupported_, queryCommandValue, queryCommandValue_, getSelection, getSelection_, getSelectionUnsafe, getSelectionUnchecked, createExpression, createExpression_, createNSResolver, createNSResolver_, evaluate, evaluate_, webkitExitFullscreen, webkitCancelFullScreen, exitPointerLock, getOverrideStyle, getOverrideStyle_, caretRangeFromPoint, caretRangeFromPoint_, getCSSCanvasContext, getCSSCanvasContext_, webkitGetNamedFlows, webkitGetNamedFlows_, createTouch, createTouch_, createTouchList, createTouchList_, getTimeline, getImplementation, getURL, getDocumentURI, getOrigin, getCompatMode, getCharacterSet, getCharset, getInputEncoding, getContentType, getDoctype, getDoctypeUnsafe, getDoctypeUnchecked, getDocumentElement, getDocumentElementUnsafe, getDocumentElementUnchecked, getLocation, getLocationUnsafe, getLocationUnchecked, setDomain, getDomain, getReferrer, setCookie, getCookie, getLastModified, getReadyState, setTitle, getTitle, setDir, getDir, setBody, getBody, getBodyUnsafe, getBodyUnchecked, getHead, getHeadUnsafe, getHeadUnchecked, getImages, getEmbeds, getPlugins, getLinks, getForms, getScripts, getCurrentScript, getCurrentScriptUnsafe, getCurrentScriptUnchecked, getDefaultView, getDefaultViewUnsafe, getDefaultViewUnchecked, setDesignMode, getDesignMode, readyStateChange, getStyleSheets, getScrollingElement, getScrollingElementUnsafe, getScrollingElementUnchecked, getWebkitFullscreenEnabled, getWebkitFullscreenElement, getWebkitFullscreenElementUnsafe, getWebkitFullscreenElementUnchecked, getWebkitIsFullScreen, getWebkitFullScreenKeyboardInputAllowed, getWebkitCurrentFullScreenElement, webKitFullscreenChange, webKitFullscreenError, pointerlockchange, pointerlockerror, getFonts, getHidden, getVisibilityState, visibilitychange, getApplets, getAnchors, getPreferredStylesheetSet, getPreferredStylesheetSetUnsafe, getPreferredStylesheetSetUnchecked, setSelectedStylesheetSet, getSelectedStylesheetSet, getSelectedStylesheetSetUnsafe, getSelectedStylesheetSetUnchecked, getXmlEncoding, getXmlEncodingUnsafe, getXmlEncodingUnchecked, setXmlVersion, getXmlVersion, getXmlVersionUnsafe, getXmlVersionUnchecked, setXmlStandalone, getXmlStandalone, selectStart, selectionchange, getRootElement, getRootElementUnsafe, getRootElementUnchecked, Document(..), gTypeDocument, IsDocument, toDocument) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/Document.getAnimations Mozilla Document.getAnimations documentation > getAnimations :: (MonadDOM m, IsDocument self) => self -> m [Animation] getAnimations self = liftDOM (((toDocument self) ^. jsf "getAnimations" ()) >>= fromJSArrayUnchecked) | < -US/docs/Web/API/Document.getAnimations Mozilla Document.getAnimations documentation > getAnimations_ :: (MonadDOM m, IsDocument self) => self -> m () getAnimations_ self = liftDOM (void ((toDocument self) ^. jsf "getAnimations" ())) | < -US/docs/Web/API/Document Mozilla Document documentation > newDocument :: (MonadDOM m) => m Document newDocument = liftDOM (Document <$> new (jsg "Document") ()) -- | <-US/docs/Web/API/Document.getElementsByTagName Mozilla Document.getElementsByTagName documentation> getElementsByTagName :: (MonadDOM m, IsDocument self, ToJSString qualifiedName) => self -> qualifiedName -> m HTMLCollection getElementsByTagName self qualifiedName = liftDOM (((toDocument self) ^. jsf "getElementsByTagName" [toJSVal qualifiedName]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.getElementsByTagName Mozilla Document.getElementsByTagName documentation> getElementsByTagName_ :: (MonadDOM m, IsDocument self, ToJSString qualifiedName) => self -> qualifiedName -> m () getElementsByTagName_ self qualifiedName = liftDOM (void ((toDocument self) ^. jsf "getElementsByTagName" [toJSVal qualifiedName])) | < -US/docs/Web/API/Document.getElementsByTagNameNS Mozilla Document.getElementsByTagNameNS documentation > getElementsByTagNameNS :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m HTMLCollection getElementsByTagNameNS self namespaceURI localName = liftDOM (((toDocument self) ^. jsf "getElementsByTagNameNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.getElementsByTagNameNS Mozilla Document.getElementsByTagNameNS documentation > getElementsByTagNameNS_ :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m () getElementsByTagNameNS_ self namespaceURI localName = liftDOM (void ((toDocument self) ^. jsf "getElementsByTagNameNS" [toJSVal namespaceURI, toJSVal localName])) | < -US/docs/Web/API/Document.getElementsByClassName Mozilla Document.getElementsByClassName documentation > getElementsByClassName :: (MonadDOM m, IsDocument self, ToJSString classNames) => self -> classNames -> m HTMLCollection getElementsByClassName self classNames = liftDOM (((toDocument self) ^. jsf "getElementsByClassName" [toJSVal classNames]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.getElementsByClassName Mozilla Document.getElementsByClassName documentation > getElementsByClassName_ :: (MonadDOM m, IsDocument self, ToJSString classNames) => self -> classNames -> m () getElementsByClassName_ self classNames = liftDOM (void ((toDocument self) ^. jsf "getElementsByClassName" [toJSVal classNames])) -- | <-US/docs/Web/API/Document.createElement Mozilla Document.createElement documentation> createElement :: (MonadDOM m, IsDocument self, ToJSString localName) => self -> localName -> m Element createElement self localName = liftDOM (((toDocument self) ^. jsf "createElement" [toJSVal localName]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.createElement Mozilla Document.createElement documentation> createElement_ :: (MonadDOM m, IsDocument self, ToJSString localName) => self -> localName -> m () createElement_ self localName = liftDOM (void ((toDocument self) ^. jsf "createElement" [toJSVal localName])) | < -US/docs/Web/API/Document.createElementNS Mozilla Document.createElementNS documentation > createElementNS :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> Maybe namespaceURI -> qualifiedName -> m Element createElementNS self namespaceURI qualifiedName = liftDOM (((toDocument self) ^. jsf "createElementNS" [toJSVal namespaceURI, toJSVal qualifiedName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createElementNS Mozilla Document.createElementNS documentation > createElementNS_ :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> Maybe namespaceURI -> qualifiedName -> m () createElementNS_ self namespaceURI qualifiedName = liftDOM (void ((toDocument self) ^. jsf "createElementNS" [toJSVal namespaceURI, toJSVal qualifiedName])) | < -US/docs/Web/API/Document.createDocumentFragment Mozilla Document.createDocumentFragment documentation > createDocumentFragment :: (MonadDOM m, IsDocument self) => self -> m DocumentFragment createDocumentFragment self = liftDOM (((toDocument self) ^. jsf "createDocumentFragment" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createDocumentFragment Mozilla Document.createDocumentFragment documentation > createDocumentFragment_ :: (MonadDOM m, IsDocument self) => self -> m () createDocumentFragment_ self = liftDOM (void ((toDocument self) ^. jsf "createDocumentFragment" ())) | < -US/docs/Web/API/Document.createTextNode Mozilla Document.createTextNode documentation > createTextNode :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m Text createTextNode self data' = liftDOM (((toDocument self) ^. jsf "createTextNode" [toJSVal data']) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createTextNode Mozilla Document.createTextNode documentation > createTextNode_ :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m () createTextNode_ self data' = liftDOM (void ((toDocument self) ^. jsf "createTextNode" [toJSVal data'])) | < -US/docs/Web/API/Document.createCDATASection Mozilla Document.createCDATASection documentation > createCDATASection :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m CDATASection createCDATASection self data' = liftDOM (((toDocument self) ^. jsf "createCDATASection" [toJSVal data']) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createCDATASection Mozilla Document.createCDATASection documentation > createCDATASection_ :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m () createCDATASection_ self data' = liftDOM (void ((toDocument self) ^. jsf "createCDATASection" [toJSVal data'])) | < -US/docs/Web/API/Document.createComment Mozilla Document.createComment documentation > createComment :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m Comment createComment self data' = liftDOM (((toDocument self) ^. jsf "createComment" [toJSVal data']) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createComment Mozilla Document.createComment documentation > createComment_ :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m () createComment_ self data' = liftDOM (void ((toDocument self) ^. jsf "createComment" [toJSVal data'])) | < -US/docs/Web/API/Document.createProcessingInstruction Mozilla Document.createProcessingInstruction documentation > createProcessingInstruction :: (MonadDOM m, IsDocument self, ToJSString target, ToJSString data') => self -> target -> data' -> m ProcessingInstruction createProcessingInstruction self target data' = liftDOM (((toDocument self) ^. jsf "createProcessingInstruction" [toJSVal target, toJSVal data']) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createProcessingInstruction Mozilla Document.createProcessingInstruction documentation > createProcessingInstruction_ :: (MonadDOM m, IsDocument self, ToJSString target, ToJSString data') => self -> target -> data' -> m () createProcessingInstruction_ self target data' = liftDOM (void ((toDocument self) ^. jsf "createProcessingInstruction" [toJSVal target, toJSVal data'])) -- | <-US/docs/Web/API/Document.importNode Mozilla Document.importNode documentation> importNode :: (MonadDOM m, IsDocument self, IsNode node) => self -> node -> Bool -> m Node importNode self node deep = liftDOM (((toDocument self) ^. jsf "importNode" [toJSVal node, toJSVal deep]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.importNode Mozilla Document.importNode documentation> importNode_ :: (MonadDOM m, IsDocument self, IsNode node) => self -> node -> Bool -> m () importNode_ self node deep = liftDOM (void ((toDocument self) ^. jsf "importNode" [toJSVal node, toJSVal deep])) | < -US/docs/Web/API/Document.adoptNode Mozilla Document.adoptNode documentation > adoptNode :: (MonadDOM m, IsDocument self, IsNode node) => self -> node -> m Node adoptNode self node = liftDOM (((toDocument self) ^. jsf "adoptNode" [toJSVal node]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.adoptNode Mozilla Document.adoptNode documentation > adoptNode_ :: (MonadDOM m, IsDocument self, IsNode node) => self -> node -> m () adoptNode_ self node = liftDOM (void ((toDocument self) ^. jsf "adoptNode" [toJSVal node])) | < -US/docs/Web/API/Document.createAttribute Mozilla Document.createAttribute documentation > createAttribute :: (MonadDOM m, IsDocument self, ToJSString localName) => self -> localName -> m Attr createAttribute self localName = liftDOM (((toDocument self) ^. jsf "createAttribute" [toJSVal localName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createAttribute Mozilla Document.createAttribute documentation > createAttribute_ :: (MonadDOM m, IsDocument self, ToJSString localName) => self -> localName -> m () createAttribute_ self localName = liftDOM (void ((toDocument self) ^. jsf "createAttribute" [toJSVal localName])) | < -US/docs/Web/API/Document.createAttributeNS Mozilla Document.createAttributeNS documentation > createAttributeNS :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> Maybe namespaceURI -> qualifiedName -> m Attr createAttributeNS self namespaceURI qualifiedName = liftDOM (((toDocument self) ^. jsf "createAttributeNS" [toJSVal namespaceURI, toJSVal qualifiedName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createAttributeNS Mozilla Document.createAttributeNS documentation > createAttributeNS_ :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> Maybe namespaceURI -> qualifiedName -> m () createAttributeNS_ self namespaceURI qualifiedName = liftDOM (void ((toDocument self) ^. jsf "createAttributeNS" [toJSVal namespaceURI, toJSVal qualifiedName])) -- | <-US/docs/Web/API/Document.createEvent Mozilla Document.createEvent documentation> createEvent :: (MonadDOM m, IsDocument self, ToJSString type') => self -> type' -> m Event createEvent self type' = liftDOM (((toDocument self) ^. jsf "createEvent" [toJSVal type']) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.createEvent Mozilla Document.createEvent documentation> createEvent_ :: (MonadDOM m, IsDocument self, ToJSString type') => self -> type' -> m () createEvent_ self type' = liftDOM (void ((toDocument self) ^. jsf "createEvent" [toJSVal type'])) | < -US/docs/Web/API/Document.createRange Mozilla Document.createRange documentation > createRange :: (MonadDOM m, IsDocument self) => self -> m Range createRange self = liftDOM (((toDocument self) ^. jsf "createRange" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createRange Mozilla Document.createRange documentation > createRange_ :: (MonadDOM m, IsDocument self) => self -> m () createRange_ self = liftDOM (void ((toDocument self) ^. jsf "createRange" ())) -- | <-US/docs/Web/API/Document.createNodeIterator Mozilla Document.createNodeIterator documentation> createNodeIterator :: (MonadDOM m, IsDocument self, IsNode root) => self -> root -> Maybe Word -> Maybe NodeFilter -> m NodeIterator createNodeIterator self root whatToShow filter = liftDOM (((toDocument self) ^. jsf "createNodeIterator" [toJSVal root, toJSVal whatToShow, toJSVal filter]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.createNodeIterator Mozilla Document.createNodeIterator documentation> createNodeIterator_ :: (MonadDOM m, IsDocument self, IsNode root) => self -> root -> Maybe Word -> Maybe NodeFilter -> m () createNodeIterator_ self root whatToShow filter = liftDOM (void ((toDocument self) ^. jsf "createNodeIterator" [toJSVal root, toJSVal whatToShow, toJSVal filter])) | < -US/docs/Web/API/Document.createTreeWalker Mozilla Document.createTreeWalker documentation > createTreeWalker :: (MonadDOM m, IsDocument self, IsNode root) => self -> root -> Maybe Word -> Maybe NodeFilter -> m TreeWalker createTreeWalker self root whatToShow filter = liftDOM (((toDocument self) ^. jsf "createTreeWalker" [toJSVal root, toJSVal whatToShow, toJSVal filter]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createTreeWalker Mozilla Document.createTreeWalker documentation > createTreeWalker_ :: (MonadDOM m, IsDocument self, IsNode root) => self -> root -> Maybe Word -> Maybe NodeFilter -> m () createTreeWalker_ self root whatToShow filter = liftDOM (void ((toDocument self) ^. jsf "createTreeWalker" [toJSVal root, toJSVal whatToShow, toJSVal filter])) -- | <-US/docs/Web/API/Document.getElementsByName Mozilla Document.getElementsByName documentation> getElementsByName :: (MonadDOM m, IsDocument self, ToJSString elementName) => self -> elementName -> m NodeList getElementsByName self elementName = liftDOM (((toDocument self) ^. jsf "getElementsByName" [toJSVal elementName]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.getElementsByName Mozilla Document.getElementsByName documentation> getElementsByName_ :: (MonadDOM m, IsDocument self, ToJSString elementName) => self -> elementName -> m () getElementsByName_ self elementName = liftDOM (void ((toDocument self) ^. jsf "getElementsByName" [toJSVal elementName])) | < -US/docs/Web/API/Document.hasFocus Mozilla Document.hasFocus documentation > hasFocus :: (MonadDOM m, IsDocument self) => self -> m Bool hasFocus self = liftDOM (((toDocument self) ^. jsf "hasFocus" ()) >>= valToBool) | < -US/docs/Web/API/Document.hasFocus Mozilla Document.hasFocus documentation > hasFocus_ :: (MonadDOM m, IsDocument self) => self -> m () hasFocus_ self = liftDOM (void ((toDocument self) ^. jsf "hasFocus" ())) | < -US/docs/Web/API/Document.execCommand Mozilla Document.execCommand documentation > execCommand :: (MonadDOM m, IsDocument self, ToJSString commandId, ToJSString value) => self -> commandId -> Bool -> Maybe value -> m Bool execCommand self commandId showUI value = liftDOM (((toDocument self) ^. jsf "execCommand" [toJSVal commandId, toJSVal showUI, toJSVal value]) >>= valToBool) | < -US/docs/Web/API/Document.execCommand Mozilla Document.execCommand documentation > execCommand_ :: (MonadDOM m, IsDocument self, ToJSString commandId, ToJSString value) => self -> commandId -> Bool -> Maybe value -> m () execCommand_ self commandId showUI value = liftDOM (void ((toDocument self) ^. jsf "execCommand" [toJSVal commandId, toJSVal showUI, toJSVal value])) | < -US/docs/Web/API/Document.queryCommandEnabled Mozilla Document.queryCommandEnabled documentation > queryCommandEnabled :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m Bool queryCommandEnabled self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandEnabled" [toJSVal commandId]) >>= valToBool) | < -US/docs/Web/API/Document.queryCommandEnabled Mozilla Document.queryCommandEnabled documentation > queryCommandEnabled_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandEnabled_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandEnabled" [toJSVal commandId])) | < -US/docs/Web/API/Document.queryCommandIndeterm Mozilla Document.queryCommandIndeterm documentation > queryCommandIndeterm :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m Bool queryCommandIndeterm self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandIndeterm" [toJSVal commandId]) >>= valToBool) | < -US/docs/Web/API/Document.queryCommandIndeterm Mozilla Document.queryCommandIndeterm documentation > queryCommandIndeterm_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandIndeterm_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandIndeterm" [toJSVal commandId])) | < -US/docs/Web/API/Document.queryCommandState Mozilla Document.queryCommandState documentation > queryCommandState :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m Bool queryCommandState self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandState" [toJSVal commandId]) >>= valToBool) | < -US/docs/Web/API/Document.queryCommandState Mozilla Document.queryCommandState documentation > queryCommandState_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandState_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandState" [toJSVal commandId])) -- | <-US/docs/Web/API/Document.queryCommandSupported Mozilla Document.queryCommandSupported documentation> queryCommandSupported :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m Bool queryCommandSupported self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandSupported" [toJSVal commandId]) >>= valToBool) -- | <-US/docs/Web/API/Document.queryCommandSupported Mozilla Document.queryCommandSupported documentation> queryCommandSupported_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandSupported_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandSupported" [toJSVal commandId])) | < -US/docs/Web/API/Document.queryCommandValue Mozilla Document.queryCommandValue documentation > queryCommandValue :: (MonadDOM m, IsDocument self, ToJSString commandId, FromJSString result) => self -> commandId -> m result queryCommandValue self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandValue" [toJSVal commandId]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.queryCommandValue Mozilla Document.queryCommandValue documentation > queryCommandValue_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandValue_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandValue" [toJSVal commandId])) -- | <-US/docs/Web/API/Document.getSelection Mozilla Document.getSelection documentation> getSelection :: (MonadDOM m, IsDocument self) => self -> m (Maybe Selection) getSelection self = liftDOM (((toDocument self) ^. jsf "getSelection" ()) >>= fromJSVal) -- | <-US/docs/Web/API/Document.getSelection Mozilla Document.getSelection documentation> getSelection_ :: (MonadDOM m, IsDocument self) => self -> m () getSelection_ self = liftDOM (void ((toDocument self) ^. jsf "getSelection" ())) -- | <-US/docs/Web/API/Document.getSelection Mozilla Document.getSelection documentation> getSelectionUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Selection getSelectionUnsafe self = liftDOM ((((toDocument self) ^. jsf "getSelection" ()) >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Document.getSelection Mozilla Document.getSelection documentation> getSelectionUnchecked :: (MonadDOM m, IsDocument self) => self -> m Selection getSelectionUnchecked self = liftDOM (((toDocument self) ^. jsf "getSelection" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createExpression Mozilla Document.createExpression documentation > createExpression :: (MonadDOM m, IsDocument self, ToJSString expression) => self -> Maybe expression -> Maybe XPathNSResolver -> m XPathExpression createExpression self expression resolver = liftDOM (((toDocument self) ^. jsf "createExpression" [toJSVal expression, toJSVal resolver]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createExpression Mozilla Document.createExpression documentation > createExpression_ :: (MonadDOM m, IsDocument self, ToJSString expression) => self -> Maybe expression -> Maybe XPathNSResolver -> m () createExpression_ self expression resolver = liftDOM (void ((toDocument self) ^. jsf "createExpression" [toJSVal expression, toJSVal resolver])) -- | <-US/docs/Web/API/Document.createNSResolver Mozilla Document.createNSResolver documentation> createNSResolver :: (MonadDOM m, IsDocument self, IsNode nodeResolver) => self -> Maybe nodeResolver -> m XPathNSResolver createNSResolver self nodeResolver = liftDOM (((toDocument self) ^. jsf "createNSResolver" [toJSVal nodeResolver]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.createNSResolver Mozilla Document.createNSResolver documentation> createNSResolver_ :: (MonadDOM m, IsDocument self, IsNode nodeResolver) => self -> Maybe nodeResolver -> m () createNSResolver_ self nodeResolver = liftDOM (void ((toDocument self) ^. jsf "createNSResolver" [toJSVal nodeResolver])) | < -US/docs/Web/API/Document.evaluate Mozilla Document.evaluate documentation > evaluate :: (MonadDOM m, IsDocument self, ToJSString expression, IsNode contextNode) => self -> Maybe expression -> Maybe contextNode -> Maybe XPathNSResolver -> Maybe Word -> Maybe XPathResult -> m XPathResult evaluate self expression contextNode resolver type' inResult = liftDOM (((toDocument self) ^. jsf "evaluate" [toJSVal expression, toJSVal contextNode, toJSVal resolver, toJSVal type', toJSVal inResult]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.evaluate Mozilla Document.evaluate documentation > evaluate_ :: (MonadDOM m, IsDocument self, ToJSString expression, IsNode contextNode) => self -> Maybe expression -> Maybe contextNode -> Maybe XPathNSResolver -> Maybe Word -> Maybe XPathResult -> m () evaluate_ self expression contextNode resolver type' inResult = liftDOM (void ((toDocument self) ^. jsf "evaluate" [toJSVal expression, toJSVal contextNode, toJSVal resolver, toJSVal type', toJSVal inResult])) | < Document.webkitExitFullscreen documentation > webkitExitFullscreen :: (MonadDOM m, IsDocument self) => self -> m () webkitExitFullscreen self = liftDOM (void ((toDocument self) ^. jsf "webkitExitFullscreen" ())) -- | <-US/docs/Web/API/Document.webkitCancelFullScreen Mozilla Document.webkitCancelFullScreen documentation> webkitCancelFullScreen :: (MonadDOM m, IsDocument self) => self -> m () webkitCancelFullScreen self = liftDOM (void ((toDocument self) ^. jsf "webkitCancelFullScreen" ())) | < -US/docs/Web/API/Document.exitPointerLock Mozilla Document.exitPointerLock documentation > exitPointerLock :: (MonadDOM m, IsDocument self) => self -> m () exitPointerLock self = liftDOM (void ((toDocument self) ^. jsf "exitPointerLock" ())) | < -US/docs/Web/API/Document.getOverrideStyle Mozilla Document.getOverrideStyle documentation > getOverrideStyle :: (MonadDOM m, IsDocument self, IsElement element, ToJSString pseudoElement) => self -> Maybe element -> Maybe pseudoElement -> m CSSStyleDeclaration getOverrideStyle self element pseudoElement = liftDOM (((toDocument self) ^. jsf "getOverrideStyle" [toJSVal element, toJSVal pseudoElement]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.getOverrideStyle Mozilla Document.getOverrideStyle documentation > getOverrideStyle_ :: (MonadDOM m, IsDocument self, IsElement element, ToJSString pseudoElement) => self -> Maybe element -> Maybe pseudoElement -> m () getOverrideStyle_ self element pseudoElement = liftDOM (void ((toDocument self) ^. jsf "getOverrideStyle" [toJSVal element, toJSVal pseudoElement])) -- | <-US/docs/Web/API/Document.caretRangeFromPoint Mozilla Document.caretRangeFromPoint documentation> caretRangeFromPoint :: (MonadDOM m, IsDocument self) => self -> Maybe Int -> Maybe Int -> m Range caretRangeFromPoint self x y = liftDOM (((toDocument self) ^. jsf "caretRangeFromPoint" [toJSVal x, toJSVal y]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.caretRangeFromPoint Mozilla Document.caretRangeFromPoint documentation> caretRangeFromPoint_ :: (MonadDOM m, IsDocument self) => self -> Maybe Int -> Maybe Int -> m () caretRangeFromPoint_ self x y = liftDOM (void ((toDocument self) ^. jsf "caretRangeFromPoint" [toJSVal x, toJSVal y])) | < -US/docs/Web/API/Document.getCSSCanvasContext Mozilla Document.getCSSCanvasContext documentation > getCSSCanvasContext :: (MonadDOM m, IsDocument self, ToJSString contextId, ToJSString name) => self -> contextId -> name -> Int -> Int -> m RenderingContext getCSSCanvasContext self contextId name width height = liftDOM (((toDocument self) ^. jsf "getCSSCanvasContext" [toJSVal contextId, toJSVal name, toJSVal width, toJSVal height]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.getCSSCanvasContext Mozilla Document.getCSSCanvasContext documentation > getCSSCanvasContext_ :: (MonadDOM m, IsDocument self, ToJSString contextId, ToJSString name) => self -> contextId -> name -> Int -> Int -> m () getCSSCanvasContext_ self contextId name width height = liftDOM (void ((toDocument self) ^. jsf "getCSSCanvasContext" [toJSVal contextId, toJSVal name, toJSVal width, toJSVal height])) | < -US/docs/Web/API/Document.webkitGetNamedFlows Mozilla Document.webkitGetNamedFlows documentation > webkitGetNamedFlows :: (MonadDOM m, IsDocument self) => self -> m DOMNamedFlowCollection webkitGetNamedFlows self = liftDOM (((toDocument self) ^. jsf "webkitGetNamedFlows" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.webkitGetNamedFlows Mozilla Document.webkitGetNamedFlows documentation > webkitGetNamedFlows_ :: (MonadDOM m, IsDocument self) => self -> m () webkitGetNamedFlows_ self = liftDOM (void ((toDocument self) ^. jsf "webkitGetNamedFlows" ())) | < -US/docs/Web/API/Document.createTouch Mozilla Document.createTouch documentation > createTouch :: (MonadDOM m, IsDocument self, IsEventTarget target) => self -> Maybe Window -> Maybe target -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Float -> Maybe Float -> m Touch createTouch self window target identifier pageX pageY screenX screenY webkitRadiusX webkitRadiusY webkitRotationAngle webkitForce = liftDOM (((toDocument self) ^. jsf "createTouch" [toJSVal window, toJSVal target, toJSVal identifier, toJSVal pageX, toJSVal pageY, toJSVal screenX, toJSVal screenY, toJSVal webkitRadiusX, toJSVal webkitRadiusY, toJSVal webkitRotationAngle, toJSVal webkitForce]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createTouch Mozilla Document.createTouch documentation > createTouch_ :: (MonadDOM m, IsDocument self, IsEventTarget target) => self -> Maybe Window -> Maybe target -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Float -> Maybe Float -> m () createTouch_ self window target identifier pageX pageY screenX screenY webkitRadiusX webkitRadiusY webkitRotationAngle webkitForce = liftDOM (void ((toDocument self) ^. jsf "createTouch" [toJSVal window, toJSVal target, toJSVal identifier, toJSVal pageX, toJSVal pageY, toJSVal screenX, toJSVal screenY, toJSVal webkitRadiusX, toJSVal webkitRadiusY, toJSVal webkitRotationAngle, toJSVal webkitForce])) | < -US/docs/Web/API/Document.createTouchList Mozilla Document.createTouchList documentation > createTouchList :: (MonadDOM m, IsDocument self) => self -> [Touch] -> m TouchList createTouchList self touches = liftDOM (((toDocument self) ^. jsf "createTouchList" [toJSVal (array touches)]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createTouchList Mozilla Document.createTouchList documentation > createTouchList_ :: (MonadDOM m, IsDocument self) => self -> [Touch] -> m () createTouchList_ self touches = liftDOM (void ((toDocument self) ^. jsf "createTouchList" [toJSVal (array touches)])) | < -US/docs/Web/API/Document.timeline Mozilla Document.timeline documentation > getTimeline :: (MonadDOM m, IsDocument self) => self -> m DocumentTimeline getTimeline self = liftDOM (((toDocument self) ^. js "timeline") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.implementation Mozilla Document.implementation documentation> getImplementation :: (MonadDOM m, IsDocument self) => self -> m DOMImplementation getImplementation self = liftDOM (((toDocument self) ^. js "implementation") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.URL Mozilla Document.URL documentation> getURL :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getURL self = liftDOM (((toDocument self) ^. js "URL") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.documentURI Mozilla Document.documentURI documentation > getDocumentURI :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getDocumentURI self = liftDOM (((toDocument self) ^. js "documentURI") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.origin Mozilla Document.origin documentation > getOrigin :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getOrigin self = liftDOM (((toDocument self) ^. js "origin") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.compatMode Mozilla Document.compatMode documentation > getCompatMode :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getCompatMode self = liftDOM (((toDocument self) ^. js "compatMode") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.characterSet Mozilla Document.characterSet documentation > getCharacterSet :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getCharacterSet self = liftDOM (((toDocument self) ^. js "characterSet") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.charset Mozilla Document.charset documentation > getCharset :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getCharset self = liftDOM (((toDocument self) ^. js "charset") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.inputEncoding Mozilla Document.inputEncoding documentation > getInputEncoding :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getInputEncoding self = liftDOM (((toDocument self) ^. js "inputEncoding") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.contentType Mozilla Document.contentType documentation> getContentType :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getContentType self = liftDOM (((toDocument self) ^. js "contentType") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.doctype Mozilla Document.doctype documentation > getDoctype :: (MonadDOM m, IsDocument self) => self -> m (Maybe DocumentType) getDoctype self = liftDOM (((toDocument self) ^. js "doctype") >>= fromJSVal) | < -US/docs/Web/API/Document.doctype Mozilla Document.doctype documentation > getDoctypeUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m DocumentType getDoctypeUnsafe self = liftDOM ((((toDocument self) ^. js "doctype") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.doctype Mozilla Document.doctype documentation > getDoctypeUnchecked :: (MonadDOM m, IsDocument self) => self -> m DocumentType getDoctypeUnchecked self = liftDOM (((toDocument self) ^. js "doctype") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.documentElement Mozilla Document.documentElement documentation> getDocumentElement :: (MonadDOM m, IsDocument self) => self -> m (Maybe Element) getDocumentElement self = liftDOM (((toDocument self) ^. js "documentElement") >>= fromJSVal) -- | <-US/docs/Web/API/Document.documentElement Mozilla Document.documentElement documentation> getDocumentElementUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Element getDocumentElementUnsafe self = liftDOM ((((toDocument self) ^. js "documentElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Document.documentElement Mozilla Document.documentElement documentation> getDocumentElementUnchecked :: (MonadDOM m, IsDocument self) => self -> m Element getDocumentElementUnchecked self = liftDOM (((toDocument self) ^. js "documentElement") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.location Mozilla Document.location documentation> getLocation :: (MonadDOM m, IsDocument self) => self -> m (Maybe Location) getLocation self = liftDOM (((toDocument self) ^. js "location") >>= fromJSVal) -- | <-US/docs/Web/API/Document.location Mozilla Document.location documentation> getLocationUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Location getLocationUnsafe self = liftDOM ((((toDocument self) ^. js "location") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Document.location Mozilla Document.location documentation> getLocationUnchecked :: (MonadDOM m, IsDocument self) => self -> m Location getLocationUnchecked self = liftDOM (((toDocument self) ^. js "location") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.domain Mozilla Document.domain documentation > setDomain :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setDomain self val = liftDOM ((toDocument self) ^. jss "domain" (toJSVal val)) | < -US/docs/Web/API/Document.domain Mozilla Document.domain documentation > getDomain :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getDomain self = liftDOM (((toDocument self) ^. js "domain") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.referrer Mozilla Document.referrer documentation > getReferrer :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getReferrer self = liftDOM (((toDocument self) ^. js "referrer") >>= fromJSValUnchecked) | < Document.cookie documentation > setCookie :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setCookie self val = liftDOM ((toDocument self) ^. jss "cookie" (toJSVal val)) | < Document.cookie documentation > getCookie :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getCookie self = liftDOM (((toDocument self) ^. js "cookie") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.lastModified Document.lastModified documentation > getLastModified :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getLastModified self = liftDOM (((toDocument self) ^. js "lastModified") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.readyState Mozilla Document.readyState documentation > getReadyState :: (MonadDOM m, IsDocument self) => self -> m DocumentReadyState getReadyState self = liftDOM (((toDocument self) ^. js "readyState") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.title Mozilla Document.title documentation > setTitle :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setTitle self val = liftDOM ((toDocument self) ^. jss "title" (toJSVal val)) | < -US/docs/Web/API/Document.title Mozilla Document.title documentation > getTitle :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getTitle self = liftDOM (((toDocument self) ^. js "title") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.dir Mozilla Document.dir documentation > setDir :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setDir self val = liftDOM ((toDocument self) ^. jss "dir" (toJSVal val)) | < -US/docs/Web/API/Document.dir Mozilla Document.dir documentation > getDir :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getDir self = liftDOM (((toDocument self) ^. js "dir") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.body Mozilla Document.body documentation > setBody :: (MonadDOM m, IsDocument self, IsHTMLElement val) => self -> Maybe val -> m () setBody self val = liftDOM ((toDocument self) ^. jss "body" (toJSVal val)) | < -US/docs/Web/API/Document.body Mozilla Document.body documentation > getBody :: (MonadDOM m, IsDocument self) => self -> m (Maybe HTMLElement) getBody self = liftDOM (((toDocument self) ^. js "body") >>= fromJSVal) | < -US/docs/Web/API/Document.body Mozilla Document.body documentation > getBodyUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m HTMLElement getBodyUnsafe self = liftDOM ((((toDocument self) ^. js "body") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.body Mozilla Document.body documentation > getBodyUnchecked :: (MonadDOM m, IsDocument self) => self -> m HTMLElement getBodyUnchecked self = liftDOM (((toDocument self) ^. js "body") >>= fromJSValUnchecked) | documentation > getHead :: (MonadDOM m, IsDocument self) => self -> m (Maybe HTMLHeadElement) getHead self = liftDOM (((toDocument self) ^. js "head") >>= fromJSVal) | documentation > getHeadUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m HTMLHeadElement getHeadUnsafe self = liftDOM ((((toDocument self) ^. js "head") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | documentation > getHeadUnchecked :: (MonadDOM m, IsDocument self) => self -> m HTMLHeadElement getHeadUnchecked self = liftDOM (((toDocument self) ^. js "head") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.images Mozilla Document.images documentation> getImages :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getImages self = liftDOM (((toDocument self) ^. js "images") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.embeds Mozilla Document.embeds documentation > getEmbeds :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getEmbeds self = liftDOM (((toDocument self) ^. js "embeds") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.plugins Mozilla Document.plugins documentation > getPlugins :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getPlugins self = liftDOM (((toDocument self) ^. js "plugins") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.links Mozilla Document.links documentation > getLinks :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getLinks self = liftDOM (((toDocument self) ^. js "links") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.forms Mozilla Document.forms documentation> getForms :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getForms self = liftDOM (((toDocument self) ^. js "forms") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.scripts Mozilla Document.scripts documentation > getScripts :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getScripts self = liftDOM (((toDocument self) ^. js "scripts") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.currentScript Mozilla Document.currentScript documentation > getCurrentScript :: (MonadDOM m, IsDocument self) => self -> m (Maybe HTMLScriptElement) getCurrentScript self = liftDOM (((toDocument self) ^. js "currentScript") >>= fromJSVal) | < -US/docs/Web/API/Document.currentScript Mozilla Document.currentScript documentation > getCurrentScriptUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m HTMLScriptElement getCurrentScriptUnsafe self = liftDOM ((((toDocument self) ^. js "currentScript") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.currentScript Mozilla Document.currentScript documentation > getCurrentScriptUnchecked :: (MonadDOM m, IsDocument self) => self -> m HTMLScriptElement getCurrentScriptUnchecked self = liftDOM (((toDocument self) ^. js "currentScript") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.defaultView Mozilla Document.defaultView documentation> getDefaultView :: (MonadDOM m, IsDocument self) => self -> m (Maybe Window) getDefaultView self = liftDOM (((toDocument self) ^. js "defaultView") >>= fromJSVal) -- | <-US/docs/Web/API/Document.defaultView Mozilla Document.defaultView documentation> getDefaultViewUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Window getDefaultViewUnsafe self = liftDOM ((((toDocument self) ^. js "defaultView") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Document.defaultView Mozilla Document.defaultView documentation> getDefaultViewUnchecked :: (MonadDOM m, IsDocument self) => self -> m Window getDefaultViewUnchecked self = liftDOM (((toDocument self) ^. js "defaultView") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.designMode Mozilla Document.designMode documentation> setDesignMode :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setDesignMode self val = liftDOM ((toDocument self) ^. jss "designMode" (toJSVal val)) -- | <-US/docs/Web/API/Document.designMode Mozilla Document.designMode documentation> getDesignMode :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getDesignMode self = liftDOM (((toDocument self) ^. js "designMode") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.onreadystatechange Mozilla Document.onreadystatechange documentation > readyStateChange :: (IsDocument self, IsEventTarget self) => EventName self Event readyStateChange = unsafeEventNameAsync (toJSString "readystatechange") | < -US/docs/Web/API/Document.styleSheets Mozilla Document.styleSheets documentation > getStyleSheets :: (MonadDOM m, IsDocument self) => self -> m StyleSheetList getStyleSheets self = liftDOM (((toDocument self) ^. js "styleSheets") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.scrollingElement Mozilla Document.scrollingElement documentation > getScrollingElement :: (MonadDOM m, IsDocument self) => self -> m (Maybe Element) getScrollingElement self = liftDOM (((toDocument self) ^. js "scrollingElement") >>= fromJSVal) | < -US/docs/Web/API/Document.scrollingElement Mozilla Document.scrollingElement documentation > getScrollingElementUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Element getScrollingElementUnsafe self = liftDOM ((((toDocument self) ^. js "scrollingElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.scrollingElement Mozilla Document.scrollingElement documentation > getScrollingElementUnchecked :: (MonadDOM m, IsDocument self) => self -> m Element getScrollingElementUnchecked self = liftDOM (((toDocument self) ^. js "scrollingElement") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.webkitFullscreenEnabled Mozilla Document.webkitFullscreenEnabled documentation > getWebkitFullscreenEnabled :: (MonadDOM m, IsDocument self) => self -> m Bool getWebkitFullscreenEnabled self = liftDOM (((toDocument self) ^. js "webkitFullscreenEnabled") >>= valToBool) -- | <-US/docs/Web/API/Document.webkitFullscreenElement Mozilla Document.webkitFullscreenElement documentation> getWebkitFullscreenElement :: (MonadDOM m, IsDocument self) => self -> m (Maybe Element) getWebkitFullscreenElement self = liftDOM (((toDocument self) ^. js "webkitFullscreenElement") >>= fromJSVal) -- | <-US/docs/Web/API/Document.webkitFullscreenElement Mozilla Document.webkitFullscreenElement documentation> getWebkitFullscreenElementUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Element getWebkitFullscreenElementUnsafe self = liftDOM ((((toDocument self) ^. js "webkitFullscreenElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Document.webkitFullscreenElement Mozilla Document.webkitFullscreenElement documentation> getWebkitFullscreenElementUnchecked :: (MonadDOM m, IsDocument self) => self -> m Element getWebkitFullscreenElementUnchecked self = liftDOM (((toDocument self) ^. js "webkitFullscreenElement") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.webkitIsFullScreen Mozilla Document.webkitIsFullScreen documentation> getWebkitIsFullScreen :: (MonadDOM m, IsDocument self) => self -> m Bool getWebkitIsFullScreen self = liftDOM (((toDocument self) ^. js "webkitIsFullScreen") >>= valToBool) | < -US/docs/Web/API/Document.webkitFullScreenKeyboardInputAllowed Mozilla Document.webkitFullScreenKeyboardInputAllowed documentation > getWebkitFullScreenKeyboardInputAllowed :: (MonadDOM m, IsDocument self) => self -> m Bool getWebkitFullScreenKeyboardInputAllowed self = liftDOM (((toDocument self) ^. js "webkitFullScreenKeyboardInputAllowed") >>= valToBool) | < -US/docs/Web/API/Document.webkitCurrentFullScreenElement Mozilla Document.webkitCurrentFullScreenElement documentation > getWebkitCurrentFullScreenElement :: (MonadDOM m, IsDocument self) => self -> m Element getWebkitCurrentFullScreenElement self = liftDOM (((toDocument self) ^. js "webkitCurrentFullScreenElement") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.onwebkitfullscreenchange Mozilla Document.onwebkitfullscreenchange documentation > webKitFullscreenChange :: (IsDocument self, IsEventTarget self) => EventName self Event webKitFullscreenChange = unsafeEventName (toJSString "webkitfullscreenchange") | < -US/docs/Web/API/Document.onwebkitfullscreenerror Mozilla Document.onwebkitfullscreenerror documentation > webKitFullscreenError :: (IsDocument self, IsEventTarget self) => EventName self Event webKitFullscreenError = unsafeEventName (toJSString "webkitfullscreenerror") | < -US/docs/Web/API/Document.onpointerlockchange Mozilla Document.onpointerlockchange documentation > pointerlockchange :: (IsDocument self, IsEventTarget self) => EventName self Event pointerlockchange = unsafeEventName (toJSString "pointerlockchange") -- | <-US/docs/Web/API/Document.onpointerlockerror Mozilla Document.onpointerlockerror documentation> pointerlockerror :: (IsDocument self, IsEventTarget self) => EventName self Event pointerlockerror = unsafeEventName (toJSString "pointerlockerror") | < -US/docs/Web/API/Document.fonts Mozilla Document.fonts documentation > getFonts :: (MonadDOM m, IsDocument self) => self -> m FontFaceSet getFonts self = liftDOM (((toDocument self) ^. js "fonts") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.hidden Mozilla Document.hidden documentation > getHidden :: (MonadDOM m, IsDocument self) => self -> m Bool getHidden self = liftDOM (((toDocument self) ^. js "hidden") >>= valToBool) | < -US/docs/Web/API/Document.visibilityState Mozilla Document.visibilityState documentation > getVisibilityState :: (MonadDOM m, IsDocument self) => self -> m VisibilityState getVisibilityState self = liftDOM (((toDocument self) ^. js "visibilityState") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.onvisibilitychange Mozilla Document.onvisibilitychange documentation > visibilitychange :: (IsDocument self, IsEventTarget self) => EventName self Event visibilitychange = unsafeEventName (toJSString "visibilitychange") | < -US/docs/Web/API/Document.applets Mozilla Document.applets documentation > getApplets :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getApplets self = liftDOM (((toDocument self) ^. js "applets") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.anchors Mozilla Document.anchors documentation > getAnchors :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getAnchors self = liftDOM (((toDocument self) ^. js "anchors") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.preferredStylesheetSet Mozilla Document.preferredStylesheetSet documentation > getPreferredStylesheetSet :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m (Maybe result) getPreferredStylesheetSet self = liftDOM (((toDocument self) ^. js "preferredStylesheetSet") >>= fromMaybeJSString) | < -US/docs/Web/API/Document.preferredStylesheetSet Mozilla Document.preferredStylesheetSet documentation > getPreferredStylesheetSetUnsafe :: (MonadDOM m, IsDocument self, HasCallStack, FromJSString result) => self -> m result getPreferredStylesheetSetUnsafe self = liftDOM ((((toDocument self) ^. js "preferredStylesheetSet") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.preferredStylesheetSet Mozilla Document.preferredStylesheetSet documentation > getPreferredStylesheetSetUnchecked :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getPreferredStylesheetSetUnchecked self = liftDOM (((toDocument self) ^. js "preferredStylesheetSet") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.selectedStylesheetSet Mozilla Document.selectedStylesheetSet documentation > setSelectedStylesheetSet :: (MonadDOM m, IsDocument self, ToJSString val) => self -> Maybe val -> m () setSelectedStylesheetSet self val = liftDOM ((toDocument self) ^. jss "selectedStylesheetSet" (toJSVal val)) | < -US/docs/Web/API/Document.selectedStylesheetSet Mozilla Document.selectedStylesheetSet documentation > getSelectedStylesheetSet :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m (Maybe result) getSelectedStylesheetSet self = liftDOM (((toDocument self) ^. js "selectedStylesheetSet") >>= fromMaybeJSString) | < -US/docs/Web/API/Document.selectedStylesheetSet Mozilla Document.selectedStylesheetSet documentation > getSelectedStylesheetSetUnsafe :: (MonadDOM m, IsDocument self, HasCallStack, FromJSString result) => self -> m result getSelectedStylesheetSetUnsafe self = liftDOM ((((toDocument self) ^. js "selectedStylesheetSet") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.selectedStylesheetSet Mozilla Document.selectedStylesheetSet documentation > getSelectedStylesheetSetUnchecked :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getSelectedStylesheetSetUnchecked self = liftDOM (((toDocument self) ^. js "selectedStylesheetSet") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.xmlEncoding Mozilla Document.xmlEncoding documentation > getXmlEncoding :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m (Maybe result) getXmlEncoding self = liftDOM (((toDocument self) ^. js "xmlEncoding") >>= fromMaybeJSString) | < -US/docs/Web/API/Document.xmlEncoding Mozilla Document.xmlEncoding documentation > getXmlEncodingUnsafe :: (MonadDOM m, IsDocument self, HasCallStack, FromJSString result) => self -> m result getXmlEncodingUnsafe self = liftDOM ((((toDocument self) ^. js "xmlEncoding") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.xmlEncoding Mozilla Document.xmlEncoding documentation > getXmlEncodingUnchecked :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getXmlEncodingUnchecked self = liftDOM (((toDocument self) ^. js "xmlEncoding") >>= fromJSValUnchecked) -- | <-US/docs/Web/API/Document.xmlVersion Mozilla Document.xmlVersion documentation> setXmlVersion :: (MonadDOM m, IsDocument self, ToJSString val) => self -> Maybe val -> m () setXmlVersion self val = liftDOM ((toDocument self) ^. jss "xmlVersion" (toJSVal val)) -- | <-US/docs/Web/API/Document.xmlVersion Mozilla Document.xmlVersion documentation> getXmlVersion :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m (Maybe result) getXmlVersion self = liftDOM (((toDocument self) ^. js "xmlVersion") >>= fromMaybeJSString) -- | <-US/docs/Web/API/Document.xmlVersion Mozilla Document.xmlVersion documentation> getXmlVersionUnsafe :: (MonadDOM m, IsDocument self, HasCallStack, FromJSString result) => self -> m result getXmlVersionUnsafe self = liftDOM ((((toDocument self) ^. js "xmlVersion") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Document.xmlVersion Mozilla Document.xmlVersion documentation> getXmlVersionUnchecked :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getXmlVersionUnchecked self = liftDOM (((toDocument self) ^. js "xmlVersion") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.xmlStandalone Mozilla Document.xmlStandalone documentation > setXmlStandalone :: (MonadDOM m, IsDocument self) => self -> Bool -> m () setXmlStandalone self val = liftDOM ((toDocument self) ^. jss "xmlStandalone" (toJSVal val)) | < -US/docs/Web/API/Document.xmlStandalone Mozilla Document.xmlStandalone documentation > getXmlStandalone :: (MonadDOM m, IsDocument self) => self -> m Bool getXmlStandalone self = liftDOM (((toDocument self) ^. js "xmlStandalone") >>= valToBool) -- | <-US/docs/Web/API/Document.onselectstart Mozilla Document.onselectstart documentation> selectStart :: (IsDocument self, IsEventTarget self) => EventName self Event selectStart = unsafeEventName (toJSString "selectstart") | < -US/docs/Web/API/Document.onselectionchange Mozilla Document.onselectionchange documentation > selectionchange :: (IsDocument self, IsEventTarget self) => EventName self onselectionchange selectionchange = unsafeEventName (toJSString "selectionchange") -- | <-US/docs/Web/API/Document.rootElement Mozilla Document.rootElement documentation> getRootElement :: (MonadDOM m, IsDocument self) => self -> m (Maybe SVGSVGElement) getRootElement self = liftDOM (((toDocument self) ^. js "rootElement") >>= fromJSVal) -- | <-US/docs/Web/API/Document.rootElement Mozilla Document.rootElement documentation> getRootElementUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m SVGSVGElement getRootElementUnsafe self = liftDOM ((((toDocument self) ^. js "rootElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <-US/docs/Web/API/Document.rootElement Mozilla Document.rootElement documentation> getRootElementUnchecked :: (MonadDOM m, IsDocument self) => self -> m SVGSVGElement getRootElementUnchecked self = liftDOM (((toDocument self) ^. js "rootElement") >>= fromJSValUnchecked)
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/Document.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | <-US/docs/Web/API/Document.getElementsByTagName Mozilla Document.getElementsByTagName documentation> | <-US/docs/Web/API/Document.getElementsByTagName Mozilla Document.getElementsByTagName documentation> | <-US/docs/Web/API/Document.createElement Mozilla Document.createElement documentation> | <-US/docs/Web/API/Document.createElement Mozilla Document.createElement documentation> | <-US/docs/Web/API/Document.importNode Mozilla Document.importNode documentation> | <-US/docs/Web/API/Document.importNode Mozilla Document.importNode documentation> | <-US/docs/Web/API/Document.createEvent Mozilla Document.createEvent documentation> | <-US/docs/Web/API/Document.createEvent Mozilla Document.createEvent documentation> | <-US/docs/Web/API/Document.createNodeIterator Mozilla Document.createNodeIterator documentation> | <-US/docs/Web/API/Document.createNodeIterator Mozilla Document.createNodeIterator documentation> | <-US/docs/Web/API/Document.getElementsByName Mozilla Document.getElementsByName documentation> | <-US/docs/Web/API/Document.getElementsByName Mozilla Document.getElementsByName documentation> | <-US/docs/Web/API/Document.queryCommandSupported Mozilla Document.queryCommandSupported documentation> | <-US/docs/Web/API/Document.queryCommandSupported Mozilla Document.queryCommandSupported documentation> | <-US/docs/Web/API/Document.getSelection Mozilla Document.getSelection documentation> | <-US/docs/Web/API/Document.getSelection Mozilla Document.getSelection documentation> | <-US/docs/Web/API/Document.getSelection Mozilla Document.getSelection documentation> | <-US/docs/Web/API/Document.getSelection Mozilla Document.getSelection documentation> | <-US/docs/Web/API/Document.createNSResolver Mozilla Document.createNSResolver documentation> | <-US/docs/Web/API/Document.createNSResolver Mozilla Document.createNSResolver documentation> | <-US/docs/Web/API/Document.webkitCancelFullScreen Mozilla Document.webkitCancelFullScreen documentation> | <-US/docs/Web/API/Document.caretRangeFromPoint Mozilla Document.caretRangeFromPoint documentation> | <-US/docs/Web/API/Document.caretRangeFromPoint Mozilla Document.caretRangeFromPoint documentation> | <-US/docs/Web/API/Document.implementation Mozilla Document.implementation documentation> | <-US/docs/Web/API/Document.URL Mozilla Document.URL documentation> | <-US/docs/Web/API/Document.contentType Mozilla Document.contentType documentation> | <-US/docs/Web/API/Document.documentElement Mozilla Document.documentElement documentation> | <-US/docs/Web/API/Document.documentElement Mozilla Document.documentElement documentation> | <-US/docs/Web/API/Document.documentElement Mozilla Document.documentElement documentation> | <-US/docs/Web/API/Document.location Mozilla Document.location documentation> | <-US/docs/Web/API/Document.location Mozilla Document.location documentation> | <-US/docs/Web/API/Document.location Mozilla Document.location documentation> | <-US/docs/Web/API/Document.images Mozilla Document.images documentation> | <-US/docs/Web/API/Document.forms Mozilla Document.forms documentation> | <-US/docs/Web/API/Document.defaultView Mozilla Document.defaultView documentation> | <-US/docs/Web/API/Document.defaultView Mozilla Document.defaultView documentation> | <-US/docs/Web/API/Document.defaultView Mozilla Document.defaultView documentation> | <-US/docs/Web/API/Document.designMode Mozilla Document.designMode documentation> | <-US/docs/Web/API/Document.designMode Mozilla Document.designMode documentation> | <-US/docs/Web/API/Document.webkitFullscreenElement Mozilla Document.webkitFullscreenElement documentation> | <-US/docs/Web/API/Document.webkitFullscreenElement Mozilla Document.webkitFullscreenElement documentation> | <-US/docs/Web/API/Document.webkitFullscreenElement Mozilla Document.webkitFullscreenElement documentation> | <-US/docs/Web/API/Document.webkitIsFullScreen Mozilla Document.webkitIsFullScreen documentation> | <-US/docs/Web/API/Document.onpointerlockerror Mozilla Document.onpointerlockerror documentation> | <-US/docs/Web/API/Document.xmlVersion Mozilla Document.xmlVersion documentation> | <-US/docs/Web/API/Document.xmlVersion Mozilla Document.xmlVersion documentation> | <-US/docs/Web/API/Document.xmlVersion Mozilla Document.xmlVersion documentation> | <-US/docs/Web/API/Document.xmlVersion Mozilla Document.xmlVersion documentation> | <-US/docs/Web/API/Document.onselectstart Mozilla Document.onselectstart documentation> | <-US/docs/Web/API/Document.rootElement Mozilla Document.rootElement documentation> | <-US/docs/Web/API/Document.rootElement Mozilla Document.rootElement documentation> | <-US/docs/Web/API/Document.rootElement Mozilla Document.rootElement documentation>
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.Document (getAnimations, getAnimations_, newDocument, getElementsByTagName, getElementsByTagName_, getElementsByTagNameNS, getElementsByTagNameNS_, getElementsByClassName, getElementsByClassName_, createElement, createElement_, createElementNS, createElementNS_, createDocumentFragment, createDocumentFragment_, createTextNode, createTextNode_, createCDATASection, createCDATASection_, createComment, createComment_, createProcessingInstruction, createProcessingInstruction_, importNode, importNode_, adoptNode, adoptNode_, createAttribute, createAttribute_, createAttributeNS, createAttributeNS_, createEvent, createEvent_, createRange, createRange_, createNodeIterator, createNodeIterator_, createTreeWalker, createTreeWalker_, getElementsByName, getElementsByName_, hasFocus, hasFocus_, execCommand, execCommand_, queryCommandEnabled, queryCommandEnabled_, queryCommandIndeterm, queryCommandIndeterm_, queryCommandState, queryCommandState_, queryCommandSupported, queryCommandSupported_, queryCommandValue, queryCommandValue_, getSelection, getSelection_, getSelectionUnsafe, getSelectionUnchecked, createExpression, createExpression_, createNSResolver, createNSResolver_, evaluate, evaluate_, webkitExitFullscreen, webkitCancelFullScreen, exitPointerLock, getOverrideStyle, getOverrideStyle_, caretRangeFromPoint, caretRangeFromPoint_, getCSSCanvasContext, getCSSCanvasContext_, webkitGetNamedFlows, webkitGetNamedFlows_, createTouch, createTouch_, createTouchList, createTouchList_, getTimeline, getImplementation, getURL, getDocumentURI, getOrigin, getCompatMode, getCharacterSet, getCharset, getInputEncoding, getContentType, getDoctype, getDoctypeUnsafe, getDoctypeUnchecked, getDocumentElement, getDocumentElementUnsafe, getDocumentElementUnchecked, getLocation, getLocationUnsafe, getLocationUnchecked, setDomain, getDomain, getReferrer, setCookie, getCookie, getLastModified, getReadyState, setTitle, getTitle, setDir, getDir, setBody, getBody, getBodyUnsafe, getBodyUnchecked, getHead, getHeadUnsafe, getHeadUnchecked, getImages, getEmbeds, getPlugins, getLinks, getForms, getScripts, getCurrentScript, getCurrentScriptUnsafe, getCurrentScriptUnchecked, getDefaultView, getDefaultViewUnsafe, getDefaultViewUnchecked, setDesignMode, getDesignMode, readyStateChange, getStyleSheets, getScrollingElement, getScrollingElementUnsafe, getScrollingElementUnchecked, getWebkitFullscreenEnabled, getWebkitFullscreenElement, getWebkitFullscreenElementUnsafe, getWebkitFullscreenElementUnchecked, getWebkitIsFullScreen, getWebkitFullScreenKeyboardInputAllowed, getWebkitCurrentFullScreenElement, webKitFullscreenChange, webKitFullscreenError, pointerlockchange, pointerlockerror, getFonts, getHidden, getVisibilityState, visibilitychange, getApplets, getAnchors, getPreferredStylesheetSet, getPreferredStylesheetSetUnsafe, getPreferredStylesheetSetUnchecked, setSelectedStylesheetSet, getSelectedStylesheetSet, getSelectedStylesheetSetUnsafe, getSelectedStylesheetSetUnchecked, getXmlEncoding, getXmlEncodingUnsafe, getXmlEncodingUnchecked, setXmlVersion, getXmlVersion, getXmlVersionUnsafe, getXmlVersionUnchecked, setXmlStandalone, getXmlStandalone, selectStart, selectionchange, getRootElement, getRootElementUnsafe, getRootElementUnchecked, Document(..), gTypeDocument, IsDocument, toDocument) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/Document.getAnimations Mozilla Document.getAnimations documentation > getAnimations :: (MonadDOM m, IsDocument self) => self -> m [Animation] getAnimations self = liftDOM (((toDocument self) ^. jsf "getAnimations" ()) >>= fromJSArrayUnchecked) | < -US/docs/Web/API/Document.getAnimations Mozilla Document.getAnimations documentation > getAnimations_ :: (MonadDOM m, IsDocument self) => self -> m () getAnimations_ self = liftDOM (void ((toDocument self) ^. jsf "getAnimations" ())) | < -US/docs/Web/API/Document Mozilla Document documentation > newDocument :: (MonadDOM m) => m Document newDocument = liftDOM (Document <$> new (jsg "Document") ()) getElementsByTagName :: (MonadDOM m, IsDocument self, ToJSString qualifiedName) => self -> qualifiedName -> m HTMLCollection getElementsByTagName self qualifiedName = liftDOM (((toDocument self) ^. jsf "getElementsByTagName" [toJSVal qualifiedName]) >>= fromJSValUnchecked) getElementsByTagName_ :: (MonadDOM m, IsDocument self, ToJSString qualifiedName) => self -> qualifiedName -> m () getElementsByTagName_ self qualifiedName = liftDOM (void ((toDocument self) ^. jsf "getElementsByTagName" [toJSVal qualifiedName])) | < -US/docs/Web/API/Document.getElementsByTagNameNS Mozilla Document.getElementsByTagNameNS documentation > getElementsByTagNameNS :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m HTMLCollection getElementsByTagNameNS self namespaceURI localName = liftDOM (((toDocument self) ^. jsf "getElementsByTagNameNS" [toJSVal namespaceURI, toJSVal localName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.getElementsByTagNameNS Mozilla Document.getElementsByTagNameNS documentation > getElementsByTagNameNS_ :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString localName) => self -> Maybe namespaceURI -> localName -> m () getElementsByTagNameNS_ self namespaceURI localName = liftDOM (void ((toDocument self) ^. jsf "getElementsByTagNameNS" [toJSVal namespaceURI, toJSVal localName])) | < -US/docs/Web/API/Document.getElementsByClassName Mozilla Document.getElementsByClassName documentation > getElementsByClassName :: (MonadDOM m, IsDocument self, ToJSString classNames) => self -> classNames -> m HTMLCollection getElementsByClassName self classNames = liftDOM (((toDocument self) ^. jsf "getElementsByClassName" [toJSVal classNames]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.getElementsByClassName Mozilla Document.getElementsByClassName documentation > getElementsByClassName_ :: (MonadDOM m, IsDocument self, ToJSString classNames) => self -> classNames -> m () getElementsByClassName_ self classNames = liftDOM (void ((toDocument self) ^. jsf "getElementsByClassName" [toJSVal classNames])) createElement :: (MonadDOM m, IsDocument self, ToJSString localName) => self -> localName -> m Element createElement self localName = liftDOM (((toDocument self) ^. jsf "createElement" [toJSVal localName]) >>= fromJSValUnchecked) createElement_ :: (MonadDOM m, IsDocument self, ToJSString localName) => self -> localName -> m () createElement_ self localName = liftDOM (void ((toDocument self) ^. jsf "createElement" [toJSVal localName])) | < -US/docs/Web/API/Document.createElementNS Mozilla Document.createElementNS documentation > createElementNS :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> Maybe namespaceURI -> qualifiedName -> m Element createElementNS self namespaceURI qualifiedName = liftDOM (((toDocument self) ^. jsf "createElementNS" [toJSVal namespaceURI, toJSVal qualifiedName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createElementNS Mozilla Document.createElementNS documentation > createElementNS_ :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> Maybe namespaceURI -> qualifiedName -> m () createElementNS_ self namespaceURI qualifiedName = liftDOM (void ((toDocument self) ^. jsf "createElementNS" [toJSVal namespaceURI, toJSVal qualifiedName])) | < -US/docs/Web/API/Document.createDocumentFragment Mozilla Document.createDocumentFragment documentation > createDocumentFragment :: (MonadDOM m, IsDocument self) => self -> m DocumentFragment createDocumentFragment self = liftDOM (((toDocument self) ^. jsf "createDocumentFragment" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createDocumentFragment Mozilla Document.createDocumentFragment documentation > createDocumentFragment_ :: (MonadDOM m, IsDocument self) => self -> m () createDocumentFragment_ self = liftDOM (void ((toDocument self) ^. jsf "createDocumentFragment" ())) | < -US/docs/Web/API/Document.createTextNode Mozilla Document.createTextNode documentation > createTextNode :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m Text createTextNode self data' = liftDOM (((toDocument self) ^. jsf "createTextNode" [toJSVal data']) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createTextNode Mozilla Document.createTextNode documentation > createTextNode_ :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m () createTextNode_ self data' = liftDOM (void ((toDocument self) ^. jsf "createTextNode" [toJSVal data'])) | < -US/docs/Web/API/Document.createCDATASection Mozilla Document.createCDATASection documentation > createCDATASection :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m CDATASection createCDATASection self data' = liftDOM (((toDocument self) ^. jsf "createCDATASection" [toJSVal data']) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createCDATASection Mozilla Document.createCDATASection documentation > createCDATASection_ :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m () createCDATASection_ self data' = liftDOM (void ((toDocument self) ^. jsf "createCDATASection" [toJSVal data'])) | < -US/docs/Web/API/Document.createComment Mozilla Document.createComment documentation > createComment :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m Comment createComment self data' = liftDOM (((toDocument self) ^. jsf "createComment" [toJSVal data']) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createComment Mozilla Document.createComment documentation > createComment_ :: (MonadDOM m, IsDocument self, ToJSString data') => self -> data' -> m () createComment_ self data' = liftDOM (void ((toDocument self) ^. jsf "createComment" [toJSVal data'])) | < -US/docs/Web/API/Document.createProcessingInstruction Mozilla Document.createProcessingInstruction documentation > createProcessingInstruction :: (MonadDOM m, IsDocument self, ToJSString target, ToJSString data') => self -> target -> data' -> m ProcessingInstruction createProcessingInstruction self target data' = liftDOM (((toDocument self) ^. jsf "createProcessingInstruction" [toJSVal target, toJSVal data']) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createProcessingInstruction Mozilla Document.createProcessingInstruction documentation > createProcessingInstruction_ :: (MonadDOM m, IsDocument self, ToJSString target, ToJSString data') => self -> target -> data' -> m () createProcessingInstruction_ self target data' = liftDOM (void ((toDocument self) ^. jsf "createProcessingInstruction" [toJSVal target, toJSVal data'])) importNode :: (MonadDOM m, IsDocument self, IsNode node) => self -> node -> Bool -> m Node importNode self node deep = liftDOM (((toDocument self) ^. jsf "importNode" [toJSVal node, toJSVal deep]) >>= fromJSValUnchecked) importNode_ :: (MonadDOM m, IsDocument self, IsNode node) => self -> node -> Bool -> m () importNode_ self node deep = liftDOM (void ((toDocument self) ^. jsf "importNode" [toJSVal node, toJSVal deep])) | < -US/docs/Web/API/Document.adoptNode Mozilla Document.adoptNode documentation > adoptNode :: (MonadDOM m, IsDocument self, IsNode node) => self -> node -> m Node adoptNode self node = liftDOM (((toDocument self) ^. jsf "adoptNode" [toJSVal node]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.adoptNode Mozilla Document.adoptNode documentation > adoptNode_ :: (MonadDOM m, IsDocument self, IsNode node) => self -> node -> m () adoptNode_ self node = liftDOM (void ((toDocument self) ^. jsf "adoptNode" [toJSVal node])) | < -US/docs/Web/API/Document.createAttribute Mozilla Document.createAttribute documentation > createAttribute :: (MonadDOM m, IsDocument self, ToJSString localName) => self -> localName -> m Attr createAttribute self localName = liftDOM (((toDocument self) ^. jsf "createAttribute" [toJSVal localName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createAttribute Mozilla Document.createAttribute documentation > createAttribute_ :: (MonadDOM m, IsDocument self, ToJSString localName) => self -> localName -> m () createAttribute_ self localName = liftDOM (void ((toDocument self) ^. jsf "createAttribute" [toJSVal localName])) | < -US/docs/Web/API/Document.createAttributeNS Mozilla Document.createAttributeNS documentation > createAttributeNS :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> Maybe namespaceURI -> qualifiedName -> m Attr createAttributeNS self namespaceURI qualifiedName = liftDOM (((toDocument self) ^. jsf "createAttributeNS" [toJSVal namespaceURI, toJSVal qualifiedName]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createAttributeNS Mozilla Document.createAttributeNS documentation > createAttributeNS_ :: (MonadDOM m, IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> Maybe namespaceURI -> qualifiedName -> m () createAttributeNS_ self namespaceURI qualifiedName = liftDOM (void ((toDocument self) ^. jsf "createAttributeNS" [toJSVal namespaceURI, toJSVal qualifiedName])) createEvent :: (MonadDOM m, IsDocument self, ToJSString type') => self -> type' -> m Event createEvent self type' = liftDOM (((toDocument self) ^. jsf "createEvent" [toJSVal type']) >>= fromJSValUnchecked) createEvent_ :: (MonadDOM m, IsDocument self, ToJSString type') => self -> type' -> m () createEvent_ self type' = liftDOM (void ((toDocument self) ^. jsf "createEvent" [toJSVal type'])) | < -US/docs/Web/API/Document.createRange Mozilla Document.createRange documentation > createRange :: (MonadDOM m, IsDocument self) => self -> m Range createRange self = liftDOM (((toDocument self) ^. jsf "createRange" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createRange Mozilla Document.createRange documentation > createRange_ :: (MonadDOM m, IsDocument self) => self -> m () createRange_ self = liftDOM (void ((toDocument self) ^. jsf "createRange" ())) createNodeIterator :: (MonadDOM m, IsDocument self, IsNode root) => self -> root -> Maybe Word -> Maybe NodeFilter -> m NodeIterator createNodeIterator self root whatToShow filter = liftDOM (((toDocument self) ^. jsf "createNodeIterator" [toJSVal root, toJSVal whatToShow, toJSVal filter]) >>= fromJSValUnchecked) createNodeIterator_ :: (MonadDOM m, IsDocument self, IsNode root) => self -> root -> Maybe Word -> Maybe NodeFilter -> m () createNodeIterator_ self root whatToShow filter = liftDOM (void ((toDocument self) ^. jsf "createNodeIterator" [toJSVal root, toJSVal whatToShow, toJSVal filter])) | < -US/docs/Web/API/Document.createTreeWalker Mozilla Document.createTreeWalker documentation > createTreeWalker :: (MonadDOM m, IsDocument self, IsNode root) => self -> root -> Maybe Word -> Maybe NodeFilter -> m TreeWalker createTreeWalker self root whatToShow filter = liftDOM (((toDocument self) ^. jsf "createTreeWalker" [toJSVal root, toJSVal whatToShow, toJSVal filter]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createTreeWalker Mozilla Document.createTreeWalker documentation > createTreeWalker_ :: (MonadDOM m, IsDocument self, IsNode root) => self -> root -> Maybe Word -> Maybe NodeFilter -> m () createTreeWalker_ self root whatToShow filter = liftDOM (void ((toDocument self) ^. jsf "createTreeWalker" [toJSVal root, toJSVal whatToShow, toJSVal filter])) getElementsByName :: (MonadDOM m, IsDocument self, ToJSString elementName) => self -> elementName -> m NodeList getElementsByName self elementName = liftDOM (((toDocument self) ^. jsf "getElementsByName" [toJSVal elementName]) >>= fromJSValUnchecked) getElementsByName_ :: (MonadDOM m, IsDocument self, ToJSString elementName) => self -> elementName -> m () getElementsByName_ self elementName = liftDOM (void ((toDocument self) ^. jsf "getElementsByName" [toJSVal elementName])) | < -US/docs/Web/API/Document.hasFocus Mozilla Document.hasFocus documentation > hasFocus :: (MonadDOM m, IsDocument self) => self -> m Bool hasFocus self = liftDOM (((toDocument self) ^. jsf "hasFocus" ()) >>= valToBool) | < -US/docs/Web/API/Document.hasFocus Mozilla Document.hasFocus documentation > hasFocus_ :: (MonadDOM m, IsDocument self) => self -> m () hasFocus_ self = liftDOM (void ((toDocument self) ^. jsf "hasFocus" ())) | < -US/docs/Web/API/Document.execCommand Mozilla Document.execCommand documentation > execCommand :: (MonadDOM m, IsDocument self, ToJSString commandId, ToJSString value) => self -> commandId -> Bool -> Maybe value -> m Bool execCommand self commandId showUI value = liftDOM (((toDocument self) ^. jsf "execCommand" [toJSVal commandId, toJSVal showUI, toJSVal value]) >>= valToBool) | < -US/docs/Web/API/Document.execCommand Mozilla Document.execCommand documentation > execCommand_ :: (MonadDOM m, IsDocument self, ToJSString commandId, ToJSString value) => self -> commandId -> Bool -> Maybe value -> m () execCommand_ self commandId showUI value = liftDOM (void ((toDocument self) ^. jsf "execCommand" [toJSVal commandId, toJSVal showUI, toJSVal value])) | < -US/docs/Web/API/Document.queryCommandEnabled Mozilla Document.queryCommandEnabled documentation > queryCommandEnabled :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m Bool queryCommandEnabled self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandEnabled" [toJSVal commandId]) >>= valToBool) | < -US/docs/Web/API/Document.queryCommandEnabled Mozilla Document.queryCommandEnabled documentation > queryCommandEnabled_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandEnabled_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandEnabled" [toJSVal commandId])) | < -US/docs/Web/API/Document.queryCommandIndeterm Mozilla Document.queryCommandIndeterm documentation > queryCommandIndeterm :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m Bool queryCommandIndeterm self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandIndeterm" [toJSVal commandId]) >>= valToBool) | < -US/docs/Web/API/Document.queryCommandIndeterm Mozilla Document.queryCommandIndeterm documentation > queryCommandIndeterm_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandIndeterm_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandIndeterm" [toJSVal commandId])) | < -US/docs/Web/API/Document.queryCommandState Mozilla Document.queryCommandState documentation > queryCommandState :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m Bool queryCommandState self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandState" [toJSVal commandId]) >>= valToBool) | < -US/docs/Web/API/Document.queryCommandState Mozilla Document.queryCommandState documentation > queryCommandState_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandState_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandState" [toJSVal commandId])) queryCommandSupported :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m Bool queryCommandSupported self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandSupported" [toJSVal commandId]) >>= valToBool) queryCommandSupported_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandSupported_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandSupported" [toJSVal commandId])) | < -US/docs/Web/API/Document.queryCommandValue Mozilla Document.queryCommandValue documentation > queryCommandValue :: (MonadDOM m, IsDocument self, ToJSString commandId, FromJSString result) => self -> commandId -> m result queryCommandValue self commandId = liftDOM (((toDocument self) ^. jsf "queryCommandValue" [toJSVal commandId]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.queryCommandValue Mozilla Document.queryCommandValue documentation > queryCommandValue_ :: (MonadDOM m, IsDocument self, ToJSString commandId) => self -> commandId -> m () queryCommandValue_ self commandId = liftDOM (void ((toDocument self) ^. jsf "queryCommandValue" [toJSVal commandId])) getSelection :: (MonadDOM m, IsDocument self) => self -> m (Maybe Selection) getSelection self = liftDOM (((toDocument self) ^. jsf "getSelection" ()) >>= fromJSVal) getSelection_ :: (MonadDOM m, IsDocument self) => self -> m () getSelection_ self = liftDOM (void ((toDocument self) ^. jsf "getSelection" ())) getSelectionUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Selection getSelectionUnsafe self = liftDOM ((((toDocument self) ^. jsf "getSelection" ()) >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) getSelectionUnchecked :: (MonadDOM m, IsDocument self) => self -> m Selection getSelectionUnchecked self = liftDOM (((toDocument self) ^. jsf "getSelection" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createExpression Mozilla Document.createExpression documentation > createExpression :: (MonadDOM m, IsDocument self, ToJSString expression) => self -> Maybe expression -> Maybe XPathNSResolver -> m XPathExpression createExpression self expression resolver = liftDOM (((toDocument self) ^. jsf "createExpression" [toJSVal expression, toJSVal resolver]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createExpression Mozilla Document.createExpression documentation > createExpression_ :: (MonadDOM m, IsDocument self, ToJSString expression) => self -> Maybe expression -> Maybe XPathNSResolver -> m () createExpression_ self expression resolver = liftDOM (void ((toDocument self) ^. jsf "createExpression" [toJSVal expression, toJSVal resolver])) createNSResolver :: (MonadDOM m, IsDocument self, IsNode nodeResolver) => self -> Maybe nodeResolver -> m XPathNSResolver createNSResolver self nodeResolver = liftDOM (((toDocument self) ^. jsf "createNSResolver" [toJSVal nodeResolver]) >>= fromJSValUnchecked) createNSResolver_ :: (MonadDOM m, IsDocument self, IsNode nodeResolver) => self -> Maybe nodeResolver -> m () createNSResolver_ self nodeResolver = liftDOM (void ((toDocument self) ^. jsf "createNSResolver" [toJSVal nodeResolver])) | < -US/docs/Web/API/Document.evaluate Mozilla Document.evaluate documentation > evaluate :: (MonadDOM m, IsDocument self, ToJSString expression, IsNode contextNode) => self -> Maybe expression -> Maybe contextNode -> Maybe XPathNSResolver -> Maybe Word -> Maybe XPathResult -> m XPathResult evaluate self expression contextNode resolver type' inResult = liftDOM (((toDocument self) ^. jsf "evaluate" [toJSVal expression, toJSVal contextNode, toJSVal resolver, toJSVal type', toJSVal inResult]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.evaluate Mozilla Document.evaluate documentation > evaluate_ :: (MonadDOM m, IsDocument self, ToJSString expression, IsNode contextNode) => self -> Maybe expression -> Maybe contextNode -> Maybe XPathNSResolver -> Maybe Word -> Maybe XPathResult -> m () evaluate_ self expression contextNode resolver type' inResult = liftDOM (void ((toDocument self) ^. jsf "evaluate" [toJSVal expression, toJSVal contextNode, toJSVal resolver, toJSVal type', toJSVal inResult])) | < Document.webkitExitFullscreen documentation > webkitExitFullscreen :: (MonadDOM m, IsDocument self) => self -> m () webkitExitFullscreen self = liftDOM (void ((toDocument self) ^. jsf "webkitExitFullscreen" ())) webkitCancelFullScreen :: (MonadDOM m, IsDocument self) => self -> m () webkitCancelFullScreen self = liftDOM (void ((toDocument self) ^. jsf "webkitCancelFullScreen" ())) | < -US/docs/Web/API/Document.exitPointerLock Mozilla Document.exitPointerLock documentation > exitPointerLock :: (MonadDOM m, IsDocument self) => self -> m () exitPointerLock self = liftDOM (void ((toDocument self) ^. jsf "exitPointerLock" ())) | < -US/docs/Web/API/Document.getOverrideStyle Mozilla Document.getOverrideStyle documentation > getOverrideStyle :: (MonadDOM m, IsDocument self, IsElement element, ToJSString pseudoElement) => self -> Maybe element -> Maybe pseudoElement -> m CSSStyleDeclaration getOverrideStyle self element pseudoElement = liftDOM (((toDocument self) ^. jsf "getOverrideStyle" [toJSVal element, toJSVal pseudoElement]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.getOverrideStyle Mozilla Document.getOverrideStyle documentation > getOverrideStyle_ :: (MonadDOM m, IsDocument self, IsElement element, ToJSString pseudoElement) => self -> Maybe element -> Maybe pseudoElement -> m () getOverrideStyle_ self element pseudoElement = liftDOM (void ((toDocument self) ^. jsf "getOverrideStyle" [toJSVal element, toJSVal pseudoElement])) caretRangeFromPoint :: (MonadDOM m, IsDocument self) => self -> Maybe Int -> Maybe Int -> m Range caretRangeFromPoint self x y = liftDOM (((toDocument self) ^. jsf "caretRangeFromPoint" [toJSVal x, toJSVal y]) >>= fromJSValUnchecked) caretRangeFromPoint_ :: (MonadDOM m, IsDocument self) => self -> Maybe Int -> Maybe Int -> m () caretRangeFromPoint_ self x y = liftDOM (void ((toDocument self) ^. jsf "caretRangeFromPoint" [toJSVal x, toJSVal y])) | < -US/docs/Web/API/Document.getCSSCanvasContext Mozilla Document.getCSSCanvasContext documentation > getCSSCanvasContext :: (MonadDOM m, IsDocument self, ToJSString contextId, ToJSString name) => self -> contextId -> name -> Int -> Int -> m RenderingContext getCSSCanvasContext self contextId name width height = liftDOM (((toDocument self) ^. jsf "getCSSCanvasContext" [toJSVal contextId, toJSVal name, toJSVal width, toJSVal height]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.getCSSCanvasContext Mozilla Document.getCSSCanvasContext documentation > getCSSCanvasContext_ :: (MonadDOM m, IsDocument self, ToJSString contextId, ToJSString name) => self -> contextId -> name -> Int -> Int -> m () getCSSCanvasContext_ self contextId name width height = liftDOM (void ((toDocument self) ^. jsf "getCSSCanvasContext" [toJSVal contextId, toJSVal name, toJSVal width, toJSVal height])) | < -US/docs/Web/API/Document.webkitGetNamedFlows Mozilla Document.webkitGetNamedFlows documentation > webkitGetNamedFlows :: (MonadDOM m, IsDocument self) => self -> m DOMNamedFlowCollection webkitGetNamedFlows self = liftDOM (((toDocument self) ^. jsf "webkitGetNamedFlows" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.webkitGetNamedFlows Mozilla Document.webkitGetNamedFlows documentation > webkitGetNamedFlows_ :: (MonadDOM m, IsDocument self) => self -> m () webkitGetNamedFlows_ self = liftDOM (void ((toDocument self) ^. jsf "webkitGetNamedFlows" ())) | < -US/docs/Web/API/Document.createTouch Mozilla Document.createTouch documentation > createTouch :: (MonadDOM m, IsDocument self, IsEventTarget target) => self -> Maybe Window -> Maybe target -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Float -> Maybe Float -> m Touch createTouch self window target identifier pageX pageY screenX screenY webkitRadiusX webkitRadiusY webkitRotationAngle webkitForce = liftDOM (((toDocument self) ^. jsf "createTouch" [toJSVal window, toJSVal target, toJSVal identifier, toJSVal pageX, toJSVal pageY, toJSVal screenX, toJSVal screenY, toJSVal webkitRadiusX, toJSVal webkitRadiusY, toJSVal webkitRotationAngle, toJSVal webkitForce]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createTouch Mozilla Document.createTouch documentation > createTouch_ :: (MonadDOM m, IsDocument self, IsEventTarget target) => self -> Maybe Window -> Maybe target -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Float -> Maybe Float -> m () createTouch_ self window target identifier pageX pageY screenX screenY webkitRadiusX webkitRadiusY webkitRotationAngle webkitForce = liftDOM (void ((toDocument self) ^. jsf "createTouch" [toJSVal window, toJSVal target, toJSVal identifier, toJSVal pageX, toJSVal pageY, toJSVal screenX, toJSVal screenY, toJSVal webkitRadiusX, toJSVal webkitRadiusY, toJSVal webkitRotationAngle, toJSVal webkitForce])) | < -US/docs/Web/API/Document.createTouchList Mozilla Document.createTouchList documentation > createTouchList :: (MonadDOM m, IsDocument self) => self -> [Touch] -> m TouchList createTouchList self touches = liftDOM (((toDocument self) ^. jsf "createTouchList" [toJSVal (array touches)]) >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.createTouchList Mozilla Document.createTouchList documentation > createTouchList_ :: (MonadDOM m, IsDocument self) => self -> [Touch] -> m () createTouchList_ self touches = liftDOM (void ((toDocument self) ^. jsf "createTouchList" [toJSVal (array touches)])) | < -US/docs/Web/API/Document.timeline Mozilla Document.timeline documentation > getTimeline :: (MonadDOM m, IsDocument self) => self -> m DocumentTimeline getTimeline self = liftDOM (((toDocument self) ^. js "timeline") >>= fromJSValUnchecked) getImplementation :: (MonadDOM m, IsDocument self) => self -> m DOMImplementation getImplementation self = liftDOM (((toDocument self) ^. js "implementation") >>= fromJSValUnchecked) getURL :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getURL self = liftDOM (((toDocument self) ^. js "URL") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.documentURI Mozilla Document.documentURI documentation > getDocumentURI :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getDocumentURI self = liftDOM (((toDocument self) ^. js "documentURI") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.origin Mozilla Document.origin documentation > getOrigin :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getOrigin self = liftDOM (((toDocument self) ^. js "origin") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.compatMode Mozilla Document.compatMode documentation > getCompatMode :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getCompatMode self = liftDOM (((toDocument self) ^. js "compatMode") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.characterSet Mozilla Document.characterSet documentation > getCharacterSet :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getCharacterSet self = liftDOM (((toDocument self) ^. js "characterSet") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.charset Mozilla Document.charset documentation > getCharset :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getCharset self = liftDOM (((toDocument self) ^. js "charset") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.inputEncoding Mozilla Document.inputEncoding documentation > getInputEncoding :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getInputEncoding self = liftDOM (((toDocument self) ^. js "inputEncoding") >>= fromJSValUnchecked) getContentType :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getContentType self = liftDOM (((toDocument self) ^. js "contentType") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.doctype Mozilla Document.doctype documentation > getDoctype :: (MonadDOM m, IsDocument self) => self -> m (Maybe DocumentType) getDoctype self = liftDOM (((toDocument self) ^. js "doctype") >>= fromJSVal) | < -US/docs/Web/API/Document.doctype Mozilla Document.doctype documentation > getDoctypeUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m DocumentType getDoctypeUnsafe self = liftDOM ((((toDocument self) ^. js "doctype") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.doctype Mozilla Document.doctype documentation > getDoctypeUnchecked :: (MonadDOM m, IsDocument self) => self -> m DocumentType getDoctypeUnchecked self = liftDOM (((toDocument self) ^. js "doctype") >>= fromJSValUnchecked) getDocumentElement :: (MonadDOM m, IsDocument self) => self -> m (Maybe Element) getDocumentElement self = liftDOM (((toDocument self) ^. js "documentElement") >>= fromJSVal) getDocumentElementUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Element getDocumentElementUnsafe self = liftDOM ((((toDocument self) ^. js "documentElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) getDocumentElementUnchecked :: (MonadDOM m, IsDocument self) => self -> m Element getDocumentElementUnchecked self = liftDOM (((toDocument self) ^. js "documentElement") >>= fromJSValUnchecked) getLocation :: (MonadDOM m, IsDocument self) => self -> m (Maybe Location) getLocation self = liftDOM (((toDocument self) ^. js "location") >>= fromJSVal) getLocationUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Location getLocationUnsafe self = liftDOM ((((toDocument self) ^. js "location") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) getLocationUnchecked :: (MonadDOM m, IsDocument self) => self -> m Location getLocationUnchecked self = liftDOM (((toDocument self) ^. js "location") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.domain Mozilla Document.domain documentation > setDomain :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setDomain self val = liftDOM ((toDocument self) ^. jss "domain" (toJSVal val)) | < -US/docs/Web/API/Document.domain Mozilla Document.domain documentation > getDomain :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getDomain self = liftDOM (((toDocument self) ^. js "domain") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.referrer Mozilla Document.referrer documentation > getReferrer :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getReferrer self = liftDOM (((toDocument self) ^. js "referrer") >>= fromJSValUnchecked) | < Document.cookie documentation > setCookie :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setCookie self val = liftDOM ((toDocument self) ^. jss "cookie" (toJSVal val)) | < Document.cookie documentation > getCookie :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getCookie self = liftDOM (((toDocument self) ^. js "cookie") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.lastModified Document.lastModified documentation > getLastModified :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getLastModified self = liftDOM (((toDocument self) ^. js "lastModified") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.readyState Mozilla Document.readyState documentation > getReadyState :: (MonadDOM m, IsDocument self) => self -> m DocumentReadyState getReadyState self = liftDOM (((toDocument self) ^. js "readyState") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.title Mozilla Document.title documentation > setTitle :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setTitle self val = liftDOM ((toDocument self) ^. jss "title" (toJSVal val)) | < -US/docs/Web/API/Document.title Mozilla Document.title documentation > getTitle :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getTitle self = liftDOM (((toDocument self) ^. js "title") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.dir Mozilla Document.dir documentation > setDir :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setDir self val = liftDOM ((toDocument self) ^. jss "dir" (toJSVal val)) | < -US/docs/Web/API/Document.dir Mozilla Document.dir documentation > getDir :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getDir self = liftDOM (((toDocument self) ^. js "dir") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.body Mozilla Document.body documentation > setBody :: (MonadDOM m, IsDocument self, IsHTMLElement val) => self -> Maybe val -> m () setBody self val = liftDOM ((toDocument self) ^. jss "body" (toJSVal val)) | < -US/docs/Web/API/Document.body Mozilla Document.body documentation > getBody :: (MonadDOM m, IsDocument self) => self -> m (Maybe HTMLElement) getBody self = liftDOM (((toDocument self) ^. js "body") >>= fromJSVal) | < -US/docs/Web/API/Document.body Mozilla Document.body documentation > getBodyUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m HTMLElement getBodyUnsafe self = liftDOM ((((toDocument self) ^. js "body") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.body Mozilla Document.body documentation > getBodyUnchecked :: (MonadDOM m, IsDocument self) => self -> m HTMLElement getBodyUnchecked self = liftDOM (((toDocument self) ^. js "body") >>= fromJSValUnchecked) | documentation > getHead :: (MonadDOM m, IsDocument self) => self -> m (Maybe HTMLHeadElement) getHead self = liftDOM (((toDocument self) ^. js "head") >>= fromJSVal) | documentation > getHeadUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m HTMLHeadElement getHeadUnsafe self = liftDOM ((((toDocument self) ^. js "head") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | documentation > getHeadUnchecked :: (MonadDOM m, IsDocument self) => self -> m HTMLHeadElement getHeadUnchecked self = liftDOM (((toDocument self) ^. js "head") >>= fromJSValUnchecked) getImages :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getImages self = liftDOM (((toDocument self) ^. js "images") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.embeds Mozilla Document.embeds documentation > getEmbeds :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getEmbeds self = liftDOM (((toDocument self) ^. js "embeds") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.plugins Mozilla Document.plugins documentation > getPlugins :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getPlugins self = liftDOM (((toDocument self) ^. js "plugins") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.links Mozilla Document.links documentation > getLinks :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getLinks self = liftDOM (((toDocument self) ^. js "links") >>= fromJSValUnchecked) getForms :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getForms self = liftDOM (((toDocument self) ^. js "forms") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.scripts Mozilla Document.scripts documentation > getScripts :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getScripts self = liftDOM (((toDocument self) ^. js "scripts") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.currentScript Mozilla Document.currentScript documentation > getCurrentScript :: (MonadDOM m, IsDocument self) => self -> m (Maybe HTMLScriptElement) getCurrentScript self = liftDOM (((toDocument self) ^. js "currentScript") >>= fromJSVal) | < -US/docs/Web/API/Document.currentScript Mozilla Document.currentScript documentation > getCurrentScriptUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m HTMLScriptElement getCurrentScriptUnsafe self = liftDOM ((((toDocument self) ^. js "currentScript") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.currentScript Mozilla Document.currentScript documentation > getCurrentScriptUnchecked :: (MonadDOM m, IsDocument self) => self -> m HTMLScriptElement getCurrentScriptUnchecked self = liftDOM (((toDocument self) ^. js "currentScript") >>= fromJSValUnchecked) getDefaultView :: (MonadDOM m, IsDocument self) => self -> m (Maybe Window) getDefaultView self = liftDOM (((toDocument self) ^. js "defaultView") >>= fromJSVal) getDefaultViewUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Window getDefaultViewUnsafe self = liftDOM ((((toDocument self) ^. js "defaultView") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) getDefaultViewUnchecked :: (MonadDOM m, IsDocument self) => self -> m Window getDefaultViewUnchecked self = liftDOM (((toDocument self) ^. js "defaultView") >>= fromJSValUnchecked) setDesignMode :: (MonadDOM m, IsDocument self, ToJSString val) => self -> val -> m () setDesignMode self val = liftDOM ((toDocument self) ^. jss "designMode" (toJSVal val)) getDesignMode :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getDesignMode self = liftDOM (((toDocument self) ^. js "designMode") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.onreadystatechange Mozilla Document.onreadystatechange documentation > readyStateChange :: (IsDocument self, IsEventTarget self) => EventName self Event readyStateChange = unsafeEventNameAsync (toJSString "readystatechange") | < -US/docs/Web/API/Document.styleSheets Mozilla Document.styleSheets documentation > getStyleSheets :: (MonadDOM m, IsDocument self) => self -> m StyleSheetList getStyleSheets self = liftDOM (((toDocument self) ^. js "styleSheets") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.scrollingElement Mozilla Document.scrollingElement documentation > getScrollingElement :: (MonadDOM m, IsDocument self) => self -> m (Maybe Element) getScrollingElement self = liftDOM (((toDocument self) ^. js "scrollingElement") >>= fromJSVal) | < -US/docs/Web/API/Document.scrollingElement Mozilla Document.scrollingElement documentation > getScrollingElementUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Element getScrollingElementUnsafe self = liftDOM ((((toDocument self) ^. js "scrollingElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.scrollingElement Mozilla Document.scrollingElement documentation > getScrollingElementUnchecked :: (MonadDOM m, IsDocument self) => self -> m Element getScrollingElementUnchecked self = liftDOM (((toDocument self) ^. js "scrollingElement") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.webkitFullscreenEnabled Mozilla Document.webkitFullscreenEnabled documentation > getWebkitFullscreenEnabled :: (MonadDOM m, IsDocument self) => self -> m Bool getWebkitFullscreenEnabled self = liftDOM (((toDocument self) ^. js "webkitFullscreenEnabled") >>= valToBool) getWebkitFullscreenElement :: (MonadDOM m, IsDocument self) => self -> m (Maybe Element) getWebkitFullscreenElement self = liftDOM (((toDocument self) ^. js "webkitFullscreenElement") >>= fromJSVal) getWebkitFullscreenElementUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m Element getWebkitFullscreenElementUnsafe self = liftDOM ((((toDocument self) ^. js "webkitFullscreenElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) getWebkitFullscreenElementUnchecked :: (MonadDOM m, IsDocument self) => self -> m Element getWebkitFullscreenElementUnchecked self = liftDOM (((toDocument self) ^. js "webkitFullscreenElement") >>= fromJSValUnchecked) getWebkitIsFullScreen :: (MonadDOM m, IsDocument self) => self -> m Bool getWebkitIsFullScreen self = liftDOM (((toDocument self) ^. js "webkitIsFullScreen") >>= valToBool) | < -US/docs/Web/API/Document.webkitFullScreenKeyboardInputAllowed Mozilla Document.webkitFullScreenKeyboardInputAllowed documentation > getWebkitFullScreenKeyboardInputAllowed :: (MonadDOM m, IsDocument self) => self -> m Bool getWebkitFullScreenKeyboardInputAllowed self = liftDOM (((toDocument self) ^. js "webkitFullScreenKeyboardInputAllowed") >>= valToBool) | < -US/docs/Web/API/Document.webkitCurrentFullScreenElement Mozilla Document.webkitCurrentFullScreenElement documentation > getWebkitCurrentFullScreenElement :: (MonadDOM m, IsDocument self) => self -> m Element getWebkitCurrentFullScreenElement self = liftDOM (((toDocument self) ^. js "webkitCurrentFullScreenElement") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.onwebkitfullscreenchange Mozilla Document.onwebkitfullscreenchange documentation > webKitFullscreenChange :: (IsDocument self, IsEventTarget self) => EventName self Event webKitFullscreenChange = unsafeEventName (toJSString "webkitfullscreenchange") | < -US/docs/Web/API/Document.onwebkitfullscreenerror Mozilla Document.onwebkitfullscreenerror documentation > webKitFullscreenError :: (IsDocument self, IsEventTarget self) => EventName self Event webKitFullscreenError = unsafeEventName (toJSString "webkitfullscreenerror") | < -US/docs/Web/API/Document.onpointerlockchange Mozilla Document.onpointerlockchange documentation > pointerlockchange :: (IsDocument self, IsEventTarget self) => EventName self Event pointerlockchange = unsafeEventName (toJSString "pointerlockchange") pointerlockerror :: (IsDocument self, IsEventTarget self) => EventName self Event pointerlockerror = unsafeEventName (toJSString "pointerlockerror") | < -US/docs/Web/API/Document.fonts Mozilla Document.fonts documentation > getFonts :: (MonadDOM m, IsDocument self) => self -> m FontFaceSet getFonts self = liftDOM (((toDocument self) ^. js "fonts") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.hidden Mozilla Document.hidden documentation > getHidden :: (MonadDOM m, IsDocument self) => self -> m Bool getHidden self = liftDOM (((toDocument self) ^. js "hidden") >>= valToBool) | < -US/docs/Web/API/Document.visibilityState Mozilla Document.visibilityState documentation > getVisibilityState :: (MonadDOM m, IsDocument self) => self -> m VisibilityState getVisibilityState self = liftDOM (((toDocument self) ^. js "visibilityState") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.onvisibilitychange Mozilla Document.onvisibilitychange documentation > visibilitychange :: (IsDocument self, IsEventTarget self) => EventName self Event visibilitychange = unsafeEventName (toJSString "visibilitychange") | < -US/docs/Web/API/Document.applets Mozilla Document.applets documentation > getApplets :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getApplets self = liftDOM (((toDocument self) ^. js "applets") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.anchors Mozilla Document.anchors documentation > getAnchors :: (MonadDOM m, IsDocument self) => self -> m HTMLCollection getAnchors self = liftDOM (((toDocument self) ^. js "anchors") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.preferredStylesheetSet Mozilla Document.preferredStylesheetSet documentation > getPreferredStylesheetSet :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m (Maybe result) getPreferredStylesheetSet self = liftDOM (((toDocument self) ^. js "preferredStylesheetSet") >>= fromMaybeJSString) | < -US/docs/Web/API/Document.preferredStylesheetSet Mozilla Document.preferredStylesheetSet documentation > getPreferredStylesheetSetUnsafe :: (MonadDOM m, IsDocument self, HasCallStack, FromJSString result) => self -> m result getPreferredStylesheetSetUnsafe self = liftDOM ((((toDocument self) ^. js "preferredStylesheetSet") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.preferredStylesheetSet Mozilla Document.preferredStylesheetSet documentation > getPreferredStylesheetSetUnchecked :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getPreferredStylesheetSetUnchecked self = liftDOM (((toDocument self) ^. js "preferredStylesheetSet") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.selectedStylesheetSet Mozilla Document.selectedStylesheetSet documentation > setSelectedStylesheetSet :: (MonadDOM m, IsDocument self, ToJSString val) => self -> Maybe val -> m () setSelectedStylesheetSet self val = liftDOM ((toDocument self) ^. jss "selectedStylesheetSet" (toJSVal val)) | < -US/docs/Web/API/Document.selectedStylesheetSet Mozilla Document.selectedStylesheetSet documentation > getSelectedStylesheetSet :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m (Maybe result) getSelectedStylesheetSet self = liftDOM (((toDocument self) ^. js "selectedStylesheetSet") >>= fromMaybeJSString) | < -US/docs/Web/API/Document.selectedStylesheetSet Mozilla Document.selectedStylesheetSet documentation > getSelectedStylesheetSetUnsafe :: (MonadDOM m, IsDocument self, HasCallStack, FromJSString result) => self -> m result getSelectedStylesheetSetUnsafe self = liftDOM ((((toDocument self) ^. js "selectedStylesheetSet") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.selectedStylesheetSet Mozilla Document.selectedStylesheetSet documentation > getSelectedStylesheetSetUnchecked :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getSelectedStylesheetSetUnchecked self = liftDOM (((toDocument self) ^. js "selectedStylesheetSet") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.xmlEncoding Mozilla Document.xmlEncoding documentation > getXmlEncoding :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m (Maybe result) getXmlEncoding self = liftDOM (((toDocument self) ^. js "xmlEncoding") >>= fromMaybeJSString) | < -US/docs/Web/API/Document.xmlEncoding Mozilla Document.xmlEncoding documentation > getXmlEncodingUnsafe :: (MonadDOM m, IsDocument self, HasCallStack, FromJSString result) => self -> m result getXmlEncodingUnsafe self = liftDOM ((((toDocument self) ^. js "xmlEncoding") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/Document.xmlEncoding Mozilla Document.xmlEncoding documentation > getXmlEncodingUnchecked :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getXmlEncodingUnchecked self = liftDOM (((toDocument self) ^. js "xmlEncoding") >>= fromJSValUnchecked) setXmlVersion :: (MonadDOM m, IsDocument self, ToJSString val) => self -> Maybe val -> m () setXmlVersion self val = liftDOM ((toDocument self) ^. jss "xmlVersion" (toJSVal val)) getXmlVersion :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m (Maybe result) getXmlVersion self = liftDOM (((toDocument self) ^. js "xmlVersion") >>= fromMaybeJSString) getXmlVersionUnsafe :: (MonadDOM m, IsDocument self, HasCallStack, FromJSString result) => self -> m result getXmlVersionUnsafe self = liftDOM ((((toDocument self) ^. js "xmlVersion") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) getXmlVersionUnchecked :: (MonadDOM m, IsDocument self, FromJSString result) => self -> m result getXmlVersionUnchecked self = liftDOM (((toDocument self) ^. js "xmlVersion") >>= fromJSValUnchecked) | < -US/docs/Web/API/Document.xmlStandalone Mozilla Document.xmlStandalone documentation > setXmlStandalone :: (MonadDOM m, IsDocument self) => self -> Bool -> m () setXmlStandalone self val = liftDOM ((toDocument self) ^. jss "xmlStandalone" (toJSVal val)) | < -US/docs/Web/API/Document.xmlStandalone Mozilla Document.xmlStandalone documentation > getXmlStandalone :: (MonadDOM m, IsDocument self) => self -> m Bool getXmlStandalone self = liftDOM (((toDocument self) ^. js "xmlStandalone") >>= valToBool) selectStart :: (IsDocument self, IsEventTarget self) => EventName self Event selectStart = unsafeEventName (toJSString "selectstart") | < -US/docs/Web/API/Document.onselectionchange Mozilla Document.onselectionchange documentation > selectionchange :: (IsDocument self, IsEventTarget self) => EventName self onselectionchange selectionchange = unsafeEventName (toJSString "selectionchange") getRootElement :: (MonadDOM m, IsDocument self) => self -> m (Maybe SVGSVGElement) getRootElement self = liftDOM (((toDocument self) ^. js "rootElement") >>= fromJSVal) getRootElementUnsafe :: (MonadDOM m, IsDocument self, HasCallStack) => self -> m SVGSVGElement getRootElementUnsafe self = liftDOM ((((toDocument self) ^. js "rootElement") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) getRootElementUnchecked :: (MonadDOM m, IsDocument self) => self -> m SVGSVGElement getRootElementUnchecked self = liftDOM (((toDocument self) ^. js "rootElement") >>= fromJSValUnchecked)
14125d3a4f83b186015ae2a647eb4d2f235487421400efbee3d4f2e8aa3a0352
kaos/ecapnp
ecapnp_val.erl
%% Copyright 2013 , < > %% 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. %% 2013 , @author < > %% @doc Cap'n Proto value support. %% %% Everything value. -module(ecapnp_val). -author("Andreas Stenius <>"). -export([set/2, set/3, get/2, get/3, size/1]). -include("ecapnp.hrl"). %% =================================================================== %% API functions %% =================================================================== -spec set(value_type(), number() | boolean()) -> binary(). %% @doc Encode value to Cap'n Proto format. set(ValueType, Value) -> value(set, {ValueType, to_value(ValueType, Value)}). -spec set(value_type(), number() | boolean(), binary()) -> binary(). %% @doc Encode value to Cap'n Proto format. %% %% The result is XOR'ed with `Default'. set(ValueType, Value, Default) when is_bitstring(Default) -> value(set, {ValueType, to_value(ValueType, Value), Default}). -spec get(value_type(), binary()) -> number() | boolean(). @doc Decode data from Cap'n Proto format . get(ValueType, Data) when is_bitstring(Data) -> from_value(ValueType, value(get, {ValueType, Data})). -spec get(value_type(), binary(), binary()) -> number() | boolean(). @doc Decode data from Cap'n Proto format . %% The ` Data ' is XOR'ed with ` Default ' prior to decoding . get(ValueType, Data, Default) when is_bitstring(Data), is_bitstring(Default) -> Value = value(get, {ValueType, Data, Default}), from_value(ValueType, Value). -spec size(value_type()) -> non_neg_integer(). @doc Get number of bits for ` ValueType ' . size(ValueType) -> value(size, ValueType). %% =================================================================== %% internal functions %% =================================================================== -define(DEFINE_TYPE(ValueType, Size, TypeSpec), value(size, ValueType) -> Size; value(get, {ValueType, Data}) -> <<Value:Size/TypeSpec>> = Data, Value; value(get, {ValueType, Data, Default}) -> PadSize = 7 - ((Size + 7) rem 8), <<Value:Size/TypeSpec, _/bits>> = apply_default( <<Data/bits, 0:PadSize/integer>>, <<Default/bits, 0:PadSize/integer>>), Value; value(set, {ValueType, Value}) -> <<Value:Size/TypeSpec>>; value(set, {ValueType, Value, Default}) -> PadSize = 7 - ((Size + 7) rem 8), <<Data:Size/bits, _/bits>> = apply_default( <<Value:Size/TypeSpec, 0:PadSize/integer>>, <<Default/bits, 0:PadSize/integer>>), Data ). ?DEFINE_TYPE(uint64, 64, integer-unsigned-little); ?DEFINE_TYPE(uint32, 32, integer-unsigned-little); ?DEFINE_TYPE(uint16, 16, integer-unsigned-little); ?DEFINE_TYPE(uint8, 8, integer-unsigned-little); ?DEFINE_TYPE(int64, 64, integer-signed-little); ?DEFINE_TYPE(int32, 32, integer-signed-little); ?DEFINE_TYPE(int16, 16, integer-signed-little); ?DEFINE_TYPE(int8, 8, integer-signed-little); ?DEFINE_TYPE(bool, 1, bits); ?DEFINE_TYPE(float32, 32, bits); %% actual float conversion is done in the to_value / from_value functions . value(size, void) -> 0; value(_, {void, _}) -> void. -define(INF_NAN_32(N,S), <<0:16,1:1,N:1,0:6,S:1,127:7>>). -define(INF_NAN_64(N,S), <<0:48,15:4,N:1,0:3,S:1,127:7>>). from_value(bool, <<0:1>>) -> false; from_value(bool, <<1:1>>) -> true; from_value(float32, ?INF_NAN_32(1, _)) -> nan; from_value(float32, ?INF_NAN_32(0, 0)) -> inf; from_value(float32, ?INF_NAN_32(0, 1)) -> '-inf'; from_value(float32, <<Value:32/float-little>>) -> Value; from_value(float64, ?INF_NAN_64(1, _)) -> nan; from_value(float64, ?INF_NAN_64(0, 0)) -> inf; from_value(float64, ?INF_NAN_64(0, 1)) -> '-inf'; from_value(float64, <<Value:64/float-little>>) -> Value; from_value(_, Value) when is_number(Value) -> Value; from_value(_, void) -> void. to_value(bool, true) -> <<1:1>>; to_value(bool, false) -> <<0:1>>; to_value(float32, inf) -> ?INF_NAN_32(0, 0); to_value(float32, '-inf') -> ?INF_NAN_32(0, 1); to_value(float32, nan) -> ?INF_NAN_32(1, 0); to_value(float32, Value) -> <<Value:32/float-little>>; to_value(float64, inf) -> ?INF_NAN_64(0, 0); to_value(float64, '-inf') -> ?INF_NAN_64(0, 1); to_value(float64, nan) -> ?INF_NAN_64(1, 0); to_value(float64, Value) -> <<Value:64/float-little>>; to_value(_, Value) when is_number(Value) -> Value; to_value(_, void) -> void. apply_default(Value, Default) -> crypto:exor(Value, Default).
null
https://raw.githubusercontent.com/kaos/ecapnp/f351c07730ba134b41b137dd6a6b93069a0908fc/src/ecapnp_val.erl
erlang
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. @doc Cap'n Proto value support. Everything value. =================================================================== API functions =================================================================== @doc Encode value to Cap'n Proto format. @doc Encode value to Cap'n Proto format. The result is XOR'ed with `Default'. =================================================================== internal functions =================================================================== actual float conversion is done in the
Copyright 2013 , < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , 2013 , @author < > -module(ecapnp_val). -author("Andreas Stenius <>"). -export([set/2, set/3, get/2, get/3, size/1]). -include("ecapnp.hrl"). -spec set(value_type(), number() | boolean()) -> binary(). set(ValueType, Value) -> value(set, {ValueType, to_value(ValueType, Value)}). -spec set(value_type(), number() | boolean(), binary()) -> binary(). set(ValueType, Value, Default) when is_bitstring(Default) -> value(set, {ValueType, to_value(ValueType, Value), Default}). -spec get(value_type(), binary()) -> number() | boolean(). @doc Decode data from Cap'n Proto format . get(ValueType, Data) when is_bitstring(Data) -> from_value(ValueType, value(get, {ValueType, Data})). -spec get(value_type(), binary(), binary()) -> number() | boolean(). @doc Decode data from Cap'n Proto format . The ` Data ' is XOR'ed with ` Default ' prior to decoding . get(ValueType, Data, Default) when is_bitstring(Data), is_bitstring(Default) -> Value = value(get, {ValueType, Data, Default}), from_value(ValueType, Value). -spec size(value_type()) -> non_neg_integer(). @doc Get number of bits for ` ValueType ' . size(ValueType) -> value(size, ValueType). -define(DEFINE_TYPE(ValueType, Size, TypeSpec), value(size, ValueType) -> Size; value(get, {ValueType, Data}) -> <<Value:Size/TypeSpec>> = Data, Value; value(get, {ValueType, Data, Default}) -> PadSize = 7 - ((Size + 7) rem 8), <<Value:Size/TypeSpec, _/bits>> = apply_default( <<Data/bits, 0:PadSize/integer>>, <<Default/bits, 0:PadSize/integer>>), Value; value(set, {ValueType, Value}) -> <<Value:Size/TypeSpec>>; value(set, {ValueType, Value, Default}) -> PadSize = 7 - ((Size + 7) rem 8), <<Data:Size/bits, _/bits>> = apply_default( <<Value:Size/TypeSpec, 0:PadSize/integer>>, <<Default/bits, 0:PadSize/integer>>), Data ). ?DEFINE_TYPE(uint64, 64, integer-unsigned-little); ?DEFINE_TYPE(uint32, 32, integer-unsigned-little); ?DEFINE_TYPE(uint16, 16, integer-unsigned-little); ?DEFINE_TYPE(uint8, 8, integer-unsigned-little); ?DEFINE_TYPE(int64, 64, integer-signed-little); ?DEFINE_TYPE(int32, 32, integer-signed-little); ?DEFINE_TYPE(int16, 16, integer-signed-little); ?DEFINE_TYPE(int8, 8, integer-signed-little); ?DEFINE_TYPE(bool, 1, bits); to_value / from_value functions . value(size, void) -> 0; value(_, {void, _}) -> void. -define(INF_NAN_32(N,S), <<0:16,1:1,N:1,0:6,S:1,127:7>>). -define(INF_NAN_64(N,S), <<0:48,15:4,N:1,0:3,S:1,127:7>>). from_value(bool, <<0:1>>) -> false; from_value(bool, <<1:1>>) -> true; from_value(float32, ?INF_NAN_32(1, _)) -> nan; from_value(float32, ?INF_NAN_32(0, 0)) -> inf; from_value(float32, ?INF_NAN_32(0, 1)) -> '-inf'; from_value(float32, <<Value:32/float-little>>) -> Value; from_value(float64, ?INF_NAN_64(1, _)) -> nan; from_value(float64, ?INF_NAN_64(0, 0)) -> inf; from_value(float64, ?INF_NAN_64(0, 1)) -> '-inf'; from_value(float64, <<Value:64/float-little>>) -> Value; from_value(_, Value) when is_number(Value) -> Value; from_value(_, void) -> void. to_value(bool, true) -> <<1:1>>; to_value(bool, false) -> <<0:1>>; to_value(float32, inf) -> ?INF_NAN_32(0, 0); to_value(float32, '-inf') -> ?INF_NAN_32(0, 1); to_value(float32, nan) -> ?INF_NAN_32(1, 0); to_value(float32, Value) -> <<Value:32/float-little>>; to_value(float64, inf) -> ?INF_NAN_64(0, 0); to_value(float64, '-inf') -> ?INF_NAN_64(0, 1); to_value(float64, nan) -> ?INF_NAN_64(1, 0); to_value(float64, Value) -> <<Value:64/float-little>>; to_value(_, Value) when is_number(Value) -> Value; to_value(_, void) -> void. apply_default(Value, Default) -> crypto:exor(Value, Default).
c64b4212b8dc5bb84bbf809f276653247a48905b526ea992aeb9493a7d1160ea
dfithian/prune-juice
DependencySpec.hs
module Data.Prune.DependencySpec where import Prelude import Control.Monad.Logger (runNoLoggingT) import Data.FileEmbed (embedFile) import Data.Text (splitOn) import Data.Text.Encoding (decodeUtf8) import System.FilePath.TH (fileRelativeToAbsolute, fileRelativeToAbsoluteStr) import Test.Hspec (Spec, describe, it, shouldBe, shouldSatisfy, xit) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Prune.Cabal (parseCabalFile) import qualified Data.Prune.Types as T -- the module being tested import Data.Prune.Dependency spec :: Spec spec = describe "Data.Prune.Dependency" $ do let thisFile = $(fileRelativeToAbsolute "DependencySpec.hs") projectRoot = $(fileRelativeToAbsolute "../../../") it "should parse the empty string" $ do pkgs <- runNoLoggingT $ parsePkg "" pkgs `shouldBe` Nothing it "should parse a ghc-pkg module" $ do let rawModuleNames = [ "Data.Text" , "Data.Text.Array" , "Data.Text.Encoding" , "Data.Text.Encoding.Error" , "Data.Text.Foreign" , "Data.Text.IO" , "Data.Text.Internal" , "Data.Text.Internal.Builder" , "Data.Text.Internal.Builder.Functions" , "Data.Text.Internal.Builder.Int.Digits" , "Data.Text.Internal.Builder.RealFloat.Functions" , "Data.Text.Internal.Encoding.Fusion" , "Data.Text.Internal.Encoding.Fusion.Common" , "Data.Text.Internal.Encoding.Utf16" , "Data.Text.Internal.Encoding.Utf32" , "Data.Text.Internal.Encoding.Utf8" , "Data.Text.Internal.Functions" , "Data.Text.Internal.Fusion" , "Data.Text.Internal.Fusion.CaseMapping" , "Data.Text.Internal.Fusion.Common" , "Data.Text.Internal.Fusion.Size" , "Data.Text.Internal.Fusion.Types" , "Data.Text.Internal.IO" , "Data.Text.Internal.Lazy" , "Data.Text.Internal.Lazy.Encoding.Fusion" , "Data.Text.Internal.Lazy.Fusion" , "Data.Text.Internal.Lazy.Search" , "Data.Text.Internal.Private" , "Data.Text.Internal.Read" , "Data.Text.Internal.Search" , "Data.Text.Internal.Unsafe" , "Data.Text.Internal.Unsafe.Char" , "Data.Text.Internal.Unsafe.Shift" , "Data.Text.Lazy" , "Data.Text.Lazy.Builder" , "Data.Text.Lazy.Builder.Int" , "Data.Text.Lazy.Builder.RealFloat" , "Data.Text.Lazy.Encoding" , "Data.Text.Lazy.IO" , "Data.Text.Lazy.Internal" , "Data.Text.Lazy.Read" , "Data.Text.Read" , "Data.Text.Unsafe" ] pkgs <- runNoLoggingT $ parsePkg $ decodeUtf8 $(embedFile =<< fileRelativeToAbsoluteStr "../../fixtures/ghc-pkg.txt") pkgs `shouldBe` Just (T.DependencyName "text", Set.fromList . fmap T.ModuleName $ rawModuleNames) -- this test doesn't succeed under `stack test` presumably because stack is using a different version of cabal xit "loads dependencies for this testing module using cabal" $ do package <- parseCabalFile projectRoot mempty thisModule <- runNoLoggingT $ getDependencyByModule thisFile T.Cabal [package] Set.unions (Map.elems thisModule) `shouldSatisfy` Set.member (T.DependencyName "base") it "loads dependencies for this testing module using stack" $ do package <- parseCabalFile projectRoot mempty thisModule <- runNoLoggingT $ getDependencyByModule thisFile T.Stack [package] Set.unions (Map.elems thisModule) `shouldSatisfy` Set.member (T.DependencyName "base") it "parses dependencies for the sublist example" $ do let dump = decodeUtf8 $(embedFile =<< fileRelativeToAbsoluteStr "../../fixtures/sublib-pkg.txt") expected = [ Just ( T.DependencyName "prune-juice-fixture" , Set.singleton (T.ModuleName "MyLib") ) , Just ( T.DependencyName "prune-juice-fixture-common" , Set.singleton (T.ModuleName "Common") ) ] pkgs <- runNoLoggingT $ traverse parsePkg . splitOn "\n---\n" $ dump pkgs `shouldBe` expected
null
https://raw.githubusercontent.com/dfithian/prune-juice/8a12636b60f5e60c71adc81fb066c7ab9fa82887/test/Data/Prune/DependencySpec.hs
haskell
the module being tested this test doesn't succeed under `stack test` presumably because stack is using a different version of cabal
module Data.Prune.DependencySpec where import Prelude import Control.Monad.Logger (runNoLoggingT) import Data.FileEmbed (embedFile) import Data.Text (splitOn) import Data.Text.Encoding (decodeUtf8) import System.FilePath.TH (fileRelativeToAbsolute, fileRelativeToAbsoluteStr) import Test.Hspec (Spec, describe, it, shouldBe, shouldSatisfy, xit) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Prune.Cabal (parseCabalFile) import qualified Data.Prune.Types as T import Data.Prune.Dependency spec :: Spec spec = describe "Data.Prune.Dependency" $ do let thisFile = $(fileRelativeToAbsolute "DependencySpec.hs") projectRoot = $(fileRelativeToAbsolute "../../../") it "should parse the empty string" $ do pkgs <- runNoLoggingT $ parsePkg "" pkgs `shouldBe` Nothing it "should parse a ghc-pkg module" $ do let rawModuleNames = [ "Data.Text" , "Data.Text.Array" , "Data.Text.Encoding" , "Data.Text.Encoding.Error" , "Data.Text.Foreign" , "Data.Text.IO" , "Data.Text.Internal" , "Data.Text.Internal.Builder" , "Data.Text.Internal.Builder.Functions" , "Data.Text.Internal.Builder.Int.Digits" , "Data.Text.Internal.Builder.RealFloat.Functions" , "Data.Text.Internal.Encoding.Fusion" , "Data.Text.Internal.Encoding.Fusion.Common" , "Data.Text.Internal.Encoding.Utf16" , "Data.Text.Internal.Encoding.Utf32" , "Data.Text.Internal.Encoding.Utf8" , "Data.Text.Internal.Functions" , "Data.Text.Internal.Fusion" , "Data.Text.Internal.Fusion.CaseMapping" , "Data.Text.Internal.Fusion.Common" , "Data.Text.Internal.Fusion.Size" , "Data.Text.Internal.Fusion.Types" , "Data.Text.Internal.IO" , "Data.Text.Internal.Lazy" , "Data.Text.Internal.Lazy.Encoding.Fusion" , "Data.Text.Internal.Lazy.Fusion" , "Data.Text.Internal.Lazy.Search" , "Data.Text.Internal.Private" , "Data.Text.Internal.Read" , "Data.Text.Internal.Search" , "Data.Text.Internal.Unsafe" , "Data.Text.Internal.Unsafe.Char" , "Data.Text.Internal.Unsafe.Shift" , "Data.Text.Lazy" , "Data.Text.Lazy.Builder" , "Data.Text.Lazy.Builder.Int" , "Data.Text.Lazy.Builder.RealFloat" , "Data.Text.Lazy.Encoding" , "Data.Text.Lazy.IO" , "Data.Text.Lazy.Internal" , "Data.Text.Lazy.Read" , "Data.Text.Read" , "Data.Text.Unsafe" ] pkgs <- runNoLoggingT $ parsePkg $ decodeUtf8 $(embedFile =<< fileRelativeToAbsoluteStr "../../fixtures/ghc-pkg.txt") pkgs `shouldBe` Just (T.DependencyName "text", Set.fromList . fmap T.ModuleName $ rawModuleNames) xit "loads dependencies for this testing module using cabal" $ do package <- parseCabalFile projectRoot mempty thisModule <- runNoLoggingT $ getDependencyByModule thisFile T.Cabal [package] Set.unions (Map.elems thisModule) `shouldSatisfy` Set.member (T.DependencyName "base") it "loads dependencies for this testing module using stack" $ do package <- parseCabalFile projectRoot mempty thisModule <- runNoLoggingT $ getDependencyByModule thisFile T.Stack [package] Set.unions (Map.elems thisModule) `shouldSatisfy` Set.member (T.DependencyName "base") it "parses dependencies for the sublist example" $ do let dump = decodeUtf8 $(embedFile =<< fileRelativeToAbsoluteStr "../../fixtures/sublib-pkg.txt") expected = [ Just ( T.DependencyName "prune-juice-fixture" , Set.singleton (T.ModuleName "MyLib") ) , Just ( T.DependencyName "prune-juice-fixture-common" , Set.singleton (T.ModuleName "Common") ) ] pkgs <- runNoLoggingT $ traverse parsePkg . splitOn "\n---\n" $ dump pkgs `shouldBe` expected
1272d3f2b676d121dd1c53a2efa207455c2b609fd03f110bfa3429c888ce11e4
codecov/example-clojure
project.clj
(defproject codecov-clojure "0.1.0" :description "codecov.io, example Clojure project" :url "-clojure" :plugins [[lein-cloverage "1.0.7-SNAPSHOT"]] :dependencies [[org.clojure/clojure "1.7.0"]])
null
https://raw.githubusercontent.com/codecov/example-clojure/d1f53656c48f852724fde219e4d2a2454a0e97f5/project.clj
clojure
(defproject codecov-clojure "0.1.0" :description "codecov.io, example Clojure project" :url "-clojure" :plugins [[lein-cloverage "1.0.7-SNAPSHOT"]] :dependencies [[org.clojure/clojure "1.7.0"]])
73287cbf75b08ac831f87b0cc577f3f940e11f26fdba992530bd9b5389347329
expipiplus1/vulkan
HLSL.hs
module Vulkan.Utils.ShaderQQ.HLSL ( hlsl , insertLineDirective ) where import Language.Haskell.TH import Language.Haskell.TH.Quote import Vulkan.Utils.Internal ( badQQ ) import Vulkan.Utils.ShaderQQ.Interpolate | ' hlsl ' is a QuasiQuoter which produces HLSL source code with a @#line@ -- directive inserted so that error locations point to the correct location in the source file . It also permits basic string interpolation . -- - Interpolated variables are prefixed with @$@ -- - They can optionally be surrounded with braces like @${foo}@ -- - Interpolated variables are converted to strings with 'show' - To escape a @$@ use @\\$@ -- -- An explicit example (@<interactive>@ is from doctest): -- > > > let foo = 450 : : Int in [ hlsl|const float foo = $ foo| ] " # line ... \"<interactive>\"\nconst float foo = 450 " -- -- Note that line number will be thrown off if any of the interpolated -- variables contain newlines. hlsl :: QuasiQuoter hlsl = (badQQ "hlsl") { quoteExp = \s -> do loc <- location -- Insert the directive here, `compileShaderQ` will insert -- another one, but it's before this one, so who cares. let codeWithLineDirective = insertLineDirective s loc interpExp codeWithLineDirective } Insert a # line directive with the specified location at the top of the file insertLineDirective :: String -> Loc -> String insertLineDirective code Loc {..} = let lineDirective = "#line " <> show (fst loc_start) <> " \"" <> loc_filename <> "\"" in lineDirective <> "\n" <> code
null
https://raw.githubusercontent.com/expipiplus1/vulkan/70d8cca16893f8de76c0eb89e79e73f5a455db76/utils/src/Vulkan/Utils/ShaderQQ/HLSL.hs
haskell
directive inserted so that error locations point to the correct location in - They can optionally be surrounded with braces like @${foo}@ - Interpolated variables are converted to strings with 'show' An explicit example (@<interactive>@ is from doctest): Note that line number will be thrown off if any of the interpolated variables contain newlines. Insert the directive here, `compileShaderQ` will insert another one, but it's before this one, so who cares.
module Vulkan.Utils.ShaderQQ.HLSL ( hlsl , insertLineDirective ) where import Language.Haskell.TH import Language.Haskell.TH.Quote import Vulkan.Utils.Internal ( badQQ ) import Vulkan.Utils.ShaderQQ.Interpolate | ' hlsl ' is a QuasiQuoter which produces HLSL source code with a @#line@ the source file . It also permits basic string interpolation . - Interpolated variables are prefixed with @$@ - To escape a @$@ use @\\$@ > > > let foo = 450 : : Int in [ hlsl|const float foo = $ foo| ] " # line ... \"<interactive>\"\nconst float foo = 450 " hlsl :: QuasiQuoter hlsl = (badQQ "hlsl") { quoteExp = \s -> do loc <- location let codeWithLineDirective = insertLineDirective s loc interpExp codeWithLineDirective } Insert a # line directive with the specified location at the top of the file insertLineDirective :: String -> Loc -> String insertLineDirective code Loc {..} = let lineDirective = "#line " <> show (fst loc_start) <> " \"" <> loc_filename <> "\"" in lineDirective <> "\n" <> code
d96a76fc8ef3c7d530311b378ba5498e55e867c8d21192cb5e4edfd44fe38864
hercules-ci/legacy-old-hercules
Redirect.hs
{-# LANGUAGE OverloadedStrings #-} module Servant.Redirect ( redirect , redirectBS ) where import Control.Monad.Except import Data.ByteString import Network.URI import Network.URI.Extra import Servant.Server import Hercules.ServerEnv redirectBS :: ByteString -> App a redirectBS uri = throwError err303 { errHeaders = [("Location", uri)] } redirect :: URI -> App a redirect = redirectBS . uriToByteString
null
https://raw.githubusercontent.com/hercules-ci/legacy-old-hercules/db10eb399a64355cdcbba0e18beb1514588772e9/backend/src/Servant/Redirect.hs
haskell
# LANGUAGE OverloadedStrings #
module Servant.Redirect ( redirect , redirectBS ) where import Control.Monad.Except import Data.ByteString import Network.URI import Network.URI.Extra import Servant.Server import Hercules.ServerEnv redirectBS :: ByteString -> App a redirectBS uri = throwError err303 { errHeaders = [("Location", uri)] } redirect :: URI -> App a redirect = redirectBS . uriToByteString
f34b959890fdf126d4ef69b09f17a7bab89404706ab83ff5f4732b69ebdfda20
daigotanaka/mern-cljs
runner.cljs
(ns mern-utils (:require [doo.runner :refer-macros [doo-tests]] [mern-utils.lib-test] [mern-utils.vogels-test])) ;(doo-tests 'mern-utils.lib-test) (doo-tests 'mern-utils.vogels-test)
null
https://raw.githubusercontent.com/daigotanaka/mern-cljs/a9dedbb3b622f96dd0b06832733b4fd961e6437d/mern_utils/test/mern_utils/test/runner.cljs
clojure
(doo-tests 'mern-utils.lib-test)
(ns mern-utils (:require [doo.runner :refer-macros [doo-tests]] [mern-utils.lib-test] [mern-utils.vogels-test])) (doo-tests 'mern-utils.vogels-test)
f1945e2e9084dd8e8718bce19db9a54c05ca9d06efa1384cb93b7fcfa2459495
gedge-platform/gedge-platform
internal_user.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2020 VMware , Inc. or its affiliates . All rights reserved . %% -module(internal_user). -include_lib("rabbit_common/include/rabbit.hrl"). -export([ new/0, new/1, record_version_to_use/0, fields/0, fields/1, upgrade/1, upgrade_to/2, pattern_match_all/0, get_username/1, get_password_hash/1, get_tags/1, get_hashing_algorithm/1, get_limits/1, create_user/3, set_password_hash/3, set_tags/2, update_limits/3, clear_limits/1 ]). -define(record_version, internal_user_v2). -type(username() :: binary()). -type(password_hash() :: binary()). -type internal_user() :: internal_user_v1:internal_user_v1() | internal_user_v2(). -record(internal_user, { username :: username() | '_', password_hash :: password_hash() | '_', tags :: [atom()] | '_', %% password hashing implementation module, %% typically rabbit_password_hashing_* but can %% come from a plugin hashing_algorithm :: atom() | '_', limits = #{} :: map() | '_'}). -type(internal_user_v2() :: #internal_user{username :: username() | '_', password_hash :: password_hash() | '_', tags :: [atom()] | '_', hashing_algorithm :: atom() | '_', limits :: map()}). -type internal_user_pattern() :: internal_user_v1:internal_user_v1_pattern() | internal_user_v2_pattern(). -type internal_user_v2_pattern() :: #internal_user{ username :: username() | '_', password_hash :: '_', tags :: '_', hashing_algorithm :: '_', limits :: '_' }. -export_type([username/0, password_hash/0, internal_user/0, internal_user_v2/0, internal_user_pattern/0, internal_user_v2_pattern/0]). -spec new() -> internal_user(). new() -> case record_version_to_use() of ?record_version -> #internal_user{ username = <<"">>, password_hash = <<"">>, tags = [] }; _ -> internal_user_v1:new() end. -spec new(tuple()) -> internal_user(). new({hashing_algorithm, HashingAlgorithm}) -> case record_version_to_use() of ?record_version -> #internal_user{ username = <<"">>, password_hash = <<"">>, tags = [], hashing_algorithm = HashingAlgorithm }; _ -> internal_user_v1:new({hashing_algorithm, HashingAlgorithm}) end; new({tags, Tags}) -> case record_version_to_use() of ?record_version -> #internal_user{ username = <<"">>, password_hash = <<"">>, tags = Tags }; _ -> internal_user_v1:new({tags, Tags}) end. -spec record_version_to_use() -> internal_user_v1 | internal_user_v2. record_version_to_use() -> case rabbit_feature_flags:is_enabled(user_limits) of true -> ?record_version; false -> internal_user_v1:record_version_to_use() end. -spec fields() -> list(). fields() -> case record_version_to_use() of ?record_version -> fields(?record_version); _ -> internal_user_v1:fields() end. -spec fields(atom()) -> list(). fields(?record_version) -> record_info(fields, internal_user); fields(Version) -> internal_user_v1:fields(Version). -spec upgrade(internal_user()) -> internal_user(). upgrade(#internal_user{} = User) -> User; upgrade(OldUser) -> upgrade_to(record_version_to_use(), OldUser). -spec upgrade_to (internal_user_v2, internal_user()) -> internal_user_v2(); (internal_user_v1, internal_user_v1:internal_user_v1()) -> internal_user_v1:internal_user_v1(). upgrade_to(?record_version, #internal_user{} = User) -> User; upgrade_to(?record_version, OldUser) -> Fields = erlang:tuple_to_list(OldUser) ++ [#{}], #internal_user{} = erlang:list_to_tuple(Fields); upgrade_to(Version, OldUser) -> internal_user_v1:upgrade_to(Version, OldUser). -spec pattern_match_all() -> internal_user_pattern(). pattern_match_all() -> case record_version_to_use() of ?record_version -> #internal_user{_ = '_'}; _ -> internal_user_v1:pattern_match_all() end. -spec get_username(internal_user()) -> username(). get_username(#internal_user{username = Value}) -> Value; get_username(User) -> internal_user_v1:get_username(User). -spec get_password_hash(internal_user()) -> password_hash(). get_password_hash(#internal_user{password_hash = Value}) -> Value; get_password_hash(User) -> internal_user_v1:get_password_hash(User). -spec get_tags(internal_user()) -> [atom()]. get_tags(#internal_user{tags = Value}) -> Value; get_tags(User) -> internal_user_v1:get_tags(User). -spec get_hashing_algorithm(internal_user()) -> atom(). get_hashing_algorithm(#internal_user{hashing_algorithm = Value}) -> Value; get_hashing_algorithm(User) -> internal_user_v1:get_hashing_algorithm(User). -spec get_limits(internal_user()) -> map(). get_limits(#internal_user{limits = Value}) -> Value; get_limits(User) -> internal_user_v1:get_limits(User). -spec create_user(username(), password_hash(), atom()) -> internal_user(). create_user(Username, PasswordHash, HashingMod) -> case record_version_to_use() of ?record_version -> #internal_user{username = Username, password_hash = PasswordHash, tags = [], hashing_algorithm = HashingMod, limits = #{} }; _ -> internal_user_v1:create_user(Username, PasswordHash, HashingMod) end. -spec set_password_hash(internal_user(), password_hash(), atom()) -> internal_user(). set_password_hash(#internal_user{} = User, PasswordHash, HashingAlgorithm) -> User#internal_user{password_hash = PasswordHash, hashing_algorithm = HashingAlgorithm}; set_password_hash(User, PasswordHash, HashingAlgorithm) -> internal_user_v1:set_password_hash(User, PasswordHash, HashingAlgorithm). -spec set_tags(internal_user(), [atom()]) -> internal_user(). set_tags(#internal_user{} = User, Tags) -> User#internal_user{tags = Tags}; set_tags(User, Tags) -> internal_user_v1:set_tags(User, Tags). -spec update_limits (add, internal_user(), map()) -> internal_user(); (remove, internal_user(), term()) -> internal_user(). update_limits(add, #internal_user{limits = Limits} = User, Term) -> User#internal_user{limits = maps:merge(Limits, Term)}; update_limits(remove, #internal_user{limits = Limits} = User, LimitType) -> User#internal_user{limits = maps:remove(LimitType, Limits)}; update_limits(Action, User, Term) -> internal_user_v1:update_limits(Action, User, Term). -spec clear_limits(internal_user()) -> internal_user(). clear_limits(#internal_user{} = User) -> User#internal_user{limits = #{}}; clear_limits(User) -> internal_user_v1:clear_limits(User).
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbit/src/internal_user.erl
erlang
password hashing implementation module, typically rabbit_password_hashing_* but can come from a plugin
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2020 VMware , Inc. or its affiliates . All rights reserved . -module(internal_user). -include_lib("rabbit_common/include/rabbit.hrl"). -export([ new/0, new/1, record_version_to_use/0, fields/0, fields/1, upgrade/1, upgrade_to/2, pattern_match_all/0, get_username/1, get_password_hash/1, get_tags/1, get_hashing_algorithm/1, get_limits/1, create_user/3, set_password_hash/3, set_tags/2, update_limits/3, clear_limits/1 ]). -define(record_version, internal_user_v2). -type(username() :: binary()). -type(password_hash() :: binary()). -type internal_user() :: internal_user_v1:internal_user_v1() | internal_user_v2(). -record(internal_user, { username :: username() | '_', password_hash :: password_hash() | '_', tags :: [atom()] | '_', hashing_algorithm :: atom() | '_', limits = #{} :: map() | '_'}). -type(internal_user_v2() :: #internal_user{username :: username() | '_', password_hash :: password_hash() | '_', tags :: [atom()] | '_', hashing_algorithm :: atom() | '_', limits :: map()}). -type internal_user_pattern() :: internal_user_v1:internal_user_v1_pattern() | internal_user_v2_pattern(). -type internal_user_v2_pattern() :: #internal_user{ username :: username() | '_', password_hash :: '_', tags :: '_', hashing_algorithm :: '_', limits :: '_' }. -export_type([username/0, password_hash/0, internal_user/0, internal_user_v2/0, internal_user_pattern/0, internal_user_v2_pattern/0]). -spec new() -> internal_user(). new() -> case record_version_to_use() of ?record_version -> #internal_user{ username = <<"">>, password_hash = <<"">>, tags = [] }; _ -> internal_user_v1:new() end. -spec new(tuple()) -> internal_user(). new({hashing_algorithm, HashingAlgorithm}) -> case record_version_to_use() of ?record_version -> #internal_user{ username = <<"">>, password_hash = <<"">>, tags = [], hashing_algorithm = HashingAlgorithm }; _ -> internal_user_v1:new({hashing_algorithm, HashingAlgorithm}) end; new({tags, Tags}) -> case record_version_to_use() of ?record_version -> #internal_user{ username = <<"">>, password_hash = <<"">>, tags = Tags }; _ -> internal_user_v1:new({tags, Tags}) end. -spec record_version_to_use() -> internal_user_v1 | internal_user_v2. record_version_to_use() -> case rabbit_feature_flags:is_enabled(user_limits) of true -> ?record_version; false -> internal_user_v1:record_version_to_use() end. -spec fields() -> list(). fields() -> case record_version_to_use() of ?record_version -> fields(?record_version); _ -> internal_user_v1:fields() end. -spec fields(atom()) -> list(). fields(?record_version) -> record_info(fields, internal_user); fields(Version) -> internal_user_v1:fields(Version). -spec upgrade(internal_user()) -> internal_user(). upgrade(#internal_user{} = User) -> User; upgrade(OldUser) -> upgrade_to(record_version_to_use(), OldUser). -spec upgrade_to (internal_user_v2, internal_user()) -> internal_user_v2(); (internal_user_v1, internal_user_v1:internal_user_v1()) -> internal_user_v1:internal_user_v1(). upgrade_to(?record_version, #internal_user{} = User) -> User; upgrade_to(?record_version, OldUser) -> Fields = erlang:tuple_to_list(OldUser) ++ [#{}], #internal_user{} = erlang:list_to_tuple(Fields); upgrade_to(Version, OldUser) -> internal_user_v1:upgrade_to(Version, OldUser). -spec pattern_match_all() -> internal_user_pattern(). pattern_match_all() -> case record_version_to_use() of ?record_version -> #internal_user{_ = '_'}; _ -> internal_user_v1:pattern_match_all() end. -spec get_username(internal_user()) -> username(). get_username(#internal_user{username = Value}) -> Value; get_username(User) -> internal_user_v1:get_username(User). -spec get_password_hash(internal_user()) -> password_hash(). get_password_hash(#internal_user{password_hash = Value}) -> Value; get_password_hash(User) -> internal_user_v1:get_password_hash(User). -spec get_tags(internal_user()) -> [atom()]. get_tags(#internal_user{tags = Value}) -> Value; get_tags(User) -> internal_user_v1:get_tags(User). -spec get_hashing_algorithm(internal_user()) -> atom(). get_hashing_algorithm(#internal_user{hashing_algorithm = Value}) -> Value; get_hashing_algorithm(User) -> internal_user_v1:get_hashing_algorithm(User). -spec get_limits(internal_user()) -> map(). get_limits(#internal_user{limits = Value}) -> Value; get_limits(User) -> internal_user_v1:get_limits(User). -spec create_user(username(), password_hash(), atom()) -> internal_user(). create_user(Username, PasswordHash, HashingMod) -> case record_version_to_use() of ?record_version -> #internal_user{username = Username, password_hash = PasswordHash, tags = [], hashing_algorithm = HashingMod, limits = #{} }; _ -> internal_user_v1:create_user(Username, PasswordHash, HashingMod) end. -spec set_password_hash(internal_user(), password_hash(), atom()) -> internal_user(). set_password_hash(#internal_user{} = User, PasswordHash, HashingAlgorithm) -> User#internal_user{password_hash = PasswordHash, hashing_algorithm = HashingAlgorithm}; set_password_hash(User, PasswordHash, HashingAlgorithm) -> internal_user_v1:set_password_hash(User, PasswordHash, HashingAlgorithm). -spec set_tags(internal_user(), [atom()]) -> internal_user(). set_tags(#internal_user{} = User, Tags) -> User#internal_user{tags = Tags}; set_tags(User, Tags) -> internal_user_v1:set_tags(User, Tags). -spec update_limits (add, internal_user(), map()) -> internal_user(); (remove, internal_user(), term()) -> internal_user(). update_limits(add, #internal_user{limits = Limits} = User, Term) -> User#internal_user{limits = maps:merge(Limits, Term)}; update_limits(remove, #internal_user{limits = Limits} = User, LimitType) -> User#internal_user{limits = maps:remove(LimitType, Limits)}; update_limits(Action, User, Term) -> internal_user_v1:update_limits(Action, User, Term). -spec clear_limits(internal_user()) -> internal_user(). clear_limits(#internal_user{} = User) -> User#internal_user{limits = #{}}; clear_limits(User) -> internal_user_v1:clear_limits(User).
49e17b899420cd7899123f76bc9615b7f3ccc71a8913dfbaabbb91b72404046b
fragnix/fragnix
System.Posix.DynamicLinker.ByteString.hs
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "dist/dist-sandbox-261cd265/build/System/Posix/DynamicLinker/ByteString.hs" #-} # LINE 1 " System / Posix / DynamicLinker / ByteString.hsc " # # LINE 2 " System / Posix / DynamicLinker / ByteString.hsc " # {-# LANGUAGE Safe #-} # LINE 6 " System / Posix / DynamicLinker / ByteString.hsc " # ----------------------------------------------------------------------------- -- | Module : System . . . ByteString Copyright : ( c ) < > 2003 -- License : BSD-style (see the file libraries/base/LICENSE) -- Maintainer : -- Stability : provisional -- Portability : non-portable (requires POSIX) -- Dynamic linker support through dlopen ( ) ----------------------------------------------------------------------------- module System.Posix.DynamicLinker.ByteString ( module System.Posix.DynamicLinker.Prim, dlopen, dlsym, dlerror, dlclose, withDL, withDL_, undl, ) -- Usage: -- ****** -- -- Let's assume you want to open a local shared library \'foo\' (.\/libfoo.so) -- offering a function @char \ * mogrify ( char\*,int)@ and invoke @str = mogrify("test",1)@ : -- -- type Fun = CString - > Int - > IO CString -- foreign import dynamic unsafe fun__ :: FunPtr Fun -> Fun -- withDL " " [ RTLD_NOW ] \$ \\ mod - > do -- funptr <- dlsym mod "mogrify" -- let fun = fun__ funptr -- withCString "test" \$ \\ str -> do strptr < - fun str 1 -- strstr <- peekCString strptr -- ... -- where import System.Posix.DynamicLinker.Common import System.Posix.DynamicLinker.Prim # LINE 58 " System / Posix / DynamicLinker / ByteString.hsc " # import Control.Exception ( bracket ) import Control.Monad ( liftM ) import Foreign import System.Posix.ByteString.FilePath dlopen :: RawFilePath -> [RTLDFlags] -> IO DL dlopen path flags = do withFilePath path $ \ p -> do liftM DLHandle $ throwDLErrorIf "dlopen" (== nullPtr) $ c_dlopen p (packRTLDFlags flags) withDL :: RawFilePath -> [RTLDFlags] -> (DL -> IO a) -> IO a withDL file flags f = bracket (dlopen file flags) (dlclose) f withDL_ :: RawFilePath -> [RTLDFlags] -> (DL -> IO a) -> IO () withDL_ file flags f = withDL file flags f >> return ()
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/application/System.Posix.DynamicLinker.ByteString.hs
haskell
# LANGUAGE Haskell2010 # # LINE 1 "dist/dist-sandbox-261cd265/build/System/Posix/DynamicLinker/ByteString.hs" # # LANGUAGE Safe # --------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Stability : provisional Portability : non-portable (requires POSIX) --------------------------------------------------------------------------- Usage: ****** Let's assume you want to open a local shared library \'foo\' (.\/libfoo.so) offering a function foreign import dynamic unsafe fun__ :: FunPtr Fun -> Fun funptr <- dlsym mod "mogrify" let fun = fun__ funptr withCString "test" \$ \\ str -> do strstr <- peekCString strptr ...
# LINE 1 " System / Posix / DynamicLinker / ByteString.hsc " # # LINE 2 " System / Posix / DynamicLinker / ByteString.hsc " # # LINE 6 " System / Posix / DynamicLinker / ByteString.hsc " # Module : System . . . ByteString Copyright : ( c ) < > 2003 Maintainer : Dynamic linker support through dlopen ( ) module System.Posix.DynamicLinker.ByteString ( module System.Posix.DynamicLinker.Prim, dlopen, dlsym, dlerror, dlclose, withDL, withDL_, undl, ) @char \ * mogrify ( char\*,int)@ and invoke @str = mogrify("test",1)@ : type Fun = CString - > Int - > IO CString withDL " " [ RTLD_NOW ] \$ \\ mod - > do strptr < - fun str 1 where import System.Posix.DynamicLinker.Common import System.Posix.DynamicLinker.Prim # LINE 58 " System / Posix / DynamicLinker / ByteString.hsc " # import Control.Exception ( bracket ) import Control.Monad ( liftM ) import Foreign import System.Posix.ByteString.FilePath dlopen :: RawFilePath -> [RTLDFlags] -> IO DL dlopen path flags = do withFilePath path $ \ p -> do liftM DLHandle $ throwDLErrorIf "dlopen" (== nullPtr) $ c_dlopen p (packRTLDFlags flags) withDL :: RawFilePath -> [RTLDFlags] -> (DL -> IO a) -> IO a withDL file flags f = bracket (dlopen file flags) (dlclose) f withDL_ :: RawFilePath -> [RTLDFlags] -> (DL -> IO a) -> IO () withDL_ file flags f = withDL file flags f >> return ()
abddd10cc73a777d8bcb77ba0835b3192d1b29c409c296ca36df79fd4d5b3401
eihli/phonetics
phonetics_test.clj
(ns com.owoga.phonetics-test (:require [clojure.test :refer :all] [com.owoga.phonetics :refer :all])) (deftest phonetics-test (testing "word to phones" (is (= [["HH" "AH0" "L" "OW1"] ["HH" "EH0" "L" "OW1"]] (get-phones "hello")))) (testing "phones to word" (is (= ["hello(1)"] (get-word ["HH" "EH0" "L" "OW1"]))) (is (= ["hello(1)"] (get-word ["HH" "EH" "L" "OW"]))) (is (= ["ensure(1)" "insure"] (get-word ["IH" "N" "SH" "UH" "R"])))) (testing "phrase to phones" (is (= [["B" "AA1" "G" "HH" "AA1" "G"] ["B" "AO1" "G" "HH" "AA1" "G"]] (phrase-phones "bog hog")))))
null
https://raw.githubusercontent.com/eihli/phonetics/e309f83630d66cd6dbfb5f816efd2a90c0dfdcda/test/com/owoga/phonetics_test.clj
clojure
(ns com.owoga.phonetics-test (:require [clojure.test :refer :all] [com.owoga.phonetics :refer :all])) (deftest phonetics-test (testing "word to phones" (is (= [["HH" "AH0" "L" "OW1"] ["HH" "EH0" "L" "OW1"]] (get-phones "hello")))) (testing "phones to word" (is (= ["hello(1)"] (get-word ["HH" "EH0" "L" "OW1"]))) (is (= ["hello(1)"] (get-word ["HH" "EH" "L" "OW"]))) (is (= ["ensure(1)" "insure"] (get-word ["IH" "N" "SH" "UH" "R"])))) (testing "phrase to phones" (is (= [["B" "AA1" "G" "HH" "AA1" "G"] ["B" "AO1" "G" "HH" "AA1" "G"]] (phrase-phones "bog hog")))))
759665481ba325627e23fa57731ee3a8ca3b7c8c19adae06f2b2466c3a31f894
vmchale/apple
B.hs
module Asm.X86.B ( bb ) where import Asm.X86 import Data.List.Split (split, whenElt) bb :: [X86 reg freg a] -> [[X86 reg freg a]] bb = split (whenElt cf) where cf J{} = True; cf Jl{} = True; cf Jg{} = True; cf Jge{} = True; cf Jle{} = True; cf Jne{} = True; cf Label{} = True; cf Call{} = True; cf Ret{} = True; cf _ = False
null
https://raw.githubusercontent.com/vmchale/apple/efa061fe1e3db632ccf6a1fa0661732f60ac196f/src/Asm/X86/B.hs
haskell
module Asm.X86.B ( bb ) where import Asm.X86 import Data.List.Split (split, whenElt) bb :: [X86 reg freg a] -> [[X86 reg freg a]] bb = split (whenElt cf) where cf J{} = True; cf Jl{} = True; cf Jg{} = True; cf Jge{} = True; cf Jle{} = True; cf Jne{} = True; cf Label{} = True; cf Call{} = True; cf Ret{} = True; cf _ = False
e21e845a9fbbcdec124650e20cc0fbb4ad42def5e9295544b49acdbb1980af88
appleshan/cl-http
sysdcl.lisp
-*- Mode : lisp ; Syntax : ansi - common - lisp ; Package : USER ; Base : 10 -*- See copyright notice in CLIM - SYS;MINIPROC file . (in-package "USER") (defvar *aclpc-directory* (make-pathname :host (pathname-host *load-pathname*) :device (pathname-device *load-pathname*) :directory (pathname-directory *load-pathname*) :name nil :type nil :version nil)) (setf (logical-pathname-translations "aclpc") `(("**;*.*.*" ,*aclpc-directory*) ("*.*.*" ,*aclpc-directory*))) (defsystem "aclpc-update" (:pretty-name "ACLPC Update to Portable CLIM-SYS package" :default-pathname #.(if (ignore-errors (logical-pathname-translations "HTTP")) "HTTP:acl;aclpc;" "aclpc:")) (:serial "format" "stream-sequence" "listener" "mintface"))
null
https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/acl/obc/aclpc/sysdcl.lisp
lisp
Syntax : ansi - common - lisp ; Package : USER ; Base : 10 -*- MINIPROC file .
(in-package "USER") (defvar *aclpc-directory* (make-pathname :host (pathname-host *load-pathname*) :device (pathname-device *load-pathname*) :directory (pathname-directory *load-pathname*) :name nil :type nil :version nil)) (setf (logical-pathname-translations "aclpc") `(("**;*.*.*" ,*aclpc-directory*) ("*.*.*" ,*aclpc-directory*))) (defsystem "aclpc-update" (:pretty-name "ACLPC Update to Portable CLIM-SYS package" :default-pathname #.(if (ignore-errors (logical-pathname-translations "HTTP")) "HTTP:acl;aclpc;" "aclpc:")) (:serial "format" "stream-sequence" "listener" "mintface"))
5a20d0c0ef4ba4a1479d5a6d50ff5f95ab978f26b57b5d48eaf9c03c2dc2849d
scrintal/heroicons-reagent
calendar.cljs
(ns com.scrintal.heroicons.mini.calendar) (defn render [] [:svg {:xmlns "" :viewBox "0 0 20 20" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M5.75 2a.75.75 0 01.75.75V4h7V2.75a.75.75 0 011.5 0V4h.25A2.75 2.75 0 0118 6.75v8.5A2.75 2.75 0 0115.25 18H4.75A2.75 2.75 0 012 15.25v-8.5A2.75 2.75 0 014.75 4H5V2.75A.75.75 0 015.75 2zm-1 5.5c-.69 0-1.25.56-1.25 1.25v6.5c0 .69.56 1.25 1.25 1.25h10.5c.69 0 1.25-.56 1.25-1.25v-6.5c0-.69-.56-1.25-1.25-1.25H4.75z" :clipRule "evenodd"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/mini/calendar.cljs
clojure
(ns com.scrintal.heroicons.mini.calendar) (defn render [] [:svg {:xmlns "" :viewBox "0 0 20 20" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M5.75 2a.75.75 0 01.75.75V4h7V2.75a.75.75 0 011.5 0V4h.25A2.75 2.75 0 0118 6.75v8.5A2.75 2.75 0 0115.25 18H4.75A2.75 2.75 0 012 15.25v-8.5A2.75 2.75 0 014.75 4H5V2.75A.75.75 0 015.75 2zm-1 5.5c-.69 0-1.25.56-1.25 1.25v6.5c0 .69.56 1.25 1.25 1.25h10.5c.69 0 1.25-.56 1.25-1.25v-6.5c0-.69-.56-1.25-1.25-1.25H4.75z" :clipRule "evenodd"}]])
22f4e236fd14b2ce34b884b43b67018f3bf300f3e8f67d6cf9c0aafe801d9950
EFanZh/EOPL-Exercises
exercise-6.10-test.rkt
#lang racket/base (require rackunit) (require "../solutions/exercise-6.10.rkt") (define (list-sum-2 loi) (list-sum/k loi 0)) (for ([f (list list-sum list-sum-2)]) (check-eq? (f '()) 0) (check-eq? (f '(0)) 0) (check-eq? (f '(1)) 1) (check-eq? (f '(2)) 2) (check-eq? (f '(0 1)) 1) (check-eq? (f '(0 1 2)) 3) (check-eq? (f '(0 1 2 3)) 6) (check-eq? (f '(0 1 2 3 4)) 10))
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/tests/exercise-6.10-test.rkt
racket
#lang racket/base (require rackunit) (require "../solutions/exercise-6.10.rkt") (define (list-sum-2 loi) (list-sum/k loi 0)) (for ([f (list list-sum list-sum-2)]) (check-eq? (f '()) 0) (check-eq? (f '(0)) 0) (check-eq? (f '(1)) 1) (check-eq? (f '(2)) 2) (check-eq? (f '(0 1)) 1) (check-eq? (f '(0 1 2)) 3) (check-eq? (f '(0 1 2 3)) 6) (check-eq? (f '(0 1 2 3 4)) 10))
d3e940f911c866b045b2b5d2310d444482aa1340497b0a4ee26dc5f6ecd301c6
mkoppmann/eselsohr
Repo.hs
module Lib.Domain.Repo ( RepositoryCommand (..) , RepositoryCommandSync (..) ) where import Lib.Domain.Collection (Collection) import Lib.Domain.Id (Id) data RepositoryCommand m = RepositoryCommand { collectionId :: !(Id Collection) , action :: !(m ()) } data RepositoryCommandSync m = RepositoryCommandSync { syncVar :: !(TMVar ()) , repoCommand :: !(RepositoryCommand m) }
null
https://raw.githubusercontent.com/mkoppmann/eselsohr/3bb8609199c1dfda94935e6dde0c46fc429de84e/src/Lib/Domain/Repo.hs
haskell
module Lib.Domain.Repo ( RepositoryCommand (..) , RepositoryCommandSync (..) ) where import Lib.Domain.Collection (Collection) import Lib.Domain.Id (Id) data RepositoryCommand m = RepositoryCommand { collectionId :: !(Id Collection) , action :: !(m ()) } data RepositoryCommandSync m = RepositoryCommandSync { syncVar :: !(TMVar ()) , repoCommand :: !(RepositoryCommand m) }
5d6096b49bdd50e34bf047db4f19b15bb011b8d5e02eb9eba142a56d6633089a
robert-strandh/CLIMatis
editor.lisp
(defpackage #:test-editor (:use #:common-lisp)) (in-package #:test-editor) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; View (defclass editor-view () ((%cursor :initform (cons 0 0) :accessor cursor) (%buffer :initform (vector (vector)) :accessor buffer))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Commands (defun editor-error (format-string &rest arguments) (apply #'format *error-output* format-string arguments) (error "get me out of here")) (defun beginning-of-line-p (view) (zerop (cdr (cursor view)))) (defun end-of-line-p (view) (with-accessors ((buffer buffer) (cursor cursor)) view (= (length (aref buffer (car cursor))) (cdr cursor)))) (defun first-line-p (view) (zerop (car (cursor view)))) (defun last-line-p (view) (= (car (cursor view)) (1- (length (buffer view))))) (defun beginning-of-buffer-p (view) (and (first-line-p view) (beginning-of-line-p view))) (defun end-of-buffer-p (view) (and (last-line-p view) (end-of-line-p view))) (defun move-to-beginning-of-line (view) (setf (cdr (cursor view)) 0)) (defun move-to-end-of-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (setf (cdr cursor) (length (aref buffer (car cursor)))))) (defun cursor-forward (view) (with-accessors ((cursor cursor)) view (if (end-of-line-p view) (if (last-line-p view) (editor-error "At the end of the buffer.") (progn (incf (car cursor)) (move-to-beginning-of-line view))) (incf (cdr cursor))))) (defun cursor-backward (view) (with-accessors ((buffer buffer) (cursor cursor)) view (if (beginning-of-line-p view) (if (first-line-p view) (editor-error "At the beginning of the buffer.") (progn (decf (car cursor)) (move-to-end-of-line view))) (decf (cdr cursor))))) (defun insert-object (view object) (with-accessors ((buffer buffer) (cursor cursor)) view (setf (aref buffer (car cursor)) (concatenate 'vector (subseq (aref buffer (car cursor)) 0 (cdr cursor)) (list object) (subseq (aref buffer (car cursor)) (cdr cursor)))) (incf (cdr cursor)))) (defun delete-object-or-merge-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (if (end-of-line-p view) (if (last-line-p view) (editor-error "At the end of the buffer.") (setf buffer (concatenate 'vector (subseq buffer 0 (car cursor)) (list (concatenate 'vector (aref buffer (car cursor)) (aref buffer (1+ (car cursor))))) (subseq buffer (+ (car cursor) 2))))) (setf (aref buffer (car cursor)) (concatenate 'vector (subseq (aref buffer (car cursor)) 0 (cdr cursor)) (subseq (aref buffer (car cursor)) (1+ (cdr cursor)))))))) (defun erase-object-or-merge-line (view) (cursor-backward view) (delete-object-or-merge-line view)) (defun split-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (let ((line (aref buffer (car cursor)))) (setf buffer (concatenate 'vector (subseq buffer 0 (car cursor)) (list (subseq line 0 (cdr cursor)) (subseq line (cdr cursor))) (subseq buffer (1+ (car cursor)))))) (incf (car cursor)) (move-to-beginning-of-line view))) (defun merge-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (if (last-line-p view) (editor-error "On last line.") (setf buffer (concatenate 'vector (subseq buffer 0 (car cursor)) (list (concatenate 'vector (aref buffer (car cursor)) (aref buffer (1+ (car cursor))))) (subseq buffer (+ (car cursor) 2))))))) (defun kill-to-end-of-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (if (end-of-line-p view) (if (last-line-p view) (editor-error "At the end of the buffer.") (merge-line view)) (setf (aref buffer (car cursor)) (subseq (aref buffer (car cursor)) 0 (cdr cursor)))))) (defun exit (view) (declare (ignore view)) (throw 'end nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Keystroke processor (defgeneric process-keystroke (keystroke-processor keystroke)) (defclass keystroke-processor () ()) (defclass emacs-like-keystroke-processor () ((%view :initarg :view :reader view) (%command-table :initarg :command-table :reader command-table) (%numeric-args :initform nil :accessor numeric-args) (%keystrokes-so-far :initform '() :accessor keystrokes-so-far))) (defun reset-keystroke-processor (keystroke-processor) (setf (numeric-args keystroke-processor) nil) (setf (keystrokes-so-far keystroke-processor) '())) (defun abort-and-reset (keystroke-processor) (editor-error "Quit.") (reset-keystroke-processor keystroke-processor)) (defparameter *fundametal-table* '((((#\x :control) (#\c :control)) . exit) (((#\f :control)) . cursor-forward) (((#\b :control)) . cursor-backward) (((#\d :control)) . delete-object-or-merge-line) (((#\h :control)) . erase-object-or-merge-line) (((#\a :control)) . move-to-beginning-of-line) (((#\e :control)) . move-to-end-of-line) (((#\k :control)) . kill-to-end-of-line) (((#\Return)) . split-line))) (defun prefix-p (partial-sentence sentence) (and (<= (length partial-sentence) (length sentence)) (every #'equal partial-sentence sentence))) (defmethod process-keystroke ((keystroke-processor emacs-like-keystroke-processor) keystroke) (if (equal keystroke '(#\g :control)) (abort-and-reset keystroke-processor) (with-accessors ((view view) (command-table command-table) (keystrokes-so-far keystrokes-so-far)) keystroke-processor (setf keystrokes-so-far (append keystrokes-so-far (list keystroke))) (let ((entries (remove-if-not (lambda (entry) (prefix-p keystrokes-so-far (car entry))) command-table))) (cond ((null entries) (if (and (null (cdr keystrokes-so-far)) (null (cdr keystroke))) ;; We have a single character. (progn (reset-keystroke-processor keystroke-processor) (insert-object view (car keystroke))) (progn (editor-error "No command for keystokes.") (reset-keystroke-processor keystroke-processor)))) ((equal keystrokes-so-far (caar entries)) ;; We found a perfect match. (reset-keystroke-processor keystroke-processor) (handler-case (funcall (cdar entries) view) (error () nil))) (t nil)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; GUI (defun string-to-words-and-spaces (string start) (if (= start (length string)) '() (if (eql (aref string start) #\Space) (let ((first-non-blank (position #\Space string :test-not #'eql :start start))) (when (null first-non-blank) (setf first-non-blank (length string))) (cons (- first-non-blank start) (string-to-words-and-spaces string first-non-blank))) (let ((first-blank (position #\Space string :start start))) (when (null first-blank) (setf first-blank (length string))) (cons (subseq string start first-blank) (string-to-words-and-spaces string first-blank)))))) (defun line-from-string (string) (clim3:hbox* (clim3:hbox (mapcar (lambda (item) (if (numberp item) (clim3:hframe* 7 7 7) (clim3-text:text (coerce item 'string) (clim3:text-style :camfer :sans :roman 12) (clim3:make-color 0.0 0.0 0.0)))) (string-to-words-and-spaces string 0))) (clim3:hframe* 0 0 nil))) (defun edit-zone (height lines) (clim3:vframe* height height height (clim3:pile* (clim3:bboard* lines) (clim3:opaque (clim3:make-color 0.95 0.95 0.95))))) (defun info-zone (height) (clim3:vframe* height height height (clim3:pile* (clim3:hbox* (clim3:hframe* 30 30 30) (clim3-text:text "Climacs" (clim3:text-style :camfer :sans :roman 12) (clim3:make-color 0.0 0.0 0.0)) (clim3:hframe* 0 0 nil)) (clim3:opaque (clim3:make-color 0.8 0.8 0.8))))) (defun minibuffer-zone (height) (clim3:vframe* height height height (clim3:pile* ;; This one should really be a scroller. (clim3:bboard* ;; The zone containing the text (clim3:hbox* (clim3:hframe* 0 0 nil))) (clim3:opaque (clim3:make-color 0.95 0.95 0.95))))) (defun stuff-buffer-text (buffer vbox) (setf (clim3:children vbox) (loop for line across buffer ;; Put the words and spaces of a line into a hbox. collect (line-from-string line) ;; Make some space between lines collect (clim3:vframe* 5 5 nil)))) (defparameter *fun* nil) (defun find-cursor (view) (with-accessors ((buffer buffer) (cursor cursor)) view (let* ((prefix (subseq (aref buffer (car cursor)) 0 (cdr cursor))) (words-and-spaces (string-to-words-and-spaces prefix 0))) (cond ((= (cdr cursor) (length (aref buffer (car cursor)))) (values (* 2 (car cursor)) nil nil)) ((vectorp (car (last words-and-spaces))) (values (* 2 (car cursor)) (1- (length words-and-spaces)) (coerce (car (last words-and-spaces)) 'string))) (t (values (* 2 (car cursor)) (length words-and-spaces) nil)))))) (defun editor-zones (width height) (let* ((lines (clim3:vbox*)) (view (make-instance 'editor-view)) (keystroke-processor (make-instance 'emacs-like-keystroke-processor :view view :command-table *fundametal-table*))) (clim3:hframe* width width width (clim3:vframe* height height height (clim3:pile* (clim3-input:key (clim3:standard-key-decoder (setf *fun* (lambda (key) (process-keystroke keystroke-processor key) (stuff-buffer-text (buffer view) lines)))) (lambda (&rest rest) (declare (ignore rest)) nil)) (clim3:vbox* (edit-zone (- height 60) lines) (info-zone 30) (minibuffer-zone 30))))))) (defun editor (width height) (let ((port (clim3:make-port :clx-framebuffer)) (root (editor-zones width height))) (clim3:connect root port) (catch 'end (clim3:event-loop port)) (clim3:disconnect root port)))
null
https://raw.githubusercontent.com/robert-strandh/CLIMatis/4949ddcc46d3f81596f956d12f64035e04589b29/Test/editor.lisp
lisp
View Commands We have a single character. We found a perfect match. GUI This one should really be a scroller. The zone containing the text Put the words and spaces of a line into a hbox. Make some space between lines
(defpackage #:test-editor (:use #:common-lisp)) (in-package #:test-editor) (defclass editor-view () ((%cursor :initform (cons 0 0) :accessor cursor) (%buffer :initform (vector (vector)) :accessor buffer))) (defun editor-error (format-string &rest arguments) (apply #'format *error-output* format-string arguments) (error "get me out of here")) (defun beginning-of-line-p (view) (zerop (cdr (cursor view)))) (defun end-of-line-p (view) (with-accessors ((buffer buffer) (cursor cursor)) view (= (length (aref buffer (car cursor))) (cdr cursor)))) (defun first-line-p (view) (zerop (car (cursor view)))) (defun last-line-p (view) (= (car (cursor view)) (1- (length (buffer view))))) (defun beginning-of-buffer-p (view) (and (first-line-p view) (beginning-of-line-p view))) (defun end-of-buffer-p (view) (and (last-line-p view) (end-of-line-p view))) (defun move-to-beginning-of-line (view) (setf (cdr (cursor view)) 0)) (defun move-to-end-of-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (setf (cdr cursor) (length (aref buffer (car cursor)))))) (defun cursor-forward (view) (with-accessors ((cursor cursor)) view (if (end-of-line-p view) (if (last-line-p view) (editor-error "At the end of the buffer.") (progn (incf (car cursor)) (move-to-beginning-of-line view))) (incf (cdr cursor))))) (defun cursor-backward (view) (with-accessors ((buffer buffer) (cursor cursor)) view (if (beginning-of-line-p view) (if (first-line-p view) (editor-error "At the beginning of the buffer.") (progn (decf (car cursor)) (move-to-end-of-line view))) (decf (cdr cursor))))) (defun insert-object (view object) (with-accessors ((buffer buffer) (cursor cursor)) view (setf (aref buffer (car cursor)) (concatenate 'vector (subseq (aref buffer (car cursor)) 0 (cdr cursor)) (list object) (subseq (aref buffer (car cursor)) (cdr cursor)))) (incf (cdr cursor)))) (defun delete-object-or-merge-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (if (end-of-line-p view) (if (last-line-p view) (editor-error "At the end of the buffer.") (setf buffer (concatenate 'vector (subseq buffer 0 (car cursor)) (list (concatenate 'vector (aref buffer (car cursor)) (aref buffer (1+ (car cursor))))) (subseq buffer (+ (car cursor) 2))))) (setf (aref buffer (car cursor)) (concatenate 'vector (subseq (aref buffer (car cursor)) 0 (cdr cursor)) (subseq (aref buffer (car cursor)) (1+ (cdr cursor)))))))) (defun erase-object-or-merge-line (view) (cursor-backward view) (delete-object-or-merge-line view)) (defun split-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (let ((line (aref buffer (car cursor)))) (setf buffer (concatenate 'vector (subseq buffer 0 (car cursor)) (list (subseq line 0 (cdr cursor)) (subseq line (cdr cursor))) (subseq buffer (1+ (car cursor)))))) (incf (car cursor)) (move-to-beginning-of-line view))) (defun merge-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (if (last-line-p view) (editor-error "On last line.") (setf buffer (concatenate 'vector (subseq buffer 0 (car cursor)) (list (concatenate 'vector (aref buffer (car cursor)) (aref buffer (1+ (car cursor))))) (subseq buffer (+ (car cursor) 2))))))) (defun kill-to-end-of-line (view) (with-accessors ((buffer buffer) (cursor cursor)) view (if (end-of-line-p view) (if (last-line-p view) (editor-error "At the end of the buffer.") (merge-line view)) (setf (aref buffer (car cursor)) (subseq (aref buffer (car cursor)) 0 (cdr cursor)))))) (defun exit (view) (declare (ignore view)) (throw 'end nil)) Keystroke processor (defgeneric process-keystroke (keystroke-processor keystroke)) (defclass keystroke-processor () ()) (defclass emacs-like-keystroke-processor () ((%view :initarg :view :reader view) (%command-table :initarg :command-table :reader command-table) (%numeric-args :initform nil :accessor numeric-args) (%keystrokes-so-far :initform '() :accessor keystrokes-so-far))) (defun reset-keystroke-processor (keystroke-processor) (setf (numeric-args keystroke-processor) nil) (setf (keystrokes-so-far keystroke-processor) '())) (defun abort-and-reset (keystroke-processor) (editor-error "Quit.") (reset-keystroke-processor keystroke-processor)) (defparameter *fundametal-table* '((((#\x :control) (#\c :control)) . exit) (((#\f :control)) . cursor-forward) (((#\b :control)) . cursor-backward) (((#\d :control)) . delete-object-or-merge-line) (((#\h :control)) . erase-object-or-merge-line) (((#\a :control)) . move-to-beginning-of-line) (((#\e :control)) . move-to-end-of-line) (((#\k :control)) . kill-to-end-of-line) (((#\Return)) . split-line))) (defun prefix-p (partial-sentence sentence) (and (<= (length partial-sentence) (length sentence)) (every #'equal partial-sentence sentence))) (defmethod process-keystroke ((keystroke-processor emacs-like-keystroke-processor) keystroke) (if (equal keystroke '(#\g :control)) (abort-and-reset keystroke-processor) (with-accessors ((view view) (command-table command-table) (keystrokes-so-far keystrokes-so-far)) keystroke-processor (setf keystrokes-so-far (append keystrokes-so-far (list keystroke))) (let ((entries (remove-if-not (lambda (entry) (prefix-p keystrokes-so-far (car entry))) command-table))) (cond ((null entries) (if (and (null (cdr keystrokes-so-far)) (null (cdr keystroke))) (progn (reset-keystroke-processor keystroke-processor) (insert-object view (car keystroke))) (progn (editor-error "No command for keystokes.") (reset-keystroke-processor keystroke-processor)))) ((equal keystrokes-so-far (caar entries)) (reset-keystroke-processor keystroke-processor) (handler-case (funcall (cdar entries) view) (error () nil))) (t nil)))))) (defun string-to-words-and-spaces (string start) (if (= start (length string)) '() (if (eql (aref string start) #\Space) (let ((first-non-blank (position #\Space string :test-not #'eql :start start))) (when (null first-non-blank) (setf first-non-blank (length string))) (cons (- first-non-blank start) (string-to-words-and-spaces string first-non-blank))) (let ((first-blank (position #\Space string :start start))) (when (null first-blank) (setf first-blank (length string))) (cons (subseq string start first-blank) (string-to-words-and-spaces string first-blank)))))) (defun line-from-string (string) (clim3:hbox* (clim3:hbox (mapcar (lambda (item) (if (numberp item) (clim3:hframe* 7 7 7) (clim3-text:text (coerce item 'string) (clim3:text-style :camfer :sans :roman 12) (clim3:make-color 0.0 0.0 0.0)))) (string-to-words-and-spaces string 0))) (clim3:hframe* 0 0 nil))) (defun edit-zone (height lines) (clim3:vframe* height height height (clim3:pile* (clim3:bboard* lines) (clim3:opaque (clim3:make-color 0.95 0.95 0.95))))) (defun info-zone (height) (clim3:vframe* height height height (clim3:pile* (clim3:hbox* (clim3:hframe* 30 30 30) (clim3-text:text "Climacs" (clim3:text-style :camfer :sans :roman 12) (clim3:make-color 0.0 0.0 0.0)) (clim3:hframe* 0 0 nil)) (clim3:opaque (clim3:make-color 0.8 0.8 0.8))))) (defun minibuffer-zone (height) (clim3:vframe* height height height (clim3:pile* (clim3:bboard* (clim3:hbox* (clim3:hframe* 0 0 nil))) (clim3:opaque (clim3:make-color 0.95 0.95 0.95))))) (defun stuff-buffer-text (buffer vbox) (setf (clim3:children vbox) (loop for line across buffer collect (line-from-string line) collect (clim3:vframe* 5 5 nil)))) (defparameter *fun* nil) (defun find-cursor (view) (with-accessors ((buffer buffer) (cursor cursor)) view (let* ((prefix (subseq (aref buffer (car cursor)) 0 (cdr cursor))) (words-and-spaces (string-to-words-and-spaces prefix 0))) (cond ((= (cdr cursor) (length (aref buffer (car cursor)))) (values (* 2 (car cursor)) nil nil)) ((vectorp (car (last words-and-spaces))) (values (* 2 (car cursor)) (1- (length words-and-spaces)) (coerce (car (last words-and-spaces)) 'string))) (t (values (* 2 (car cursor)) (length words-and-spaces) nil)))))) (defun editor-zones (width height) (let* ((lines (clim3:vbox*)) (view (make-instance 'editor-view)) (keystroke-processor (make-instance 'emacs-like-keystroke-processor :view view :command-table *fundametal-table*))) (clim3:hframe* width width width (clim3:vframe* height height height (clim3:pile* (clim3-input:key (clim3:standard-key-decoder (setf *fun* (lambda (key) (process-keystroke keystroke-processor key) (stuff-buffer-text (buffer view) lines)))) (lambda (&rest rest) (declare (ignore rest)) nil)) (clim3:vbox* (edit-zone (- height 60) lines) (info-zone 30) (minibuffer-zone 30))))))) (defun editor (width height) (let ((port (clim3:make-port :clx-framebuffer)) (root (editor-zones width height))) (clim3:connect root port) (catch 'end (clim3:event-loop port)) (clim3:disconnect root port)))
745744e8c0fb9e6ebfbc0d8297db0d83e538cc9cdf39ca4de52ab953fc588ad4
witan-org/witan
demon.mli
(*************************************************************************) This file is part of Witan . (* *) Copyright ( C ) 2017 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) ( Institut National de Recherche en Informatique et en (* Automatique) *) CNRS ( Centre national de la recherche scientifique ) (* *) (* 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 . (* *) (* It 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. *) (* *) (* See the GNU Lesser General Public License version 2.1 *) for more details ( enclosed in the file licenses / LGPLv2.1 ) . (*************************************************************************) open Witan_popop_lib open Nodes module Create : sig type 'b event = (** the domain dom of the class is watched *) | EventDom : Node.t * 'a DomKind.t * 'b -> 'b event (** the value of the class is watched *) | EventValue : Node.t * 'a ValueKind.t * 'b -> 'b event (** the values of the class is watched *) | EventAnyValue : Node.t * 'b -> 'b event (** we want to register this class *) | EventRegCl : Node.t * 'b -> 'b event (** Warn when the class is not the representant of its eq-class anymore *) | EventChange : Node.t * 'b -> 'b event (** a new theory term 'a appear *) | EventRegSem : 'a ThTermKind.t * 'b -> 'b event (** a new value 'a appear *) | EventRegValue : 'a ValueKind.t * 'b -> 'b event val pp: 'b event Format.printer type 'b t = 'b event list end type 'k alive = | AliveReattached | AliveStopped | AliveRedirected of 'k module Key: sig type ('k,'d,'i) t val create: string -> ('k,'d,'i) t module type S = sig module Key: Stdlib.Datatype module Data: Stdlib.Printable type info val default: info val key: (Key.t, Data.t, info) t val immediate: bool val wakeup: Egraph.t -> Key.t -> Data.t Events.Fired.t -> info -> Key.t alive * the Events.t in wakeup is a subset of the one given in watch end module Register (D:S): sig val init: Egraph.t -> unit (** to run for each new delayed *) end type ('k,'i) state = | SUnborn | SAlive of 'i | SDead | SRedirected of 'k val attach: Egraph.t -> ('k,'d,'i) t -> 'k -> 'd Create.t -> unit * raise AlreadyDead if this key is already dead val is_attached: Egraph.t -> ('k,'d,'i) t -> 'k -> ('k,'i) state val set_info: Egraph.t -> ('k, 'd, 'i) t -> 'k -> 'i -> unit exception CantBeKilled val kill : Egraph.t -> ('a, 'b,'c) t -> 'a -> unit end module Fast: sig type 'd t val create: string -> 'd t module type S = sig module Data: sig type t val pp: t Format.printer end val key: Data.t t (** never killed *) val immediate: bool val throttle: int (** todo int ref? *) (** number of time run in a row *) val wakeup: Egraph.t -> Data.t Events.Fired.event -> unit end module Register (D:S): sig val init: Egraph.t -> unit (** to run for each new delayed *) end val attach: Egraph.t -> 'd t -> 'd Create.t -> unit (** helper *) val register_init_daemon: name:string -> ?immediate:bool -> ?throttle:int -> (module RegisteredThTerm with type t = 'a) -> (Egraph.t -> 'a -> unit) -> Egraph.t -> unit (** *) (** helper *) val register_init_daemon_value: name:string -> ?immediate:bool -> ?throttle:int -> (module RegisteredValue with type t = 'a) -> (Egraph.t -> 'a -> unit) -> Egraph.t -> unit (** *) end
null
https://raw.githubusercontent.com/witan-org/witan/d26f9f810fc34bf44daccb91f71ad3258eb62037/src/core/demon.mli
ocaml
*********************************************************************** alternatives) Automatique) you can redistribute it and/or modify it under the terms of the GNU It 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. See the GNU Lesser General Public License version 2.1 *********************************************************************** * the domain dom of the class is watched * the value of the class is watched * the values of the class is watched * we want to register this class * Warn when the class is not the representant of its eq-class anymore * a new theory term 'a appear * a new value 'a appear * to run for each new delayed * never killed * todo int ref? * number of time run in a row * to run for each new delayed * helper * * helper *
This file is part of Witan . Copyright ( C ) 2017 CEA ( Commissariat à l'énergie atomique et aux énergies ( Institut National de Recherche en Informatique et en CNRS ( Centre national de la recherche scientifique ) Lesser General Public License as published by the Free Software Foundation , version 2.1 . for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Witan_popop_lib open Nodes module Create : sig type 'b event = | EventDom : Node.t * 'a DomKind.t * 'b -> 'b event | EventValue : Node.t * 'a ValueKind.t * 'b -> 'b event | EventAnyValue : Node.t * 'b -> 'b event | EventRegCl : Node.t * 'b -> 'b event | EventChange : Node.t * 'b -> 'b event | EventRegSem : 'a ThTermKind.t * 'b -> 'b event | EventRegValue : 'a ValueKind.t * 'b -> 'b event val pp: 'b event Format.printer type 'b t = 'b event list end type 'k alive = | AliveReattached | AliveStopped | AliveRedirected of 'k module Key: sig type ('k,'d,'i) t val create: string -> ('k,'d,'i) t module type S = sig module Key: Stdlib.Datatype module Data: Stdlib.Printable type info val default: info val key: (Key.t, Data.t, info) t val immediate: bool val wakeup: Egraph.t -> Key.t -> Data.t Events.Fired.t -> info -> Key.t alive * the Events.t in wakeup is a subset of the one given in watch end module Register (D:S): sig val init: Egraph.t -> unit end type ('k,'i) state = | SUnborn | SAlive of 'i | SDead | SRedirected of 'k val attach: Egraph.t -> ('k,'d,'i) t -> 'k -> 'd Create.t -> unit * raise AlreadyDead if this key is already dead val is_attached: Egraph.t -> ('k,'d,'i) t -> 'k -> ('k,'i) state val set_info: Egraph.t -> ('k, 'd, 'i) t -> 'k -> 'i -> unit exception CantBeKilled val kill : Egraph.t -> ('a, 'b,'c) t -> 'a -> unit end module Fast: sig type 'd t val create: string -> 'd t module type S = sig module Data: sig type t val pp: t Format.printer end val key: Data.t t val immediate: bool val wakeup: Egraph.t -> Data.t Events.Fired.event -> unit end module Register (D:S): sig val init: Egraph.t -> unit end val attach: Egraph.t -> 'd t -> 'd Create.t -> unit val register_init_daemon: name:string -> ?immediate:bool -> ?throttle:int -> (module RegisteredThTerm with type t = 'a) -> (Egraph.t -> 'a -> unit) -> Egraph.t -> unit val register_init_daemon_value: name:string -> ?immediate:bool -> ?throttle:int -> (module RegisteredValue with type t = 'a) -> (Egraph.t -> 'a -> unit) -> Egraph.t -> unit end
db578c045eb55d55dfa91abce39d56bcddc72fb057a7b4223711d56631c5791e
isovector/circuitry
Numeric.hs
module Circuitry.Numeric where import Circuitry.Category (first') import Clash.Sized.Vector (Vec(..)) import qualified Clash.Sized.Vector as V import qualified Data.Bits as B import Data.Word import Circuitry.Embed import Circuitry.Word class Numeric a where zero :: a default zero :: Num a => a zero = 0 one :: a default one :: Num a => a one = 1 addNumeric :: a -> a -> (a, Bool) default addNumeric :: (Num a, Ord a, Bounded a) => a -> a -> (a, Bool) addNumeric a b = (a + b, maxBound - a <= b) instance Numeric Bool where zero = False one = True addNumeric a b = (B.xor a b, a && b) instance Numeric Word2 instance Numeric Word3 instance Numeric Word4 instance Numeric Word8 instance Numeric Word16 instance Numeric Word32 instance Numeric Word64 instance Numeric (Vec 8 Bool) where zero = V.repeat False one = V.repeat False V.++ Cons True Nil addNumeric v1 v2 = first' embed $ reify @Word8 v1 `addNumeric` reify v2
null
https://raw.githubusercontent.com/isovector/circuitry/81f018a67937de9348eda9f2e95236e75c90ea85/src/Circuitry/Numeric.hs
haskell
module Circuitry.Numeric where import Circuitry.Category (first') import Clash.Sized.Vector (Vec(..)) import qualified Clash.Sized.Vector as V import qualified Data.Bits as B import Data.Word import Circuitry.Embed import Circuitry.Word class Numeric a where zero :: a default zero :: Num a => a zero = 0 one :: a default one :: Num a => a one = 1 addNumeric :: a -> a -> (a, Bool) default addNumeric :: (Num a, Ord a, Bounded a) => a -> a -> (a, Bool) addNumeric a b = (a + b, maxBound - a <= b) instance Numeric Bool where zero = False one = True addNumeric a b = (B.xor a b, a && b) instance Numeric Word2 instance Numeric Word3 instance Numeric Word4 instance Numeric Word8 instance Numeric Word16 instance Numeric Word32 instance Numeric Word64 instance Numeric (Vec 8 Bool) where zero = V.repeat False one = V.repeat False V.++ Cons True Nil addNumeric v1 v2 = first' embed $ reify @Word8 v1 `addNumeric` reify v2
ef776fa12cddeafcd7ac89e6357c73e634c7f109f6188e0d0b2c27adfcc7e0c8
bendoerr/real-world-haskell
RoundToEven.hs
file : / RoundToEven.hs isOdd n = mod n 2 == 1
null
https://raw.githubusercontent.com/bendoerr/real-world-haskell/fa43aa59e42a162f5d2d5655b274b964ebeb8f0a/ch02/RoundToEven.hs
haskell
file : / RoundToEven.hs isOdd n = mod n 2 == 1
e5e28478effe99a866e855a2f3ce92fd3ec6ba7c240deccf58cb9dbfb38719a5
earl-ducaine/cl-garnet
popup-menu-button.lisp
-*- Mode : LISP ; Syntax : Common - Lisp ; Package : GARNET - GADGETS ; Base : 10 -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; The Garnet User Interface Development Environment . ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This code was written as part of the Garnet project at ;;; Carnegie Mellon University , and has been placed in the public ; ; ; domain . If you are using this code or any part of Garnet , ; ; ; ;;; please contact to be put on the mailing list. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Popup menu from a button ;;; ;;; Slots: (like those of menu and text-button) ;;; :left - default 0 ;;; :top - default 0 : string - default GG : LINES - BITMAP ; the string or object in the ;;; button. Default is a small bitmap showing a few lines Another useful bitmap is GG : DOWNARROW - BITMAP ;;; NOTE: do not use these bitmaps directly, but rather use something like ;;; (:string (create-instance NIL GG:DOWNARROW-BITMAP)) ;;; :items - Items in the pop-up menu ;;; :item-to-string-function - Converts items to strings for the menu ;;; :v-spacing - default 0 ; of the menu ;;; :h-align - default :LEFT ; of the menu ;;; :item-font - default opal:default-font ; for the menu strings : selection - function - default NIL ; called with the menu selection ;;; :keep-menu-in-screen-p - default T ; if T, then menu will be ;;; adjusted if it would go offscreen ;;; :position - default :below; where menu pops up. Choices are : below , : left , : right or a list of two numbers ;;; (can be computed with a formula) : min - menu - width - default 0 ; the minimum width for the menu : shadow - offset - default 2 ; for the button : text - offset - default 3 ; for the button : gray - width - default 2 ; for the button ;;; ;;; Read-Only ;;; :value - The value selected in the menu ;;; ;;; Designed and written by who stole most of the code from ;;; CHANGE LOG : 05/23/94 : window formula in : SELECTOR interactor ;;; to check if menu's window is non-NIL before continuing gv's. 04/23/93 - Added : do - not - dump - slots 04/13/93 typo : * screen - height * -- > * screen - width * in Fix - Menu - Out - Of - Screen 03/17/93 - add special - popdown functions for gilt , etc . ;;; - fixed :string-set-func so can edit label 03/10/93 typo in : string - set - func ( added opal package prefix to Aggrelist - Edit - String - Func ) 02/23/93 add / remove - item functions ; added ;;; :string-set-func 02/10/93 : items of type items - type 01/28/93 : width and : height formulas of menu window so that NIL : items list wo n't crash ; added ;;; :item-to-string-function 12/15/92 - Added type and parameter declarations 10/28/92 : min - menu - width takes advantage of the ;;; menu's new :min-menu-width slot 10/06/92 - support min - width and fix bugs 10/05/92 load of needed gadgets into loader file 10/04/92 - made work 09/17/92 (in-package "GARNET-GADGETS") (eval-when (:execute :load-toplevel :compile-toplevel) (export '(Popup-Menu-Button lines-bitmap downarrow-bitmap)) #+garnet-test (export '(Popup-Menu-Button-Go Popup-Menu-Button-Stop))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; First functions display the submenu from gilt , etc . ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun Put-Down-Garnet-button-Popup (gadget) (let ((win (g-value gadget :menu-window))) (when (schema-p win) (s-value win :visible NIL) (opal:update win)))) ;; doesn't seem to be seeing the s-value ;; return the popped up window (defun Garnet-popup-button-item (gadget) (let ((menu (g-value gadget :menu)) (menuwin (g-value gadget :menu-window))) (SetPopUpMenuPosition gadget menu menuwin) menuwin)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; This is responsible for determining if the menu is out ;; of the screen or not. If the menu is out of screen at ;; any of the sides, it will reset the :top and :left ;; attributes of the window to place it on the screen. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun Fix-Menu-Out-Of-Screen (menuwin) (if (< (g-value menuwin :top) 0) (s-value menuwin :top 0) (if (> (+ (g-value menuwin :top) (g-value menuwin :height)) gem:*screen-height*) (s-value menuwin :top (- gem:*screen-height* (g-value menuwin :height))) ) ) (if (< (g-value menuwin :left) 0) (s-value menuwin :left 0) (if (> (+ (g-value menuwin :left) (g-value menuwin :width)) gem:*screen-width*) (s-value menuwin :left (- gem:*screen-width* (g-value menuwin :width))) ) ) ) (defun SetPopUpMenuPosition (popupbutton menu menuwin) (let* ((pos (g-value popupbutton :position)) (shadowoffset (g-value popupbutton :shadow-offset)) x y) (cond ((eq pos :below) (setq x (+ (g-value popupbutton :left) shadowoffset)) (setq y (+ (g-value popupbutton :top) (g-value popupbutton :height)))) ((eq pos :right) (setq x (opal:right popupbutton)) (setq y (- (g-value popupbutton :top) (floor (- (g-value menu :height) (g-value popupbutton :height)) 2) 1))) ((eq pos :left) (setq x (+ (- (g-value popupbutton :left) (g-value menu :width)) shadowoffset 1)) (setq y (- (g-value popupbutton :top) (floor (- (g-value menu :height) (g-value popupbutton :height)) 2)))) ((listp pos) (setq x (car pos)) (setq y (cadr pos))) (T (error ":position argument for ~s must be :below :right :left or list of (x y), but it is ~s" popupbutton pos))) (multiple-value-bind (wx wy) (opal:convert-coordinates (g-value popupbutton :window) x y NIL) (s-value menuwin :left wx) (s-value menuwin :top wy) (when (g-value popupbutton :keep-menu-in-screen-p) (Fix-Menu-Out-Of-Screen menuwin)) (s-value menuwin :visible T) (opal:raise-window menuwin)))) ;; raise calls update ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Call this function to show the popup-menu. ;; It positions the menu at the given place, pops up the ;; menu, and starts the interactor. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun Pop-Up-Pop-Up (popupbutton) (let* ((event inter:*current-event*) (menu (g-value popupbutton :menu)) (menuwin (g-value popupbutton :menu-window))) (SetPopUpMenuPosition popupbutton menu menuwin) (setf (inter:event-window event) menuwin) (setf (inter:event-x event) -10) (setf (inter:event-y event) -10) ; make sure is :outside (inter:start-interactor (g-value menu :selector) event) ;; make sure the menu interactor processes the event, so will be :outside (inter::general-go (g-value menu :selector) event))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; This is the popup menu gadget itself. Really it's ;; just a window. A menu gets put inside on ;; initialization. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (create-instance 'lines-bitmap opal:bitmap (:image (opal:read-image (merge-pathnames "pop-up-icon-no-border.bm" common-lisp-user::Garnet-Bitmap-Pathname)))) (create-instance 'downarrow-bitmap opal:bitmap (:image (opal:read-image (merge-pathnames "downarrow.bm" common-lisp-user::Garnet-Bitmap-Pathname)))) (create-instance 'Popup-Menu-Button gg:text-button :declare ((:parameters :left :top :string :items :v-spacing :h-align :item-font :keep-menu-in-screen-p :position :min-menu-width :shadow-offset :text-offset :gray-width :selection-function :visible) (:type ((or string (satisfies schema-p)) :string) (items-type :items) (integer :v-spacing :min-menu-width :shadow-offset :text-offset :gray-width) ((member :left :center :right) :h-align) ((or (is-a-p opal:font) (is-a-p opal:font-from-file)) :item-font) (kr-boolean :keep-menu-in-screen-p) ((or (member :below :left :right) list) :position) ((or null function symbol) :selection-function))) (:left 0) (:top 0) (:string #-apple lines-bitmap #+apple "Menu") (:items '("Item 1" "Item 2" "Item 3" "Item 4")) (:v-spacing 0) (:h-align :LEFT) (:title NIL) (:item-font opal:default-font) (:item-to-string-function #'(lambda (item) (if item (if (or (stringp item) (schema-p item)) item (string-capitalize (string-trim ":" item))) ""))) (:selection-function NIL) (:value-obj (o-formula (gvl :menu :value-obj))) (:value (o-formula (gvl :value-obj :string))) (:keep-menu-in-screen-p T) (:position :below) (:min-menu-width 0) (:shadow-offset 2) (:text-offset 3) (:gray-width 2) ;; internal slots (:final-feedback-p NIL) (:menu NIL) ; filled in by initialize with the menu (:menu-window NIL) ; filled in by initialize with the menu's window (:special-popup-func 'Garnet-popup-button-item) (:special-popdown-func 'Put-Down-Garnet-button-Popup) (:update-slots (cons :visible (g-value gg:text-button :update-slots))) (:interactors `((:text-button-press :modify (:running-where T) (:window ,(o-formula (let* ((oper (gvl :operates-on)) (my-win (gv oper :window)) (menu-win (gv oper :menu-window))) (if (and my-win menu-win) (list my-win menu-win) my-win)))) (:start-action ,#'(lambda (inter button) (call-prototype-method inter button) (pop-up-pop-up button))) (:final-function ,#'(lambda (int val) (declare (ignore val)) (let* ((oper (g-value int :operates-on)) (menu (g-value oper :menu)) (menuinter (g-value menu :selector)) (outside (g-value menuinter :current-state)) val) (inter:stop-interactor menuinter) ; in case still running when is outside , then will abort , so do n't do ;; selection function, etc. (unless (eq outside :outside) (setq val (g-value menu :value)) ; do this after stop-inter (s-value oper :value val) (kr-send oper :selection-function oper val))))) )))) (s-value POPUP-MENU-BUTTON :do-not-dump-slots (append '(:menu-window :menu) (g-value POPUP-MENU-BUTTON :do-not-dump-slots))) (define-method :fix-update-slots Popup-Menu-Button (ob) ;; will be called when :visible changes (unless (g-value ob :visible) (Put-Down-Garnet-button-Popup ob)) (call-prototype-method ob)) (create-instance 'popupbuttonmenuproto gg:menu (:left 0) (:top 0) (:popup NIL) (:v-spacing (o-formula (gvl :popup :v-spacing))) (:h-align (o-formula (gvl :popup :h-align))) (:shadow-offset 0) (:text-offset (o-formula (gvl :popup :text-offset))) (:title NIL) (:items (o-formula (gvl :popup :items))) (:item-to-string-function (o-formula (gvl :popup :item-to-string-function))) (:item-font (o-formula (gvl :popup :item-font))) (:min-menu-width (o-formula (gvl :popup :min-menu-width))) (:interactors `((:selector :modify (:window ,(o-formula (let* ((oper (gv-local (gv :self) :operates-on)) (my-win (gv-local oper :window))) (when my-win (let ((button-win (gv oper :popup :window))) (if button-win (list my-win button-win) my-win)))))) (:stop-action ,#'(lambda (int val) (call-prototype-method int val) (let ((window (g-value int :operates-on :window))) (s-value window :visible NIL)))) (:abort-action ,#'(lambda (int val) (call-prototype-method int val) (let ((window (g-value int :operates-on :window))) (s-value window :visible NIL)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; This is the initialize method for the popup menu. ;; It automatically creates a menu gadget inside the ;; popup window. ;; Then , it fixes up the interactors in the menu . First , ;; the stop event is set to be leftup, which is releasing ;; the mouse button. Then, it sets up the stop action of ;; the menu so that the window is made invisible. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-method :initialize Popup-Menu-Button (popup) (let (popmenu window) (call-prototype-method popup) (let ((kr::*demons-disabled* NIL)) ; turn on all demons (setq popmenu (create-instance NIL popupbuttonmenuproto (:popup popup))) ;; change the formula so the menu's width will be bigger if necessary (setq window (create-instance NIL inter:interactor-window (:omit-title-bar-p T) (:double-buffered-p T) (:save-under T) (:border-width 0) (:menu popmenu) (:aggregate popmenu) (:popup popup) (:modal-p (o-formula (gv-local :self :popup :window :modal-p))) A drawable width or height of 0 causes CLX to crash (:height (o-formula (max 1 (gvl :menu :height)))) (:width (o-formula (max 1 (gvl :menu :width)))) (:visible NIL))) (s-value popup :menu popmenu) (s-value popup :menu-window window) (opal:Update window)))) (define-method :destroy-me Popup-Menu-Button (popup &optional erase) (let ((menu-win (g-value popup :menu-window))) (Put-Down-Garnet-button-Popup popup) (when menu-win (opal:destroy menu-win)) (call-prototype-method popup erase))) (define-method :add-local-item POPUP-MENU-BUTTON (gadget item &rest args) (opal::Gadget-Add-Local-Item gadget item '(:menu :menu-item-list) args)) (define-method :add-item POPUP-MENU-BUTTON (gadget item &rest args) (opal::Gadget-Add-Item gadget item '(:menu :menu-item-list) args)) (define-method :remove-local-item POPUP-MENU-BUTTON (gadget &optional item &key (key #'opal:no-func)) (opal::Gadget-Remove-Local-Item gadget item '(:menu :menu-item-list) key)) (define-method :remove-item POPUP-MENU-BUTTON (gadget &optional item &key (key #'opal:no-func)) (opal::Gadget-Remove-Item gadget item '(:menu :menu-item-list) key)) (s-value POPUP-MENU-BUTTON :change-item (g-value opal:aggrelist :change-item)) (s-value POPUP-MENU-BUTTON :remove-nth-item (g-value opal:aggrelist :remove-nth-item)) (define-method :string-set-func POPUP-MENU-BUTTON (gadget-obj str-obj final-event final-string) (if (eq str-obj (g-value gadget-obj :text)) (progn ;; then is the label of the button (s-value gadget-obj :string final-string) T) ;; else must be in the menu (let ((aggrel (g-value gadget-obj :MENU :MENU-ITEM-LIST))) (opal::Aggrelist-Edit-String-Func gadget-obj aggrel str-obj final-event final-string :rank)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; This is like the mini-demo function for this gadget. ;; It basically creates a window with a button. Pressing ;; the button will cause a popup window to appear. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #+garnet-test (defun Popup-Menu-Button-Go () (create-instance 'demo-popup-win inter:interactor-window (:title "Popup Menu Button Demo") (:left 100) (:top 100) (:height 90) (:width 180)) (create-instance 'demo-popup-agg opal:aggregate) (s-value demo-popup-win :aggregate demo-popup-agg) (opal:update demo-popup-win) (create-instance 'demo-popup-text-label opal:text (:top 50) (:left 15) (:string "Selected: ")) (create-instance 'demo-popup-button Popup-Menu-Button (:left 15) (:top 10) (:string "foo") (:items '("Red" "Blue" "Green" "Yellow" "Aquamarine" "Cyan" "Fluorescent")) (:selection-function #'(lambda (g v) (declare (ignore g)) (format T "Selected is ~s~%" v)))) (create-instance 'demo-popup-text opal:text (:top 50) (:left (o-formula (+ (g-value demo-popup-text-label :left) (g-value demo-popup-text-label :width)))) (:string (o-formula (format NIL "~s" (gv demo-popup-button :value))))) (create-instance 'popup-special-popup-inter inter:button-interactor (:start-event #\p) (:start-where (list :in demo-popup-button)) (:continuous NIL) (:window demo-popup-win) (:final-function #'(lambda (inter obj) (declare (ignore inter obj)) (kr-send demo-popup-button :special-popup-func demo-popup-button)))) (opal:add-components demo-popup-agg demo-popup-button demo-popup-text demo-popup-text-label) (opal:update demo-popup-win) ) #+garnet-test (defun Popup-Menu-Button-Stop () (opal:destroy demo-popup-win) )
null
https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/gadgets/popup-menu-button.lisp
lisp
Syntax : Common - Lisp ; Package : GARNET - GADGETS ; Base : 10 -*- ; ; This code was written as part of the Garnet project at ;;; ; ; ; ; please contact to be put on the mailing list. ;;; Popup menu from a button Slots: (like those of menu and text-button) :left - default 0 :top - default 0 the string or object in the button. Default is a small bitmap showing a few lines NOTE: do not use these bitmaps directly, but rather use something like (:string (create-instance NIL GG:DOWNARROW-BITMAP)) :items - Items in the pop-up menu :item-to-string-function - Converts items to strings for the menu :v-spacing - default 0 ; of the menu :h-align - default :LEFT ; of the menu :item-font - default opal:default-font ; for the menu strings called with the menu selection :keep-menu-in-screen-p - default T ; if T, then menu will be adjusted if it would go offscreen :position - default :below; where menu pops up. Choices are (can be computed with a formula) the minimum width for the menu for the button for the button for the button Read-Only :value - The value selected in the menu to check if menu's window is non-NIL before continuing gv's. - fixed :string-set-func so can edit label added :string-set-func added :item-to-string-function menu's new :min-menu-width slot doesn't seem to be seeing the s-value return the popped up window This is responsible for determining if the menu is out of the screen or not. If the menu is out of screen at any of the sides, it will reset the :top and :left attributes of the window to place it on the screen. raise calls update Call this function to show the popup-menu. It positions the menu at the given place, pops up the menu, and starts the interactor. make sure is :outside make sure the menu interactor processes the event, so will be :outside This is the popup menu gadget itself. Really it's just a window. A menu gets put inside on initialization. internal slots filled in by initialize with the menu filled in by initialize with the menu's window in case still running selection function, etc. do this after stop-inter will be called when :visible changes This is the initialize method for the popup menu. It automatically creates a menu gadget inside the popup window. the stop event is set to be leftup, which is releasing the mouse button. Then, it sets up the stop action of the menu so that the window is made invisible. turn on all demons change the formula so the menu's width will be bigger if necessary then is the label of the button else must be in the menu This is like the mini-demo function for this gadget. It basically creates a window with a button. Pressing the button will cause a popup window to appear.
Another useful bitmap is GG : DOWNARROW - BITMAP : below , : left , : right or a list of two numbers Designed and written by who stole most of the code from CHANGE LOG : 05/23/94 : window formula in : SELECTOR interactor 04/23/93 - Added : do - not - dump - slots 04/13/93 typo : * screen - height * -- > * screen - width * in Fix - Menu - Out - Of - Screen 03/17/93 - add special - popdown functions for gilt , etc . 03/10/93 typo in : string - set - func ( added opal package prefix to Aggrelist - Edit - String - Func ) 02/10/93 : items of type items - type 01/28/93 : width and : height formulas of menu 12/15/92 - Added type and parameter declarations 10/28/92 : min - menu - width takes advantage of the 10/06/92 - support min - width and fix bugs 10/05/92 load of needed gadgets into loader file 10/04/92 - made work 09/17/92 (in-package "GARNET-GADGETS") (eval-when (:execute :load-toplevel :compile-toplevel) (export '(Popup-Menu-Button lines-bitmap downarrow-bitmap)) #+garnet-test (export '(Popup-Menu-Button-Go Popup-Menu-Button-Stop))) First functions display the submenu from gilt , etc . (defun Put-Down-Garnet-button-Popup (gadget) (let ((win (g-value gadget :menu-window))) (when (schema-p win) (s-value win :visible NIL) (defun Garnet-popup-button-item (gadget) (let ((menu (g-value gadget :menu)) (menuwin (g-value gadget :menu-window))) (SetPopUpMenuPosition gadget menu menuwin) menuwin)) (defun Fix-Menu-Out-Of-Screen (menuwin) (if (< (g-value menuwin :top) 0) (s-value menuwin :top 0) (if (> (+ (g-value menuwin :top) (g-value menuwin :height)) gem:*screen-height*) (s-value menuwin :top (- gem:*screen-height* (g-value menuwin :height))) ) ) (if (< (g-value menuwin :left) 0) (s-value menuwin :left 0) (if (> (+ (g-value menuwin :left) (g-value menuwin :width)) gem:*screen-width*) (s-value menuwin :left (- gem:*screen-width* (g-value menuwin :width))) ) ) ) (defun SetPopUpMenuPosition (popupbutton menu menuwin) (let* ((pos (g-value popupbutton :position)) (shadowoffset (g-value popupbutton :shadow-offset)) x y) (cond ((eq pos :below) (setq x (+ (g-value popupbutton :left) shadowoffset)) (setq y (+ (g-value popupbutton :top) (g-value popupbutton :height)))) ((eq pos :right) (setq x (opal:right popupbutton)) (setq y (- (g-value popupbutton :top) (floor (- (g-value menu :height) (g-value popupbutton :height)) 2) 1))) ((eq pos :left) (setq x (+ (- (g-value popupbutton :left) (g-value menu :width)) shadowoffset 1)) (setq y (- (g-value popupbutton :top) (floor (- (g-value menu :height) (g-value popupbutton :height)) 2)))) ((listp pos) (setq x (car pos)) (setq y (cadr pos))) (T (error ":position argument for ~s must be :below :right :left or list of (x y), but it is ~s" popupbutton pos))) (multiple-value-bind (wx wy) (opal:convert-coordinates (g-value popupbutton :window) x y NIL) (s-value menuwin :left wx) (s-value menuwin :top wy) (when (g-value popupbutton :keep-menu-in-screen-p) (Fix-Menu-Out-Of-Screen menuwin)) (s-value menuwin :visible T) (defun Pop-Up-Pop-Up (popupbutton) (let* ((event inter:*current-event*) (menu (g-value popupbutton :menu)) (menuwin (g-value popupbutton :menu-window))) (SetPopUpMenuPosition popupbutton menu menuwin) (setf (inter:event-window event) menuwin) (setf (inter:event-x event) -10) (inter:start-interactor (g-value menu :selector) event) (inter::general-go (g-value menu :selector) event))) (create-instance 'lines-bitmap opal:bitmap (:image (opal:read-image (merge-pathnames "pop-up-icon-no-border.bm" common-lisp-user::Garnet-Bitmap-Pathname)))) (create-instance 'downarrow-bitmap opal:bitmap (:image (opal:read-image (merge-pathnames "downarrow.bm" common-lisp-user::Garnet-Bitmap-Pathname)))) (create-instance 'Popup-Menu-Button gg:text-button :declare ((:parameters :left :top :string :items :v-spacing :h-align :item-font :keep-menu-in-screen-p :position :min-menu-width :shadow-offset :text-offset :gray-width :selection-function :visible) (:type ((or string (satisfies schema-p)) :string) (items-type :items) (integer :v-spacing :min-menu-width :shadow-offset :text-offset :gray-width) ((member :left :center :right) :h-align) ((or (is-a-p opal:font) (is-a-p opal:font-from-file)) :item-font) (kr-boolean :keep-menu-in-screen-p) ((or (member :below :left :right) list) :position) ((or null function symbol) :selection-function))) (:left 0) (:top 0) (:string #-apple lines-bitmap #+apple "Menu") (:items '("Item 1" "Item 2" "Item 3" "Item 4")) (:v-spacing 0) (:h-align :LEFT) (:title NIL) (:item-font opal:default-font) (:item-to-string-function #'(lambda (item) (if item (if (or (stringp item) (schema-p item)) item (string-capitalize (string-trim ":" item))) ""))) (:selection-function NIL) (:value-obj (o-formula (gvl :menu :value-obj))) (:value (o-formula (gvl :value-obj :string))) (:keep-menu-in-screen-p T) (:position :below) (:min-menu-width 0) (:shadow-offset 2) (:text-offset 3) (:gray-width 2) (:final-feedback-p NIL) (:special-popup-func 'Garnet-popup-button-item) (:special-popdown-func 'Put-Down-Garnet-button-Popup) (:update-slots (cons :visible (g-value gg:text-button :update-slots))) (:interactors `((:text-button-press :modify (:running-where T) (:window ,(o-formula (let* ((oper (gvl :operates-on)) (my-win (gv oper :window)) (menu-win (gv oper :menu-window))) (if (and my-win menu-win) (list my-win menu-win) my-win)))) (:start-action ,#'(lambda (inter button) (call-prototype-method inter button) (pop-up-pop-up button))) (:final-function ,#'(lambda (int val) (declare (ignore val)) (let* ((oper (g-value int :operates-on)) (menu (g-value oper :menu)) (menuinter (g-value menu :selector)) (outside (g-value menuinter :current-state)) val) when is outside , then will abort , so do n't do (unless (eq outside :outside) (s-value oper :value val) (kr-send oper :selection-function oper val))))) )))) (s-value POPUP-MENU-BUTTON :do-not-dump-slots (append '(:menu-window :menu) (g-value POPUP-MENU-BUTTON :do-not-dump-slots))) (define-method :fix-update-slots Popup-Menu-Button (ob) (unless (g-value ob :visible) (Put-Down-Garnet-button-Popup ob)) (call-prototype-method ob)) (create-instance 'popupbuttonmenuproto gg:menu (:left 0) (:top 0) (:popup NIL) (:v-spacing (o-formula (gvl :popup :v-spacing))) (:h-align (o-formula (gvl :popup :h-align))) (:shadow-offset 0) (:text-offset (o-formula (gvl :popup :text-offset))) (:title NIL) (:items (o-formula (gvl :popup :items))) (:item-to-string-function (o-formula (gvl :popup :item-to-string-function))) (:item-font (o-formula (gvl :popup :item-font))) (:min-menu-width (o-formula (gvl :popup :min-menu-width))) (:interactors `((:selector :modify (:window ,(o-formula (let* ((oper (gv-local (gv :self) :operates-on)) (my-win (gv-local oper :window))) (when my-win (let ((button-win (gv oper :popup :window))) (if button-win (list my-win button-win) my-win)))))) (:stop-action ,#'(lambda (int val) (call-prototype-method int val) (let ((window (g-value int :operates-on :window))) (s-value window :visible NIL)))) (:abort-action ,#'(lambda (int val) (call-prototype-method int val) (let ((window (g-value int :operates-on :window))) (s-value window :visible NIL)))))))) Then , it fixes up the interactors in the menu . First , (define-method :initialize Popup-Menu-Button (popup) (let (popmenu window) (call-prototype-method popup) (setq popmenu (create-instance NIL popupbuttonmenuproto (:popup popup))) (setq window (create-instance NIL inter:interactor-window (:omit-title-bar-p T) (:double-buffered-p T) (:save-under T) (:border-width 0) (:menu popmenu) (:aggregate popmenu) (:popup popup) (:modal-p (o-formula (gv-local :self :popup :window :modal-p))) A drawable width or height of 0 causes CLX to crash (:height (o-formula (max 1 (gvl :menu :height)))) (:width (o-formula (max 1 (gvl :menu :width)))) (:visible NIL))) (s-value popup :menu popmenu) (s-value popup :menu-window window) (opal:Update window)))) (define-method :destroy-me Popup-Menu-Button (popup &optional erase) (let ((menu-win (g-value popup :menu-window))) (Put-Down-Garnet-button-Popup popup) (when menu-win (opal:destroy menu-win)) (call-prototype-method popup erase))) (define-method :add-local-item POPUP-MENU-BUTTON (gadget item &rest args) (opal::Gadget-Add-Local-Item gadget item '(:menu :menu-item-list) args)) (define-method :add-item POPUP-MENU-BUTTON (gadget item &rest args) (opal::Gadget-Add-Item gadget item '(:menu :menu-item-list) args)) (define-method :remove-local-item POPUP-MENU-BUTTON (gadget &optional item &key (key #'opal:no-func)) (opal::Gadget-Remove-Local-Item gadget item '(:menu :menu-item-list) key)) (define-method :remove-item POPUP-MENU-BUTTON (gadget &optional item &key (key #'opal:no-func)) (opal::Gadget-Remove-Item gadget item '(:menu :menu-item-list) key)) (s-value POPUP-MENU-BUTTON :change-item (g-value opal:aggrelist :change-item)) (s-value POPUP-MENU-BUTTON :remove-nth-item (g-value opal:aggrelist :remove-nth-item)) (define-method :string-set-func POPUP-MENU-BUTTON (gadget-obj str-obj final-event final-string) (if (eq str-obj (g-value gadget-obj :text)) (s-value gadget-obj :string final-string) T) (let ((aggrel (g-value gadget-obj :MENU :MENU-ITEM-LIST))) (opal::Aggrelist-Edit-String-Func gadget-obj aggrel str-obj final-event final-string :rank)))) #+garnet-test (defun Popup-Menu-Button-Go () (create-instance 'demo-popup-win inter:interactor-window (:title "Popup Menu Button Demo") (:left 100) (:top 100) (:height 90) (:width 180)) (create-instance 'demo-popup-agg opal:aggregate) (s-value demo-popup-win :aggregate demo-popup-agg) (opal:update demo-popup-win) (create-instance 'demo-popup-text-label opal:text (:top 50) (:left 15) (:string "Selected: ")) (create-instance 'demo-popup-button Popup-Menu-Button (:left 15) (:top 10) (:string "foo") (:items '("Red" "Blue" "Green" "Yellow" "Aquamarine" "Cyan" "Fluorescent")) (:selection-function #'(lambda (g v) (declare (ignore g)) (format T "Selected is ~s~%" v)))) (create-instance 'demo-popup-text opal:text (:top 50) (:left (o-formula (+ (g-value demo-popup-text-label :left) (g-value demo-popup-text-label :width)))) (:string (o-formula (format NIL "~s" (gv demo-popup-button :value))))) (create-instance 'popup-special-popup-inter inter:button-interactor (:start-event #\p) (:start-where (list :in demo-popup-button)) (:continuous NIL) (:window demo-popup-win) (:final-function #'(lambda (inter obj) (declare (ignore inter obj)) (kr-send demo-popup-button :special-popup-func demo-popup-button)))) (opal:add-components demo-popup-agg demo-popup-button demo-popup-text demo-popup-text-label) (opal:update demo-popup-win) ) #+garnet-test (defun Popup-Menu-Button-Stop () (opal:destroy demo-popup-win) )
2f8ecbacbbc56b387bf28df30966d83beb7e63105549ad9fb328a6483673164d
nikomatsakis/a-mir-formality
coherence--issue-99940.rkt
#lang racket (require redex/reduction-semantics "../../util.rkt" "../grammar.rkt" "../prove.rkt" "../libcore.rkt" ) (module+ test (redex-let* formality-rust [] ; Test from this comment: ; -lang/rust/issues/99940#issuecomment-1201504984 ; The test has one impl for ` < ( ) as Assoc>::Ty ` and one impl for ` ` . In the downstream crate , we are not able to prove that ` < ( ) as Assoc>::Ty = = is ; false in coherence-mode: we get back ambiguous. This is weaker than necessary, in some sense, ; because an impl DOES exist for `<() as Assoc>::Ty` and it cannot be taken back, but it falls ; out from the way we've setup the coherence-mode structure. (traced '() (test-equal (term (rust:is-program-ok ([(crate one { (trait Assoc[] where [] { (type Ty[] : [] where [])}) (impl[] Assoc[] for () where [] { (type Ty[] = () where [])}) (trait Trait[] where [] {}) (impl[] Trait[] for (< () as Assoc[] > :: Ty[]) where [] {}) }) (crate two { (struct LocalTy[] where [] {}) (impl[] Trait[] for (LocalTy < >) where [] {}) })] two))) #f )) Related test : one crate ( to sidestep orphan rule restrictions ) using a ` Mirror ` trait where ` < T as Mirror>::Ty ` normalizes to ` T ` . ; In this case , we have one impl for ` < ( ) as Mirror>::Ty ` and for ` u32 ` . Should be ok . (traced '() (test-equal (term (rust:is-program-ok ([(crate one { (trait Mirror[] where [] { (type Ty[] : [] where [])}) (impl[(type T)] Mirror[] for T where [] { (type Ty[] = T where [])}) (trait Trait[] where [] {}) (impl[] Trait[] for (< () as Mirror[] > :: Ty[]) where [] {}) (impl[] Trait[] for u32 where [] {}) }) ] one))) #t )) Another mirror test , but with ` < ( ) as Mirror>::Ty ` and for ` ( ) ` . Should not be ok . (traced '() (test-equal (term (rust:is-program-ok ([(crate one { (trait Mirror[] where [] { (type Ty[] : [] where [])}) (impl[(type T)] Mirror[] for T where [] { (type Ty[] = T where [])}) (trait Trait[] where [] {}) (impl[] Trait[] for (< () as Mirror[] > :: Ty[]) where [] {}) (impl[] Trait[] for () where [] {}) }) ] one))) #f )) ) )
null
https://raw.githubusercontent.com/nikomatsakis/a-mir-formality/262bcefa6d7e9cad708b58560a875c7ae9d21425/racket-src/rust/test/coherence--issue-99940.rkt
racket
Test from this comment: false in coherence-mode: we get back ambiguous. This is weaker than necessary, in some sense, because an impl DOES exist for `<() as Assoc>::Ty` and it cannot be taken back, but it falls out from the way we've setup the coherence-mode structure.
#lang racket (require redex/reduction-semantics "../../util.rkt" "../grammar.rkt" "../prove.rkt" "../libcore.rkt" ) (module+ test (redex-let* formality-rust [] -lang/rust/issues/99940#issuecomment-1201504984 The test has one impl for ` < ( ) as Assoc>::Ty ` and one impl for ` ` . In the downstream crate , we are not able to prove that ` < ( ) as Assoc>::Ty = = is (traced '() (test-equal (term (rust:is-program-ok ([(crate one { (trait Assoc[] where [] { (type Ty[] : [] where [])}) (impl[] Assoc[] for () where [] { (type Ty[] = () where [])}) (trait Trait[] where [] {}) (impl[] Trait[] for (< () as Assoc[] > :: Ty[]) where [] {}) }) (crate two { (struct LocalTy[] where [] {}) (impl[] Trait[] for (LocalTy < >) where [] {}) })] two))) #f )) Related test : one crate ( to sidestep orphan rule restrictions ) using a ` Mirror ` trait where ` < T as Mirror>::Ty ` normalizes to ` T ` . In this case , we have one impl for ` < ( ) as Mirror>::Ty ` and for ` u32 ` . Should be ok . (traced '() (test-equal (term (rust:is-program-ok ([(crate one { (trait Mirror[] where [] { (type Ty[] : [] where [])}) (impl[(type T)] Mirror[] for T where [] { (type Ty[] = T where [])}) (trait Trait[] where [] {}) (impl[] Trait[] for (< () as Mirror[] > :: Ty[]) where [] {}) (impl[] Trait[] for u32 where [] {}) }) ] one))) #t )) Another mirror test , but with ` < ( ) as Mirror>::Ty ` and for ` ( ) ` . Should not be ok . (traced '() (test-equal (term (rust:is-program-ok ([(crate one { (trait Mirror[] where [] { (type Ty[] : [] where [])}) (impl[(type T)] Mirror[] for T where [] { (type Ty[] = T where [])}) (trait Trait[] where [] {}) (impl[] Trait[] for (< () as Mirror[] > :: Ty[]) where [] {}) (impl[] Trait[] for () where [] {}) }) ] one))) #f )) ) )
30db192d9ae8e2683e0ec90c1329d02ffc2570771aedfbddaed399bcccd464ca
sqd/haskell-C89-interpreter
Interpret.hs
module Interpret( run )where import Grammar import Utils import Runtime import Value import Definition import Type import Storage import Parse import Control.Applicative import Control.Monad hiding (void) import qualified Data.Map.Strict as M import Data.List import Data.Maybe import Control.Exception.Base type SymbolTable = M.Map Identifier Id data State = State Memory (Stack SymbolTable) deriving Show declareVar :: Program -> State -> VariableDeclaration -> IO State declareVar p s (VarDecl type' name init') = do (v, newS) <- if isJust init' then initialize p s $ fromJust init' else return (defaultVal type', s) return $ newVar newS name v declareArr :: Program -> State -> VariableDeclaration -> IO State declareArr p s@(State mem _) (ArrDecl type' name size init') = do (RVal _ size', State newMem table) <- computeExp p s size let sizeVal = read size' :: Int let (newNewMem, ptr) = blockAllocate newMem (defaultVal type') sizeVal let (Type typeName ptrLv) = type' let newState = newVar (State newNewMem table) name (RVal (Type typeName (ptrLv + 1)) (show ptr)) -- TODO: initialization return newState pushScope :: State -> State pushScope (State m s) = State m $ push (M.empty) s popScope :: State -> State popScope (State m s) = State (M.foldl (\m i -> free m i) m $ top s) $ pop s toRVal :: State -> Value -> Value toRVal s@(State m _) (LVal i) = toRVal s $ readMem m i toRVal _ x = x isLVal (LVal _) = True isLVal _ = False isRVal = not . isLVal -- Return left value getVar :: State -> Identifier -> Value getVar (State m s) x = LVal $ work s x where work s' x' = if x' `M.member` top s' then (top s') M.! x' else work (pop s') x' -- Follow left value link follow :: Memory -> Id -> Id follow m t = case readMem m t of LVal k -> follow m k _ -> t -- If identifier is a left value, follow the link modifyVar :: State -> Identifier -> (Value -> Value) -> State modifyVar state@(State m s) x f = State (modify m i f) s where i = let LVal k = getVar state x in follow m k -- Return right value getVal :: State -> Identifier -> Value getVal s = toRVal s . getVar s newVar :: State -> Identifier -> Value -> State newVar state@(State m s) n v = let (newM, i) = allocate m v in State newM $ updateTop (M.insert n i) s data StructureRt = Breaked | Normal | Continued | Returned Value deriving Eq rt2Value :: StructureRt -> Value rt2Value (Returned v) = v rt2Value _ = void -- Run a program Input : Program , Entry function , -- run :: Program -> Identifier -> [Value] -> IO Value run p@(Program _ _ vars ) entry args = fst < $ > computeFunc p initialState ( getFunc p entry ) args where run p@(Program fs ss vars) entry args = computeFunc newP initialState (getFunc newP entry) args where newP = Program (fs ++ compileDarkMagicBook darkMagicBook ++ magicBook) ss vars initialState = State newMem empty getFunc :: Program -> Identifier -> FunctionDefinition getFunc (Program fs _ _) n = fromJust $ find (\(FuncDef x _ _ _) -> x == n) fs computeFunc :: Program -> State -> FunctionDefinition -> [Value] -> IO (Value, State) computeFunc p s (FuncDef name rtType paras ins) args = do let lrVal = if isDarkMagic name then id else map $ toRVal s let cast = if isDarkMagic name then flip const else typeCast let argVals = zipWith (\(t, n) v -> (n, cast t v)) paras $ lrVal args let state = foldl (uncurry . newVar) (pushScope s) argVals snd' popScope <$> fst' (cast rtType . rt2Value) <$> runStructure p state ins -- Really smelly hack, but I doubt if I can bypass it without thorough modifications computeArgs :: Program -> State -> [Exp] -> IO ([Value], State) computeArgs _ s [] = return ([], s) computeArgs p s (x:xs) = do (v, newS) <- computeExp p s x fst' (v:) <$> computeArgs p newS xs -- Return Left Value if Possible computeExp :: Program -> State -> Exp -> IO (Value, State) computeExp p s (Constant x) | x `elem` ["true", "false"] = return (RVal boolType x, s) | isValidIdentifier x = return (getVar s x, s) | otherwise = return (RVal Polymorphism x, s) computeExp p s (Exp "?" args) = undefined -- lazy trinary computeExp p s (Exp f args) = do (para, newS) <- computeArgs p s args computeFunc p newS (getFunc p f) para runStructure :: Program -> State -> [Structure] -> IO (StructureRt, State) runStructure _ s [] = return (Normal, s) runStructure p _s (t:ts) = handler _s t where handler :: State -> Structure -> IO (StructureRt, State) handler = case t of IfBlock _ _ _ -> runIfBlock WhileBlock _ _ -> runWhileBlock DoWhileBlock _ _ -> runDoWhileBlock ForBlock _ _ _ _ -> runForBlock Expression _ -> runExpression Declaration _ -> runDeclaration UCJump _ -> runUCJump DarkMagic _ -> runDarkMagic where runIfBlock s (IfBlock con pri alt) = do (conVal, newS) <- computeExp p (pushScope s) con (rt, newerS) <- if isTrue $ toRVal newS conVal then snd' popScope <$> runStructure p newS pri else runStructure p newS alt if rt `elem` [Normal, Breaked] then snd' popScope <$> runStructure p newerS ts else return (rt, popScope newerS) runWhileBlock s (WhileBlock con body) = snd' popScope <$> (loop $ pushScope s) where loop :: State -> IO (StructureRt, State) loop state = do (conVal, newS) <- computeExp p state con if isTrue conVal then do (rt, newS) <- runStructure p newS body case rt of Normal -> loop newS Breaked -> runStructure p newS ts k@(Returned _) -> return (k, newS) else runStructure p newS ts runDoWhileBlock s (DoWhileBlock con body) = snd' popScope <$> runStructure p (pushScope s) (body ++ [WhileBlock con body]) runForBlock s (ForBlock init' con delta body) = do (init', newS) <- computeExp p s init' runWhileBlock newS $ WhileBlock con (body ++ [Expression delta]) runExpression s (Expression exp) = do (_, newS) <- computeExp p s exp runStructure p newS ts runDeclaration s (Declaration decl) = do newS <- (case decl of (VarDecl _ _ _) -> declareVar (ArrDecl _ _ _ _) -> declareArr) p s decl runStructure p newS ts runUCJump s (UCJump Break) = return (Breaked, s) runUCJump s (UCJump Continue) = return (Continued, s) runUCJump s (UCJump (Return exp)) = do (v, newS) <- computeExp p s exp return (Returned $ toRVal newS v, newS) runDarkMagic s (DarkMagic curse) = fst' Returned <$> getDarkMagic curse s initialize :: Program -> State -> VarInit -> IO (Value, State) initialize p s (InitExp exp) = computeExp p s exp type Magic = State -> IO (Value, State) uselessMagic s = return (void, s) getDarkMagic :: Identifier -> Magic getDarkMagic = (M.!) _darkMagic _darkMagic = M.fromList $ map (\(n, it ,im) -> (n, im)) darkMagicBook isDarkMagic s = (not $ isValidIdentifier s) || s `M.member` _darkMagic -- (Name, Interface, Implement) darkMagicBook :: [(Identifier, FunctionDefinition, Magic)] darkMagicBook = [("/", divide, divideMagic), ("+", add, addMagic), ("-neg", neg, negMagic), ("=", assign, assignMagic), ("debuginfo", debugInfo, debugInfoMagic), ("debugprint", debugPrint, debugPrintMagic), ("&addr", addr, addrMagic), ("*deref", deref, derefMagic), ("print", print_, printMagic), ("input", input, inputMagic), ("*", multi, multiMagic), ("==", eq, eqMagic), ("<", less, lessMagic), ("!", logNeg, logNegMagic), ("&&", logAnd, logAndMagic), ("||", logOr, logOrMagic), ("-=", minusAssign, uselessMagic), ("+=", plusAssign, uselessMagic), ("*=", multiAssign, uselessMagic), ("/=", divideAssign, uselessMagic), ("--suf", suffixDec, uselessMagic), ("++suf", suffixInc, uselessMagic), ("--pre", prefixDec, uselessMagic), ("++pre", prefixInc, uselessMagic)] compileDarkMagicBook = map (\(n, it, im) -> it) add = FuncDef "+" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "+"] addMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (RVal intType $ show (read a + read b :: Integer), s) divide = FuncDef "/" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "/"] divideMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (RVal intType $ show (read a `div` read b :: Integer), s) -- TODO: support float plusAssign = FuncDef "+=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] $ parseFuncBody "a=a+b;return a;" minusAssign = FuncDef "-=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] $ parseFuncBody "a=a-b;return a;" multiAssign = FuncDef "*=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] $ parseFuncBody "a=a*b;return a;" divideAssign = FuncDef "/=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] $ parseFuncBody "a=a/b;return a;" prefixInc = FuncDef "++pre" Polymorphism [(Polymorphism, "a")] $ parseFuncBody "a+=1;return a;" prefixDec = FuncDef "--pre" Polymorphism [(Polymorphism, "a")] $ parseFuncBody "a-=1;return a;" suffixInc = FuncDef "++suf" Polymorphism [(Polymorphism, "a")] $ parseFuncBody "a+=1;return a-1;" suffixDec = FuncDef "--suf" Polymorphism [(Polymorphism, "a")] $ parseFuncBody "a-=1;return a+1;" multi = FuncDef "*" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "*"] multiMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (RVal intType $ show (read a * read b :: Integer), s) eq = FuncDef "==" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "=="] eqMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (if a == b then true else false, s) less = FuncDef "<" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "<"] lessMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (if (read a :: Integer) < (read b :: Integer) then true else false, s) neg = FuncDef "-neg" Polymorphism [(Polymorphism, "a")] [DarkMagic "-neg"] negMagic s = let RVal _ a = getVal s "a" in return (RVal intType $ show (- read a :: Integer), s) logNeg = FuncDef "!" Polymorphism [(Polymorphism, "a")] [DarkMagic "!"] logNegMagic s = let b = toBool $ getVal s "a" in return (if b == true then false else true, s) logAnd = FuncDef "&&" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "&&"] logAndMagic s = let a = toBool $ getVal s "a"; b = toBool $ getVal s "b" in return (if a == true && b == true then true else false, s) logOr = FuncDef "||" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "||"] logOrMagic s = let a = toBool $ getVal s "a"; b = toBool $ getVal s "b" in return (if a == true || b == true then true else false, s) assign = FuncDef "=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "="] assignMagic s = let var = getVar s "a"; val@(RVal _ _) = getVal s "b" in return (var, modifyVar s "a" (return val)) debugInfo = FuncDef "debuginfo" voidType [] [DarkMagic "debuginfo"] debugInfoMagic s = (print $ popScope s) >> return (void, s) debugPrint = FuncDef "debugprint" voidType [(Polymorphism, "a")] [DarkMagic "debugprint"] debugPrintMagic s@(State m t) = (print $ getVar s "a") >> return (void, s) addr = FuncDef "&addr" Polymorphism [(Polymorphism, "a")] [DarkMagic "&addr"] addrMagic s@(State m _) = let LVal i = getVar s "a" in return (RVal (makePtr "void" 1) $ show $ follow m i, s) deref = FuncDef "*deref" Polymorphism [(Polymorphism, "a")] [DarkMagic "*deref"] derefMagic s@(State m _) = let RVal _ a = getVal s "a" in return (LVal $ follow m (read a :: Id), s) print_ = FuncDef "print" voidType [(Polymorphism, "a")] [DarkMagic "print"] printMagic s = let RVal _ x = getVal s "a" in putStrLn x >> return (void, s) input = FuncDef "input" Polymorphism [] [DarkMagic "input"] inputMagic s = do x <- getString return (RVal Polymorphism x, s) magicBook = writeMagicBook theStandardBookOfSpell writeMagicBook :: [(Identifier, String)] -> [FunctionDefinition] writeMagicBook spells = (\(name, s) -> let Program [f] _ _ = parse s in let FuncDef _ rt args ins = f in FuncDef name rt args ins) <$> spells theStandardBookOfSpell = [("-", "int f(int a,int b){return a+(-b);}"), ("!=", "int f(int a,int b){return !(a==b);}"), ("<=", "int f(int a,int b){return (a<b)||(a==b);}"), (">", "int f(int a,int b){return !(a<=b);}"), (">=", "int f(int a,int b){return (a>b)||(a==b);}"), (",", "int f(int a,int b){return b;}")]
null
https://raw.githubusercontent.com/sqd/haskell-C89-interpreter/cd0cd344cf07eba29a906b62fb31ea120adfca86/Interpret.hs
haskell
TODO: initialization Return left value Follow left value link If identifier is a left value, follow the link Return right value Run a program run :: Program -> Identifier -> [Value] -> IO Value Really smelly hack, but I doubt if I can bypass it without thorough modifications Return Left Value if Possible lazy trinary (Name, Interface, Implement) TODO: support float
module Interpret( run )where import Grammar import Utils import Runtime import Value import Definition import Type import Storage import Parse import Control.Applicative import Control.Monad hiding (void) import qualified Data.Map.Strict as M import Data.List import Data.Maybe import Control.Exception.Base type SymbolTable = M.Map Identifier Id data State = State Memory (Stack SymbolTable) deriving Show declareVar :: Program -> State -> VariableDeclaration -> IO State declareVar p s (VarDecl type' name init') = do (v, newS) <- if isJust init' then initialize p s $ fromJust init' else return (defaultVal type', s) return $ newVar newS name v declareArr :: Program -> State -> VariableDeclaration -> IO State declareArr p s@(State mem _) (ArrDecl type' name size init') = do (RVal _ size', State newMem table) <- computeExp p s size let sizeVal = read size' :: Int let (newNewMem, ptr) = blockAllocate newMem (defaultVal type') sizeVal let (Type typeName ptrLv) = type' let newState = newVar (State newNewMem table) name (RVal (Type typeName (ptrLv + 1)) (show ptr)) return newState pushScope :: State -> State pushScope (State m s) = State m $ push (M.empty) s popScope :: State -> State popScope (State m s) = State (M.foldl (\m i -> free m i) m $ top s) $ pop s toRVal :: State -> Value -> Value toRVal s@(State m _) (LVal i) = toRVal s $ readMem m i toRVal _ x = x isLVal (LVal _) = True isLVal _ = False isRVal = not . isLVal getVar :: State -> Identifier -> Value getVar (State m s) x = LVal $ work s x where work s' x' = if x' `M.member` top s' then (top s') M.! x' else work (pop s') x' follow :: Memory -> Id -> Id follow m t = case readMem m t of LVal k -> follow m k _ -> t modifyVar :: State -> Identifier -> (Value -> Value) -> State modifyVar state@(State m s) x f = State (modify m i f) s where i = let LVal k = getVar state x in follow m k getVal :: State -> Identifier -> Value getVal s = toRVal s . getVar s newVar :: State -> Identifier -> Value -> State newVar state@(State m s) n v = let (newM, i) = allocate m v in State newM $ updateTop (M.insert n i) s data StructureRt = Breaked | Normal | Continued | Returned Value deriving Eq rt2Value :: StructureRt -> Value rt2Value (Returned v) = v rt2Value _ = void Input : Program , Entry function , run p@(Program _ _ vars ) entry args = fst < $ > computeFunc p initialState ( getFunc p entry ) args where run p@(Program fs ss vars) entry args = computeFunc newP initialState (getFunc newP entry) args where newP = Program (fs ++ compileDarkMagicBook darkMagicBook ++ magicBook) ss vars initialState = State newMem empty getFunc :: Program -> Identifier -> FunctionDefinition getFunc (Program fs _ _) n = fromJust $ find (\(FuncDef x _ _ _) -> x == n) fs computeFunc :: Program -> State -> FunctionDefinition -> [Value] -> IO (Value, State) computeFunc p s (FuncDef name rtType paras ins) args = do let lrVal = if isDarkMagic name then id else map $ toRVal s let cast = if isDarkMagic name then flip const else typeCast let argVals = zipWith (\(t, n) v -> (n, cast t v)) paras $ lrVal args let state = foldl (uncurry . newVar) (pushScope s) argVals snd' popScope <$> fst' (cast rtType . rt2Value) <$> runStructure p state ins computeArgs :: Program -> State -> [Exp] -> IO ([Value], State) computeArgs _ s [] = return ([], s) computeArgs p s (x:xs) = do (v, newS) <- computeExp p s x fst' (v:) <$> computeArgs p newS xs computeExp :: Program -> State -> Exp -> IO (Value, State) computeExp p s (Constant x) | x `elem` ["true", "false"] = return (RVal boolType x, s) | isValidIdentifier x = return (getVar s x, s) | otherwise = return (RVal Polymorphism x, s) computeExp p s (Exp f args) = do (para, newS) <- computeArgs p s args computeFunc p newS (getFunc p f) para runStructure :: Program -> State -> [Structure] -> IO (StructureRt, State) runStructure _ s [] = return (Normal, s) runStructure p _s (t:ts) = handler _s t where handler :: State -> Structure -> IO (StructureRt, State) handler = case t of IfBlock _ _ _ -> runIfBlock WhileBlock _ _ -> runWhileBlock DoWhileBlock _ _ -> runDoWhileBlock ForBlock _ _ _ _ -> runForBlock Expression _ -> runExpression Declaration _ -> runDeclaration UCJump _ -> runUCJump DarkMagic _ -> runDarkMagic where runIfBlock s (IfBlock con pri alt) = do (conVal, newS) <- computeExp p (pushScope s) con (rt, newerS) <- if isTrue $ toRVal newS conVal then snd' popScope <$> runStructure p newS pri else runStructure p newS alt if rt `elem` [Normal, Breaked] then snd' popScope <$> runStructure p newerS ts else return (rt, popScope newerS) runWhileBlock s (WhileBlock con body) = snd' popScope <$> (loop $ pushScope s) where loop :: State -> IO (StructureRt, State) loop state = do (conVal, newS) <- computeExp p state con if isTrue conVal then do (rt, newS) <- runStructure p newS body case rt of Normal -> loop newS Breaked -> runStructure p newS ts k@(Returned _) -> return (k, newS) else runStructure p newS ts runDoWhileBlock s (DoWhileBlock con body) = snd' popScope <$> runStructure p (pushScope s) (body ++ [WhileBlock con body]) runForBlock s (ForBlock init' con delta body) = do (init', newS) <- computeExp p s init' runWhileBlock newS $ WhileBlock con (body ++ [Expression delta]) runExpression s (Expression exp) = do (_, newS) <- computeExp p s exp runStructure p newS ts runDeclaration s (Declaration decl) = do newS <- (case decl of (VarDecl _ _ _) -> declareVar (ArrDecl _ _ _ _) -> declareArr) p s decl runStructure p newS ts runUCJump s (UCJump Break) = return (Breaked, s) runUCJump s (UCJump Continue) = return (Continued, s) runUCJump s (UCJump (Return exp)) = do (v, newS) <- computeExp p s exp return (Returned $ toRVal newS v, newS) runDarkMagic s (DarkMagic curse) = fst' Returned <$> getDarkMagic curse s initialize :: Program -> State -> VarInit -> IO (Value, State) initialize p s (InitExp exp) = computeExp p s exp type Magic = State -> IO (Value, State) uselessMagic s = return (void, s) getDarkMagic :: Identifier -> Magic getDarkMagic = (M.!) _darkMagic _darkMagic = M.fromList $ map (\(n, it ,im) -> (n, im)) darkMagicBook isDarkMagic s = (not $ isValidIdentifier s) || s `M.member` _darkMagic darkMagicBook :: [(Identifier, FunctionDefinition, Magic)] darkMagicBook = [("/", divide, divideMagic), ("+", add, addMagic), ("-neg", neg, negMagic), ("=", assign, assignMagic), ("debuginfo", debugInfo, debugInfoMagic), ("debugprint", debugPrint, debugPrintMagic), ("&addr", addr, addrMagic), ("*deref", deref, derefMagic), ("print", print_, printMagic), ("input", input, inputMagic), ("*", multi, multiMagic), ("==", eq, eqMagic), ("<", less, lessMagic), ("!", logNeg, logNegMagic), ("&&", logAnd, logAndMagic), ("||", logOr, logOrMagic), ("-=", minusAssign, uselessMagic), ("+=", plusAssign, uselessMagic), ("*=", multiAssign, uselessMagic), ("/=", divideAssign, uselessMagic), ("--suf", suffixDec, uselessMagic), ("++suf", suffixInc, uselessMagic), ("--pre", prefixDec, uselessMagic), ("++pre", prefixInc, uselessMagic)] compileDarkMagicBook = map (\(n, it, im) -> it) add = FuncDef "+" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "+"] addMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (RVal intType $ show (read a + read b :: Integer), s) divide = FuncDef "/" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "/"] divideMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (RVal intType $ show (read a `div` read b :: Integer), s) plusAssign = FuncDef "+=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] $ parseFuncBody "a=a+b;return a;" minusAssign = FuncDef "-=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] $ parseFuncBody "a=a-b;return a;" multiAssign = FuncDef "*=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] $ parseFuncBody "a=a*b;return a;" divideAssign = FuncDef "/=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] $ parseFuncBody "a=a/b;return a;" prefixInc = FuncDef "++pre" Polymorphism [(Polymorphism, "a")] $ parseFuncBody "a+=1;return a;" prefixDec = FuncDef "--pre" Polymorphism [(Polymorphism, "a")] $ parseFuncBody "a-=1;return a;" suffixInc = FuncDef "++suf" Polymorphism [(Polymorphism, "a")] $ parseFuncBody "a+=1;return a-1;" suffixDec = FuncDef "--suf" Polymorphism [(Polymorphism, "a")] $ parseFuncBody "a-=1;return a+1;" multi = FuncDef "*" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "*"] multiMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (RVal intType $ show (read a * read b :: Integer), s) eq = FuncDef "==" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "=="] eqMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (if a == b then true else false, s) less = FuncDef "<" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "<"] lessMagic s = let RVal _ a = getVal s "a"; RVal _ b = getVal s "b" in return (if (read a :: Integer) < (read b :: Integer) then true else false, s) neg = FuncDef "-neg" Polymorphism [(Polymorphism, "a")] [DarkMagic "-neg"] negMagic s = let RVal _ a = getVal s "a" in return (RVal intType $ show (- read a :: Integer), s) logNeg = FuncDef "!" Polymorphism [(Polymorphism, "a")] [DarkMagic "!"] logNegMagic s = let b = toBool $ getVal s "a" in return (if b == true then false else true, s) logAnd = FuncDef "&&" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "&&"] logAndMagic s = let a = toBool $ getVal s "a"; b = toBool $ getVal s "b" in return (if a == true && b == true then true else false, s) logOr = FuncDef "||" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "||"] logOrMagic s = let a = toBool $ getVal s "a"; b = toBool $ getVal s "b" in return (if a == true || b == true then true else false, s) assign = FuncDef "=" Polymorphism [(Polymorphism, "a"), (Polymorphism, "b")] [DarkMagic "="] assignMagic s = let var = getVar s "a"; val@(RVal _ _) = getVal s "b" in return (var, modifyVar s "a" (return val)) debugInfo = FuncDef "debuginfo" voidType [] [DarkMagic "debuginfo"] debugInfoMagic s = (print $ popScope s) >> return (void, s) debugPrint = FuncDef "debugprint" voidType [(Polymorphism, "a")] [DarkMagic "debugprint"] debugPrintMagic s@(State m t) = (print $ getVar s "a") >> return (void, s) addr = FuncDef "&addr" Polymorphism [(Polymorphism, "a")] [DarkMagic "&addr"] addrMagic s@(State m _) = let LVal i = getVar s "a" in return (RVal (makePtr "void" 1) $ show $ follow m i, s) deref = FuncDef "*deref" Polymorphism [(Polymorphism, "a")] [DarkMagic "*deref"] derefMagic s@(State m _) = let RVal _ a = getVal s "a" in return (LVal $ follow m (read a :: Id), s) print_ = FuncDef "print" voidType [(Polymorphism, "a")] [DarkMagic "print"] printMagic s = let RVal _ x = getVal s "a" in putStrLn x >> return (void, s) input = FuncDef "input" Polymorphism [] [DarkMagic "input"] inputMagic s = do x <- getString return (RVal Polymorphism x, s) magicBook = writeMagicBook theStandardBookOfSpell writeMagicBook :: [(Identifier, String)] -> [FunctionDefinition] writeMagicBook spells = (\(name, s) -> let Program [f] _ _ = parse s in let FuncDef _ rt args ins = f in FuncDef name rt args ins) <$> spells theStandardBookOfSpell = [("-", "int f(int a,int b){return a+(-b);}"), ("!=", "int f(int a,int b){return !(a==b);}"), ("<=", "int f(int a,int b){return (a<b)||(a==b);}"), (">", "int f(int a,int b){return !(a<=b);}"), (">=", "int f(int a,int b){return (a>b)||(a==b);}"), (",", "int f(int a,int b){return b;}")]
b2d10c27089e9cf0bc253ab4f6e9189054b78f0751863a2373c8985fed36d27a
logseq/mldoc
document.ml
open Prelude open Type type toc = toc_item list [@@deriving yojson] and toc_item = { title : Inline.t_with_pos list ; level : int ; anchor : string ; numbering : int list ; items : toc } type directives = (string * string) list [@@deriving yojson] * A document is : - some content before the first heading - a list of top - level headings - a list of directive - the footnotes inside the beginning of the file . A document is: - some content before the first heading - a list of top-level headings - a list of directive - the footnotes inside the beginning of the file. *) type t = { filename : string option (** The filename the document was parsed from *) ; blocks : blocks (** Blocks content *) ; directives : directives (** The directives present in the file *) ; title : string option [@default None] (** The document's title *) ; subtitle : string option [@default None] (** The document's subtitle *) ; author : string option [@default None] (** The document's author *) ; toc : toc (** Table of content *) } [@@deriving yojson] exception Non_timestamp let get_timestamps inlines = let open Inline in try List.fold_left (fun acc t -> match t with | Timestamp t -> t :: acc | Break_Line | Hard_Break_Line -> acc | _ -> raise Non_timestamp) [] inlines with Non_timestamp -> [] let compute_heading_numbering level toc = match toc with | [] -> [ 1 ] | p :: _ -> if p.level = level then drop_last 1 p.numbering @ [ last p.numbering + 1 ] else if p.level < level then (* child *) p.numbering @ [ 1 ] else (* breakout *) let diff = p.level - level in let offset = List.length p.numbering - (diff + 1) in let before, after = split_n offset p.numbering in before @ [ List.hd after + 1 ] let ast_to_json ast = toc_item_to_yojson ast |> Yojson.Safe.to_string let rec toc_append_item parent depth item = if depth = 1 then { parent with items = parent.items @ [ item ] } else let item = let parent' = last parent.items in toc_append_item parent' (depth - 1) item in { parent with items = drop_last 1 parent.items @ [ item ] } let toc_tree items = let rec go acc = function | [] -> List.rev acc | ({ numbering; _ } as h) :: tl -> ( match List.length numbering with | 1 -> (* parent *) go (h :: acc) tl | _ -> (* child *) let parent = List.hd acc in let depth = List.length numbering - 1 in let parent = toc_append_item parent depth h in go (parent :: List.tl acc) tl) in go [] items let from_ast filename ast = let find_directive directives k = try let r = List.assoc k directives in Some r with Not_found -> None in let rec aut directives blocks toc = function | [] -> (List.rev directives, List.rev blocks, List.rev toc) | (h, pos_meta) :: tl -> ( let update_meta f = match blocks with | (Heading heading, pos_meta) :: _tl -> (Heading (f heading), pos_meta) :: List.tl blocks | _ -> (h, pos_meta) :: blocks in match h with | Directive (k, v) -> let directives = (k, v) :: directives in aut directives blocks toc tl | Heading { title ; tags ; marker ; level ; priority ; anchor ; meta ; unordered ; size ; _ } -> let numbering = compute_heading_numbering level toc in let h = Heading { title ; tags ; marker ; level ; priority ; anchor ; meta ; numbering = Some numbering ; unordered ; size } in let toc_item = { title; level; anchor; numbering; items = [] } in aut directives ((h, pos_meta) :: blocks) (toc_item :: toc) tl | Paragraph inlines -> let blocks = match get_timestamps (Type_op.inline_list_strip_pos inlines) with | [] -> (h, pos_meta) :: blocks | timestamps -> update_meta (fun heading -> let timestamps' = List.append timestamps heading.meta.timestamps in { heading with meta = { heading.meta with timestamps = timestamps' } }) in aut directives blocks toc tl | Property_Drawer properties -> let blocks = update_meta (fun heading -> { heading with meta = { heading.meta with properties } }) in aut directives blocks toc tl | _ -> aut directives ((h, pos_meta) :: blocks) toc tl) in let directives, blocks, toc = aut [] [] [] ast in { filename ; directives ; blocks ; title = find_directive directives "TITLE" ; subtitle = find_directive directives "SUBTITLE" ; author = find_directive directives "AUTHOR" ; toc = toc_tree toc }
null
https://raw.githubusercontent.com/logseq/mldoc/376bcdca3fef551d233ce8ebdc618e06edfe2e44/lib/document.ml
ocaml
* The filename the document was parsed from * Blocks content * The directives present in the file * The document's title * The document's subtitle * The document's author * Table of content child breakout parent child
open Prelude open Type type toc = toc_item list [@@deriving yojson] and toc_item = { title : Inline.t_with_pos list ; level : int ; anchor : string ; numbering : int list ; items : toc } type directives = (string * string) list [@@deriving yojson] * A document is : - some content before the first heading - a list of top - level headings - a list of directive - the footnotes inside the beginning of the file . A document is: - some content before the first heading - a list of top-level headings - a list of directive - the footnotes inside the beginning of the file. *) type t = } [@@deriving yojson] exception Non_timestamp let get_timestamps inlines = let open Inline in try List.fold_left (fun acc t -> match t with | Timestamp t -> t :: acc | Break_Line | Hard_Break_Line -> acc | _ -> raise Non_timestamp) [] inlines with Non_timestamp -> [] let compute_heading_numbering level toc = match toc with | [] -> [ 1 ] | p :: _ -> if p.level = level then drop_last 1 p.numbering @ [ last p.numbering + 1 ] else if p.level < level then p.numbering @ [ 1 ] else let diff = p.level - level in let offset = List.length p.numbering - (diff + 1) in let before, after = split_n offset p.numbering in before @ [ List.hd after + 1 ] let ast_to_json ast = toc_item_to_yojson ast |> Yojson.Safe.to_string let rec toc_append_item parent depth item = if depth = 1 then { parent with items = parent.items @ [ item ] } else let item = let parent' = last parent.items in toc_append_item parent' (depth - 1) item in { parent with items = drop_last 1 parent.items @ [ item ] } let toc_tree items = let rec go acc = function | [] -> List.rev acc | ({ numbering; _ } as h) :: tl -> ( match List.length numbering with | 1 -> go (h :: acc) tl | _ -> let parent = List.hd acc in let depth = List.length numbering - 1 in let parent = toc_append_item parent depth h in go (parent :: List.tl acc) tl) in go [] items let from_ast filename ast = let find_directive directives k = try let r = List.assoc k directives in Some r with Not_found -> None in let rec aut directives blocks toc = function | [] -> (List.rev directives, List.rev blocks, List.rev toc) | (h, pos_meta) :: tl -> ( let update_meta f = match blocks with | (Heading heading, pos_meta) :: _tl -> (Heading (f heading), pos_meta) :: List.tl blocks | _ -> (h, pos_meta) :: blocks in match h with | Directive (k, v) -> let directives = (k, v) :: directives in aut directives blocks toc tl | Heading { title ; tags ; marker ; level ; priority ; anchor ; meta ; unordered ; size ; _ } -> let numbering = compute_heading_numbering level toc in let h = Heading { title ; tags ; marker ; level ; priority ; anchor ; meta ; numbering = Some numbering ; unordered ; size } in let toc_item = { title; level; anchor; numbering; items = [] } in aut directives ((h, pos_meta) :: blocks) (toc_item :: toc) tl | Paragraph inlines -> let blocks = match get_timestamps (Type_op.inline_list_strip_pos inlines) with | [] -> (h, pos_meta) :: blocks | timestamps -> update_meta (fun heading -> let timestamps' = List.append timestamps heading.meta.timestamps in { heading with meta = { heading.meta with timestamps = timestamps' } }) in aut directives blocks toc tl | Property_Drawer properties -> let blocks = update_meta (fun heading -> { heading with meta = { heading.meta with properties } }) in aut directives blocks toc tl | _ -> aut directives ((h, pos_meta) :: blocks) toc tl) in let directives, blocks, toc = aut [] [] [] ast in { filename ; directives ; blocks ; title = find_directive directives "TITLE" ; subtitle = find_directive directives "SUBTITLE" ; author = find_directive directives "AUTHOR" ; toc = toc_tree toc }
e8a4a5191b1215858ba6ed891667a6371fda41b5aa7bd7d1a51bbf5e9fc05518
jakemcc/sicp-study
test_ex3_55.clj
(ns test-ex3-55 (:use clojure.test ex3-55)) (def integers (iterate inc 1)) (deftest partial-sum-works (let [sums (partial-sum integers)] (is (= '(1 3 6 10 15) (take 5 sums)))))
null
https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section3.5/test/test_ex3_55.clj
clojure
(ns test-ex3-55 (:use clojure.test ex3-55)) (def integers (iterate inc 1)) (deftest partial-sum-works (let [sums (partial-sum integers)] (is (= '(1 3 6 10 15) (take 5 sums)))))
4fa0de3d6f47daecd6716e111fea9c4b5413272bfa78e155612ad64c39d175d4
shirok/Gauche-LoL
lazy.scm
The features implemented in lazy.lisp is available in Gauche as ;; util.stream. Here we only show the correspondence. (use util.stream) ;; macro: lazy expr ... ;; == stream-delay (begin expr ...) ;; macro: lazy-cons a d ;; == stream-cons a d ;; function: lazy-car x ;; == stream-car x ;; function: lazy-cdr x ;; == stream-cdr x ;; function: lazy-nil ;; == (^[] stream-null) ;; function: lazy-null x ;; == stream-null? x function : make - lazy lst = = list->stream lst ;; function: take n s ;; == stream->list (stream-take s n) ;; function: take-all s = = stream->list s ;; function: lazy-mapcar fun s ;; == stream-map fun s ;; function: lazy-mapcan fun s ;; == stream-concatenate (stream-map fun s) ;; function: lazy-find-if fun s ;; == stream-find fun s ;; function: lazy-nth n s ;; == stream-ref s n
null
https://raw.githubusercontent.com/shirok/Gauche-LoL/9636176ca817d039ef1cbfd236ac8edfb25ea5d7/lazy.scm
scheme
util.stream. Here we only show the correspondence. macro: lazy expr ... == stream-delay (begin expr ...) macro: lazy-cons a d == stream-cons a d function: lazy-car x == stream-car x function: lazy-cdr x == stream-cdr x function: lazy-nil == (^[] stream-null) function: lazy-null x == stream-null? x function: take n s == stream->list (stream-take s n) function: take-all s function: lazy-mapcar fun s == stream-map fun s function: lazy-mapcan fun s == stream-concatenate (stream-map fun s) function: lazy-find-if fun s == stream-find fun s function: lazy-nth n s == stream-ref s n
The features implemented in lazy.lisp is available in Gauche as (use util.stream) function : make - lazy lst = = list->stream lst = = stream->list s
2c24fa62b5ea3b4ae8abac71278c89d012f0b5e556059a638bb5c9b46218d1fe
ocsigen/eliom
eliom_route_base.shared.ml
Ocsigen * * Module eliommod_services.ml * Copyright ( C ) 2007 * * 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 , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Module eliommod_services.ml * Copyright (C) 2007 Vincent Balat * * 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, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open Eliom_lib open Lwt let section = Lwt_log.Section.make "eliom:service" module type PARAM = sig type site_data type info type params type result val sess_info_of_info : info -> Eliom_common.sess_info val meth_of_info : info -> Eliom_common.meth val subpath_of_info : info -> string list val make_params : site_data -> info -> string list option -> Eliom_common.full_state_name option -> params val handle_directory : info -> result Lwt.t val get_number_of_reloads : unit -> int module Node : sig type t val up : t -> unit val remove : t -> unit end module Table : sig type t val empty : unit -> t val add : Eliom_common.page_table_key -> Node.t option * (params, result) Eliom_common.service list -> t -> t val find : Eliom_common.page_table_key -> t -> Node.t option * (params, result) Eliom_common.service list val remove : Eliom_common.page_table_key -> t -> t end module Container : sig type t val set_contains_timeout : t -> bool -> unit val dlist_add : ?sp:Eliom_common.server_params -> t -> ( Table.t ref * Eliom_common.page_table_key , Eliom_common.na_key_serv ) Eliom_lib.leftright -> Node.t val get : t -> (int * int * Table.t Eliom_common.dircontent ref) list val set : t -> (int * int * Table.t Eliom_common.dircontent ref) list -> unit end end module Make (P : PARAM) = struct let find_page_table nosuffixversion now (pagetableref : P.Table.t ref) fullsessname (site_data : P.site_data) (info : P.info) (urlsuffix : _ option) k : P.result Lwt.t = let sp = P.make_params site_data info urlsuffix fullsessname in Lwt.catch (fun () -> Lwt.return (P.Table.find k !pagetableref)) (function Not_found -> fail Eliom_common.Eliom_404 | e -> fail e) >>= fun (node, l) -> let rec aux toremove = function | [] -> Lwt.return (Eliom_common.Notfound Eliom_common.Eliom_Wrong_parameter, []) | ({Eliom_common.s_max_use; s_expire; s_f} as a) :: l -> ( match s_expire with | Some (_, e) when !e < now -> (* Service expired. Removing it. *) Lwt_log.ign_info ~section "Service expired. Removing it"; aux toremove l >>= fun (r, toremove) -> Lwt.return (r, a :: toremove) | _ -> catch (fun () -> Lwt_log.ign_info ~section "Trying a service"; s_f nosuffixversion sp >>= fun p -> warning : the list ll may change during if register something on the same URL ! ! if funct register something on the same URL!! *) Lwt_log.ign_info ~section "Page found and generated successfully"; If this is an anonymous coservice , we place it at the top of the dlist ( limitation of number of coservices ) we place it at the top of the dlist (limitation of number of coservices) *) (match node with None -> () | Some node -> P.Node.up node); (* We update the expiration date *) (match s_expire with | Some (timeout, e) -> e := timeout +. now | None -> ()); let newtoremove = match s_max_use with | Some s_max_use -> if s_max_use = 1 then a :: toremove else ( a.s_max_use <- Some (s_max_use - 1); toremove) | _ -> toremove in Lwt.return (Eliom_common.Found p, newtoremove)) (function | Eliom_common.Eliom_Wrong_parameter -> aux toremove l >>= fun (r, toremove) -> Lwt.return (r, toremove) | e -> Lwt.return (Eliom_common.Notfound e, toremove))) in aux [] l >>= fun (r, toremove) -> (match node, toremove with | _, [] -> () | Some node, _ -> it is an anonymous coservice that has expired . We remove it form the dlist . This will do the removal from this table automatically . Note that in that case , toremove has length 1 ( like the initial list l ) . We remove it form the dlist. This will do the removal from this table automatically. Note that in that case, toremove has length 1 (like the initial list l). *) P.Node.remove node | None, _ -> ( (* removing manually *) try let _, l = P.Table.find k !pagetableref and newptr = P.Table.remove k !pagetableref in (* We do find once again because it may have changed! *) let newlist = List.fold_left (fun l a -> List.remove_first_if_any_q a l) (* physical equality! *) l toremove in pagetableref := match newlist with | [] -> newptr | newlist -> P.Table.add k (None, newlist) newptr with Not_found -> ())); match r with | Eliom_common.Found r -> Lwt.return (r : P.result) | Eliom_common.Notfound e -> fail e let remove_id services id = List.filter (fun {Eliom_common.s_id} -> s_id <> id) services let find_and_remove_id services id = let found, l = let f (found, l) ({Eliom_common.s_id} as x) = if id = s_id then Some x, l else found, x :: l in List.fold_left f (None, []) services in match found with Some found -> found, List.rev l | None -> raise Not_found let add_page_table tables url_act tref key ({Eliom_common.s_id; s_expire} as service) = let sp = Eliom_common.get_sp_option () in (match s_expire with | Some _ -> P.Container.set_contains_timeout tables true | _ -> ()); Duplicate registration forbidden in global table with same generation match key with | {Eliom_common.key_state = Eliom_common.SAtt_anon _, _; key_meth = `Get} | { Eliom_common.key_state = _, Eliom_common.SAtt_anon _ ; key_meth = `Post | `Put | `Delete } -> ( : - only one for each key - we add a node in the dlist to limit their number - only one for each key - we add a node in the dlist to limit their number *) try let (nodeopt, _), newt = P.Table.find key !tref, P.Table.remove key !tref in (match nodeopt with | None -> () (* should not occur *) | Some node -> P.Node.up node); tref := P.Table.add key (nodeopt, [service]) newt with Not_found -> let node = P.Container.dlist_add ?sp tables (Left (tref, key)) in tref := P.Table.add key (Some node, [service]) !tref) | {Eliom_common.key_state = Eliom_common.SAtt_no, Eliom_common.SAtt_no} -> ( try let _nodeopt, l = P.Table.find key !tref and newt = P.Table.remove key !tref in (* nodeopt should be None *) try (* verify that we haven't registered something similar *) let _, oldl = find_and_remove_id l s_id in (* if there was an old version with the same id, we remove it? *) if sp = None then (* but if there was already one with same generation, we fail (if during initialisation) *) raise (Eliom_common.Eliom_duplicate_registration (Url.string_of_url_path ~encode:false url_act)) else (* We insert as last element so that services are tried in registration order *) tref := P.Table.add key (None, oldl @ [service]) newt with Not_found -> tref := P.Table.add key (None, l @ [service]) newt with Not_found -> tref := P.Table.add key (None, [service]) !tref) | _ -> ( try let _nodeopt, l = P.Table.find key !tref and newt = P.Table.remove key !tref in let _, oldl = find_and_remove_id l s_id in (* if there was an old version with the same id, we remove it *) tref := P.Table.add key (None, oldl @ [service]) newt with Not_found -> tref := P.Table.add key (None, [service]) !tref) let remove_page_table _ _ tref key id = Actually this does not remove empty directories . But this will be done by the next service GC But this will be done by the next service GC *) let nodeopt, l = P.Table.find key !tref in match nodeopt with | Some node -> In that case , l has size 1 , and the i d is correct , because it is an anonymous coservice because it is an anonymous coservice *) VVV the key is searched twice P.Node.remove node | None -> ( let newt = P.Table.remove key !tref in match remove_id l id with | [] -> tref := newt (* In that case, we must remove it, otherwise we get "Wrong parameters" instead of "404 Not found" *) | newl -> tref := P.Table.add key (None, newl) newt) let add_dircontent dc (key, (elt : P.Table.t Eliom_common.direlt ref)) = match dc with | Eliom_common.Vide -> Eliom_common.Table (String.Table.add key elt String.Table.empty) | Eliom_common.Table t -> Eliom_common.Table (String.Table.add key elt t) let find_dircontent dc k = match dc with | Eliom_common.Vide -> raise Not_found | Eliom_common.Table t -> String.Table.find k t let add_or_remove_service f tables table url_act page_table_key va = let rec aux dircontentref a l = try let direltref = find_dircontent !dircontentref a in match !direltref with | Eliom_common.Dir dcr -> search_page_table_ref dcr l | Eliom_common.File _ -> raise (Eliom_common.Eliom_page_erasing a) with Not_found -> let newdcr = ref (Eliom_common.empty_dircontent ()) in dircontentref := add_dircontent !dircontentref (a, ref (Eliom_common.Dir newdcr)); search_page_table_ref newdcr l and search_page_table_ref dircontentref = function | [] | [""] -> search_page_table_ref dircontentref [Eliom_common.defaultpagename] | [a] -> ( try let direltref = find_dircontent !dircontentref a in match !direltref with | Eliom_common.Dir _ -> raise (Eliom_common.Eliom_page_erasing a) | Eliom_common.File ptr -> ptr with Not_found -> let newpagetableref = ref (P.Table.empty ()) in dircontentref := add_dircontent !dircontentref (a, ref (Eliom_common.File newpagetableref)); newpagetableref) | "" :: l -> search_page_table_ref dircontentref l | a :: l -> aux dircontentref a l in let page_table_ref = search_page_table_ref table url_act in f tables url_act page_table_ref page_table_key va let add_service priority tables url_act page_table_key va = let generation = P.get_number_of_reloads () in let rec find_table = function | [] -> let t = ref (Eliom_common.empty_dircontent ()) in t, [generation, priority, t] | (g, p, t) :: _ as l when g = generation && p = priority -> t, l | (g, p, _) :: _ as l when g < generation || p < priority -> let t = ref (Eliom_common.empty_dircontent ()) in t, (generation, priority, t) :: l | ((g, p, _) as a) :: l when g = generation && p > priority -> let t, ll = find_table l in t, a :: ll | _ -> assert false in let table, new_table_services = find_table (P.Container.get tables) in P.Container.set tables new_table_services; add_or_remove_service add_page_table tables table url_act page_table_key va let remove_service tables path k unique_id = let rec aux = function | [] -> () | (_, _, table) :: l -> ( try add_or_remove_service remove_page_table tables table path k unique_id with Not_found -> aux l) in aux (P.Container.get tables) exception Exn1 let find_service now tables fullsessname sitedata info : P.result Lwt.t = let rec search_page_table dircontent : _ -> P.result Lwt.t = let find nosuffixversion page_table_ref suffix = let si = P.sess_info_of_info info in find_page_table nosuffixversion now page_table_ref fullsessname sitedata info suffix { Eliom_common.key_state = ( Eliom_common.att_key_serv_of_req (fst si.Eliom_common.si_state_info) , Eliom_common.att_key_serv_of_req (snd si.Eliom_common.si_state_info) ) ; Eliom_common.key_meth = P.meth_of_info info } in let aux a l = let aa = match a with None -> Eliom_common.defaultpagename | Some aa -> aa in Lwt.catch (fun () -> let dc = try !(find_dircontent dircontent aa) with Not_found -> raise Exn1 in match dc with | Eliom_common.Dir dircontentref2 -> search_page_table !dircontentref2 l | Eliom_common.File page_table_ref -> ( match l with | [] -> find false page_table_ref None | _ -> (* We have a file with suffix *) raise Eliom_common.Eliom_Wrong_parameter)) (function | (Exn1 | Eliom_common.Eliom_Wrong_parameter) as e -> ( (* If no service matches, we try a suffix service *) try match !(try find_dircontent dircontent Eliom_common.eliom_suffix_internal_name with Not_found -> raise e) with | Eliom_common.Dir _ -> Lwt.fail Exn1 | Eliom_common.File page_table_ref -> find false page_table_ref (if a = None then Some [] else Some (aa :: l)) with e -> Lwt.fail e) | e -> Lwt.fail e) in function | [] -> (* It is a directory, without / at the end. We do a redirection. *) P.handle_directory info | [""] -> aux None [] | [a] when a = Eliom_common.eliom_nosuffix_page -> ( (* version without suffix of suffix service *) try match !(try find_dircontent dircontent Eliom_common.eliom_suffix_internal_name with Not_found -> raise Exn1) with | Eliom_common.Dir _ -> Lwt.fail Exn1 | Eliom_common.File page_table_ref -> find true page_table_ref None with e -> Lwt.fail e) | " " : : l - > search_page_table dircontent l (* We do not remove "//" any more because of optional suffixes *) | a :: l -> aux (Some a) l in let search_by_priority_generation tables path = New in 1.91 : There is now one table for each pair ( generation , priority ) (generation, priority) *) List.fold_left (fun prev (_prio, _gen, table) -> Lwt.catch (fun () -> prev) (function | Exn1 | Eliom_common.Eliom_404 | Eliom_common.Eliom_Wrong_parameter -> search_page_table !table path | e -> fail e)) (fail Exn1) tables in Lwt.catch (fun () -> search_by_priority_generation (P.Container.get tables) (Url.change_empty_list (P.subpath_of_info info))) (function Exn1 -> Lwt.fail Eliom_common.Eliom_404 | e -> Lwt.fail e) end
null
https://raw.githubusercontent.com/ocsigen/eliom/c3e0eea5bef02e0af3942b6d27585add95d01d6c/src/lib/eliom_route_base.shared.ml
ocaml
Service expired. Removing it. We update the expiration date removing manually We do find once again because it may have changed! physical equality! should not occur nodeopt should be None verify that we haven't registered something similar if there was an old version with the same id, we remove it? but if there was already one with same generation, we fail (if during initialisation) We insert as last element so that services are tried in registration order if there was an old version with the same id, we remove it In that case, we must remove it, otherwise we get "Wrong parameters" instead of "404 Not found" We have a file with suffix If no service matches, we try a suffix service It is a directory, without / at the end. We do a redirection. version without suffix of suffix service We do not remove "//" any more because of optional suffixes
Ocsigen * * Module eliommod_services.ml * Copyright ( C ) 2007 * * 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 , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Module eliommod_services.ml * Copyright (C) 2007 Vincent Balat * * 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, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open Eliom_lib open Lwt let section = Lwt_log.Section.make "eliom:service" module type PARAM = sig type site_data type info type params type result val sess_info_of_info : info -> Eliom_common.sess_info val meth_of_info : info -> Eliom_common.meth val subpath_of_info : info -> string list val make_params : site_data -> info -> string list option -> Eliom_common.full_state_name option -> params val handle_directory : info -> result Lwt.t val get_number_of_reloads : unit -> int module Node : sig type t val up : t -> unit val remove : t -> unit end module Table : sig type t val empty : unit -> t val add : Eliom_common.page_table_key -> Node.t option * (params, result) Eliom_common.service list -> t -> t val find : Eliom_common.page_table_key -> t -> Node.t option * (params, result) Eliom_common.service list val remove : Eliom_common.page_table_key -> t -> t end module Container : sig type t val set_contains_timeout : t -> bool -> unit val dlist_add : ?sp:Eliom_common.server_params -> t -> ( Table.t ref * Eliom_common.page_table_key , Eliom_common.na_key_serv ) Eliom_lib.leftright -> Node.t val get : t -> (int * int * Table.t Eliom_common.dircontent ref) list val set : t -> (int * int * Table.t Eliom_common.dircontent ref) list -> unit end end module Make (P : PARAM) = struct let find_page_table nosuffixversion now (pagetableref : P.Table.t ref) fullsessname (site_data : P.site_data) (info : P.info) (urlsuffix : _ option) k : P.result Lwt.t = let sp = P.make_params site_data info urlsuffix fullsessname in Lwt.catch (fun () -> Lwt.return (P.Table.find k !pagetableref)) (function Not_found -> fail Eliom_common.Eliom_404 | e -> fail e) >>= fun (node, l) -> let rec aux toremove = function | [] -> Lwt.return (Eliom_common.Notfound Eliom_common.Eliom_Wrong_parameter, []) | ({Eliom_common.s_max_use; s_expire; s_f} as a) :: l -> ( match s_expire with | Some (_, e) when !e < now -> Lwt_log.ign_info ~section "Service expired. Removing it"; aux toremove l >>= fun (r, toremove) -> Lwt.return (r, a :: toremove) | _ -> catch (fun () -> Lwt_log.ign_info ~section "Trying a service"; s_f nosuffixversion sp >>= fun p -> warning : the list ll may change during if register something on the same URL ! ! if funct register something on the same URL!! *) Lwt_log.ign_info ~section "Page found and generated successfully"; If this is an anonymous coservice , we place it at the top of the dlist ( limitation of number of coservices ) we place it at the top of the dlist (limitation of number of coservices) *) (match node with None -> () | Some node -> P.Node.up node); (match s_expire with | Some (timeout, e) -> e := timeout +. now | None -> ()); let newtoremove = match s_max_use with | Some s_max_use -> if s_max_use = 1 then a :: toremove else ( a.s_max_use <- Some (s_max_use - 1); toremove) | _ -> toremove in Lwt.return (Eliom_common.Found p, newtoremove)) (function | Eliom_common.Eliom_Wrong_parameter -> aux toremove l >>= fun (r, toremove) -> Lwt.return (r, toremove) | e -> Lwt.return (Eliom_common.Notfound e, toremove))) in aux [] l >>= fun (r, toremove) -> (match node, toremove with | _, [] -> () | Some node, _ -> it is an anonymous coservice that has expired . We remove it form the dlist . This will do the removal from this table automatically . Note that in that case , toremove has length 1 ( like the initial list l ) . We remove it form the dlist. This will do the removal from this table automatically. Note that in that case, toremove has length 1 (like the initial list l). *) P.Node.remove node | None, _ -> ( try let _, l = P.Table.find k !pagetableref and newptr = P.Table.remove k !pagetableref in let newlist = List.fold_left (fun l a -> List.remove_first_if_any_q a l) l toremove in pagetableref := match newlist with | [] -> newptr | newlist -> P.Table.add k (None, newlist) newptr with Not_found -> ())); match r with | Eliom_common.Found r -> Lwt.return (r : P.result) | Eliom_common.Notfound e -> fail e let remove_id services id = List.filter (fun {Eliom_common.s_id} -> s_id <> id) services let find_and_remove_id services id = let found, l = let f (found, l) ({Eliom_common.s_id} as x) = if id = s_id then Some x, l else found, x :: l in List.fold_left f (None, []) services in match found with Some found -> found, List.rev l | None -> raise Not_found let add_page_table tables url_act tref key ({Eliom_common.s_id; s_expire} as service) = let sp = Eliom_common.get_sp_option () in (match s_expire with | Some _ -> P.Container.set_contains_timeout tables true | _ -> ()); Duplicate registration forbidden in global table with same generation match key with | {Eliom_common.key_state = Eliom_common.SAtt_anon _, _; key_meth = `Get} | { Eliom_common.key_state = _, Eliom_common.SAtt_anon _ ; key_meth = `Post | `Put | `Delete } -> ( : - only one for each key - we add a node in the dlist to limit their number - only one for each key - we add a node in the dlist to limit their number *) try let (nodeopt, _), newt = P.Table.find key !tref, P.Table.remove key !tref in (match nodeopt with | Some node -> P.Node.up node); tref := P.Table.add key (nodeopt, [service]) newt with Not_found -> let node = P.Container.dlist_add ?sp tables (Left (tref, key)) in tref := P.Table.add key (Some node, [service]) !tref) | {Eliom_common.key_state = Eliom_common.SAtt_no, Eliom_common.SAtt_no} -> ( try let _nodeopt, l = P.Table.find key !tref and newt = P.Table.remove key !tref in try let _, oldl = find_and_remove_id l s_id in if sp = None then raise (Eliom_common.Eliom_duplicate_registration (Url.string_of_url_path ~encode:false url_act)) else tref := P.Table.add key (None, oldl @ [service]) newt with Not_found -> tref := P.Table.add key (None, l @ [service]) newt with Not_found -> tref := P.Table.add key (None, [service]) !tref) | _ -> ( try let _nodeopt, l = P.Table.find key !tref and newt = P.Table.remove key !tref in let _, oldl = find_and_remove_id l s_id in tref := P.Table.add key (None, oldl @ [service]) newt with Not_found -> tref := P.Table.add key (None, [service]) !tref) let remove_page_table _ _ tref key id = Actually this does not remove empty directories . But this will be done by the next service GC But this will be done by the next service GC *) let nodeopt, l = P.Table.find key !tref in match nodeopt with | Some node -> In that case , l has size 1 , and the i d is correct , because it is an anonymous coservice because it is an anonymous coservice *) VVV the key is searched twice P.Node.remove node | None -> ( let newt = P.Table.remove key !tref in match remove_id l id with | [] -> tref := newt | newl -> tref := P.Table.add key (None, newl) newt) let add_dircontent dc (key, (elt : P.Table.t Eliom_common.direlt ref)) = match dc with | Eliom_common.Vide -> Eliom_common.Table (String.Table.add key elt String.Table.empty) | Eliom_common.Table t -> Eliom_common.Table (String.Table.add key elt t) let find_dircontent dc k = match dc with | Eliom_common.Vide -> raise Not_found | Eliom_common.Table t -> String.Table.find k t let add_or_remove_service f tables table url_act page_table_key va = let rec aux dircontentref a l = try let direltref = find_dircontent !dircontentref a in match !direltref with | Eliom_common.Dir dcr -> search_page_table_ref dcr l | Eliom_common.File _ -> raise (Eliom_common.Eliom_page_erasing a) with Not_found -> let newdcr = ref (Eliom_common.empty_dircontent ()) in dircontentref := add_dircontent !dircontentref (a, ref (Eliom_common.Dir newdcr)); search_page_table_ref newdcr l and search_page_table_ref dircontentref = function | [] | [""] -> search_page_table_ref dircontentref [Eliom_common.defaultpagename] | [a] -> ( try let direltref = find_dircontent !dircontentref a in match !direltref with | Eliom_common.Dir _ -> raise (Eliom_common.Eliom_page_erasing a) | Eliom_common.File ptr -> ptr with Not_found -> let newpagetableref = ref (P.Table.empty ()) in dircontentref := add_dircontent !dircontentref (a, ref (Eliom_common.File newpagetableref)); newpagetableref) | "" :: l -> search_page_table_ref dircontentref l | a :: l -> aux dircontentref a l in let page_table_ref = search_page_table_ref table url_act in f tables url_act page_table_ref page_table_key va let add_service priority tables url_act page_table_key va = let generation = P.get_number_of_reloads () in let rec find_table = function | [] -> let t = ref (Eliom_common.empty_dircontent ()) in t, [generation, priority, t] | (g, p, t) :: _ as l when g = generation && p = priority -> t, l | (g, p, _) :: _ as l when g < generation || p < priority -> let t = ref (Eliom_common.empty_dircontent ()) in t, (generation, priority, t) :: l | ((g, p, _) as a) :: l when g = generation && p > priority -> let t, ll = find_table l in t, a :: ll | _ -> assert false in let table, new_table_services = find_table (P.Container.get tables) in P.Container.set tables new_table_services; add_or_remove_service add_page_table tables table url_act page_table_key va let remove_service tables path k unique_id = let rec aux = function | [] -> () | (_, _, table) :: l -> ( try add_or_remove_service remove_page_table tables table path k unique_id with Not_found -> aux l) in aux (P.Container.get tables) exception Exn1 let find_service now tables fullsessname sitedata info : P.result Lwt.t = let rec search_page_table dircontent : _ -> P.result Lwt.t = let find nosuffixversion page_table_ref suffix = let si = P.sess_info_of_info info in find_page_table nosuffixversion now page_table_ref fullsessname sitedata info suffix { Eliom_common.key_state = ( Eliom_common.att_key_serv_of_req (fst si.Eliom_common.si_state_info) , Eliom_common.att_key_serv_of_req (snd si.Eliom_common.si_state_info) ) ; Eliom_common.key_meth = P.meth_of_info info } in let aux a l = let aa = match a with None -> Eliom_common.defaultpagename | Some aa -> aa in Lwt.catch (fun () -> let dc = try !(find_dircontent dircontent aa) with Not_found -> raise Exn1 in match dc with | Eliom_common.Dir dircontentref2 -> search_page_table !dircontentref2 l | Eliom_common.File page_table_ref -> ( match l with | [] -> find false page_table_ref None | _ -> raise Eliom_common.Eliom_Wrong_parameter)) (function | (Exn1 | Eliom_common.Eliom_Wrong_parameter) as e -> ( try match !(try find_dircontent dircontent Eliom_common.eliom_suffix_internal_name with Not_found -> raise e) with | Eliom_common.Dir _ -> Lwt.fail Exn1 | Eliom_common.File page_table_ref -> find false page_table_ref (if a = None then Some [] else Some (aa :: l)) with e -> Lwt.fail e) | e -> Lwt.fail e) in function | [] -> P.handle_directory info | [""] -> aux None [] | [a] when a = Eliom_common.eliom_nosuffix_page -> ( try match !(try find_dircontent dircontent Eliom_common.eliom_suffix_internal_name with Not_found -> raise Exn1) with | Eliom_common.Dir _ -> Lwt.fail Exn1 | Eliom_common.File page_table_ref -> find true page_table_ref None with e -> Lwt.fail e) | " " : : l - > search_page_table dircontent l | a :: l -> aux (Some a) l in let search_by_priority_generation tables path = New in 1.91 : There is now one table for each pair ( generation , priority ) (generation, priority) *) List.fold_left (fun prev (_prio, _gen, table) -> Lwt.catch (fun () -> prev) (function | Exn1 | Eliom_common.Eliom_404 | Eliom_common.Eliom_Wrong_parameter -> search_page_table !table path | e -> fail e)) (fail Exn1) tables in Lwt.catch (fun () -> search_by_priority_generation (P.Container.get tables) (Url.change_empty_list (P.subpath_of_info info))) (function Exn1 -> Lwt.fail Eliom_common.Eliom_404 | e -> Lwt.fail e) end
58c54c1ae8e353862902de6d429eeec31ed2f84ff23584465a09f0546ba005af
juxt/stoic
zk.clj
(ns stoic.config.zk "Namespace to faciliate Stoic interaction with Zookeeper." (:require [zookeeper :as zk] [zookeeper.data :as zk-data] [stoic.protocols.config-supplier] [stoic.config.data :refer :all] [stoic.config.env :refer :all] [clojure.tools.logging :as log] [com.stuartsierra.component :as component])) (defn connect [] (log/info "Connecting to ZK") (zk/connect (zk-ips) :timeout-msec 10000)) (defn close [client] (zk/close client)) (defn add-to-zk [client path m] (when-not (zk/exists client path) (zk/create-all client path :persistent? true)) (let [v (:version (zk/exists client path))] (zk/set-data client path (serialize-form m) v))) (defn read-from-zk [client path] (deserialize-form (:data (zk/data client path)))) (defn profiles [client] (map keyword (zk/children client "/stoic"))) (defn components [client profile] (map keyword (zk/children client (format "/stoic/%s/components" profile)))) (defrecord ZkConfigSupplier [root] stoic.protocols.config-supplier/ConfigSupplier component/Lifecycle (start [{:keys [client] :as this}] (if client this (assoc this :client (connect)))) (stop [{:keys [client] :as this}] (when client (log/info "Disconnecting from ZK") (close client)) this) (fetch [{:keys [client]} k] (let [path (path-for root k)] (when-not (zk/exists client path) (zk/create-all client path :persistent? true)) (read-from-zk client path))) (watch! [{:keys [client]} k watcher-fn] (let [path (path-for root k)] (zk/exists client path :watcher (fn the-watcher [event] (when (= :NodeDataChanged (:event-type event)) (log/info "Data changed, firing watcher" event) (watcher-fn) (zk/exists client path :watcher the-watcher))))))) (defn zk-config-supplier [] (ZkConfigSupplier. (zk-root)))
null
https://raw.githubusercontent.com/juxt/stoic/047103f8ba4bcb999b0eefdf084ecd72ff844568/src/stoic/config/zk.clj
clojure
(ns stoic.config.zk "Namespace to faciliate Stoic interaction with Zookeeper." (:require [zookeeper :as zk] [zookeeper.data :as zk-data] [stoic.protocols.config-supplier] [stoic.config.data :refer :all] [stoic.config.env :refer :all] [clojure.tools.logging :as log] [com.stuartsierra.component :as component])) (defn connect [] (log/info "Connecting to ZK") (zk/connect (zk-ips) :timeout-msec 10000)) (defn close [client] (zk/close client)) (defn add-to-zk [client path m] (when-not (zk/exists client path) (zk/create-all client path :persistent? true)) (let [v (:version (zk/exists client path))] (zk/set-data client path (serialize-form m) v))) (defn read-from-zk [client path] (deserialize-form (:data (zk/data client path)))) (defn profiles [client] (map keyword (zk/children client "/stoic"))) (defn components [client profile] (map keyword (zk/children client (format "/stoic/%s/components" profile)))) (defrecord ZkConfigSupplier [root] stoic.protocols.config-supplier/ConfigSupplier component/Lifecycle (start [{:keys [client] :as this}] (if client this (assoc this :client (connect)))) (stop [{:keys [client] :as this}] (when client (log/info "Disconnecting from ZK") (close client)) this) (fetch [{:keys [client]} k] (let [path (path-for root k)] (when-not (zk/exists client path) (zk/create-all client path :persistent? true)) (read-from-zk client path))) (watch! [{:keys [client]} k watcher-fn] (let [path (path-for root k)] (zk/exists client path :watcher (fn the-watcher [event] (when (= :NodeDataChanged (:event-type event)) (log/info "Data changed, firing watcher" event) (watcher-fn) (zk/exists client path :watcher the-watcher))))))) (defn zk-config-supplier [] (ZkConfigSupplier. (zk-root)))
d1f897d06bec53f5d19bd88e2b067235efb8136b6f01b275bd8f8f87df0911fc
david-broman/modelyze
uArg.ml
type keylist = ustring list type description = ustring type usage_msg = ustring type opt = | ArgHeading of ustring | ArgString of keylist * ustring ref * description | ArgSet of keylist * bool ref * description | ArgClear of keylist * bool ref * description | ArgRest of ustring * (ustring list) ref * description exception Unknown_arg of ustring exception Option_already_exists of ustring hash table module UStrHashtbl = Hashtbl.Make(Ustring) let parse_argv argv options usage_msg = (* Setup option hash table *) let ophash = UStrHashtbl.create 512 in let hash_op k v = try USHashtbl.find ophash k; raise (Option_already_exits k) with Not_found -> UStrHashtbl.add ophash o v in let get_keys o = match o with | ArgHeading(_) -> [] | ArgString(keys,_,_) | ArgSet(keys,_,_) | ArgClear(keys,_,_) -> List.map (fun s -> Ustring.sub_before s us' ') keys | ArgRest(key,_,_) -> Ustring.sub_before key us' ' in [] let match_key a keys = List.exists ( fun s - > Ustring.sub_before s ( uc ' ' ) = . a ) keys in let rec set_if_match_op opt a = match opt with | ArgSet(keys , r , _ ) when match_key a keys - > r : = true ; true | ArgClear(keys , r , _ ) when match_key a keys - > r:= false ; true | o::ol - > set_if_match_op ol a | [ ] - > false in let rec parse rest = match arglist with | a::al - > when set_if_match_op options a - > parse al | a::p::al - > when set_if_match_op_param options a p - > parse al | a::al when Ustring.first_sub a 1 = . us"- " - > raise ( Unknown_arg a ) | a::al - > if is_rest then rest : = a::!rest ; a::(parse al ) | [ ] - > [ ] in parse ( List.map Ustring.from_utf8 ( Array.to_list argv ) ) let match_key a keys = List.exists (fun s -> Ustring.sub_before s (uc' ') =. a) keys in let rec set_if_match_op opt a = match opt with | ArgSet(keys,r,_) when match_key a keys -> r := true; true | ArgClear(keys,r,_) when match_key a keys -> r:= false; true | o::ol -> set_if_match_op ol a | [] -> false in let rec parse arglst is_rest rest = match arglist with | a::al -> when set_if_match_op options a -> parse al | a::p::al -> when set_if_match_op_param options a p -> parse al | a::al when Ustring.first_sub a 1 =. us"-" -> raise (Unknown_arg a) | a::al -> if is_rest then rest := a::!rest; a::(parse al) | [] -> [] in parse (List.map Ustring.from_utf8 (Array.to_list argv)) *)
null
https://raw.githubusercontent.com/david-broman/modelyze/e48c934283e683e268a9dfd0fed49d3c10277298/ext/ucamlib/src/uArg.ml
ocaml
Setup option hash table
type keylist = ustring list type description = ustring type usage_msg = ustring type opt = | ArgHeading of ustring | ArgString of keylist * ustring ref * description | ArgSet of keylist * bool ref * description | ArgClear of keylist * bool ref * description | ArgRest of ustring * (ustring list) ref * description exception Unknown_arg of ustring exception Option_already_exists of ustring hash table module UStrHashtbl = Hashtbl.Make(Ustring) let parse_argv argv options usage_msg = let ophash = UStrHashtbl.create 512 in let hash_op k v = try USHashtbl.find ophash k; raise (Option_already_exits k) with Not_found -> UStrHashtbl.add ophash o v in let get_keys o = match o with | ArgHeading(_) -> [] | ArgString(keys,_,_) | ArgSet(keys,_,_) | ArgClear(keys,_,_) -> List.map (fun s -> Ustring.sub_before s us' ') keys | ArgRest(key,_,_) -> Ustring.sub_before key us' ' in [] let match_key a keys = List.exists ( fun s - > Ustring.sub_before s ( uc ' ' ) = . a ) keys in let rec set_if_match_op opt a = match opt with | ArgSet(keys , r , _ ) when match_key a keys - > r : = true ; true | ArgClear(keys , r , _ ) when match_key a keys - > r:= false ; true | o::ol - > set_if_match_op ol a | [ ] - > false in let rec parse rest = match arglist with | a::al - > when set_if_match_op options a - > parse al | a::p::al - > when set_if_match_op_param options a p - > parse al | a::al when Ustring.first_sub a 1 = . us"- " - > raise ( Unknown_arg a ) | a::al - > if is_rest then rest : = a::!rest ; a::(parse al ) | [ ] - > [ ] in parse ( List.map Ustring.from_utf8 ( Array.to_list argv ) ) let match_key a keys = List.exists (fun s -> Ustring.sub_before s (uc' ') =. a) keys in let rec set_if_match_op opt a = match opt with | ArgSet(keys,r,_) when match_key a keys -> r := true; true | ArgClear(keys,r,_) when match_key a keys -> r:= false; true | o::ol -> set_if_match_op ol a | [] -> false in let rec parse arglst is_rest rest = match arglist with | a::al -> when set_if_match_op options a -> parse al | a::p::al -> when set_if_match_op_param options a p -> parse al | a::al when Ustring.first_sub a 1 =. us"-" -> raise (Unknown_arg a) | a::al -> if is_rest then rest := a::!rest; a::(parse al) | [] -> [] in parse (List.map Ustring.from_utf8 (Array.to_list argv)) *)
533056cfd5b497d07a65bfb11a4c28167f27fd265381d2eef37e819ed099483c
wavewave/HROOT.old
random2dApp.hs
module Main where import Control.Monad import HROOT main :: IO () main = do tapp <- newTApplication "test" [0] ["test"] tcanvas <- newTCanvas "Test" "Test" 640 480 h2 <- newTH2F "test" "test" 100 (-5.0) 5.0 100 (-5.0) 5.0 tRandom <- newTRandom 65535 let dist1 = gaus tRandom 0 2 dist2 = gaus tRandom 0 2 let go n | n < 0 = return () | otherwise = do histfill dist1 dist2 h2 go (n-1) go 1000000 draw h2 "lego" run tapp 1 delete h2 delete tapp histfill :: IO Double -> IO Double-> TH2F -> IO () histfill dist1 dist2 hist = do x <- dist1 y <- dist2 fill2 hist x y return ()
null
https://raw.githubusercontent.com/wavewave/HROOT.old/6be1bae246ff4c82159d84981cf7e4389011b17a/example/random2dApp.hs
haskell
module Main where import Control.Monad import HROOT main :: IO () main = do tapp <- newTApplication "test" [0] ["test"] tcanvas <- newTCanvas "Test" "Test" 640 480 h2 <- newTH2F "test" "test" 100 (-5.0) 5.0 100 (-5.0) 5.0 tRandom <- newTRandom 65535 let dist1 = gaus tRandom 0 2 dist2 = gaus tRandom 0 2 let go n | n < 0 = return () | otherwise = do histfill dist1 dist2 h2 go (n-1) go 1000000 draw h2 "lego" run tapp 1 delete h2 delete tapp histfill :: IO Double -> IO Double-> TH2F -> IO () histfill dist1 dist2 hist = do x <- dist1 y <- dist2 fill2 hist x y return ()
c039b78aea81945614fb2bfb8612d8bd2d7f91af6d721dc318cd789cdcaa474f
xapi-project/xen-api
test_map_check.ml
* Copyright ( C ) 2006 - 2015 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) 2006-2015 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. *) open Map_check open Test_highlevel let string_of_requirement requirement = Printf.sprintf "{key = \"%s\"; default_value = \"%s\"}" requirement.key (Test_printers.(option string) requirement.default_value) let string_of_unit_result = Fmt.(str "%a" Dump.(result ~ok:(any "()") ~error:exn)) let pp_list_assoc fmt_fst fmt_snd = Fmt.(Dump.list @@ pair ~sep:(any "=") fmt_fst fmt_snd) let true_fun _ = true let false_fun _ = false module AddDefaults = Generic.MakeStateless (struct module Io = struct type input_t = requirement list * (string * string) list type output_t = (string * string) list let string_of_input_t = Test_printers.( assoc_pair (list string_of_requirement) (assoc_list string string) ) let string_of_output_t = Test_printers.(assoc_list string string) end let transform (requirements, old_map) = add_defaults requirements old_map let tests = `QuickAndAutoDocumented [ (* If default value is None, no value should be added. *) (([{key= "abc"; default_value= None; is_valid_value= true_fun}], []), []) ; (* If default value is Some _, the default should be added. *) ( ( [{key= "abc"; default_value= Some "def"; is_valid_value= true_fun}] , [] ) , [("abc", "def")] ) ; (* If default value is None, an existing value should not be overwritten. *) ( ( [{key= "abc"; default_value= None; is_valid_value= true_fun}] , [("abc", "ghi")] ) , [("abc", "ghi")] ) ; (* If default value is Some _, an existing value should not be overwritten. *) ( ( [{key= "abc"; default_value= Some "def"; is_valid_value= true_fun}] , [("abc", "ghi")] ) , [("abc", "ghi")] ) ] end) module ValidateKVPair = Generic.MakeStateless (struct module Io = struct type input_t = requirement list * string * string type output_t = (unit, exn) result let string_of_input_t (requirements, key, value) = Printf.sprintf "%s, %s, %s" ((Test_printers.list string_of_requirement) requirements) key value let string_of_output_t = string_of_unit_result end let transform (requirements, key, value) = try Ok (validate_kvpair "test_field" requirements (key, value)) with e -> Error e let tests = `QuickAndAutoDocumented [ (* If all values are valid, the exception should not be thrown. *) ( ( [{key= "abc"; default_value= None; is_valid_value= true_fun}] , "abc" , "def" ) , Ok () ) ; (* If there is no valid value, the exception should always be thrown. *) ( ( [{key= "abc"; default_value= None; is_valid_value= false_fun}] , "abc" , "def" ) , Error Api_errors.( Server_error (invalid_value, ["test_field"; "abc = def"]) ) ) ] end) module Accessors = Generic.MakeStateless (struct module Io = struct type input_t = string * (string * string) list type output_t = int let string_of_input_t = Test_printers.(pair string (list (pair string string))) let string_of_output_t = Test_printers.int end let transform (key, map) = getf (field key int) map let tests = `QuickAndAutoDocumented [(("a", [("a", "1")]), 1)] end) let string_of_ty = function String -> "String" | _ -> "" let string_of_ks ks = let _, kss = ks in List.map (fun (a, b) -> let inner_string = List.map (fun (c, d) -> let e, f = d in c ^ "," ^ string_of_ty e ^ f ) b |> String.concat ";" in "[" ^ a ^ "," ^ "[" ^ inner_string ^ "]]" ) kss |> String.concat ";" module AssertAllKeys = Generic.MakeStateless (struct module Io = struct type input_t = string * (string * (string * (string * (Map_check.key_type * string)) list) list) * (string * string) list * (string * string) list type output_t = (string * string) list let string_of_input_t (ty, ks, value, db) = Printf.sprintf "frequency=%s, keys=%s, input_value=%s, db_value=%s" ty (string_of_ks ks) (Test_printers.(assoc_list string string) value) (Test_printers.(assoc_list string string) db) let string_of_output_t = Test_printers.(assoc_list string string) end let transform (ty, ks, value, db) = assert_all_keys ~ty ~ks ~value ~db let tests = `QuickAndAutoDocumented [ Tests for hourly snapshots ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("min", "30")] , [("min", "0")] ) , [("min", "30")] ) ; ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("hour", "1"); ("min", "0")] , [("min", "0")] ) , [("min", "0")] ) ; ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("day", "Monday"); ("hour", "1"); ("min", "0")] , [("min", "0")] ) , [("min", "0")] ) Change hourly snapshots to daily and weekly ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10"); ("min", "30")] , [("min", "0")] ) , [("hour", "10"); ("min", "30")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] , [("min", "0")] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] ) Tests for daily snapshots ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10"); ("min", "30")] , [("hour", "0"); ("min", "0")] ) , [("hour", "10"); ("min", "30")] ) ; ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("day", "Monday"); ("hour", "0"); ("min", "0")] , [("hour", "0"); ("min", "0")] ) , [("hour", "0"); ("min", "0")] ) ; ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("min", "30")] , [("hour", "0"); ("min", "0")] ) , [("hour", "0"); ("min", "30")] ) ; ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10")] , [("hour", "0"); ("min", "0")] ) , [("hour", "10"); ("min", "0")] ) Change daily snapshots to hourly and weekly ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("min", "30")] , [("hour", "0"); ("min", "0")] ) , [("min", "30")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] , [("hour", "0"); ("min", "0")] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] ) Tests for weekly snapshots ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] , [("day", "Wednesday"); ("hour", "0"); ("min", "0")] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Wednesday")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("day", "Wednesday"); ("hour", "0"); ("min", "0")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("hour", "10")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("day", "Monday"); ("hour", "10"); ("min", "0")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("day", "Monday"); ("hour", "0"); ("min", "30")] ) Change weekly snapshots to hourly and daily ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("min", "30")] ) ; ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10"); ("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("hour", "10"); ("min", "30")] ) ] end) module AssertKeys = Generic.MakeStateless (struct module Io = struct type input_t = string * (string * (string * (string * (Map_check.key_type * string)) list) list) * (string * string) list * (string * string) list type output_t = ((string * string) list, exn) result let string_of_input_t (_, ks, value, db) = Printf.sprintf "keys=%s, input_value=%s, db_value=%s" (string_of_ks ks) (Test_printers.(assoc_list string string) value) (Test_printers.(assoc_list string string) db) let string_of_output_t = Fmt.(str "%a" Dump.(result ~ok:(pp_list_assoc string string) ~error:exn)) end let transform (ty, ks, value, db) = try Ok (assert_keys ~ty ~ks ~value ~db) with e -> Error e let tests = `QuickAndAutoDocumented [ Tests hourly keys ( ( "" , ("", [("", [("min", (String, ""))])]) , [("min", "30")] , [("min", "0")] ) , Ok [("min", "30")] ) ; ( ( "" , ("", [("", [("min", (String, ""))])]) , [("hour", "0")] , [("min", "0")] ) , Error Api_errors.(Server_error (invalid_value, [":hour"; "0"])) ) ; ( ( "" , ("", [("", [("min", (String, ""))])]) , [("day", "Monday")] , [("min", "0")] ) , Error Api_errors.(Server_error (invalid_value, [":day"; "Monday"])) ) Tests daily keys ( ( "" , ("", [("", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10"); ("min", "30")] , [("hour", "0"); ("min", "0")] ) , Ok [("hour", "10"); ("min", "30")] ) ; ( ( "" , ("", [("", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10")] , [("hour", "0"); ("min", "0")] ) , Ok [("hour", "10"); ("min", "0")] ) ; ( ( "" , ("", [("", [("hour", (String, "")); ("min", (String, ""))])]) , [("min", "30")] , [("hour", "0"); ("min", "0")] ) , Ok [("hour", "0"); ("min", "30")] ) ; ( ( "" , ("", [("", [("hour", (String, "")); ("min", (String, ""))])]) , [("day", "Monday")] , [("hour", "0"); ("min", "0")] ) , Error Api_errors.(Server_error (invalid_value, [":day"; "Monday"])) ) Tests weekly keys ( ( "" , ( "" , [ ( "" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Wednesday"); ("hour", "10"); ("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , Ok [("day", "Wednesday"); ("hour", "10"); ("min", "30")] ) ; ( ( "" , ( "" , [ ( "" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Wednesday")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , Ok [("day", "Wednesday"); ("hour", "0"); ("min", "0")] ) ; ( ( "" , ( "" , [ ( "" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("hour", "10")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , Ok [("day", "Monday"); ("hour", "10"); ("min", "0")] ) ; ( ( "" , ( "" , [ ( "" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , Ok [("day", "Monday"); ("hour", "0"); ("min", "30")] ) ] end) let tests = List.map (fun (s, t) -> (Format.sprintf "test_map_check_%s" s, t)) [ ("add_defaults", AddDefaults.tests) ; ("validate_kvpair", ValidateKVPair.tests) ; ("accessors", Accessors.tests) ; ("assert_all_keys", AssertAllKeys.tests) ; ("assert_keys", AssertKeys.tests) ]
null
https://raw.githubusercontent.com/xapi-project/xen-api/e984d34bd9ff60d7224a841270db0fe1dfe42e7a/ocaml/tests/test_map_check.ml
ocaml
If default value is None, no value should be added. If default value is Some _, the default should be added. If default value is None, an existing value should not be overwritten. If default value is Some _, an existing value should not be overwritten. If all values are valid, the exception should not be thrown. If there is no valid value, the exception should always be thrown.
* Copyright ( C ) 2006 - 2015 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) 2006-2015 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. *) open Map_check open Test_highlevel let string_of_requirement requirement = Printf.sprintf "{key = \"%s\"; default_value = \"%s\"}" requirement.key (Test_printers.(option string) requirement.default_value) let string_of_unit_result = Fmt.(str "%a" Dump.(result ~ok:(any "()") ~error:exn)) let pp_list_assoc fmt_fst fmt_snd = Fmt.(Dump.list @@ pair ~sep:(any "=") fmt_fst fmt_snd) let true_fun _ = true let false_fun _ = false module AddDefaults = Generic.MakeStateless (struct module Io = struct type input_t = requirement list * (string * string) list type output_t = (string * string) list let string_of_input_t = Test_printers.( assoc_pair (list string_of_requirement) (assoc_list string string) ) let string_of_output_t = Test_printers.(assoc_list string string) end let transform (requirements, old_map) = add_defaults requirements old_map let tests = `QuickAndAutoDocumented [ (([{key= "abc"; default_value= None; is_valid_value= true_fun}], []), []) ( ( [{key= "abc"; default_value= Some "def"; is_valid_value= true_fun}] , [] ) , [("abc", "def")] ) ( ( [{key= "abc"; default_value= None; is_valid_value= true_fun}] , [("abc", "ghi")] ) , [("abc", "ghi")] ) ( ( [{key= "abc"; default_value= Some "def"; is_valid_value= true_fun}] , [("abc", "ghi")] ) , [("abc", "ghi")] ) ] end) module ValidateKVPair = Generic.MakeStateless (struct module Io = struct type input_t = requirement list * string * string type output_t = (unit, exn) result let string_of_input_t (requirements, key, value) = Printf.sprintf "%s, %s, %s" ((Test_printers.list string_of_requirement) requirements) key value let string_of_output_t = string_of_unit_result end let transform (requirements, key, value) = try Ok (validate_kvpair "test_field" requirements (key, value)) with e -> Error e let tests = `QuickAndAutoDocumented [ ( ( [{key= "abc"; default_value= None; is_valid_value= true_fun}] , "abc" , "def" ) , Ok () ) ( ( [{key= "abc"; default_value= None; is_valid_value= false_fun}] , "abc" , "def" ) , Error Api_errors.( Server_error (invalid_value, ["test_field"; "abc = def"]) ) ) ] end) module Accessors = Generic.MakeStateless (struct module Io = struct type input_t = string * (string * string) list type output_t = int let string_of_input_t = Test_printers.(pair string (list (pair string string))) let string_of_output_t = Test_printers.int end let transform (key, map) = getf (field key int) map let tests = `QuickAndAutoDocumented [(("a", [("a", "1")]), 1)] end) let string_of_ty = function String -> "String" | _ -> "" let string_of_ks ks = let _, kss = ks in List.map (fun (a, b) -> let inner_string = List.map (fun (c, d) -> let e, f = d in c ^ "," ^ string_of_ty e ^ f ) b |> String.concat ";" in "[" ^ a ^ "," ^ "[" ^ inner_string ^ "]]" ) kss |> String.concat ";" module AssertAllKeys = Generic.MakeStateless (struct module Io = struct type input_t = string * (string * (string * (string * (Map_check.key_type * string)) list) list) * (string * string) list * (string * string) list type output_t = (string * string) list let string_of_input_t (ty, ks, value, db) = Printf.sprintf "frequency=%s, keys=%s, input_value=%s, db_value=%s" ty (string_of_ks ks) (Test_printers.(assoc_list string string) value) (Test_printers.(assoc_list string string) db) let string_of_output_t = Test_printers.(assoc_list string string) end let transform (ty, ks, value, db) = assert_all_keys ~ty ~ks ~value ~db let tests = `QuickAndAutoDocumented [ Tests for hourly snapshots ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("min", "30")] , [("min", "0")] ) , [("min", "30")] ) ; ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("hour", "1"); ("min", "0")] , [("min", "0")] ) , [("min", "0")] ) ; ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("day", "Monday"); ("hour", "1"); ("min", "0")] , [("min", "0")] ) , [("min", "0")] ) Change hourly snapshots to daily and weekly ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10"); ("min", "30")] , [("min", "0")] ) , [("hour", "10"); ("min", "30")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] , [("min", "0")] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] ) Tests for daily snapshots ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10"); ("min", "30")] , [("hour", "0"); ("min", "0")] ) , [("hour", "10"); ("min", "30")] ) ; ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("day", "Monday"); ("hour", "0"); ("min", "0")] , [("hour", "0"); ("min", "0")] ) , [("hour", "0"); ("min", "0")] ) ; ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("min", "30")] , [("hour", "0"); ("min", "0")] ) , [("hour", "0"); ("min", "30")] ) ; ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10")] , [("hour", "0"); ("min", "0")] ) , [("hour", "10"); ("min", "0")] ) Change daily snapshots to hourly and weekly ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("min", "30")] , [("hour", "0"); ("min", "0")] ) , [("min", "30")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] , [("hour", "0"); ("min", "0")] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] ) Tests for weekly snapshots ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] , [("day", "Wednesday"); ("hour", "0"); ("min", "0")] ) , [("day", "Monday"); ("hour", "10"); ("min", "30")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Wednesday")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("day", "Wednesday"); ("hour", "0"); ("min", "0")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("hour", "10")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("day", "Monday"); ("hour", "10"); ("min", "0")] ) ; ( ( "weekly" , ( "" , [ ( "weekly" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("day", "Monday"); ("hour", "0"); ("min", "30")] ) Change weekly snapshots to hourly and daily ( ( "hourly" , ("", [("hourly", [("min", (String, ""))])]) , [("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("min", "30")] ) ; ( ( "daily" , ("", [("daily", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10"); ("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , [("hour", "10"); ("min", "30")] ) ] end) module AssertKeys = Generic.MakeStateless (struct module Io = struct type input_t = string * (string * (string * (string * (Map_check.key_type * string)) list) list) * (string * string) list * (string * string) list type output_t = ((string * string) list, exn) result let string_of_input_t (_, ks, value, db) = Printf.sprintf "keys=%s, input_value=%s, db_value=%s" (string_of_ks ks) (Test_printers.(assoc_list string string) value) (Test_printers.(assoc_list string string) db) let string_of_output_t = Fmt.(str "%a" Dump.(result ~ok:(pp_list_assoc string string) ~error:exn)) end let transform (ty, ks, value, db) = try Ok (assert_keys ~ty ~ks ~value ~db) with e -> Error e let tests = `QuickAndAutoDocumented [ Tests hourly keys ( ( "" , ("", [("", [("min", (String, ""))])]) , [("min", "30")] , [("min", "0")] ) , Ok [("min", "30")] ) ; ( ( "" , ("", [("", [("min", (String, ""))])]) , [("hour", "0")] , [("min", "0")] ) , Error Api_errors.(Server_error (invalid_value, [":hour"; "0"])) ) ; ( ( "" , ("", [("", [("min", (String, ""))])]) , [("day", "Monday")] , [("min", "0")] ) , Error Api_errors.(Server_error (invalid_value, [":day"; "Monday"])) ) Tests daily keys ( ( "" , ("", [("", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10"); ("min", "30")] , [("hour", "0"); ("min", "0")] ) , Ok [("hour", "10"); ("min", "30")] ) ; ( ( "" , ("", [("", [("hour", (String, "")); ("min", (String, ""))])]) , [("hour", "10")] , [("hour", "0"); ("min", "0")] ) , Ok [("hour", "10"); ("min", "0")] ) ; ( ( "" , ("", [("", [("hour", (String, "")); ("min", (String, ""))])]) , [("min", "30")] , [("hour", "0"); ("min", "0")] ) , Ok [("hour", "0"); ("min", "30")] ) ; ( ( "" , ("", [("", [("hour", (String, "")); ("min", (String, ""))])]) , [("day", "Monday")] , [("hour", "0"); ("min", "0")] ) , Error Api_errors.(Server_error (invalid_value, [":day"; "Monday"])) ) Tests weekly keys ( ( "" , ( "" , [ ( "" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Wednesday"); ("hour", "10"); ("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , Ok [("day", "Wednesday"); ("hour", "10"); ("min", "30")] ) ; ( ( "" , ( "" , [ ( "" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("day", "Wednesday")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , Ok [("day", "Wednesday"); ("hour", "0"); ("min", "0")] ) ; ( ( "" , ( "" , [ ( "" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("hour", "10")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , Ok [("day", "Monday"); ("hour", "10"); ("min", "0")] ) ; ( ( "" , ( "" , [ ( "" , [ ("day", (String, "")) ; ("hour", (String, "")) ; ("min", (String, "")) ] ) ] ) , [("min", "30")] , [("day", "Monday"); ("hour", "0"); ("min", "0")] ) , Ok [("day", "Monday"); ("hour", "0"); ("min", "30")] ) ] end) let tests = List.map (fun (s, t) -> (Format.sprintf "test_map_check_%s" s, t)) [ ("add_defaults", AddDefaults.tests) ; ("validate_kvpair", ValidateKVPair.tests) ; ("accessors", Accessors.tests) ; ("assert_all_keys", AssertAllKeys.tests) ; ("assert_keys", AssertKeys.tests) ]
51051e15edc93778c0ffb417b227d245de26178272063ff8865f181158a5a857
Frama-C/Frama-C-snapshot
abstract_value.mli
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 . (* *) (* It 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. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (** Abstract numeric values of the analysis. *) open Cil_types open Eval * Type for the truth value of an assertion in a value abstraction . The two last tags should be used only for a product of value abstractions . last tags should be used only for a product of value abstractions. *) type 'v truth = [ `False (* The assertion is always false for the value abstraction, leading to bottom and a red alarm. *) | `Unknown of 'v (* The assertion may be true or false for different concretization of the abstraction. The value is reduced by assuming the assertion. *) | `True (* The assertion is always true for the value abstraction (that cannot be reduced). *) | `TrueReduced of 'v (* The assertion is always true according to a component of a product of values, but other components have been reduced by assuming the assertion. *) | `Unreachable ] (* A product of values was incompatible and has led to inconsistent truth value for the assertion. *) type bound_kind = Alarms.bound_kind = Lower_bound | Upper_bound type bound = Int of Integer.t | Float of float * fkind type pointer_comparison = Equality | Relation | Subtraction (** Signature of abstract numerical values. *) module type S = sig include Datatype.S val pretty_typ: typ option -> t Pretty_utils.formatter (** Pretty the abstract value assuming it has the type given as argument. *) (** {3 Lattice Structure} *) val top : t val is_included : t -> t -> bool val join : t -> t -> t val narrow : t -> t -> t or_bottom * { 3 Constructors } val zero: t val one: t val top_int : t val inject_int : typ -> Integer.t -> t (** Abstract address for the given varinfo. (With type "pointer to the type of the variable" if the abstract values are typed.) *) * { 3 Alarms } (** These functions are used to create the alarms that report undesirable behaviors, when a value abstraction does not meet the prerequisites of an operation. Thereafter, the value is assumed to meet them to continue the analysis. See the documentation of the [truth] type for more details. *) Assumes that the integer value represents only non zero values . val assume_non_zero: t -> t truth [ assume_bounded Lower_bound b v ] assumes that the value [ v ] represents only values greater or equal to the lower bound [ b ] . [ assume_bounded Upper_bound b v ] assumes that the value [ v ] represents only values lower or equal to the greater bound [ b ] . Depending on the bound , [ v ] is an integer or a floating - point value . only values greater or equal to the lower bound [b]. [assume_bounded Upper_bound b v] assumes that the value [v] represents only values lower or equal to the greater bound [b]. Depending on the bound, [v] is an integer or a floating-point value. *) val assume_bounded: bound_kind -> bound -> t -> t truth (* Assumes that the floating-point value does not represent NaN. If [assume_finite] is true, assumes that the value represents only finite floating-point values. *) val assume_not_nan: assume_finite:bool -> fkind -> t -> t truth [ assume_comparable cmp v1 v2 ] assumes that the integer or pointer values [ v1 ] and [ v2 ] are comparable for [ cmp ] . Integers are always comparable . If one value is a pointer , then both values should be pointers , and : and according to [ cmp ] : - if [ cmp ] is Equality : either one pointer is NULL , or both pointers are valid ( pointing into their object ) , or both pointers are nearly valid ( pointing into or just beyond their object ) and point to the same object . - if [ cmp ] is Relation : both pointers should point into or just beyond the same object ; - if [ cmp ] is Subtraction : both pointers should point to the same object , without any restriction on their offsets . [v1] and [v2] are comparable for [cmp]. Integers are always comparable. If one value is a pointer, then both values should be pointers, and: and according to [cmp]: - if [cmp] is Equality: either one pointer is NULL, or both pointers are valid (pointing into their object), or both pointers are nearly valid (pointing into or just beyond their object) and point to the same object. - if [cmp] is Relation: both pointers should point into or just beyond the same object; - if [cmp] is Subtraction: both pointers should point to the same object, without any restriction on their offsets. *) val assume_comparable: pointer_comparison -> t -> t -> (t * t) truth (** {3 Forward Operations } *) * constants into value abstractions : returns an abstract value for the given constant . The constant can not be an enumeration constant . for the given constant. The constant cannot be an enumeration constant. *) val constant : exp -> constant -> t (** [forward_unop typ unop v] evaluates the value [unop v], resulting from the application of the unary operator [unop] to the value [v]. [typ] is the type of [v]. *) val forward_unop : typ -> unop -> t -> t or_bottom (** [forward_binop typ binop v1 v2] evaluates the value [v1 binop v2], resulting from the application of the binary operator [binop] to the values [v1] and [v2]. [typ] is the type of [v1]. *) val forward_binop : typ -> binop -> t -> t -> t or_bottom * [ rewrap_integer irange t ] wraps around the abstract value [ t ] to fit the integer range [ irange ] , assuming 2 's complement . integer range [irange], assuming 2's complement. *) val rewrap_integer: Eval_typ.integer_range -> t -> t (** Abstract evaluation of casts operators from [src_type] to [dst_type]. *) val forward_cast : src_type: Eval_typ.scalar_typ -> dst_type: Eval_typ.scalar_typ -> t -> t or_bottom * { 3 Backward Operations } * For an unary forward operation F , the inverse backward operator B tries to reduce the argument values of the operation , given its result . It must satisfy : if [ B arg res ] = v then ∀ a ⊆ arg such that [ F a ] ⊆ res , a ⊆ v i.e. [ B arg res ] returns a value [ v ] larger than all subvalues of [ arg ] whose result through F is included in [ res ] . If [ F arg ] ∈ [ res ] is impossible , then [ v ] should be bottom . If the value [ arg ] can not be reduced , then [ v ] should be None . Any n - ary operator may be considered as a unary operator on a vector of values , the inclusion being lifted pointwise . reduce the argument values of the operation, given its result. It must satisfy: if [B arg res] = v then ∀ a ⊆ arg such that [F a] ⊆ res, a ⊆ v i.e. [B arg res] returns a value [v] larger than all subvalues of [arg] whose result through F is included in [res]. If [F arg] ∈ [res] is impossible, then [v] should be bottom. If the value [arg] cannot be reduced, then [v] should be None. Any n-ary operator may be considered as a unary operator on a vector of values, the inclusion being lifted pointwise. *) * Backward evaluation of the binary operation [ left right = result ] ; tries to reduce the argument [ left ] and [ right ] according to [ result ] . [ input_type ] is the type of [ left ] , [ resulting_type ] the type of [ result ] . tries to reduce the argument [left] and [right] according to [result]. [input_type] is the type of [left], [resulting_type] the type of [result]. *) val backward_binop : input_type:typ -> resulting_type:typ -> binop -> left:t -> right:t -> result:t -> (t option * t option) or_bottom (** Backward evaluation of the unary operation [unop arg = res]; tries to reduce the argument [arg] according to [res]. [typ_arg] is the type of [arg]. *) val backward_unop : typ_arg:typ -> unop -> arg:t -> res:t -> t option or_bottom (** Backward evaluation of the cast of the value [src_val] of type [src_typ] into the value [dst_val] of type [dst_typ]. Tries to reduce [scr_val] according to [dst_val]. *) val backward_cast: src_typ: typ -> dst_typ: typ -> src_val: t -> dst_val: t -> t option or_bottom val resolve_functions : t -> Kernel_function.t list or_top * bool (** [resolve_functions v] returns the list of functions that may be pointed to by the abstract value [v] (representing a function pointer). The returned boolean must be [true] if some of the values represented by [v] do not correspond to functions. It is always safe to return [`Top, true]. *) end type 'v key = 'v Structure.Key_Value.key (** Signature for a leaf module of abstract values. *) module type Leaf = sig include S (** The key identifies the module and the type [t] of abstract values. *) val key: t key end (* Local Variables: compile-command: "make -C ../../../.." End: *)
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/value/values/abstract_value.mli
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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. ************************************************************************ * Abstract numeric values of the analysis. The assertion is always false for the value abstraction, leading to bottom and a red alarm. The assertion may be true or false for different concretization of the abstraction. The value is reduced by assuming the assertion. The assertion is always true for the value abstraction (that cannot be reduced). The assertion is always true according to a component of a product of values, but other components have been reduced by assuming the assertion. A product of values was incompatible and has led to inconsistent truth value for the assertion. * Signature of abstract numerical values. * Pretty the abstract value assuming it has the type given as argument. * {3 Lattice Structure} * Abstract address for the given varinfo. (With type "pointer to the type of the variable" if the abstract values are typed.) * These functions are used to create the alarms that report undesirable behaviors, when a value abstraction does not meet the prerequisites of an operation. Thereafter, the value is assumed to meet them to continue the analysis. See the documentation of the [truth] type for more details. Assumes that the floating-point value does not represent NaN. If [assume_finite] is true, assumes that the value represents only finite floating-point values. * {3 Forward Operations } * [forward_unop typ unop v] evaluates the value [unop v], resulting from the application of the unary operator [unop] to the value [v]. [typ] is the type of [v]. * [forward_binop typ binop v1 v2] evaluates the value [v1 binop v2], resulting from the application of the binary operator [binop] to the values [v1] and [v2]. [typ] is the type of [v1]. * Abstract evaluation of casts operators from [src_type] to [dst_type]. * Backward evaluation of the unary operation [unop arg = res]; tries to reduce the argument [arg] according to [res]. [typ_arg] is the type of [arg]. * Backward evaluation of the cast of the value [src_val] of type [src_typ] into the value [dst_val] of type [dst_typ]. Tries to reduce [scr_val] according to [dst_val]. * [resolve_functions v] returns the list of functions that may be pointed to by the abstract value [v] (representing a function pointer). The returned boolean must be [true] if some of the values represented by [v] do not correspond to functions. It is always safe to return [`Top, true]. * Signature for a leaf module of abstract values. * The key identifies the module and the type [t] of abstract values. Local Variables: compile-command: "make -C ../../../.." End:
This file is part of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types open Eval * Type for the truth value of an assertion in a value abstraction . The two last tags should be used only for a product of value abstractions . last tags should be used only for a product of value abstractions. *) type 'v truth = type bound_kind = Alarms.bound_kind = Lower_bound | Upper_bound type bound = Int of Integer.t | Float of float * fkind type pointer_comparison = Equality | Relation | Subtraction module type S = sig include Datatype.S val pretty_typ: typ option -> t Pretty_utils.formatter val top : t val is_included : t -> t -> bool val join : t -> t -> t val narrow : t -> t -> t or_bottom * { 3 Constructors } val zero: t val one: t val top_int : t val inject_int : typ -> Integer.t -> t * { 3 Alarms } Assumes that the integer value represents only non zero values . val assume_non_zero: t -> t truth [ assume_bounded Lower_bound b v ] assumes that the value [ v ] represents only values greater or equal to the lower bound [ b ] . [ assume_bounded Upper_bound b v ] assumes that the value [ v ] represents only values lower or equal to the greater bound [ b ] . Depending on the bound , [ v ] is an integer or a floating - point value . only values greater or equal to the lower bound [b]. [assume_bounded Upper_bound b v] assumes that the value [v] represents only values lower or equal to the greater bound [b]. Depending on the bound, [v] is an integer or a floating-point value. *) val assume_bounded: bound_kind -> bound -> t -> t truth val assume_not_nan: assume_finite:bool -> fkind -> t -> t truth [ assume_comparable cmp v1 v2 ] assumes that the integer or pointer values [ v1 ] and [ v2 ] are comparable for [ cmp ] . Integers are always comparable . If one value is a pointer , then both values should be pointers , and : and according to [ cmp ] : - if [ cmp ] is Equality : either one pointer is NULL , or both pointers are valid ( pointing into their object ) , or both pointers are nearly valid ( pointing into or just beyond their object ) and point to the same object . - if [ cmp ] is Relation : both pointers should point into or just beyond the same object ; - if [ cmp ] is Subtraction : both pointers should point to the same object , without any restriction on their offsets . [v1] and [v2] are comparable for [cmp]. Integers are always comparable. If one value is a pointer, then both values should be pointers, and: and according to [cmp]: - if [cmp] is Equality: either one pointer is NULL, or both pointers are valid (pointing into their object), or both pointers are nearly valid (pointing into or just beyond their object) and point to the same object. - if [cmp] is Relation: both pointers should point into or just beyond the same object; - if [cmp] is Subtraction: both pointers should point to the same object, without any restriction on their offsets. *) val assume_comparable: pointer_comparison -> t -> t -> (t * t) truth * constants into value abstractions : returns an abstract value for the given constant . The constant can not be an enumeration constant . for the given constant. The constant cannot be an enumeration constant. *) val constant : exp -> constant -> t val forward_unop : typ -> unop -> t -> t or_bottom val forward_binop : typ -> binop -> t -> t -> t or_bottom * [ rewrap_integer irange t ] wraps around the abstract value [ t ] to fit the integer range [ irange ] , assuming 2 's complement . integer range [irange], assuming 2's complement. *) val rewrap_integer: Eval_typ.integer_range -> t -> t val forward_cast : src_type: Eval_typ.scalar_typ -> dst_type: Eval_typ.scalar_typ -> t -> t or_bottom * { 3 Backward Operations } * For an unary forward operation F , the inverse backward operator B tries to reduce the argument values of the operation , given its result . It must satisfy : if [ B arg res ] = v then ∀ a ⊆ arg such that [ F a ] ⊆ res , a ⊆ v i.e. [ B arg res ] returns a value [ v ] larger than all subvalues of [ arg ] whose result through F is included in [ res ] . If [ F arg ] ∈ [ res ] is impossible , then [ v ] should be bottom . If the value [ arg ] can not be reduced , then [ v ] should be None . Any n - ary operator may be considered as a unary operator on a vector of values , the inclusion being lifted pointwise . reduce the argument values of the operation, given its result. It must satisfy: if [B arg res] = v then ∀ a ⊆ arg such that [F a] ⊆ res, a ⊆ v i.e. [B arg res] returns a value [v] larger than all subvalues of [arg] whose result through F is included in [res]. If [F arg] ∈ [res] is impossible, then [v] should be bottom. If the value [arg] cannot be reduced, then [v] should be None. Any n-ary operator may be considered as a unary operator on a vector of values, the inclusion being lifted pointwise. *) * Backward evaluation of the binary operation [ left right = result ] ; tries to reduce the argument [ left ] and [ right ] according to [ result ] . [ input_type ] is the type of [ left ] , [ resulting_type ] the type of [ result ] . tries to reduce the argument [left] and [right] according to [result]. [input_type] is the type of [left], [resulting_type] the type of [result]. *) val backward_binop : input_type:typ -> resulting_type:typ -> binop -> left:t -> right:t -> result:t -> (t option * t option) or_bottom val backward_unop : typ_arg:typ -> unop -> arg:t -> res:t -> t option or_bottom val backward_cast: src_typ: typ -> dst_typ: typ -> src_val: t -> dst_val: t -> t option or_bottom val resolve_functions : t -> Kernel_function.t list or_top * bool end type 'v key = 'v Structure.Key_Value.key module type Leaf = sig include S val key: t key end
c56c33c6bc6e0cc1e735f3d0025c2e615f40b481093fa48e6197a24728485faf
Eduap-com/WordMat
inference_result.lisp
;; COPYRIGHT NOTICE ;; Copyright ( C ) 2006 - 2012 ;; ;; This program is free software; you can redistribute ;; it and/or modify it under the terms of the ;; GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . ;; ;; This program is distributed in the hope that it ;; will be useful, but WITHOUT ANY WARRANTY; ;; without even the implied warranty of MERCHANTABILITY ;; or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details at ;; ;; This package handles objects returned by statistical inference ;; procedures. Some code was copied and adapted from displa.lisp ;; For questions, suggestions, bugs and the like, feel free ;; to contact me at mario @@@ edu DOT xunta DOT es (in-package :maxima) Constructs the ' inference_result ' object , with ;; title: string with the name of the inference procedure : Maxima list , the elements of which are lists of ;; the form: ["Value's name", value] selection : Maxima list numbering the values to be displayed (defun $inference_result (title val selection) (list '($inference_result) title val selection)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; DISPLAY PROPERTIES FOR inference_result ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Functions d - matrixz , , and are similar to d - matrix , , and dim-$matrix , respectively , from displa.lisp . The left and right characters ( $ lmxchar and in displa.lisp ) are ;; defined without additional global variables. (defun d-matrixz (linear? direction h d) (declare (fixnum h d)) (d-vbar linear? h d (if (eq direction 'right) #\space #\|))) ; <- right and left characters (defun matoutz (dmstr cstr rstr result) (push `(d-matrixz left ,height ,depth) result) (push #\space result) (do ((d dmstr (cdr d)) (c cstr (cdr c)) (w 0 0)) ((null d)) (declare (fixnum w)) (do ((d (car d) (cdr d)) (r rstr (cdr r))) ((null d)) (rplaca (cddar d) (f- height (car r))) (rplaca (cdar d) (f- (truncate (f- (car c) (caar d)) 2) w)) (setq w (truncate (f+ (car c) (caar d)) 2)) (rplaca d (cdar d))) (setq result (cons (list (f+ 2 (f- (car c) w)) 0) (nreconc (car d) result)))) (setq width (f+ 2 width)) (update-heights height depth) (rplaca (car result) (f1- (caar result))) (push `(d-matrixz right ,height ,depth) result) result) (defun coloutz (dmstr cstr result) (setq width 0 height 1 depth 0) (do ((r dmstr (cdr r)) (c cstr (cdr c)) (col 1 (f1+ col)) (w 0 0) (h -1 -1) (d 0)) ((null r)) (declare (fixnum col w h d)) (push-string " Col " result) (setq result (nreconc (exploden col) result)) (push-string " = " result) (setq width (f+ 8 (flatc col) width)) (do ((r (car r) (cdr r))) ((null r)) (setq h (f+ 1 h (cadar r) (caddar r))) (rplaca (cddar r) (f- h (cadar r))) (rplaca (cdar r) (f- (truncate (f- (car c) (caar r)) 2) w)) (setq w (truncate (f+ (car c) (caar r)) 2)) (rplaca r (cdar r))) (setq d (truncate h 2) h (f- h d)) (push `(d-matrixz left ,h ,d) result) (push #\space result) (push `(0 ,(f- d) . ,(nreverse (car r))) result) (push `(,(f1+ (f- (car c) w)) 0) result) (push `(d-matrixz right ,h ,d) result) (setq width (f+ 4 (car c) width) height (max h height) depth (max d depth)) (update-heights h d) (checkbreak result width)) result) (displa-def $inference_result dim-$inference_result) (defun dim-$inference_result (form result) (declare (special linearray)) (prog (dmstr rstr cstr consp) (if (or (null (cdr form)) (not (member 'simp (cdar form) :test #'eq)) (memalike '((mlist simp)) (cdr form)) (dolist (row (cdr form)) (if (not ($listp row)) (return t)))) (return (dimension-function form result))) (do ((l (cdadr form) (cdr l))) ((null l)) (setq dmstr (cons nil dmstr) cstr (cons 0 cstr))) (do ((r (cdr form) (cdr r)) (h1 0) (d1 0)) ((or consp (null r)) (setq width 0) (do ((cs cstr (cdr cs))) ((null cs)) (setq width (f+ 2 (car cs) width))) (setq h1 (f1- (f+ h1 d1)) depth (truncate h1 2) height (f- h1 depth))) (declare (fixnum h1 d1)) (do ((c (cdar r) (cdr c)) (nc dmstr (cdr nc)) (cs cstr (cdr cs)) (dummy) (h2 0) (d2 0)) ((null c) (setq d1 (f+ d1 h1 h2) h1 (f1+ d2))) (declare (fixnum h2 d2)) (setq dummy (dimension (car c) nil 'mparen 'mparen nil 0) h2 (max h2 height) d2 (max d2 depth)) (cond ((not (checkfit (f+ 14. width))) (setq consp t) (return nil)) (t (rplaca nc (cons (list* width height depth dummy) (car nc))) (rplaca cs (max width (car cs)))))) (setq rstr (cons d1 rstr))) (when (> (+ height depth) (length linearray)) (setq consp t)) (return (cond ((and (not consp) (checkfit (f+ 2 width))) (matoutz dmstr cstr rstr result)) ((and (not consp) (<= level 2)) (coloutz dmstr cstr result)) (t (dimension-function form result)))))) ;; Sets display properties (displa-def $inference_result dimension-inference) (defun dimension-inference (form result) (let ((title (cadr form)) (outputitems (reverse (cdr (cadddr form)))) (output nil) aux) (dolist (k outputitems 'done) (setf aux (rest (nth k (caddr form)))) (push (list '(mlist simp) (list '(mequal simp) (car aux) (cadr aux))) output)) ; variable output has the following structure: ; '(($inference_result simp) ( ( mlist simp ) , title ) ( ( mlist ) ( ( simp ) value_name1 ) ) ( ( mlist ) ( ( simp ) value_name2 value2 ) ) ( ( mlist ) ( ( mequal simp ) value_name3 value3 ) ) ) (setf output (append (list '($inference_result simp) (list '(mlist simp) title)) output)) (dim-$inference_result output result))) Format TeX output (defprop $inference_result tex-inference_result tex) (defun tex-inference_result (x l r) ;; inference_result looks like ( ( inference_result ) string ( ( mlist ) ( ( mlist ) .. ) ( ( mlist ) .. ) .. ) ) (append l `("\\left | \\matrix{" ) (list "\\hbox{" (cadr x) "} \\cr \\matrix{") (mapcan #'(lambda(y) (tex-list `(((mequal) ,(cadr y) ,(caddr y))) nil (list "\\cr ") "&")) (cdar (butlast (cddr x)))) '("}} \\right .") r)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;; FUNCTIONS FOR inference_result ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Returns true or false, depending on whether 'obj' is an ;; 'inference_result' object or not. (defun $inferencep (obj) (and (listp obj) (equalp (car obj) '($inference_result simp)) )) Returns a Maxima list with the names ;; of the items stored in the 'inference_result' object (defun $items_inference (obj) (let ((items (cdaddr obj))) (cons '(mlist) (mapcar #'second items)))) ;; Returns the n-th value of the 'inference_result' object, ;; or the list of values associated to the indices in n, if n is a Maxima list . (defun $take_inference (n obj) (if ($inferencep obj) (cond ((and ($integerp n) (<= n (length (cdaddr obj)))) (caddr (nth (- n 1) (cdaddr obj)))) (($listp n) (let ((values nil) (items (reverse (rest n)))) (dolist (k items (cons '(mlist) values)) (setf values (cons ($take_inference k obj) values)))) ) (t (let ((m (position n (mapcar #'second (cdaddr obj))))) (if (equal m nil) (merror "Wrong label in 'take_inference' call") (caddr (nth m (cdaddr obj))))))) (merror "Wrong object in 'take_inference' call") )) ;; Returns the title of the 'inference_result' object (defun $title_inference (obj) (if ($inferencep obj) (second obj) (merror "Wrong object in 'title_inference' call")) )
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/stats/inference_result.lisp
lisp
COPYRIGHT NOTICE This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by either version 2 This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details at This package handles objects returned by statistical inference procedures. Some code was copied and adapted from displa.lisp For questions, suggestions, bugs and the like, feel free to contact me at title: string with the name of the inference procedure the form: ["Value's name", value] ;; DISPLAY PROPERTIES FOR inference_result ;; ;; defined without additional global variables. <- right and left characters Sets display properties variable output has the following structure: '(($inference_result simp) inference_result looks like ;; FUNCTIONS FOR inference_result ;; ;; Returns true or false, depending on whether 'obj' is an 'inference_result' object or not. of the items stored in the 'inference_result' object Returns the n-th value of the 'inference_result' object, or the list of values associated to the indices in n, Returns the title of the 'inference_result' object
Copyright ( C ) 2006 - 2012 of the License , or ( at your option ) any later version . mario @@@ edu DOT xunta DOT es (in-package :maxima) Constructs the ' inference_result ' object , with : Maxima list , the elements of which are lists of selection : Maxima list numbering the values to be displayed (defun $inference_result (title val selection) (list '($inference_result) title val selection)) Functions d - matrixz , , and are similar to d - matrix , , and dim-$matrix , respectively , from displa.lisp . The left and right characters ( $ lmxchar and in displa.lisp ) are (defun d-matrixz (linear? direction h d) (declare (fixnum h d)) (defun matoutz (dmstr cstr rstr result) (push `(d-matrixz left ,height ,depth) result) (push #\space result) (do ((d dmstr (cdr d)) (c cstr (cdr c)) (w 0 0)) ((null d)) (declare (fixnum w)) (do ((d (car d) (cdr d)) (r rstr (cdr r))) ((null d)) (rplaca (cddar d) (f- height (car r))) (rplaca (cdar d) (f- (truncate (f- (car c) (caar d)) 2) w)) (setq w (truncate (f+ (car c) (caar d)) 2)) (rplaca d (cdar d))) (setq result (cons (list (f+ 2 (f- (car c) w)) 0) (nreconc (car d) result)))) (setq width (f+ 2 width)) (update-heights height depth) (rplaca (car result) (f1- (caar result))) (push `(d-matrixz right ,height ,depth) result) result) (defun coloutz (dmstr cstr result) (setq width 0 height 1 depth 0) (do ((r dmstr (cdr r)) (c cstr (cdr c)) (col 1 (f1+ col)) (w 0 0) (h -1 -1) (d 0)) ((null r)) (declare (fixnum col w h d)) (push-string " Col " result) (setq result (nreconc (exploden col) result)) (push-string " = " result) (setq width (f+ 8 (flatc col) width)) (do ((r (car r) (cdr r))) ((null r)) (setq h (f+ 1 h (cadar r) (caddar r))) (rplaca (cddar r) (f- h (cadar r))) (rplaca (cdar r) (f- (truncate (f- (car c) (caar r)) 2) w)) (setq w (truncate (f+ (car c) (caar r)) 2)) (rplaca r (cdar r))) (setq d (truncate h 2) h (f- h d)) (push `(d-matrixz left ,h ,d) result) (push #\space result) (push `(0 ,(f- d) . ,(nreverse (car r))) result) (push `(,(f1+ (f- (car c) w)) 0) result) (push `(d-matrixz right ,h ,d) result) (setq width (f+ 4 (car c) width) height (max h height) depth (max d depth)) (update-heights h d) (checkbreak result width)) result) (displa-def $inference_result dim-$inference_result) (defun dim-$inference_result (form result) (declare (special linearray)) (prog (dmstr rstr cstr consp) (if (or (null (cdr form)) (not (member 'simp (cdar form) :test #'eq)) (memalike '((mlist simp)) (cdr form)) (dolist (row (cdr form)) (if (not ($listp row)) (return t)))) (return (dimension-function form result))) (do ((l (cdadr form) (cdr l))) ((null l)) (setq dmstr (cons nil dmstr) cstr (cons 0 cstr))) (do ((r (cdr form) (cdr r)) (h1 0) (d1 0)) ((or consp (null r)) (setq width 0) (do ((cs cstr (cdr cs))) ((null cs)) (setq width (f+ 2 (car cs) width))) (setq h1 (f1- (f+ h1 d1)) depth (truncate h1 2) height (f- h1 depth))) (declare (fixnum h1 d1)) (do ((c (cdar r) (cdr c)) (nc dmstr (cdr nc)) (cs cstr (cdr cs)) (dummy) (h2 0) (d2 0)) ((null c) (setq d1 (f+ d1 h1 h2) h1 (f1+ d2))) (declare (fixnum h2 d2)) (setq dummy (dimension (car c) nil 'mparen 'mparen nil 0) h2 (max h2 height) d2 (max d2 depth)) (cond ((not (checkfit (f+ 14. width))) (setq consp t) (return nil)) (t (rplaca nc (cons (list* width height depth dummy) (car nc))) (rplaca cs (max width (car cs)))))) (setq rstr (cons d1 rstr))) (when (> (+ height depth) (length linearray)) (setq consp t)) (return (cond ((and (not consp) (checkfit (f+ 2 width))) (matoutz dmstr cstr rstr result)) ((and (not consp) (<= level 2)) (coloutz dmstr cstr result)) (t (dimension-function form result)))))) (displa-def $inference_result dimension-inference) (defun dimension-inference (form result) (let ((title (cadr form)) (outputitems (reverse (cdr (cadddr form)))) (output nil) aux) (dolist (k outputitems 'done) (setf aux (rest (nth k (caddr form)))) (push (list '(mlist simp) (list '(mequal simp) (car aux) (cadr aux))) output)) ( ( mlist simp ) , title ) ( ( mlist ) ( ( simp ) value_name1 ) ) ( ( mlist ) ( ( simp ) value_name2 value2 ) ) ( ( mlist ) ( ( mequal simp ) value_name3 value3 ) ) ) (setf output (append (list '($inference_result simp) (list '(mlist simp) title)) output)) (dim-$inference_result output result))) Format TeX output (defprop $inference_result tex-inference_result tex) (defun tex-inference_result (x l r) ( ( inference_result ) string ( ( mlist ) ( ( mlist ) .. ) ( ( mlist ) .. ) .. ) ) (append l `("\\left | \\matrix{" ) (list "\\hbox{" (cadr x) "} \\cr \\matrix{") (mapcan #'(lambda(y) (tex-list `(((mequal) ,(cadr y) ,(caddr y))) nil (list "\\cr ") "&")) (cdar (butlast (cddr x)))) '("}} \\right .") r)) (defun $inferencep (obj) (and (listp obj) (equalp (car obj) '($inference_result simp)) )) Returns a Maxima list with the names (defun $items_inference (obj) (let ((items (cdaddr obj))) (cons '(mlist) (mapcar #'second items)))) if n is a Maxima list . (defun $take_inference (n obj) (if ($inferencep obj) (cond ((and ($integerp n) (<= n (length (cdaddr obj)))) (caddr (nth (- n 1) (cdaddr obj)))) (($listp n) (let ((values nil) (items (reverse (rest n)))) (dolist (k items (cons '(mlist) values)) (setf values (cons ($take_inference k obj) values)))) ) (t (let ((m (position n (mapcar #'second (cdaddr obj))))) (if (equal m nil) (merror "Wrong label in 'take_inference' call") (caddr (nth m (cdaddr obj))))))) (merror "Wrong object in 'take_inference' call") )) (defun $title_inference (obj) (if ($inferencep obj) (second obj) (merror "Wrong object in 'title_inference' call")) )
82429544bb22f82e27862f65207f28a9ed6a8f4299f0d71cac4b79f1d6806052
KirinDave/clj-time
intervals.clj
(ns clj-time.fuzzy-parser.intervals (:use [clojure.contrib.def :only (defvar defvar-)]) (:import (org.joda.time DateTime Period) (org.joda.time.format DateTimeFormat DateTimeFormatter ISODateTimeFormat))) (defn gen-intregexp [regexp-str] (re-pattern (str "([0-9]+) " regexp-str))) (defvar interval-patterns { :second [(gen-intregexp "?(s|secs?|seconds?)") 1] :minute [(gen-intregexp "?(m|mins?|minutes?)") 60] :hour [(gen-intregexp "?(h|hours?|hr)") 3600] :day [(gen-intregexp "?(d|days?)") 86400] :year [(gen-intregexp "?(y|years?)") 31536000]}) (defn- pat [k] ((k interval-patterns) 0)) (defn- sec [k] ((k interval-patterns) 1)) (defn integer-from-str [str regexp] (if-let [matches (re-find regexp str)] (Integer/parseInt (matches 1)) 0)) (defn seconds-from-str [str] (reduce + 0 (map #(* (or (integer-from-str str (pat %1)) 0) (sec %1)) (keys interval-patterns)))) (defn period-from-str [str] (let [secs (seconds-from-str str)] (if (> secs 0) (Period. (long (* (seconds-from-str str) 1000))) nil)))
null
https://raw.githubusercontent.com/KirinDave/clj-time/41259ac14f4604d54e6561fde4a52867e6834b79/src/clj_time/fuzzy_parser/intervals.clj
clojure
(ns clj-time.fuzzy-parser.intervals (:use [clojure.contrib.def :only (defvar defvar-)]) (:import (org.joda.time DateTime Period) (org.joda.time.format DateTimeFormat DateTimeFormatter ISODateTimeFormat))) (defn gen-intregexp [regexp-str] (re-pattern (str "([0-9]+) " regexp-str))) (defvar interval-patterns { :second [(gen-intregexp "?(s|secs?|seconds?)") 1] :minute [(gen-intregexp "?(m|mins?|minutes?)") 60] :hour [(gen-intregexp "?(h|hours?|hr)") 3600] :day [(gen-intregexp "?(d|days?)") 86400] :year [(gen-intregexp "?(y|years?)") 31536000]}) (defn- pat [k] ((k interval-patterns) 0)) (defn- sec [k] ((k interval-patterns) 1)) (defn integer-from-str [str regexp] (if-let [matches (re-find regexp str)] (Integer/parseInt (matches 1)) 0)) (defn seconds-from-str [str] (reduce + 0 (map #(* (or (integer-from-str str (pat %1)) 0) (sec %1)) (keys interval-patterns)))) (defn period-from-str [str] (let [secs (seconds-from-str str)] (if (> secs 0) (Period. (long (* (seconds-from-str str) 1000))) nil)))
c3646034cf9879f0533551af7a9077c22ca98b4609313ca512c5d97d79d912c2
lambdamikel/VISCO
optimizer10.lisp
-*- Mode : Lisp ; Syntax : Ansi - Common - Lisp ; Package : QUERY - COMPILER ; Base : 10 -*- (in-package query-compiler) ;;; ;;; ;;; (defun get-sorted-and-activated-ccs-no-generator-required (obj) (remove-if #'(lambda (cc) (or (not (activated-p cc)) (ignored-p cc))) (sorted-testers obj))) (defmethod get-sorted-and-activated-ccs ((obj enclosure)) (get-sorted-and-activated-ccs-no-generator-required obj)) (defmethod get-sorted-and-activated-ccs ((obj transparency)) (get-sorted-and-activated-ccs-no-generator-required obj)) (defmethod get-sorted-and-activated-ccs ((obj visco-object)) (let ((generator (find-if #'(lambda (cc) (and (activated-p cc) evtl . ist ein ignorierter Generator dennoch sehr gut ? ! (sorted-generators obj)))) (cons generator (remove-if #'(lambda (cc) (or (eq cc generator) (ignored-p cc) (not (activated-p cc)))) (sorted-testers obj))))) ;;; ;;; ;;; (defun get-object-rank-no-generator-required (obj) (loop as cc in (sorted-testers obj) when (and (activated-p cc) (not (ignored-p cc))) sum (tester-rank cc))) (defmethod get-object-rank ((obj enclosure)) (get-object-rank-no-generator-required obj)) (defmethod get-object-rank ((obj transparency)) (get-object-rank-no-generator-required obj)) (defmethod get-object-rank ((obj visco-object)) (let ((generator (find-if #'activated-p (sorted-generators obj)))) (* (1+ (generator-rank generator)) (loop as cc in (sorted-testers obj) when (and (not (eq cc generator)) (activated-p cc) (not (ignored-p cc))) sum (tester-rank cc))))) ;;; ;;; ;;; (defmethod compare-nodes ((node1 visco-object) (node2 visco-object)) (typecase node1 (transparency t) (enclosure (activated-p (on-transparency node1))) (otherwise (typecase node2 (transparency nil) (enclosure (not (activated-p (on-transparency node2)))) (otherwise (> (get-object-rank node1) ; echte Kosten (get-object-rank node2))))))) ;;; ;;; ;;; (defun finalize-and-install-plan (plan) (dolist (obj plan) (setf (activated-and-sorted-compiler-conditions obj) (get-sorted-and-activated-ccs obj)) (activate obj)) (deactivate-all (reverse plan)) plan) (defun determine-best-plan (plans) (finalize-and-install-plan (get-best plans))) (defun get-best (plans) (let ((max-rank nil) (max-plan nil)) (dolist (plan plans max-plan) (let ((rank (get-plan-rank plan))) (when (or (not max-rank) (> rank max-rank)) (setf max-rank rank max-plan plan)))))) (defun get-plan-rank (plan) (let ((count 0)) (prog1 (loop as obj in plan sum (float (* (get-object-rank obj) (exp count))) do (progn (decf count) (activate obj))) (deactivate-all (reverse plan))))) ;;; ;;; ;;; (defconstant +generator-hash-pos+ (let ((ht (make-hash-table)) (order '(cc-construct-chain-or-polygon-from-components cc-construct-atomic-rubberband-from-components cc-construct-rubberband-from-components cc-construct-intersection-point cc-has-centroid cc-centroid-of cc-endpoint-of cc-has-endpoint cc-joins cc-position-is cc-segment-of cc-has-segment cc-point-of cc-has-point cc-rubberband-of cc-has-rubberband cc-intersects cc-inside cc-contains cc-inside-epsilon))) (dolist (g order) (setf (gethash g ht) (position g order))) ht)) (defmethod generator-is-better-than-p ((cc1 compiler-condition) (cc2 compiler-condition)) (let ((pos1 (or (gethash (type-of cc1) +generator-hash-pos+) 1000)) (pos2 (or (gethash (type-of cc2) +generator-hash-pos+) 1000))) (if (= pos1 pos2) (compare-equal-generators cc1 cc2) (< pos1 pos2)))) (defmethod compare-equal-generators ((cc1 compiler-condition) (cc2 compiler-condition)) nil) ;;; ;;; ;;; (defconstant +tester-hash-pos+ (let ((ht (make-hash-table)) (order '(cc-type-is cc-is-primary cc-position-is cc-position-is-inverse cc-semantics-is cc-length-is cc-length-is-inverse cc-orientation-is cc-orientation-is-inverse cc-angle-between cc-has-centroid cc-centroid-of cc-endpoint-of cc-has-endpoint cc-joins cc-point-of cc-has-point cc-segment-of cc-has-segment cc-construct-atomic-rubberband-from-components cc-at-most-has-segments-is cc-at-least-has-segments-is cc-rubberband-of cc-has-rubberband cc-construct-rubberband-from-components cc-construct-chain-or-polygon-from-components cc-intersects cc-disjoint cc-inside cc-contains cc-outside cc-excludes cc-inside-epsilon cc-epsilon-contains #| cc-relations-exists-is |#))) (dolist (g order) (setf (gethash g ht) (position g order))) ht)) (defmethod tester-is-better-than-p ((cc1 compiler-condition) (cc2 compiler-condition)) (let ((pos1 (or (gethash (type-of cc1) +tester-hash-pos+) 1000)) (pos2 (or (gethash (type-of cc2) +tester-hash-pos+) 1000))) (if (= pos1 pos2) (compare-equal-testers cc1 cc2) (< pos1 pos2)))) (defmethod compare-equal-testers ((cc1 compiler-condition) (cc2 compiler-condition)) nil) (defmethod compare-equal-testers ((cc1 cc-type-is) (cc2 cc-type-is)) (let ((c1 (candidate cc1)) (c2 (candidate cc2))) (typecase c1 (chain-or-polygon t) (line (or (typep c2 'point) (typep c2 'rubberband))) (point (not (typep c2 'rubberband))) (rubberband nil))))
null
https://raw.githubusercontent.com/lambdamikel/VISCO/836d325b5c6037517470835c635b3063446d3d8a/src/query-compiler/optimizer10.lisp
lisp
Syntax : Ansi - Common - Lisp ; Package : QUERY - COMPILER ; Base : 10 -*- echte Kosten cc-relations-exists-is
(in-package query-compiler) (defun get-sorted-and-activated-ccs-no-generator-required (obj) (remove-if #'(lambda (cc) (or (not (activated-p cc)) (ignored-p cc))) (sorted-testers obj))) (defmethod get-sorted-and-activated-ccs ((obj enclosure)) (get-sorted-and-activated-ccs-no-generator-required obj)) (defmethod get-sorted-and-activated-ccs ((obj transparency)) (get-sorted-and-activated-ccs-no-generator-required obj)) (defmethod get-sorted-and-activated-ccs ((obj visco-object)) (let ((generator (find-if #'(lambda (cc) (and (activated-p cc) evtl . ist ein ignorierter Generator dennoch sehr gut ? ! (sorted-generators obj)))) (cons generator (remove-if #'(lambda (cc) (or (eq cc generator) (ignored-p cc) (not (activated-p cc)))) (sorted-testers obj))))) (defun get-object-rank-no-generator-required (obj) (loop as cc in (sorted-testers obj) when (and (activated-p cc) (not (ignored-p cc))) sum (tester-rank cc))) (defmethod get-object-rank ((obj enclosure)) (get-object-rank-no-generator-required obj)) (defmethod get-object-rank ((obj transparency)) (get-object-rank-no-generator-required obj)) (defmethod get-object-rank ((obj visco-object)) (let ((generator (find-if #'activated-p (sorted-generators obj)))) (* (1+ (generator-rank generator)) (loop as cc in (sorted-testers obj) when (and (not (eq cc generator)) (activated-p cc) (not (ignored-p cc))) sum (tester-rank cc))))) (defmethod compare-nodes ((node1 visco-object) (node2 visco-object)) (typecase node1 (transparency t) (enclosure (activated-p (on-transparency node1))) (otherwise (typecase node2 (transparency nil) (enclosure (not (activated-p (on-transparency node2)))) (otherwise (get-object-rank node2))))))) (defun finalize-and-install-plan (plan) (dolist (obj plan) (setf (activated-and-sorted-compiler-conditions obj) (get-sorted-and-activated-ccs obj)) (activate obj)) (deactivate-all (reverse plan)) plan) (defun determine-best-plan (plans) (finalize-and-install-plan (get-best plans))) (defun get-best (plans) (let ((max-rank nil) (max-plan nil)) (dolist (plan plans max-plan) (let ((rank (get-plan-rank plan))) (when (or (not max-rank) (> rank max-rank)) (setf max-rank rank max-plan plan)))))) (defun get-plan-rank (plan) (let ((count 0)) (prog1 (loop as obj in plan sum (float (* (get-object-rank obj) (exp count))) do (progn (decf count) (activate obj))) (deactivate-all (reverse plan))))) (defconstant +generator-hash-pos+ (let ((ht (make-hash-table)) (order '(cc-construct-chain-or-polygon-from-components cc-construct-atomic-rubberband-from-components cc-construct-rubberband-from-components cc-construct-intersection-point cc-has-centroid cc-centroid-of cc-endpoint-of cc-has-endpoint cc-joins cc-position-is cc-segment-of cc-has-segment cc-point-of cc-has-point cc-rubberband-of cc-has-rubberband cc-intersects cc-inside cc-contains cc-inside-epsilon))) (dolist (g order) (setf (gethash g ht) (position g order))) ht)) (defmethod generator-is-better-than-p ((cc1 compiler-condition) (cc2 compiler-condition)) (let ((pos1 (or (gethash (type-of cc1) +generator-hash-pos+) 1000)) (pos2 (or (gethash (type-of cc2) +generator-hash-pos+) 1000))) (if (= pos1 pos2) (compare-equal-generators cc1 cc2) (< pos1 pos2)))) (defmethod compare-equal-generators ((cc1 compiler-condition) (cc2 compiler-condition)) nil) (defconstant +tester-hash-pos+ (let ((ht (make-hash-table)) (order '(cc-type-is cc-is-primary cc-position-is cc-position-is-inverse cc-semantics-is cc-length-is cc-length-is-inverse cc-orientation-is cc-orientation-is-inverse cc-angle-between cc-has-centroid cc-centroid-of cc-endpoint-of cc-has-endpoint cc-joins cc-point-of cc-has-point cc-segment-of cc-has-segment cc-construct-atomic-rubberband-from-components cc-at-most-has-segments-is cc-at-least-has-segments-is cc-rubberband-of cc-has-rubberband cc-construct-rubberband-from-components cc-construct-chain-or-polygon-from-components cc-intersects cc-disjoint cc-inside cc-contains cc-outside cc-excludes cc-inside-epsilon cc-epsilon-contains (dolist (g order) (setf (gethash g ht) (position g order))) ht)) (defmethod tester-is-better-than-p ((cc1 compiler-condition) (cc2 compiler-condition)) (let ((pos1 (or (gethash (type-of cc1) +tester-hash-pos+) 1000)) (pos2 (or (gethash (type-of cc2) +tester-hash-pos+) 1000))) (if (= pos1 pos2) (compare-equal-testers cc1 cc2) (< pos1 pos2)))) (defmethod compare-equal-testers ((cc1 compiler-condition) (cc2 compiler-condition)) nil) (defmethod compare-equal-testers ((cc1 cc-type-is) (cc2 cc-type-is)) (let ((c1 (candidate cc1)) (c2 (candidate cc2))) (typecase c1 (chain-or-polygon t) (line (or (typep c2 'point) (typep c2 'rubberband))) (point (not (typep c2 'rubberband))) (rubberband nil))))
aeea2cc65c34eb7cf013e0331cee38362c788bcf6656f8269aa90385fb0ad7e2
informatimago/lisp
list.lisp
-*- coding : utf-8 -*- ;;;;**************************************************************************** ;;;;FILE: list.lisp ;;;;LANGUAGE: common-lisp ;;;;SYSTEM: UNIX USER - INTERFACE : UNIX ;;;;DESCRIPTION ;;;; This module exports some list utility functions. < PJB > < > MODIFICATIONS 2015 - 08 - 19 < PJB > Removed dll from this package . cf . the dll package . 2014 - 11 - 18 < PJB > Added map - cartesian - product . 2012 - 03 - 14 < PJB > Added plist - keys . 2012 - 02 - 19 < PJB > Moved HASHED- * functions that work on sequence to COM.INFORMATIMAGO.COMMON - LISP.CESARUM.SEQUENCE . 2011 - 04 - 03 < PJB > Added LIST - LENGTHS . 2008 - 06 - 24 < PJB > Added ENSURE - CIRCULAR , MAKE - CIRCULAR - LIST , CIRCULAR - LENGTH . 2007 - 01 - 05 < PJB > Added REPLACE - TREE ( should move to a new package later ) . 2005 - 09 - 02 < PJB > Moved EQUIVALENCE - CLASSES in from ECMA048 . 2005 - 08 - 10 < PJB > Moved TRIM - LIST in from make - depends . 2004 - 10 - 15 < PJB > Added IOTA . 2004 - 08 - 24 < PJB > Added TRANSPOSE , HASHED - REMOVE - DUPLICATE . 2003 - 06 - 10 < PJB > Added NSPLIT - LIST 2002 - 12 - 03 < PJB > Common - Lisp'ized . 2001 - 11 - 30 < PJB > Added list - remove - elements . ? ? < PJB > Creation . ;;;;LEGAL AGPL3 ;;;; Copyright 2002 - 2016 ;;;; ;;;; 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 </> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" (:use "COMMON-LISP") (:export "APPENDF" "PREPENDF" "PREPEND" "PUSH*" "EQUIVALENCE-CLASSES" "SUBSETS" "COMBINE" "IOTA" "MAKE-LIST-OF-RANDOM-NUMBERS" "LIST-INSERT-SEPARATOR" "NSPLIT-LIST-ON-INDICATOR" "NSPLIT-LIST" "DEEPEST-REC" "DEEPEST" "DEPTH" "FLATTEN" "LIST-TRIM" "TRANSPOSE" "AGET" "MEMQ" "MAP-CARTESIAN-PRODUCT" "PLIST-KEYS" "PLIST-REMOVE" "PLIST-GET" "PLIST-PUT" "PLIST-CLEANUP" "HASHED-INTERSECTION" " HASHED - REMOVE - DUPLICATES " moved to COM.INFORMATIMAGO.COMMON - LISP.CESARUM.SEQUENCE "ENSURE-LIST" "PROPER-LIST-P" "LIST-LENGTHS" "LIST-ELEMENTS" "ENSURE-CIRCULAR" "MAKE-CIRCULAR-LIST" "CIRCULAR-LENGTH" "TREE-FIND" "TREE-DIFFERENCE" "REPLACE-TREE" "META-LIST" "MAPTREE") (:documentation " This package exports list processing functions. License: AGPL3 Copyright Pascal J. Bourguignon 2003 - 2014 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 </> ")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST") (defun prepend (tail &rest lists) (apply (function append) (append lists (list tail)))) (define-modify-macro prependf (&rest lists) prepend "Prepend the LISTS at the beginning of the PLACE.") (define-modify-macro appendf (&rest lists) append "Append the LISTS at the end of the PLACE.") (defmacro push* (&rest elements-and-place) `(prependf ,(car (last elements-and-place)) (list ,@(butlast elements-and-place)))) (assert (equal (let ((i -1) (v (vector nil))) (push* 5 6 7 8 (aref v (incf i))) (decf i) (push* 1 2 3 4 (aref v (incf i))) (aref v 0)) '(1 2 3 4 5 6 7 8))) (defun meta-list (list) " Returns a list whose CARs are the CONS cells of the LIST. LIST must be a proper list. " (loop :for meta :on list :collect meta)) (defun ensure-list (object) " RETURN: If OBJECT is a list then OBJECT, otherwise a fresh list containing OBJECT. " (if (listp object) object (list object))) (defun proper-list-p (object) " RETURN: whether OBJECT is a proper list NOTE: terminates with any kind of list, dotted, circular, etc. " (and (listp object) (loop :named proper :for current = object :then (cddr current) :for slow = (cons nil object) :then (cdr slow) :do (cond ((null current) (return-from proper t)) ((atom current) (return-from proper nil)) ((null (cdr current)) (return-from proper t)) ((atom (cdr current)) (return-from proper nil)) ((eq current slow) (return-from proper nil))))) #-(and) (labels ((proper (current slow) (cond ((null current) t) ((atom current) nil) ((null (cdr current)) t) ((atom (cdr current)) nil) ((eq current slow) nil) (t (proper (cddr current) (cdr slow)))))) (and (listp object) (proper object (cons nil object))))) (defun dotted-list-length (dotted-list) " DOTTED-LIST must be a dotted list or a proper list. RETURN: the number of cons cells in the list. " (loop :for length :from 0 :for current = dotted-list :then (cdr current) :until (atom current) :finally (return length))) (defun circular-list-lengths (circular-list) " CIRCULAR-LIST must be a circular list. RETURN: the length of the stem; the length of the circle. " (let ((cells (make-hash-table))) (loop :for index :from 0 :for cell = circular-list :then (cdr cell) :for previous = (gethash cell cells) :do (if previous (return-from circular-list-lengths (values previous (- index previous))) (setf (gethash cell cells) index))))) (defun list-lengths (list) " LIST is any kind of list: proper-list, circular-list or dotted-list. RETURN: for a proper list, the length of the list and 0; for a circular list, the length of the stem, and the length of the circle; for a dotted list, the number of cons cells, and nil; for an atom, 0, and nil. " (typecase list (cons (loop :named proper :for current = list :then (cddr current) :for slow = (cons nil list) :then (cdr slow) :do (cond ((null current) (return-from proper (values (list-length list) 0))) ((atom current) (return-from proper (values (dotted-list-length list) nil))) ((null (cdr current)) (return-from proper (values (list-length list) 0))) ((atom (cdr current)) (return-from proper (values (dotted-list-length list) nil))) ((eq current slow) (return-from proper (circular-list-lengths list)))))) (null (values 0 0)) (t (values 0 nil))) #-(and) (labels ((proper (current slow) ;; (print (list 'proper current slow)) (cond ((null current) (values (list-length list) 0)) ((atom current) (values (dotted-list-length list) nil)) ((null (cdr current)) (values (list-length list) 0)) ((atom (cdr current)) (values (dotted-list-length list) nil)) ((eq current slow) (circular-list-lengths list)) (t (proper (cddr current) (cdr slow)))))) (typecase list (cons (proper list (cons nil list))) (null (values 0 0)) (t (values 0 nil))))) (defun list-elements (clist) " CLIST is any kind of list: proper-list, circular-list or dotted-list. RETURN: for a proper list: a copy of clist, the length of the list and 0; for a circular list: a list of elements in the clist, the length of the stem, and the length of the circle; for a dotted list: a list of the elements in the clist, the number of cons cells, and nil; for an atom: a list of the atom, 0, and nil. " (cond ((null clist) ; a proper list (values '() 0 0)) ((atom clist) (values (list clist) 0 nil)) (t (loop :named scan :with cells = (make-hash-table) :with elements = '() :for index :from 0 :for cell = clist :then (cdr cell) :for previous = (gethash cell cells) :do (cond ((null cell) ; proper list (return-from scan (values (nreverse elements) index 0))) ((atom cell) ; dotted list (push cell elements) (return-from scan (values (nreverse elements) index nil))) (previous ; a circular list (return-from scan (values (nreverse elements) previous (- index previous)))) (t ; in the middle (setf (gethash cell cells) index) (push (car cell) elements))))))) (defun ensure-circular (list) " If list is not a circular list, then modify it to make it circular. RETURN: LIST " (if (proper-list-p list) (setf (cdr (last list)) list) list)) (defun make-circular-list (size &key initial-element) " RETURN: a new circular list of length SIZE. POST: (circular-length (make-circular-list size)) == (values size 0 size) " (let ((list (make-list size :initial-element initial-element))) (setf (cdr (last list)) list) list)) (defun circular-length (list) "LIST must be either a proper-list or a circular-list, not a dotted-list. RETURN: the total length ; the length of the stem ; the length of the circle. " (let ((indexes (make-hash-table))) (loop :for i :from 0 :for current :on list :do (let ((index (gethash current indexes))) (if index ;; found loop (return (values i index (- i index))) (setf (gethash current indexes) i))) :finally (return (values i i 0))))) (defun map-cartesian-product (fun &rest lists) " DO: Call FUN with as arguments the elements of the cartesian products of the lists in LISTS. RETURN: A list of all the results of FUN. EXAMPLE: (map-cartesian-product (function list) '(1 2 3) '(a b c) '(11 22)) --> ((1 a 11) (1 a 22) (1 b 11) (1 b 22) (1 c 11) (1 c 22) (2 a 11) (2 a 22) (2 b 11) (2 b 22) (2 c 11) (2 c 22) (3 a 11) (3 a 22) (3 b 11) (3 b 22) (3 c 11) (3 c 22)) " (unless (null lists) (if (null (cdr lists)) (mapcar fun (car lists)) (mapcan (lambda (element) (apply (function map-cartesian-product) (lambda (&rest args) (apply fun element args)) (cdr lists))) (car lists))))) (declaim (inline plist-put plist-get plist-remove memq)) (defun plist-keys (plist) "Returns a list of the properties in PLIST." (remove-duplicates (loop :for (key) :on plist :by (function cddr) :collect key))) (defun plist-cleanup (plist) "Returns a plist that has the same associations than PLIST, but with a single occurence of each key and the first value found. EXAMPLE: (plist-cleanup '(:a 1 :b 2 :a 11 :c 3)) --> (:b 2 :c 3 :a 1) " (loop :with h = (make-hash-table) :for (key value) :on plist :by (function cddr) :do (when (eq h (gethash key h h)) (setf (gethash key h) value)) :finally (let ((result '())) (maphash (lambda (key value) (push value result) (push key result)) h) (return result)))) (defun plist-put (plist prop value) " Change value in PLIST of PROP to VALUE. PLIST is a property list, which is a list of the form (PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VALUE is any object. If PROP is already a property on the list, its value is set to VALUE, otherwise the new PROP VALUE pair is added. The new plist is returned; use `(setq x (plist-put x prop val))' to be sure to use the new value. The PLIST is modified by side effects. " (setf (getf plist prop) value) plist) (defun plist-get (plist prop) " Extract a value from a property list. PLIST is a property list, which is a list of the form (PROP1 VALUE1 PROP2 VALUE2...). This function returns the value corresponding to the given PROP, or nil if PROP is not one of the properties on the list. " (getf plist prop)) (defun plist-remove (plist prop) " DO: (REMF PLIST PROP) RETURN: The modified PLIST. " (remf plist prop) plist) (defun memq (item list) " RETURN: (MEMBER ITEM LIST :TEST (FUNCTION EQ)) " (member item list :test (function eq))) (defun transpose (tree) " RETURN: A tree where all the CAR and CDR are exchanged. " (if (atom tree) tree (cons (transpose (cdr tree)) (transpose (car tree))))) (defun list-trim (bag list &key (test (function eql)) (key (function identity))) " RETURN: A sublist of LIST with the elements in the BAG removed from both ends. " (do ((list (reverse list) (cdr list))) ((or (null list) (not (member (car list) bag :test test :key key))) (do ((list (nreverse list) (cdr list))) ((or (null list) (not (member (car list) bag :test test :key key))) list))))) (defun list-trim-test () (every (lambda (x) (equalp '(d e f) x)) (list (list-trim '(a b c) '( a b c d e f a b c c c )) (list-trim '((a 1)(b 2)(c 3)) '( a b c d e f a b c c ) :key (function car)) (list-trim '(:a :b :c) '( a b c d e f a b c c ) :test (function string=)) (list-trim '(a b c) '( a b c d e f)) (list-trim '(a b c) '( d e f a b c c c ))))) (defun maptree (fun &rest trees) " DO: Calls FUN on each non-null atom of the TREES. PRE: The trees in TREES must be congruent, or else the result is pruned like the smallest tree. RETURN: A tree congruent to the TREES, each node being the result of FUN (it may be a subtree). " (cond ((null trees) nil) ((every (function null) trees) nil) ((every (function atom) trees) (apply fun trees)) ((every (function consp) trees) (cons (apply (function maptree) fun (mapcar (function car) trees)) (apply (function maptree) fun (mapcar (function cdr) trees)))) (t nil))) (defun flatten (tree) " RETURN: A list containing all the elements of the `tree'. " (loop :with result = nil :with stack = nil :while (or tree stack) :do (cond ((null tree) (setq tree (pop stack))) ((atom tree) (push tree result) (setq tree (pop stack))) ((listp (car tree)) (push (cdr tree) stack) (setq tree (car tree))) (t (push (car tree) result) (setq tree (cdr tree)))) :finally (return (nreverse result)))) (defun depth (tree) " RETURN: The depth of the tree. " (if (atom tree) 0 (1+ (apply (function max) 0 (do ((tree tree (cdr tree)) (results '())) ((atom tree) results) (if (listp (car tree)) (push (depth (car tree)) results))))))) (defun deepest-rec (tree) " RETURN: The deepest list in the tree. NOTE: Recursive algorithm. SEE-ALSO: deepest-iti " (let ((subtree (delete-if (function atom) tree))) (cond ((null subtree) tree) ((every (lambda (item) (every (function atom) item)) subtree) (car subtree)) (t (deepest-rec (apply 'concatenate 'list subtree)))))) (defun deepest (tree) " RETURN: The deepest list in the tree. NOTE: Iterative algorithm. SEE-ALSO: deepest-rec " (do* ((tree tree (apply 'concatenate 'list subtree)) (subtree (delete-if (function atom) tree) (delete-if (function atom) tree))) ((or (null subtree) (every (lambda (item) (every (function atom) item)) subtree)) (if (null subtree) tree (car subtree))))) (defun nsplit-list (list position &key (from-end nil)) " PRE: 0<=POSITION<=(LENGTH LIST) DO: SPLIT THE LIST IN TWO AT THE GIVEN POSITION. (NSPLIT-LIST (LIST 'A 'B 'C) 0) --> NIL ; (A B C) (NSPLIT-LIST (LIST 'A 'B 'C) 1) --> (A) ; (B C) (NSPLIT-LIST (LIST 'A 'B 'C) 2) --> (A B) ; (C) NIL POSITION: POSITION OF THE SPLIT; WHEN FROM-START AND 0<=POSITION<=(LENGTH LIST), THAT'S THE LENGTH OF THE FIRST RESULT FROM-START: THE DEFAULT, SPLIT COUNTING FROM THE START. FROM-END: WHEN SET, COUNT FROM THE END OF THE LIST. (NSPLIT-LIST L P :FROM-END T) === (NSPLIT-LIST L (- (LENGTH L) P)) RETURN: THE FIRST PART ; THE LAST PART " (if from-end (nsplit-list list (- (length list) position)) (do* ((prev nil rest) (rest list (cdr rest))) ((or (null rest) (zerop position)) (progn (if prev (setf (cdr prev) nil) (setf list nil)) (values list rest))) (decf position)))) (defun nsplit-list-on-indicator (list indicator) " RETURN: a list of sublists of list (the conses from list are reused), the list is splited between items a and b for which (indicator a b). " (declare (type (function (t t) t) indicator)) (let* ((result nil) (sublist list) (current list) (next (cdr current))) (loop :while next :do (if (funcall indicator (car current) (car next)) (progn ;; split (setf (cdr current) nil) (push sublist result) (setq current next) (setq next (cdr current)) (setq sublist current)) (progn ;; keep (setq current next) (setq next (cdr current))))) (push sublist result) (nreverse result))) (defun list-insert-separator (list separator) " RETURN: A list composed of all the elements in `list' with `separator' in-between. EXAMPLE: (list-insert-separator '(a b (d e f) c) 'x) ==> (a x b x (d e f) x c) " (cond ((null list) '()) ((null (cdr list)) (list (car list))) (t (do ((result '()) (items list (cdr items))) ((endp items) (nreverse (cdr result))) (push (car items) result) (push separator result))))) (defun iota (count &optional (start 0) (step 1)) " RETURN: A list containing the elements (start start+step ... start+(count-1)*step) The start and step parameters default to 0 and 1, respectively. This procedure takes its name from the APL primitive. EXAMPLE: (iota 5) => (0 1 2 3 4) (iota 5 0 -0.1) => (0 -0.1 -0.2 -0.3 -0.4) " (loop :repeat count :for item = start :then (+ item step) :collect item)) (defun make-list-of-random-numbers (length &key (modulo most-positive-fixnum)) " RETURN: A list of length `length' filled with random numbers MODULO: The argument to RANDOM. " (loop while (< 0 length) collect (random modulo) into result do (setq length (1- length)) finally (return result))) (defun combine (&rest args) " RETURN: (elt args 0) x (elt args 1) x ... x (elt args (1- (length args))) = the set of tuples built taking one item in order from each list in args. EXAMPLE: (COMBINE '(WWW FTP) '(EXA) '(COM ORG))) --> ((WWW EXA COM) (WWW EXA ORG) (FTP EXA COM) (FTP EXA ORG)) " (cond ((null args) '(())) Do n't consider empty set for one of the arguments since the combination ;; should produce the empty set: ;; {} x {1,2} = {} ;; Instead, let it fall to the default case, considering it as the symbol NIL. ;; ((null (car args)) (apply (function combine) (cdr args))) ((consp (car args)) (mapcan (lambda (item) (apply (function combine) item (cdr args))) (car args))) (t (mapcan (lambda (rest) (list (cons (car args) rest))) (apply (function combine) (cdr args)))))) ;; Sets: (defun hashed-intersection (set1 set2) " AUTHORS: Paul F. Dietz <> Thomas A. Russ <> " (declare (optimize speed (safety 0) (debug 0)) (list set1 set2)) (let ((table (make-hash-table :size (length set2))) (result nil)) (dolist (e set2) (setf (gethash e table) t)) (dolist (e set1) (when (gethash e table) (push e result) (setf (gethash e table) nil))) result)) (defun subsets (set) " RETURN: The set of all subsets of the strict SET. " (loop :with card = (length set) :for indicator :from 0 :below (expt 2 card) :collect (loop :for index :from 0 :below card :for item :in set :nconc (if (logbitp index indicator) (list item) nil) :into result :finally (return result)) :into result :finally (return result))) (defun equivalence-classes (set &key (test (function eql)) (key (function identity))) " RETURN: The equivalence classes of SET, via KEY, modulo TEST. " (loop :with classes = '() :for item :in set :for item-key = (funcall key item) :for class = (car (member item-key classes :test test :key (function second))) :do (if class (push item (cddr class)) (push (list :class item-key item ) classes)) :finally (return (mapcar (function cddr) classes)))) ;; A-lists: (defun aget (place indicator &optional default) " RETURN: The value of the entry INDICATOR of the a-list PLACE, or DEFAULT. " (let ((a (assoc indicator place))) (if a (cdr a) default))) ( DEFSETF AGET ( PLACE INDICATOR & OPTIONAL DEFAULT ) ( VALUE ) ;; " ;; DO: Set or add a new entry INDICATOR in the a-list at PLACE. ;; " ;; (DECLARE (IGNORE DEFAULT)) ;; (ERROR "THIS DOES NOT WORK. DEALING WITH SETF EXPANSION IS NEEDED HERE!") ;; (LET ((ACS (GENSYM "AC"))) ;; `(LET* ((,ACS (ASSOC ,INDICATOR ,PLACE))) ;; (IF ,ACS ( SETF ( CDR , ACS ) , VALUE ) ( SETF , PLACE ( ACONS , INDICATOR , VALUE , PLACE ) ) ) ;; ,VALUE))) (define-setf-expander aget (place indicator &optional default &environment env) (multiple-value-bind (vars vals store-vars writer-form reader-form) (get-setf-expansion place env) (let* ((vindicator (gensym "INDICATOR")) (vvalue (gensym "VALUE")) (vstore (first store-vars)) (acs (gensym "PAIR"))) (values (list* vindicator vars) (list* indicator vals) (list vvalue) `(let* ((,acs (assoc ,vindicator ,reader-form))) (if ,acs (setf (cdr ,acs) ,vvalue) (let ((,vstore (acons ,vindicator ,vvalue ,reader-form))) ,writer-form)) ,vvalue) `(let ((,acs (assoc ,vindicator ,reader-form))) (if ,acs (cdr ,acs) ,default)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun tree-find (object tree &key (key (function identity)) (test (function eql))) " RETURN: The object in TREE that matches OBJECT (using the KEY and TEST functions. TREE: A sexp. " (if (atom tree) (if (funcall test object (funcall key tree)) tree nil) (or (tree-find object (car tree) :key key :test test) (tree-find object (cdr tree) :key key :test test)))) (defun tree-difference (a b &key (test (function eql))) " RETURN: A tree congruent to A and B where each node is = when the corresponding nodes are equal (as indicated by TEST), or (/= a-elem b-elem) otherwise. EXAMPLE: (tree-difference '((a b c) 1 (d e f)) '((a b c) (1) (d x f))) --> ((= = = . =) (/= 1 (1)) (= (/= e x) = . =) . =) " (cond ((funcall test a b) '=) ((or (atom a) (atom b)) `(/= ,a ,b)) (t (cons (tree-difference (car a) (car b) :test test) (tree-difference (cdr a) (cdr b) :test test))))) (defun tree-structure-and-leaf-difference (a b &key (test (function eql))) (cond ((and (null a) (null b)) '=) ((or (null a) (null b)) `(/= ,a ,b)) ((and (atom a) (atom b)) (if (funcall test a b) '= `(/= ,a ,b))) ((or (atom a) (atom b)) `(/= ,a ,b)) (t (cons (tree-structure-and-leaf-difference (car a) (car b) :test test) (tree-structure-and-leaf-difference (cdr a) (cdr b) :test test))))) (defun replace-tree (dst src) " DO: Copies the elements of the src tree into the dst tree. If dst is missing cons cells, structure sharing occurs. RETURN: dst " (cond ((atom dst) src) ((atom src) nil) (t (if (or (atom (car dst)) (atom (car src))) (setf (car dst) (car src)) (replace-tree (car dst) (car src))) (if (or (atom (cdr dst)) (atom (cdr src))) (setf (cdr dst) (cdr src)) (replace-tree (cdr dst) (cdr src))) dst))) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; Sets ;;; (DEFUN CONS-LESSP (A B) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (DO* ( (AP A (CDR AP)) ;;; (AI (CAR AP) (CAR AP)) ( BP B ( CDR BP ) ) ;;; (BI (CAR BP) (CAR BP)) ) ( ( NOT ( AND AI BI ( EQ AI BI ) ) ) ;;; (ANY-LESSP AI BI) ) ;;; ) ) ; ; ( DEFUN FORMATED - LESSP ( A B ) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (STRING-LESSP (FORMAT NIL "~S" A) (FORMAT NIL "~S" B)) ;;; );;formated-lessp ( DEFUN SYMBOL - LESSP ( A B ) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (STRING-LESSP (SYMBOL-NAME A) (SYMBOL-NAME B)) ) ; ; ( DEFUN VECTOR - LESSP ( A B ) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (IF (= (LENGTH A) (LENGTH B)) ;;; (LOOP FOR I FROM 0 BELOW (LENGTH A) ;;; FOR AI = (AREF A I) ;;; FOR BI = (AREF B I) WHILE ( EQ AI BI ) ;;; ;;do (show ai bi) ;;; ;;finally (show ai bi) (show (or bi (not ai))) ;;; FINALLY (RETURN (ANY-LESSP AI BI))) ;;; (< (LENGTH A) (LENGTH B))) ) ; ; vector - lessp ( DEFUN ANY - LESSP ( A B ) ;;; "PRIVATE. ;;; RETURN: a<=b ;;; " ;;; (IF (EQ (TYPE-OF A) (TYPE-OF B)) ;;; (FUNCALL ;;; (CDR (ASSOC ;;; (TYPE-OF A) ' ( ( BOOL - VECTOR . VECTOR - LESSP ) ( BUFFER . FORMATED - LESSP ) ( CHAR - TABLE . VECTOR - LESSP ) ( COMPILED - FUNCTION . VECTOR - LESSP ) ;;; (CONS . CONS-LESSP) ;;; (FLOAT . <=) ( FRAME . FORMATED - LESSP ) ( INTEGER . < =) ( MARKER . < =) ( OVERLAY . FORMATED - LESSP ) ( PROCESS . FORMATED - LESSP ) ;;; (STRING . STRING-LESSP) ( SUBR . FORMATED - LESSP ) ( SYMBOL . SYMBOL - LESSP ) ( VECTOR . VECTOR - LESSP ) ( WINDOW . FORMATED - LESSP ) ( WINDOW - CONFIGURATION . FORMATED - LESSP ) ;;; ))) A B) ;;; (STRING-LESSP (SYMBOL-NAME (TYPE-OF A)) ;;; (SYMBOL-NAME (TYPE-OF B)))) ;;; );;any-lessp ( DEFUN LIST - TO - SET - SORTED ( LIST ) ;;; " ;;; RETURN: A set, that is a list where duplicate elements from `list' are removed. NOTE : This implementation first sorts the list , so its complexity should be ;;; of the order of O(N*(1+log(N))) [N==(length list)] ;;; BUT, it's still slower than list-to-set ;;; " ;;; (IF (NULL LIST) ;;; NIL ;;; (LET* ((SORTED-LIST (SORT LIST 'ANY-LESSP)) ( FIRST ( CAR SORTED - LIST ) ) ;;; (REST (CDR SORTED-LIST)) ;;; (SET NIL)) ;;; (LOOP WHILE REST DO ;;; (IF (EQ FIRST (CAR REST)) ;;; (SETQ REST (CDR REST)) ( PROGN ;;; (PUSH FIRST SET) ;;; (SETQ FIRST (CAR REST) ;;; REST (CDR REST))))) ;;; SET)));;list-to-set-sorted ( loop for size = 10 then ( * 10 size ) ;;; for l1 = (make-list-of-random-numbers size) ;;; for l2 = (copy-seq l1) ;;; do ;;; (format t "~%-----------~%list-to-set (~s)~%-----------" size) ;;; (finish-output) ( time ( setf l1 ( list - to - set l1 ) ) ) ;;; (format t "~%-----------~%list-to-set-sorted (~s)~%-----------" size) ;;; (finish-output) ( time ( setf l2 ( list - to - set l2 ) ) ) ) ;; (array->list array) --> (coerce array 'list) ;;;; THE END ;;;;
null
https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/common-lisp/cesarum/list.lisp
lisp
**************************************************************************** FILE: list.lisp LANGUAGE: common-lisp SYSTEM: UNIX DESCRIPTION This module exports some list utility functions. LEGAL This program is free software: you can redistribute it and/or modify (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 along with this program. If not, see </> **************************************************************************** without even the implied warranty of the length of the circle. (print (list 'proper current slow)) a proper list proper list dotted list a circular list in the middle the length of the stem ; the length of the circle. found loop (A B C) (B C) (C) THE LAST PART split keep should produce the empty set: {} x {1,2} = {} Instead, let it fall to the default case, considering it as the symbol NIL. ((null (car args)) (apply (function combine) (cdr args))) Sets: A-lists: " DO: Set or add a new entry INDICATOR in the a-list at PLACE. " (DECLARE (IGNORE DEFAULT)) (ERROR "THIS DOES NOT WORK. DEALING WITH SETF EXPANSION IS NEEDED HERE!") (LET ((ACS (GENSYM "AC"))) `(LET* ((,ACS (ASSOC ,INDICATOR ,PLACE))) (IF ,ACS ,VALUE))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Sets (DEFUN CONS-LESSP (A B) "PRIVATE. RETURN: a<=b " (DO* ( (AP A (CDR AP)) (AI (CAR AP) (CAR AP)) (BI (CAR BP) (CAR BP)) ) (ANY-LESSP AI BI) ) ) ; "PRIVATE. RETURN: a<=b " (STRING-LESSP (FORMAT NIL "~S" A) (FORMAT NIL "~S" B)) );;formated-lessp "PRIVATE. RETURN: a<=b " (STRING-LESSP (SYMBOL-NAME A) (SYMBOL-NAME B)) ; "PRIVATE. RETURN: a<=b " (IF (= (LENGTH A) (LENGTH B)) (LOOP FOR I FROM 0 BELOW (LENGTH A) FOR AI = (AREF A I) FOR BI = (AREF B I) ;;do (show ai bi) ;;finally (show ai bi) (show (or bi (not ai))) FINALLY (RETURN (ANY-LESSP AI BI))) (< (LENGTH A) (LENGTH B))) ; vector - lessp "PRIVATE. RETURN: a<=b " (IF (EQ (TYPE-OF A) (TYPE-OF B)) (FUNCALL (CDR (ASSOC (TYPE-OF A) (CONS . CONS-LESSP) (FLOAT . <=) (STRING . STRING-LESSP) ))) A B) (STRING-LESSP (SYMBOL-NAME (TYPE-OF A)) (SYMBOL-NAME (TYPE-OF B)))) );;any-lessp " RETURN: A set, that is a list where duplicate elements from `list' are removed. of the order of O(N*(1+log(N))) [N==(length list)] BUT, it's still slower than list-to-set " (IF (NULL LIST) NIL (LET* ((SORTED-LIST (SORT LIST 'ANY-LESSP)) (REST (CDR SORTED-LIST)) (SET NIL)) (LOOP WHILE REST DO (IF (EQ FIRST (CAR REST)) (SETQ REST (CDR REST)) (PUSH FIRST SET) (SETQ FIRST (CAR REST) REST (CDR REST))))) SET)));;list-to-set-sorted for l1 = (make-list-of-random-numbers size) for l2 = (copy-seq l1) do (format t "~%-----------~%list-to-set (~s)~%-----------" size) (finish-output) (format t "~%-----------~%list-to-set-sorted (~s)~%-----------" size) (finish-output) (array->list array) --> (coerce array 'list) THE END ;;;;
-*- coding : utf-8 -*- USER - INTERFACE : UNIX < PJB > < > MODIFICATIONS 2015 - 08 - 19 < PJB > Removed dll from this package . cf . the dll package . 2014 - 11 - 18 < PJB > Added map - cartesian - product . 2012 - 03 - 14 < PJB > Added plist - keys . 2012 - 02 - 19 < PJB > Moved HASHED- * functions that work on sequence to COM.INFORMATIMAGO.COMMON - LISP.CESARUM.SEQUENCE . 2011 - 04 - 03 < PJB > Added LIST - LENGTHS . 2008 - 06 - 24 < PJB > Added ENSURE - CIRCULAR , MAKE - CIRCULAR - LIST , CIRCULAR - LENGTH . 2007 - 01 - 05 < PJB > Added REPLACE - TREE ( should move to a new package later ) . 2005 - 09 - 02 < PJB > Moved EQUIVALENCE - CLASSES in from ECMA048 . 2005 - 08 - 10 < PJB > Moved TRIM - LIST in from make - depends . 2004 - 10 - 15 < PJB > Added IOTA . 2004 - 08 - 24 < PJB > Added TRANSPOSE , HASHED - REMOVE - DUPLICATE . 2003 - 06 - 10 < PJB > Added NSPLIT - LIST 2002 - 12 - 03 < PJB > Common - Lisp'ized . 2001 - 11 - 30 < PJB > Added list - remove - elements . ? ? < PJB > Creation . AGPL3 Copyright 2002 - 2016 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 GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST" (:use "COMMON-LISP") (:export "APPENDF" "PREPENDF" "PREPEND" "PUSH*" "EQUIVALENCE-CLASSES" "SUBSETS" "COMBINE" "IOTA" "MAKE-LIST-OF-RANDOM-NUMBERS" "LIST-INSERT-SEPARATOR" "NSPLIT-LIST-ON-INDICATOR" "NSPLIT-LIST" "DEEPEST-REC" "DEEPEST" "DEPTH" "FLATTEN" "LIST-TRIM" "TRANSPOSE" "AGET" "MEMQ" "MAP-CARTESIAN-PRODUCT" "PLIST-KEYS" "PLIST-REMOVE" "PLIST-GET" "PLIST-PUT" "PLIST-CLEANUP" "HASHED-INTERSECTION" " HASHED - REMOVE - DUPLICATES " moved to COM.INFORMATIMAGO.COMMON - LISP.CESARUM.SEQUENCE "ENSURE-LIST" "PROPER-LIST-P" "LIST-LENGTHS" "LIST-ELEMENTS" "ENSURE-CIRCULAR" "MAKE-CIRCULAR-LIST" "CIRCULAR-LENGTH" "TREE-FIND" "TREE-DIFFERENCE" "REPLACE-TREE" "META-LIST" "MAPTREE") (:documentation " This package exports list processing functions. License: AGPL3 Copyright Pascal J. Bourguignon 2003 - 2014 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, 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 </> ")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST") (defun prepend (tail &rest lists) (apply (function append) (append lists (list tail)))) (define-modify-macro prependf (&rest lists) prepend "Prepend the LISTS at the beginning of the PLACE.") (define-modify-macro appendf (&rest lists) append "Append the LISTS at the end of the PLACE.") (defmacro push* (&rest elements-and-place) `(prependf ,(car (last elements-and-place)) (list ,@(butlast elements-and-place)))) (assert (equal (let ((i -1) (v (vector nil))) (push* 5 6 7 8 (aref v (incf i))) (decf i) (push* 1 2 3 4 (aref v (incf i))) (aref v 0)) '(1 2 3 4 5 6 7 8))) (defun meta-list (list) " Returns a list whose CARs are the CONS cells of the LIST. LIST must be a proper list. " (loop :for meta :on list :collect meta)) (defun ensure-list (object) " RETURN: If OBJECT is a list then OBJECT, otherwise a fresh list containing OBJECT. " (if (listp object) object (list object))) (defun proper-list-p (object) " RETURN: whether OBJECT is a proper list NOTE: terminates with any kind of list, dotted, circular, etc. " (and (listp object) (loop :named proper :for current = object :then (cddr current) :for slow = (cons nil object) :then (cdr slow) :do (cond ((null current) (return-from proper t)) ((atom current) (return-from proper nil)) ((null (cdr current)) (return-from proper t)) ((atom (cdr current)) (return-from proper nil)) ((eq current slow) (return-from proper nil))))) #-(and) (labels ((proper (current slow) (cond ((null current) t) ((atom current) nil) ((null (cdr current)) t) ((atom (cdr current)) nil) ((eq current slow) nil) (t (proper (cddr current) (cdr slow)))))) (and (listp object) (proper object (cons nil object))))) (defun dotted-list-length (dotted-list) " DOTTED-LIST must be a dotted list or a proper list. RETURN: the number of cons cells in the list. " (loop :for length :from 0 :for current = dotted-list :then (cdr current) :until (atom current) :finally (return length))) (defun circular-list-lengths (circular-list) " CIRCULAR-LIST must be a circular list. " (let ((cells (make-hash-table))) (loop :for index :from 0 :for cell = circular-list :then (cdr cell) :for previous = (gethash cell cells) :do (if previous (return-from circular-list-lengths (values previous (- index previous))) (setf (gethash cell cells) index))))) (defun list-lengths (list) " LIST is any kind of list: proper-list, circular-list or dotted-list. for an atom, 0, and nil. " (typecase list (cons (loop :named proper :for current = list :then (cddr current) :for slow = (cons nil list) :then (cdr slow) :do (cond ((null current) (return-from proper (values (list-length list) 0))) ((atom current) (return-from proper (values (dotted-list-length list) nil))) ((null (cdr current)) (return-from proper (values (list-length list) 0))) ((atom (cdr current)) (return-from proper (values (dotted-list-length list) nil))) ((eq current slow) (return-from proper (circular-list-lengths list)))))) (null (values 0 0)) (t (values 0 nil))) #-(and) (labels ((proper (current slow) (cond ((null current) (values (list-length list) 0)) ((atom current) (values (dotted-list-length list) nil)) ((null (cdr current)) (values (list-length list) 0)) ((atom (cdr current)) (values (dotted-list-length list) nil)) ((eq current slow) (circular-list-lengths list)) (t (proper (cddr current) (cdr slow)))))) (typecase list (cons (proper list (cons nil list))) (null (values 0 0)) (t (values 0 nil))))) (defun list-elements (clist) " CLIST is any kind of list: proper-list, circular-list or dotted-list. for an atom: a list of the atom, 0, and nil. " (cond (values '() 0 0)) ((atom clist) (values (list clist) 0 nil)) (t (loop :named scan :with cells = (make-hash-table) :with elements = '() :for index :from 0 :for cell = clist :then (cdr cell) :for previous = (gethash cell cells) :do (cond (return-from scan (values (nreverse elements) index 0))) (push cell elements) (return-from scan (values (nreverse elements) index nil))) (return-from scan (values (nreverse elements) previous (- index previous)))) (setf (gethash cell cells) index) (push (car cell) elements))))))) (defun ensure-circular (list) " If list is not a circular list, then modify it to make it circular. RETURN: LIST " (if (proper-list-p list) (setf (cdr (last list)) list) list)) (defun make-circular-list (size &key initial-element) " RETURN: a new circular list of length SIZE. POST: (circular-length (make-circular-list size)) == (values size 0 size) " (let ((list (make-list size :initial-element initial-element))) (setf (cdr (last list)) list) list)) (defun circular-length (list) "LIST must be either a proper-list or a circular-list, not a dotted-list. " (let ((indexes (make-hash-table))) (loop :for i :from 0 :for current :on list :do (let ((index (gethash current indexes))) (if index (return (values i index (- i index))) (setf (gethash current indexes) i))) :finally (return (values i i 0))))) (defun map-cartesian-product (fun &rest lists) " DO: Call FUN with as arguments the elements of the cartesian products of the lists in LISTS. RETURN: A list of all the results of FUN. EXAMPLE: (map-cartesian-product (function list) '(1 2 3) '(a b c) '(11 22)) --> ((1 a 11) (1 a 22) (1 b 11) (1 b 22) (1 c 11) (1 c 22) (2 a 11) (2 a 22) (2 b 11) (2 b 22) (2 c 11) (2 c 22) (3 a 11) (3 a 22) (3 b 11) (3 b 22) (3 c 11) (3 c 22)) " (unless (null lists) (if (null (cdr lists)) (mapcar fun (car lists)) (mapcan (lambda (element) (apply (function map-cartesian-product) (lambda (&rest args) (apply fun element args)) (cdr lists))) (car lists))))) (declaim (inline plist-put plist-get plist-remove memq)) (defun plist-keys (plist) "Returns a list of the properties in PLIST." (remove-duplicates (loop :for (key) :on plist :by (function cddr) :collect key))) (defun plist-cleanup (plist) "Returns a plist that has the same associations than PLIST, but with a single occurence of each key and the first value found. EXAMPLE: (plist-cleanup '(:a 1 :b 2 :a 11 :c 3)) --> (:b 2 :c 3 :a 1) " (loop :with h = (make-hash-table) :for (key value) :on plist :by (function cddr) :do (when (eq h (gethash key h h)) (setf (gethash key h) value)) :finally (let ((result '())) (maphash (lambda (key value) (push value result) (push key result)) h) (return result)))) (defun plist-put (plist prop value) " Change value in PLIST of PROP to VALUE. PLIST is a property list, which is a list of the form (PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VALUE is any object. If PROP is already a property on the list, its value is set to VALUE, use `(setq x (plist-put x prop val))' to be sure to use the new value. The PLIST is modified by side effects. " (setf (getf plist prop) value) plist) (defun plist-get (plist prop) " Extract a value from a property list. PLIST is a property list, which is a list of the form (PROP1 VALUE1 PROP2 VALUE2...). This function returns the value corresponding to the given PROP, or nil if PROP is not one of the properties on the list. " (getf plist prop)) (defun plist-remove (plist prop) " DO: (REMF PLIST PROP) RETURN: The modified PLIST. " (remf plist prop) plist) (defun memq (item list) " RETURN: (MEMBER ITEM LIST :TEST (FUNCTION EQ)) " (member item list :test (function eq))) (defun transpose (tree) " RETURN: A tree where all the CAR and CDR are exchanged. " (if (atom tree) tree (cons (transpose (cdr tree)) (transpose (car tree))))) (defun list-trim (bag list &key (test (function eql)) (key (function identity))) " RETURN: A sublist of LIST with the elements in the BAG removed from both ends. " (do ((list (reverse list) (cdr list))) ((or (null list) (not (member (car list) bag :test test :key key))) (do ((list (nreverse list) (cdr list))) ((or (null list) (not (member (car list) bag :test test :key key))) list))))) (defun list-trim-test () (every (lambda (x) (equalp '(d e f) x)) (list (list-trim '(a b c) '( a b c d e f a b c c c )) (list-trim '((a 1)(b 2)(c 3)) '( a b c d e f a b c c ) :key (function car)) (list-trim '(:a :b :c) '( a b c d e f a b c c ) :test (function string=)) (list-trim '(a b c) '( a b c d e f)) (list-trim '(a b c) '( d e f a b c c c ))))) (defun maptree (fun &rest trees) " DO: Calls FUN on each non-null atom of the TREES. PRE: The trees in TREES must be congruent, or else the result is pruned like the smallest tree. RETURN: A tree congruent to the TREES, each node being the result of FUN (it may be a subtree). " (cond ((null trees) nil) ((every (function null) trees) nil) ((every (function atom) trees) (apply fun trees)) ((every (function consp) trees) (cons (apply (function maptree) fun (mapcar (function car) trees)) (apply (function maptree) fun (mapcar (function cdr) trees)))) (t nil))) (defun flatten (tree) " RETURN: A list containing all the elements of the `tree'. " (loop :with result = nil :with stack = nil :while (or tree stack) :do (cond ((null tree) (setq tree (pop stack))) ((atom tree) (push tree result) (setq tree (pop stack))) ((listp (car tree)) (push (cdr tree) stack) (setq tree (car tree))) (t (push (car tree) result) (setq tree (cdr tree)))) :finally (return (nreverse result)))) (defun depth (tree) " RETURN: The depth of the tree. " (if (atom tree) 0 (1+ (apply (function max) 0 (do ((tree tree (cdr tree)) (results '())) ((atom tree) results) (if (listp (car tree)) (push (depth (car tree)) results))))))) (defun deepest-rec (tree) " RETURN: The deepest list in the tree. NOTE: Recursive algorithm. SEE-ALSO: deepest-iti " (let ((subtree (delete-if (function atom) tree))) (cond ((null subtree) tree) ((every (lambda (item) (every (function atom) item)) subtree) (car subtree)) (t (deepest-rec (apply 'concatenate 'list subtree)))))) (defun deepest (tree) " RETURN: The deepest list in the tree. NOTE: Iterative algorithm. SEE-ALSO: deepest-rec " (do* ((tree tree (apply 'concatenate 'list subtree)) (subtree (delete-if (function atom) tree) (delete-if (function atom) tree))) ((or (null subtree) (every (lambda (item) (every (function atom) item)) subtree)) (if (null subtree) tree (car subtree))))) (defun nsplit-list (list position &key (from-end nil)) " PRE: 0<=POSITION<=(LENGTH LIST) DO: SPLIT THE LIST IN TWO AT THE GIVEN POSITION. NIL WHEN FROM-START AND 0<=POSITION<=(LENGTH LIST), THAT'S THE LENGTH OF THE FIRST RESULT FROM-START: THE DEFAULT, SPLIT COUNTING FROM THE START. FROM-END: WHEN SET, COUNT FROM THE END OF THE LIST. (NSPLIT-LIST L P :FROM-END T) === (NSPLIT-LIST L (- (LENGTH L) P)) " (if from-end (nsplit-list list (- (length list) position)) (do* ((prev nil rest) (rest list (cdr rest))) ((or (null rest) (zerop position)) (progn (if prev (setf (cdr prev) nil) (setf list nil)) (values list rest))) (decf position)))) (defun nsplit-list-on-indicator (list indicator) " RETURN: a list of sublists of list (the conses from list are reused), the list is splited between items a and b for which (indicator a b). " (declare (type (function (t t) t) indicator)) (let* ((result nil) (sublist list) (current list) (next (cdr current))) (loop :while next :do (if (funcall indicator (car current) (car next)) (setf (cdr current) nil) (push sublist result) (setq current next) (setq next (cdr current)) (setq sublist current)) (setq current next) (setq next (cdr current))))) (push sublist result) (nreverse result))) (defun list-insert-separator (list separator) " RETURN: A list composed of all the elements in `list' with `separator' in-between. EXAMPLE: (list-insert-separator '(a b (d e f) c) 'x) ==> (a x b x (d e f) x c) " (cond ((null list) '()) ((null (cdr list)) (list (car list))) (t (do ((result '()) (items list (cdr items))) ((endp items) (nreverse (cdr result))) (push (car items) result) (push separator result))))) (defun iota (count &optional (start 0) (step 1)) " RETURN: A list containing the elements (start start+step ... start+(count-1)*step) The start and step parameters default to 0 and 1, respectively. This procedure takes its name from the APL primitive. EXAMPLE: (iota 5) => (0 1 2 3 4) (iota 5 0 -0.1) => (0 -0.1 -0.2 -0.3 -0.4) " (loop :repeat count :for item = start :then (+ item step) :collect item)) (defun make-list-of-random-numbers (length &key (modulo most-positive-fixnum)) " RETURN: A list of length `length' filled with random numbers MODULO: The argument to RANDOM. " (loop while (< 0 length) collect (random modulo) into result do (setq length (1- length)) finally (return result))) (defun combine (&rest args) " RETURN: (elt args 0) x (elt args 1) x ... x (elt args (1- (length args))) = the set of tuples built taking one item in order from each list in args. EXAMPLE: (COMBINE '(WWW FTP) '(EXA) '(COM ORG))) --> ((WWW EXA COM) (WWW EXA ORG) (FTP EXA COM) (FTP EXA ORG)) " (cond ((null args) '(())) Do n't consider empty set for one of the arguments since the combination ((consp (car args)) (mapcan (lambda (item) (apply (function combine) item (cdr args))) (car args))) (t (mapcan (lambda (rest) (list (cons (car args) rest))) (apply (function combine) (cdr args)))))) (defun hashed-intersection (set1 set2) " AUTHORS: Paul F. Dietz <> Thomas A. Russ <> " (declare (optimize speed (safety 0) (debug 0)) (list set1 set2)) (let ((table (make-hash-table :size (length set2))) (result nil)) (dolist (e set2) (setf (gethash e table) t)) (dolist (e set1) (when (gethash e table) (push e result) (setf (gethash e table) nil))) result)) (defun subsets (set) " RETURN: The set of all subsets of the strict SET. " (loop :with card = (length set) :for indicator :from 0 :below (expt 2 card) :collect (loop :for index :from 0 :below card :for item :in set :nconc (if (logbitp index indicator) (list item) nil) :into result :finally (return result)) :into result :finally (return result))) (defun equivalence-classes (set &key (test (function eql)) (key (function identity))) " RETURN: The equivalence classes of SET, via KEY, modulo TEST. " (loop :with classes = '() :for item :in set :for item-key = (funcall key item) :for class = (car (member item-key classes :test test :key (function second))) :do (if class (push item (cddr class)) (push (list :class item-key item ) classes)) :finally (return (mapcar (function cddr) classes)))) (defun aget (place indicator &optional default) " RETURN: The value of the entry INDICATOR of the a-list PLACE, or DEFAULT. " (let ((a (assoc indicator place))) (if a (cdr a) default))) ( DEFSETF AGET ( PLACE INDICATOR & OPTIONAL DEFAULT ) ( VALUE ) ( SETF ( CDR , ACS ) , VALUE ) ( SETF , PLACE ( ACONS , INDICATOR , VALUE , PLACE ) ) ) (define-setf-expander aget (place indicator &optional default &environment env) (multiple-value-bind (vars vals store-vars writer-form reader-form) (get-setf-expansion place env) (let* ((vindicator (gensym "INDICATOR")) (vvalue (gensym "VALUE")) (vstore (first store-vars)) (acs (gensym "PAIR"))) (values (list* vindicator vars) (list* indicator vals) (list vvalue) `(let* ((,acs (assoc ,vindicator ,reader-form))) (if ,acs (setf (cdr ,acs) ,vvalue) (let ((,vstore (acons ,vindicator ,vvalue ,reader-form))) ,writer-form)) ,vvalue) `(let ((,acs (assoc ,vindicator ,reader-form))) (if ,acs (cdr ,acs) ,default)))))) (defun tree-find (object tree &key (key (function identity)) (test (function eql))) " RETURN: The object in TREE that matches OBJECT (using the KEY and TEST functions. TREE: A sexp. " (if (atom tree) (if (funcall test object (funcall key tree)) tree nil) (or (tree-find object (car tree) :key key :test test) (tree-find object (cdr tree) :key key :test test)))) (defun tree-difference (a b &key (test (function eql))) " RETURN: A tree congruent to A and B where each node is = when the corresponding nodes are equal (as indicated by TEST), or (/= a-elem b-elem) otherwise. EXAMPLE: (tree-difference '((a b c) 1 (d e f)) '((a b c) (1) (d x f))) --> ((= = = . =) (/= 1 (1)) (= (/= e x) = . =) . =) " (cond ((funcall test a b) '=) ((or (atom a) (atom b)) `(/= ,a ,b)) (t (cons (tree-difference (car a) (car b) :test test) (tree-difference (cdr a) (cdr b) :test test))))) (defun tree-structure-and-leaf-difference (a b &key (test (function eql))) (cond ((and (null a) (null b)) '=) ((or (null a) (null b)) `(/= ,a ,b)) ((and (atom a) (atom b)) (if (funcall test a b) '= `(/= ,a ,b))) ((or (atom a) (atom b)) `(/= ,a ,b)) (t (cons (tree-structure-and-leaf-difference (car a) (car b) :test test) (tree-structure-and-leaf-difference (cdr a) (cdr b) :test test))))) (defun replace-tree (dst src) " DO: Copies the elements of the src tree into the dst tree. If dst is missing cons cells, structure sharing occurs. RETURN: dst " (cond ((atom dst) src) ((atom src) nil) (t (if (or (atom (car dst)) (atom (car src))) (setf (car dst) (car src)) (replace-tree (car dst) (car src))) (if (or (atom (cdr dst)) (atom (cdr src))) (setf (cdr dst) (cdr src)) (replace-tree (cdr dst) (cdr src))) dst))) ( BP B ( CDR BP ) ) ( ( NOT ( AND AI BI ( EQ AI BI ) ) ) ( DEFUN FORMATED - LESSP ( A B ) ( DEFUN SYMBOL - LESSP ( A B ) ( DEFUN VECTOR - LESSP ( A B ) WHILE ( EQ AI BI ) ( DEFUN ANY - LESSP ( A B ) ' ( ( BOOL - VECTOR . VECTOR - LESSP ) ( BUFFER . FORMATED - LESSP ) ( CHAR - TABLE . VECTOR - LESSP ) ( COMPILED - FUNCTION . VECTOR - LESSP ) ( FRAME . FORMATED - LESSP ) ( INTEGER . < =) ( MARKER . < =) ( OVERLAY . FORMATED - LESSP ) ( PROCESS . FORMATED - LESSP ) ( SUBR . FORMATED - LESSP ) ( SYMBOL . SYMBOL - LESSP ) ( VECTOR . VECTOR - LESSP ) ( WINDOW . FORMATED - LESSP ) ( WINDOW - CONFIGURATION . FORMATED - LESSP ) ( DEFUN LIST - TO - SET - SORTED ( LIST ) NOTE : This implementation first sorts the list , so its complexity should be ( FIRST ( CAR SORTED - LIST ) ) ( PROGN ( loop for size = 10 then ( * 10 size ) ( time ( setf l1 ( list - to - set l1 ) ) ) ( time ( setf l2 ( list - to - set l2 ) ) ) )
532ca2c93fd5a6b3cc6129a8f894d656cbc7216efd96ee8a07aadae38ab40e9a
toothbrush/dotfs
DotFS.hs
module Main where import System.DotFS.Util.Options import System.DotFS.Util.Sanity import System.DotFS.Core.FSActions import System.DotFS.Core.Datatypes import Data.List import System.Console.GetOpt import System.Environment import System.IO import System.Fuse import Control.Monad {- - TODO: we can fill in actualPath now. do we want to though? -} {- TODO * There's currently no real error checking whatsoever. * Thread in logging * Can I delete "dotfsVirtualPath"? * need to add unit tests -} --------------------------------------------------------------------------------- Parse arguments and main --------------------------------------------------------------------------------- main :: IO () main = do (args, fuseargs) <- liftM (break (== "--")) getArgs -- send arguments after "--" to fusermount let (actions, dirList, errors) = getOpt Permute options args -- Currently ignoring. Need to thread logging throughout opts <- foldl (>>=) (return defaultOptions) actions (mp, dirs) <- validateDirs dirList hPutStrLn stderr ("Mountpoint = \t "++mp) hPutStrLn stderr (" Conf = \t "++show dirs) case script opts of True -> hPutStrLn stdout (printScript mp dirs) False -> return () withArgs (mp:fuseargs) $ fuseMain (dotFSOps opts mp dirs) defaultExceptionHandler printScript :: FilePath -> Conf -> String printScript mountpoint (C confdir) = concat (intersperse "\n" [ "#!/bin/bash" , "#" , "# The idea here is to make symlinks to all the files in " , "# the mounted conf directory, inside the user's home (~)" , "#" , "# Should only need to be run once." , "# Will not overwrite files or directories, but will update" , "# symlinks, if found." , "#" , "# (c) Paul van der Walt, April 2012" , "" , "home=$HOME" , "confdir=\"" ++ confdir ++ "\"" , "" , "mountpoint=\"" ++ mountpoint ++ "\"" , "" , "for i in $(ls -a $confdir) ;" , "do" , " # skip the breadcrumbs" , " # skip .git too, since it makes shit way slow" , " if [ \"$i\" = \".\" ] || [ \"$i\" = \"..\" ] || [ \"$i\" = \".git\" ] || [ \"${i##*.}\" = \"dontlink\" ]; " , " then " , " continue" , " fi" , " # here we should make symlinks, only if the source" , " # doesn't yet exist" , " newsource=\"$home/$(basename $i)\"" , " # note that preserving the tree structure here" , " # happens automatically, since `ls` only goes 1 deep." , " target=\"$mountpoint/$i\"" , " target_orig=\"$confdir/$i\"" , " if [ -L \"$newsource\" ] ; # -L <=> exists and is symlink" , " then" , " # rm old link" , " echo rm -v \"$newsource\"" , " fi" , " # you would think it's now enough to let ln try to make" , " # a symlink, since it'll fail if the newsource exists, but" , " # in the case of directories, it thinks the newsource is" , " # WHERE you'd like the link, i.e. you get stuff like:" , " # `~/.somefolder/.somefolder` -> `mountpoint/.somefolder`" , " echo \"if [ ! -e \"$newsource\" ] ; then # -e <=> file exists\"" , " echo \" if [ -e \"$target_orig.dontlink\" ] ; then\"" , " echo \" ln -s -v \"$target_orig\" \"$newsource\"\"" , " echo \" else\"" , " echo \" ln -s -v \"$target\" \"$newsource\"\"" , " echo \" fi\"" , " echo \"fi\"" , "done" ])
null
https://raw.githubusercontent.com/toothbrush/dotfs/36c7e62bda235728ffbb501fe1d2c34210a870a8/System/DotFS/DotFS.hs
haskell
- TODO: we can fill in actualPath now. do we want to though? TODO * There's currently no real error checking whatsoever. * Thread in logging * Can I delete "dotfsVirtualPath"? * need to add unit tests ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- send arguments after "--" to fusermount Currently ignoring. Need to thread logging throughout
module Main where import System.DotFS.Util.Options import System.DotFS.Util.Sanity import System.DotFS.Core.FSActions import System.DotFS.Core.Datatypes import Data.List import System.Console.GetOpt import System.Environment import System.IO import System.Fuse import Control.Monad Parse arguments and main main :: IO () main = do let (actions, dirList, errors) = getOpt Permute options args opts <- foldl (>>=) (return defaultOptions) actions (mp, dirs) <- validateDirs dirList hPutStrLn stderr ("Mountpoint = \t "++mp) hPutStrLn stderr (" Conf = \t "++show dirs) case script opts of True -> hPutStrLn stdout (printScript mp dirs) False -> return () withArgs (mp:fuseargs) $ fuseMain (dotFSOps opts mp dirs) defaultExceptionHandler printScript :: FilePath -> Conf -> String printScript mountpoint (C confdir) = concat (intersperse "\n" [ "#!/bin/bash" , "#" , "# The idea here is to make symlinks to all the files in " , "# the mounted conf directory, inside the user's home (~)" , "#" , "# Should only need to be run once." , "# Will not overwrite files or directories, but will update" , "# symlinks, if found." , "#" , "# (c) Paul van der Walt, April 2012" , "" , "home=$HOME" , "confdir=\"" ++ confdir ++ "\"" , "" , "mountpoint=\"" ++ mountpoint ++ "\"" , "" , "for i in $(ls -a $confdir) ;" , "do" , " # skip the breadcrumbs" , " # skip .git too, since it makes shit way slow" , " if [ \"$i\" = \".\" ] || [ \"$i\" = \"..\" ] || [ \"$i\" = \".git\" ] || [ \"${i##*.}\" = \"dontlink\" ]; " , " then " , " continue" , " fi" , " # here we should make symlinks, only if the source" , " # doesn't yet exist" , " newsource=\"$home/$(basename $i)\"" , " # note that preserving the tree structure here" , " # happens automatically, since `ls` only goes 1 deep." , " target=\"$mountpoint/$i\"" , " target_orig=\"$confdir/$i\"" , " if [ -L \"$newsource\" ] ; # -L <=> exists and is symlink" , " then" , " # rm old link" , " echo rm -v \"$newsource\"" , " fi" , " # you would think it's now enough to let ln try to make" , " # a symlink, since it'll fail if the newsource exists, but" , " # in the case of directories, it thinks the newsource is" , " # WHERE you'd like the link, i.e. you get stuff like:" , " # `~/.somefolder/.somefolder` -> `mountpoint/.somefolder`" , " echo \"if [ ! -e \"$newsource\" ] ; then # -e <=> file exists\"" , " echo \" if [ -e \"$target_orig.dontlink\" ] ; then\"" , " echo \" ln -s -v \"$target_orig\" \"$newsource\"\"" , " echo \" else\"" , " echo \" ln -s -v \"$target\" \"$newsource\"\"" , " echo \" fi\"" , " echo \"fi\"" , "done" ])
fa953d259029472b698a9ff767a1aa1e0ea5393333bf8bfbafd5a3ecb9fe211f
MLstate/opalang
bslTracker.mli
Copyright © 2011 , 2012 MLstate This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . 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 . If not , see < / > . Copyright © 2011, 2012 MLstate This file is part of Opa. Opa is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Opa 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 Opa. If not, see </>. *) * Some utils related to Pass Tracking for Bypasses . @author Some utils related to Pass Tracking for Bypasses. @author Quentin Bourgerie *) * This module defines some utils for branching compilers working on QmlAst with the pass tracking system developed in passlib , in [ PassHandler ] and [ PassTracker ] In particular , it defines , given a [ QmlAst.code ] extractor some : + [ printers ] + [ trackers ] Any language should implement a module named [ LangTracker ] , [ LangCheck ] , etc ... @see " passlib / passdesign.ml " for a global overview of the Pass System This module defines some utils for branching compilers working on QmlAst with the pass tracking system developed in passlib, in [PassHandler] and [PassTracker] In particular, it defines, given a [QmlAst.code] extractor some : + [printers] + [trackers] Any language should implement a module named [LangTracker], [LangCheck], etc... @see "passlib/passdesign.ml" for a global overview of the Pass System *) * { 6 Printers } * Regroup some of common printer of the module [ Printer ] in one list . The ignored argument is for an optimal branching with PassHandler . + bymap The ignored argument is for an optimal branching with PassHandler. + bymap *) val printers : ('env -> BslLib.env_bsl) -> 'opt -> (PassHandler.printer_id * 'env PassHandler.printer) list module Printer : sig (** Regular bymap printer: print all keys of bypasses *) val bymap : BslLib.env_bsl PassHandler.printer end
null
https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/libbsl/bslTracker.mli
ocaml
* Regular bymap printer: print all keys of bypasses
Copyright © 2011 , 2012 MLstate This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . 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 . If not , see < / > . Copyright © 2011, 2012 MLstate This file is part of Opa. Opa is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Opa 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 Opa. If not, see </>. *) * Some utils related to Pass Tracking for Bypasses . @author Some utils related to Pass Tracking for Bypasses. @author Quentin Bourgerie *) * This module defines some utils for branching compilers working on QmlAst with the pass tracking system developed in passlib , in [ PassHandler ] and [ PassTracker ] In particular , it defines , given a [ QmlAst.code ] extractor some : + [ printers ] + [ trackers ] Any language should implement a module named [ LangTracker ] , [ LangCheck ] , etc ... @see " passlib / passdesign.ml " for a global overview of the Pass System This module defines some utils for branching compilers working on QmlAst with the pass tracking system developed in passlib, in [PassHandler] and [PassTracker] In particular, it defines, given a [QmlAst.code] extractor some : + [printers] + [trackers] Any language should implement a module named [LangTracker], [LangCheck], etc... @see "passlib/passdesign.ml" for a global overview of the Pass System *) * { 6 Printers } * Regroup some of common printer of the module [ Printer ] in one list . The ignored argument is for an optimal branching with PassHandler . + bymap The ignored argument is for an optimal branching with PassHandler. + bymap *) val printers : ('env -> BslLib.env_bsl) -> 'opt -> (PassHandler.printer_id * 'env PassHandler.printer) list module Printer : sig val bymap : BslLib.env_bsl PassHandler.printer end
4dc8943d74ebeae00b0f2e56916c0d045d43002fd39378d248b94ccdba216fe3
dalaing/little-languages
BigStep.hs
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} # LANGUAGE TemplateHaskell # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FunctionalDependencies # # LANGUAGE FlexibleInstances # {-# LANGUAGE RankNTypes #-} module Component.Term.Eval.BigStep ( BigStepRule(..) , BigStepInput(..) , BigStepOutput(..) , HasBigStepOutput(..) , mkBigStep ) where import Data.Maybe (fromMaybe) import Data.Foldable (asum) import Control.Lens.TH (makeClassy) import Component.Term.Note.Strip (StripNoteTerm(..)) -- | data BigStepRule tm = BigStepBase (forall nTy nTm. tm nTy nTm String -> Maybe (tm nTy nTm String)) -- ^ | BigStepRecurse (forall nTy nTm. (tm nTy nTm String -> Maybe (tm nTy nTm String)) -> tm nTy nTm String -> Maybe (tm nTy nTm String)) -- ^ -- | fixBigStepRule :: (tm nTy nTm String -> Maybe (tm nTy nTm String)) -> BigStepRule tm -> tm nTy nTm String -> Maybe (tm nTy nTm String) fixBigStepRule _ (BigStepBase f) x = f x fixBigStepRule step (BigStepRecurse f) x = f step x -- | data BigStepInput tm = BigStepInput [BigStepRule tm] -- ^ instance Monoid (BigStepInput tm) where mempty = BigStepInput mempty mappend (BigStepInput v1) (BigStepInput v2) = BigStepInput (mappend v1 v2) -- | data BigStepOutput tm = BigStepOutput { _bigStep :: forall nTy nTm. tm nTy nTm String -> Maybe (tm nTy nTm String) -- ^ , _bigStepRules :: forall nTy nTm. [tm nTy nTm String -> Maybe (tm nTy nTm String)] -- ^ , _bigStepEval :: forall nTy nTm. tm nTy nTm String -> tm nTy nTm String -- ^ } makeClassy ''BigStepOutput -- | mkBigStep :: StripNoteTerm tm tm => BigStepInput tm -- ^ -> BigStepOutput tm -- ^ mkBigStep (BigStepInput i) = let bigStepRules' = fmap (fixBigStepRule bigStep') i bigStep' tm = asum . fmap ($ stripNoteTerm tm) $ bigStepRules' bigStepEval' tm = fromMaybe (stripNoteTerm tm) . bigStep' $ tm in BigStepOutput bigStep' bigStepRules' bigStepEval'
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/modular/common-lang/src/Component/Term/Eval/BigStep.hs
haskell
# LANGUAGE RankNTypes # | ^ ^ | | ^ | ^ ^ ^ | ^ ^
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} # LANGUAGE TemplateHaskell # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FunctionalDependencies # # LANGUAGE FlexibleInstances # module Component.Term.Eval.BigStep ( BigStepRule(..) , BigStepInput(..) , BigStepOutput(..) , HasBigStepOutput(..) , mkBigStep ) where import Data.Maybe (fromMaybe) import Data.Foldable (asum) import Control.Lens.TH (makeClassy) import Component.Term.Note.Strip (StripNoteTerm(..)) data BigStepRule tm = fixBigStepRule :: (tm nTy nTm String -> Maybe (tm nTy nTm String)) -> BigStepRule tm -> tm nTy nTm String -> Maybe (tm nTy nTm String) fixBigStepRule _ (BigStepBase f) x = f x fixBigStepRule step (BigStepRecurse f) x = f step x data BigStepInput tm = instance Monoid (BigStepInput tm) where mempty = BigStepInput mempty mappend (BigStepInput v1) (BigStepInput v2) = BigStepInput (mappend v1 v2) data BigStepOutput tm = BigStepOutput { } makeClassy ''BigStepOutput mkBigStep :: StripNoteTerm tm tm mkBigStep (BigStepInput i) = let bigStepRules' = fmap (fixBigStepRule bigStep') i bigStep' tm = asum . fmap ($ stripNoteTerm tm) $ bigStepRules' bigStepEval' tm = fromMaybe (stripNoteTerm tm) . bigStep' $ tm in BigStepOutput bigStep' bigStepRules' bigStepEval'
18bda0ae70285d167555db3795e824a56f731d155ee728d25dcc90554f7ec224
thheller/next-cljs
next_js.cljs
(ns shadow.next-js (:require [goog.object :as gobj])) (defn add-query [page-fn query-fn] (gobj/set page-fn "getInitialProps" (fn [req] (-> (query-fn req) SSR transforms all CLJS data to JSON ;; which makes it pretty much useless ;; this is terrible but oh well ... (.then clj->js)))))
null
https://raw.githubusercontent.com/thheller/next-cljs/03cbc22732cac2d904f9b9f1fa7838317ff97675/src/main/shadow/next_js.cljs
clojure
which makes it pretty much useless this is terrible but oh well ...
(ns shadow.next-js (:require [goog.object :as gobj])) (defn add-query [page-fn query-fn] (gobj/set page-fn "getInitialProps" (fn [req] (-> (query-fn req) SSR transforms all CLJS data to JSON (.then clj->js)))))
45917413e7ed45afdf4803dc8e9e8dd531a8feee54b75bfa8c4affc8df5c01d4
rd--/hsc3
b_set.help.hs
Sound.Sc3.Lang.Help.viewServerHelp "/b_set"
null
https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Server/b_set.help.hs
haskell
Sound.Sc3.Lang.Help.viewServerHelp "/b_set"
b94a61a4b7ebd8af98b4e827ba35d0001e579bb6aeed070756b374181920d964
sgbj/MaximaSharp
dscal.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ " " f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " ) ;;; Using Lisp CMU Common Lisp 20d (20D Unicode) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format double-float)) (in-package :blas) (defun dscal (n da dx incx) (declare (type (array double-float (*)) dx) (type (double-float) da) (type (f2cl-lib:integer4) incx n)) (f2cl-lib:with-multi-array-data ((dx double-float dx-%data% dx-%offset%)) (prog ((i 0) (m 0) (mp1 0) (nincx 0)) (declare (type (f2cl-lib:integer4) nincx mp1 m i)) (if (or (<= n 0) (<= incx 0)) (go end_label)) (if (= incx 1) (go label20)) (setf nincx (f2cl-lib:int-mul n incx)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i incx)) ((> i nincx) nil) (tagbody (setf (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))) label10)) (go end_label) label20 (setf m (mod n 5)) (if (= m 0) (go label40)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i m) nil) (tagbody (setf (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))) label30)) (if (< n 5) (go end_label)) label40 (setf mp1 (f2cl-lib:int-add m 1)) (f2cl-lib:fdo (i mp1 (f2cl-lib:int-add i 5)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))) (setf (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 1)) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 1)) ((1 *)) dx-%offset%))) (setf (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 2)) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 2)) ((1 *)) dx-%offset%))) (setf (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 3)) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 3)) ((1 *)) dx-%offset%))) (setf (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 4)) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 4)) ((1 *)) dx-%offset%))) label50)) (go end_label) end_label (return (values nil nil nil nil))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dscal fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (double-float) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil) :calls 'nil)))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/blas/dscal.lisp
lisp
Compiled by f2cl version: Using Lisp CMU Common Lisp 20d (20D Unicode) Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format double-float))
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ " " f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " ) (in-package :blas) (defun dscal (n da dx incx) (declare (type (array double-float (*)) dx) (type (double-float) da) (type (f2cl-lib:integer4) incx n)) (f2cl-lib:with-multi-array-data ((dx double-float dx-%data% dx-%offset%)) (prog ((i 0) (m 0) (mp1 0) (nincx 0)) (declare (type (f2cl-lib:integer4) nincx mp1 m i)) (if (or (<= n 0) (<= incx 0)) (go end_label)) (if (= incx 1) (go label20)) (setf nincx (f2cl-lib:int-mul n incx)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i incx)) ((> i nincx) nil) (tagbody (setf (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))) label10)) (go end_label) label20 (setf m (mod n 5)) (if (= m 0) (go label40)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i m) nil) (tagbody (setf (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))) label30)) (if (< n 5) (go end_label)) label40 (setf mp1 (f2cl-lib:int-add m 1)) (f2cl-lib:fdo (i mp1 (f2cl-lib:int-add i 5)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))) (setf (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 1)) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 1)) ((1 *)) dx-%offset%))) (setf (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 2)) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 2)) ((1 *)) dx-%offset%))) (setf (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 3)) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 3)) ((1 *)) dx-%offset%))) (setf (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 4)) ((1 *)) dx-%offset%) (* da (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 4)) ((1 *)) dx-%offset%))) label50)) (go end_label) end_label (return (values nil nil nil nil))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dscal fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (double-float) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil) :calls 'nil)))
56ef4bba41e3c0220fb703cec7a393cbb2513bd187af8557df154c1d7b889d49
mpickering/apply-refact
Lambda24.hs
f = bar (flip Foo.bar x)
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Lambda24.hs
haskell
f = bar (flip Foo.bar x)
ac9184d2d2b5c37d86c60bf843aeea64cdf3d911e3aba1c9839f8a779e773f9d
orionsbelt-battlegrounds/obb-rules
eagle.cljc
(ns ^{:added "1.6" :author "Pedro Santos"} obb-rules.units.eagle "Metadata information for the Eagle unit") (def metadata {:name "eagle" :code "e" :attack 1500 :attack-type :catapult :defense 1200 :range 3 :value 70 :type :mechanic :category :medium :displacement :air :movement-type :diagonal :movement-cost 2})
null
https://raw.githubusercontent.com/orionsbelt-battlegrounds/obb-rules/97fad6506eb81142f74f4722aca58b80d618bf45/src/obb_rules/units/eagle.cljc
clojure
(ns ^{:added "1.6" :author "Pedro Santos"} obb-rules.units.eagle "Metadata information for the Eagle unit") (def metadata {:name "eagle" :code "e" :attack 1500 :attack-type :catapult :defense 1200 :range 3 :value 70 :type :mechanic :category :medium :displacement :air :movement-type :diagonal :movement-cost 2})
55cc2378aab9249fceb22bc2b612867ad31303729bec7178cca7630f0a860f46
huangjs/cl
nalgfa.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 ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ( c ) Copyright 1980 Massachusetts Institute of Technology ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) (macsyma-module nalgfa) (declare-top (special vlist *var *nosplitf *algvar *denom *num *ans algfac* $nalgfac alpha)) (load-macsyma-macros rzmac ratmac) (defun new-alg () (newsym (gentemp (symbol-name '$alg)))) (defun psqfrp (p var) (zerop (pdegree (pgcd p (pderivative p var)) var))) (defun pgsubst (val var p) ;;generalized psubst substitutes any expression for any var in p ((eq var (car p)) (cond ((pzerop val) (pterm (cdr p) 0)) ((do ((ld (cadr p) (car a)) (a (cdddr p) (cddr a)) (ans (caddr p) (pplus (ptimes ans (pexpt val (- ld (car a)))) (cadr a)))) ((null a) (ptimes ans (pexpt val ld))))))) ((pointergp var (car p)) p) ((do ((a (cdddr p) (cddr a)) (ans (ptimes (list (car p) (cadr p) 1) (pgsubst val var (caddr p))) (pplus ans (ptimes (list (car p) (car a) 1) (pgsubst val var (cadr a)))))) ((null a) ans))))) (defun pvsubst (nvar ovar p) (cond ((or (pcoefp p) (pointergp ovar (car p))) p) ((eq ovar (car p)) (cons nvar (cdr p))) (t (pgsubst (make-poly nvar) ovar p)))) (defun ordervar (var l) (let ((mvar (lmainvar l))) (cond ((null mvar) l) ((null (pointergp mvar var)) (cons var l)) ((let ((newvar (gensym))) (setq genvar (append genvar (list newvar))) (setf (symbol-plist newvar) (symbol-plist var)) (setf (symbol-value newvar) (1+ (symbol-value mvar))) (cons newvar (mapcar #'(lambda (p) (pvsubst newvar var p)) l))))))) (defun lmainvar (l) ;;main var of list of poly's (do ((l l (cdr l)) (v)) ((null l) v) (cond ((pcoefp (car l))) ((null v) (setq v (caar l))) ((pointergp (caar l) v) (setq v (caar l)))))) (defun presult (p1 p2 var) ;;change call in algsys? (let ((genvar genvar)) (setq var (ordervar var (list p1 p2)) p1 (cadr var) p2 (caddr var) var (car var)) (cond ((zerop (pdegree p1 var)) (cond ((zerop (pdegree p2 var)) 1) ((pexpt p1 (cadr p2))))) ((zerop (pdegree p2 var)) (pexpt p2 (cadr p1))) ((resultant p1 p2))))) (defun pcoefvec (p) (cond ((pcoefp p) (list p)) ((do ((l) (i (cadr p) (1- i)) (p (cdr p))) ((signp l i) (nreverse l)) (push (cond ((and p (= (car p) i)) (prog1 (cadr p) (setq p (cddr p)))) ( 0 )) l))))) (defun algtrace1 (bvec tvec) (do ((i (- (length tvec) (length bvec)) (1- i))) ((zerop i) (algtrace* bvec tvec)) (setq bvec (cons 0 bvec)))) (defun algtrace* (bvec tvec) (do ((b bvec (cdr b)) (tr (car (last bvec)) (pplus tr (car (last b))))) ((null (cdr b)) tr) (or (pzerop (car b)) (do ((l (cdr b) (cdr l)) (tv tvec (cdr tv))) ((null l)) (rplaca l (pdifference (car l) (ptimes (car b) (car tv)))))))) (defun algtrace (r p) (cond ((eq (caar r) (car p)) (ratreduce (algtrace1 (pcoefvec (car r)) (cdr (pcoefvec p))) (cdr r))) ((ratreduce (pctimes (cadr p) (car r)) (cdr r))))) (defmfun $algtrace (r p var) (let ((varlist (list var)) (genvar nil)) (rdis* (algtrace (rform r) (car (rform p)))))) (defun good-form (l) ;;bad -> good (do ((l l (cddr l)) (ans)) ((null l) (nreverse ans)) (push (cons (cadr l) (car l)) ans))) (defun bad-form (l) ;;good -> bad (mapcar #'(lambda (q) (list (cdr q) (car q))) l)) (defmfun $algfac (a1 &optional (a2 nil a2?) (a3 nil a3?)) (if a3? ($pfactoralg a1 a2 a3) (let ((varlist)) (cond (a2? (newvar a2) (if (alike1 a2 (car varlist)) ($pfactoralg a1 nil a2) ($pfactoralg a1 a2 (car (last varlist))))) (t (newvar a1) (setq varlist (mapcan #'(lambda (q) (if (algpget q) (list q) nil)) varlist)) (cond ((= (length varlist) 1) ($pfactoralg a1 nil (car varlist))) ((> (length varlist) 1) (merror "too many algebraics")) (t (merror "no algebraics")))))))) (defmfun $pfactoralg (f p alg) (let ((varlist (list alg)) (genvar) (vlist) (tellratlist) ($ratfac) ($gcd '$algebraic) ($algebraic) ($ratalgdenom t) (*denom 1) (*num 1) (*ans)) (cond ((and (null p) (radfunp alg t)) (newvar (cadr alg))) (t (newvar p))) (newvar1 f) (cond ((null vlist) (merror "attempt to factor a constant"))) (setq varlist (nconc varlist (sortgreat vlist))) (cond (p (setq p (cadr (ratrep* p))) (push (cons alg (mapcar #'pdis (cdr p))) tellratlist)) (t (setq p (algpget alg)) (setq p (pdifference (pexpt (cadr (ratrep* alg)) (car p)) (cadr p))))) (setq $algebraic t) (setq f (cadr (ratrep* f))) (setq f (pfactoralg1 f p 0)) (cons '(mtimes) (cons (rdis (ratreduce *num *denom)) (mapcar 'pdis f))))) also redefine to call nalgfac correctly (defun nalgfac (p mp) (let ((*num 1) (*denom 1) (*ans) (algfac*) ($nalgfac) ($algebraic t) ($gcd '$algebraic)) (setq p (pfactoralg1 p mp 0)) (setq adn* (* adn* *denom)) (cond ((equal *num 1) p) (t (cons *num p))))) (setq *nosplitf t) (defun pfactoralg1 (f p ind) (cond ((pcoefp f) (setq *num (ptimeschk f *num)) *ans) ((= (cadr f) 1) (setq f (pshift f (car p) ind)) (push (algnormal f) *ans) (setq f (rquotient f (car *ans)) *denom (ptimeschk (cdr f) *denom) *num (ptimeschk (car f) *num)) *ans) ((equal (cdr f) (cdr p)) (push (pdifference (make-poly (car f)) (make-poly (car p))) *ans) (setq f (rquotient f (car *ans)) *denom (ptimeschk (cdr f) *denom)) (pfactoralg1 (car f) p ind)) ((zerop (pdegree f (car p))) (mapc #'(lambda (q) (if (pcoefp q) nil (pfactoralg1 (pshift q (car p) -1) p (1+ ind)))) (let (($algebraic nil) ($gcd (car *gcdl*))) (pfactor1 f))) *ans) (t (do ((l (let (($algebraic nil) ($gcd (car *gcdl*))) (pfactor (algnorm f p))) (cddr l)) (polys) (temp) (alg (car p))) ((null l) (setq *num (ptimeschk f *num)) (mapc #'(lambda (q) (pfactoralg1 (pshift q alg -1) p (1+ ind))) polys) *ans) (cond ((pcoefp (car l)) nil) (t (setq temp (cond ((null (cddr l)) f) (t (pgcd f (car l))))) (cond ((pcoefp temp) nil) ((= (cadr temp) 1) (setq temp (algnormal temp)) (push (pshift temp alg ind) *ans)) ((= (cadr l) 1) (setq temp (algnormal temp)) (push (pshift temp alg ind) *ans) (or *nosplitf (setq *nosplitf (list (car l) temp ind)))) (t (push temp polys))) (setq f (rquotient f temp) *denom (ptimeschk (cdr f) *denom) f (car f)))) )))) (defun pshift (f alg c) (if (= c 0) f (pgsubst (pplus (make-poly (car f)) (pctimes c (make-poly alg))) (car f) f))) (defmfun $splitfield (p var) (let ((varlist) (genvar) (genpairs) (*algvar) ($gcd '$algebraic)) (newsym var) (setq *algvar (caar (new-alg))) (setq p (psplit-field (cadr (ratf p)))) (cons '(mlist) (cons (pdis* (car p)) (mapcar 'rdis* (cdr p)))))) (defun psplit-field (p) ;modresult? (let ((l (mapcar #'(lambda (q) (psplit-field1 (cdr q))) (good-form (pfactor p)))) ;don't normalize lcfs? ($algebraic t)) (if (null (cdr l)) (car l) (do ((l l (cdr l)) (prim) (zeroes) (temp)) ((null l) (cons (or prim '|$splits in q|) zeroes)) (cond ((eq (caar l) 'linear) (setq zeroes (cons (cdar l) zeroes))) ((null prim) (setq prim (caar l) zeroes (nconc (cdar l) zeroes))) ((setq temp (primelmt (cons (car p) (cdr prim)) (cons (car p) (cdaar l)) *algvar) zeroes (nconc (mapcar #'(lambda (q) (ratgsubst (cadddr temp) (caaar l) q)) (cdar l)) (mapcar #'(lambda (q) (ratgsubst (caddr temp) (car prim) q)) zeroes)) prim (car temp)))))))) (defun plsolve (p) (ratreduce (pterm (cdr p) 0) (pminus (pterm (cdr p) 1)))) (defun psplit-field1 (p) ;;returns minimal poly and list of roots ;;p must be square free (*bind* ((minpoly (cons *algvar (cdr p))) (zeroes) ($algebraic t) ($ratalgdenom t)) (if (equal (cadr p) 1) (return (cons 'linear (plsolve p)))) (do ((polys (list p) ) (nminpoly) (*nosplitf nil nil) (alpha (cons (make-poly (car minpoly)) 1))) ((null polys) (cons minpoly zeroes)) (push alpha zeroes) (putprop (car minpoly) (cdr minpoly) 'tellrat) (rplaca polys (car (rquotient (pctimes (cdr alpha) (car polys)) (pdifference (pctimes (cdr alpha) (pget (caar polys))) (car alpha))))) (setq polys (mapcan #'(lambda (q) linear factor (push (plsolve q) zeroes) nil) ;;flush linear factor ((list q)))) (mapcan #'(lambda (q) (let ((*ans) (*num 1) (*denom 1)) (nreverse (pfactoralg1 q minpoly 0)))) polys))) (when *nosplitf (setq nminpoly (car *nosplitf) *nosplitf (cdr *nosplitf)) (putprop *algvar (cdr nminpoly) 'tellrat) (let ((beta (plsolve (pgcd (cons (caar *nosplitf) (cdr minpoly)) (exchangevar (car *nosplitf) *algvar))))) (setq alpha (ratplus (cons (make-poly *algvar) 1) (rattimes (cons (- (cadr *nosplitf)) 1) beta t))) (setq zeroes (mapcar #'(lambda (q) (ratgsubst beta (car minpoly) q)) zeroes)) (setq polys (mapcar #'(lambda (q) (car (rgsubst beta (car minpoly) q))) polys)) (setq minpoly (cons *algvar (cdr nminpoly)))))))) (defun exchangevar (poly var) (let ((newvar (gensym)) (ovar (car poly))) (set newvar (1+ (eval ovar))) (pvsubst ovar newvar (pvsubst var ovar (pvsubst newvar var poly))))) (defun rgsubst (val var p) ;;generalized psubst substitutes any (cond ((pcoefp p) expression for any var in p ((eq var (car p)) (cond ((pzerop val) (cons (pterm (cdr p) 0) 1)) ((do ((ld (cadr p) (car a)) (a (cdddr p) (cddr a)) (ans (cons (caddr p) 1) (ratplus (rattimes ans (ratexpt val (- ld (car a))) t) (cons (cadr a) 1)))) ((null a) (rattimes ans (ratexpt val ld) t)))))) ((pointergp var (car p)) (cons p 1)) (t (let ((newsym (gensym))) (set newsym (1+ (symbol-value (car p)))) (rgsubst val newsym (pvsubst newsym var p)))))) (defun ratgsubst (val var rat) (ratquotient (rgsubst val var (car rat)) (rgsubst val var (cdr rat)))) (defun algnorm (f p) (presult f p (car p))) (defmfun $algnorm (r p var) (let ((varlist (list var)) (genvar)) (setq r (ratf r) p (cadr (ratf p))) (rdis* (cons (algnorm (cadr r) p) (algnorm (cddr r) p))))) f must be sqfr , p is minpoly , fvar # pvar (*bind* ((pvar (car p))) new main var will be car of p p (cadr f) f (car f)) ;make mainvar of f = mainvar(p) (do ((i 0 (1+ i)) (dif (pdifference (make-poly fvar) (make-poly (car p)))) (f f (pgsubst dif fvar f)) (res)) ((and (eq (car f) (car p)) (setq res (primpart (algnorm f p))) (psqfrp res fvar)) (list res (*bind* (($algebraic t)) ;;;modified f (putprop pvar (cdr p) 'tellrat) (pvsubst pvar (car p) f)) (car p) p i))))) (defun primelmt (a b gvar &aux ($algebraic nil)) a is a poly with 's in ) ;;gvar is new variable (let ((norm (sqfrnorm (cons gvar (cdr a)) b gvar)) (alpha) (beta) ($ratalgdenom t)) (rplaca norm (primpart (car norm))) (putprop gvar (cdar norm) 'tellrat) (setq $algebraic t beta (pgcd (cadddr norm) (pvsubst (caddr norm) (car b) (cadr norm)))) (setq beta (plsolve beta) alpha (ratplus (cons (make-poly gvar) 1) (rattimes (cons (- (cadddr (cdr norm))) 1) beta t))) (list (car norm) ;;minimal poly (pplus (make-poly a) ;;new prim elm in old guys (list (car b) 1 (- (cadddr (cdr norm))))) alpha beta))) ;;in terms of gamma ;; discriminant of a basis (defmfun $bdiscr (&rest args) (let ((varlist) (genvar)) (xcons (bdiscr (mapcar #'rform (butlast args)) (car (rform (car (last args))))) (list 'mrat 'simp varlist genvar)))) (defun bdiscr (l minp) (det (mapcar #'(lambda (q1) (mapcar #'(lambda (q2) (algtrace (ptimes q1 q2) minp)) l)) l)))
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/src/nalgfa.lisp
lisp
Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; The data in this file contains enhancments. ;;;;; ;;;;; ; ; ; ; All rights reserved ;;;;; ; ; generalized psubst substitutes any main var of list of poly's change call in algsys? bad -> good good -> bad modresult? don't normalize lcfs? returns minimal poly and list of roots p must be square free flush linear factor generalized psubst substitutes any make mainvar of f = mainvar(p) modified f gvar is new variable minimal poly new prim elm in old guys in terms of gamma discriminant of a basis
(in-package :maxima) (macsyma-module nalgfa) (declare-top (special vlist *var *nosplitf *algvar *denom *num *ans algfac* $nalgfac alpha)) (load-macsyma-macros rzmac ratmac) (defun new-alg () (newsym (gentemp (symbol-name '$alg)))) (defun psqfrp (p var) (zerop (pdegree (pgcd p (pderivative p var)) var))) expression for any var in p ((eq var (car p)) (cond ((pzerop val) (pterm (cdr p) 0)) ((do ((ld (cadr p) (car a)) (a (cdddr p) (cddr a)) (ans (caddr p) (pplus (ptimes ans (pexpt val (- ld (car a)))) (cadr a)))) ((null a) (ptimes ans (pexpt val ld))))))) ((pointergp var (car p)) p) ((do ((a (cdddr p) (cddr a)) (ans (ptimes (list (car p) (cadr p) 1) (pgsubst val var (caddr p))) (pplus ans (ptimes (list (car p) (car a) 1) (pgsubst val var (cadr a)))))) ((null a) ans))))) (defun pvsubst (nvar ovar p) (cond ((or (pcoefp p) (pointergp ovar (car p))) p) ((eq ovar (car p)) (cons nvar (cdr p))) (t (pgsubst (make-poly nvar) ovar p)))) (defun ordervar (var l) (let ((mvar (lmainvar l))) (cond ((null mvar) l) ((null (pointergp mvar var)) (cons var l)) ((let ((newvar (gensym))) (setq genvar (append genvar (list newvar))) (setf (symbol-plist newvar) (symbol-plist var)) (setf (symbol-value newvar) (1+ (symbol-value mvar))) (cons newvar (mapcar #'(lambda (p) (pvsubst newvar var p)) l))))))) (do ((l l (cdr l)) (v)) ((null l) v) (cond ((pcoefp (car l))) ((null v) (setq v (caar l))) ((pointergp (caar l) v) (setq v (caar l)))))) (let ((genvar genvar)) (setq var (ordervar var (list p1 p2)) p1 (cadr var) p2 (caddr var) var (car var)) (cond ((zerop (pdegree p1 var)) (cond ((zerop (pdegree p2 var)) 1) ((pexpt p1 (cadr p2))))) ((zerop (pdegree p2 var)) (pexpt p2 (cadr p1))) ((resultant p1 p2))))) (defun pcoefvec (p) (cond ((pcoefp p) (list p)) ((do ((l) (i (cadr p) (1- i)) (p (cdr p))) ((signp l i) (nreverse l)) (push (cond ((and p (= (car p) i)) (prog1 (cadr p) (setq p (cddr p)))) ( 0 )) l))))) (defun algtrace1 (bvec tvec) (do ((i (- (length tvec) (length bvec)) (1- i))) ((zerop i) (algtrace* bvec tvec)) (setq bvec (cons 0 bvec)))) (defun algtrace* (bvec tvec) (do ((b bvec (cdr b)) (tr (car (last bvec)) (pplus tr (car (last b))))) ((null (cdr b)) tr) (or (pzerop (car b)) (do ((l (cdr b) (cdr l)) (tv tvec (cdr tv))) ((null l)) (rplaca l (pdifference (car l) (ptimes (car b) (car tv)))))))) (defun algtrace (r p) (cond ((eq (caar r) (car p)) (ratreduce (algtrace1 (pcoefvec (car r)) (cdr (pcoefvec p))) (cdr r))) ((ratreduce (pctimes (cadr p) (car r)) (cdr r))))) (defmfun $algtrace (r p var) (let ((varlist (list var)) (genvar nil)) (rdis* (algtrace (rform r) (car (rform p)))))) (do ((l l (cddr l)) (ans)) ((null l) (nreverse ans)) (push (cons (cadr l) (car l)) ans))) (mapcar #'(lambda (q) (list (cdr q) (car q))) l)) (defmfun $algfac (a1 &optional (a2 nil a2?) (a3 nil a3?)) (if a3? ($pfactoralg a1 a2 a3) (let ((varlist)) (cond (a2? (newvar a2) (if (alike1 a2 (car varlist)) ($pfactoralg a1 nil a2) ($pfactoralg a1 a2 (car (last varlist))))) (t (newvar a1) (setq varlist (mapcan #'(lambda (q) (if (algpget q) (list q) nil)) varlist)) (cond ((= (length varlist) 1) ($pfactoralg a1 nil (car varlist))) ((> (length varlist) 1) (merror "too many algebraics")) (t (merror "no algebraics")))))))) (defmfun $pfactoralg (f p alg) (let ((varlist (list alg)) (genvar) (vlist) (tellratlist) ($ratfac) ($gcd '$algebraic) ($algebraic) ($ratalgdenom t) (*denom 1) (*num 1) (*ans)) (cond ((and (null p) (radfunp alg t)) (newvar (cadr alg))) (t (newvar p))) (newvar1 f) (cond ((null vlist) (merror "attempt to factor a constant"))) (setq varlist (nconc varlist (sortgreat vlist))) (cond (p (setq p (cadr (ratrep* p))) (push (cons alg (mapcar #'pdis (cdr p))) tellratlist)) (t (setq p (algpget alg)) (setq p (pdifference (pexpt (cadr (ratrep* alg)) (car p)) (cadr p))))) (setq $algebraic t) (setq f (cadr (ratrep* f))) (setq f (pfactoralg1 f p 0)) (cons '(mtimes) (cons (rdis (ratreduce *num *denom)) (mapcar 'pdis f))))) also redefine to call nalgfac correctly (defun nalgfac (p mp) (let ((*num 1) (*denom 1) (*ans) (algfac*) ($nalgfac) ($algebraic t) ($gcd '$algebraic)) (setq p (pfactoralg1 p mp 0)) (setq adn* (* adn* *denom)) (cond ((equal *num 1) p) (t (cons *num p))))) (setq *nosplitf t) (defun pfactoralg1 (f p ind) (cond ((pcoefp f) (setq *num (ptimeschk f *num)) *ans) ((= (cadr f) 1) (setq f (pshift f (car p) ind)) (push (algnormal f) *ans) (setq f (rquotient f (car *ans)) *denom (ptimeschk (cdr f) *denom) *num (ptimeschk (car f) *num)) *ans) ((equal (cdr f) (cdr p)) (push (pdifference (make-poly (car f)) (make-poly (car p))) *ans) (setq f (rquotient f (car *ans)) *denom (ptimeschk (cdr f) *denom)) (pfactoralg1 (car f) p ind)) ((zerop (pdegree f (car p))) (mapc #'(lambda (q) (if (pcoefp q) nil (pfactoralg1 (pshift q (car p) -1) p (1+ ind)))) (let (($algebraic nil) ($gcd (car *gcdl*))) (pfactor1 f))) *ans) (t (do ((l (let (($algebraic nil) ($gcd (car *gcdl*))) (pfactor (algnorm f p))) (cddr l)) (polys) (temp) (alg (car p))) ((null l) (setq *num (ptimeschk f *num)) (mapc #'(lambda (q) (pfactoralg1 (pshift q alg -1) p (1+ ind))) polys) *ans) (cond ((pcoefp (car l)) nil) (t (setq temp (cond ((null (cddr l)) f) (t (pgcd f (car l))))) (cond ((pcoefp temp) nil) ((= (cadr temp) 1) (setq temp (algnormal temp)) (push (pshift temp alg ind) *ans)) ((= (cadr l) 1) (setq temp (algnormal temp)) (push (pshift temp alg ind) *ans) (or *nosplitf (setq *nosplitf (list (car l) temp ind)))) (t (push temp polys))) (setq f (rquotient f temp) *denom (ptimeschk (cdr f) *denom) f (car f)))) )))) (defun pshift (f alg c) (if (= c 0) f (pgsubst (pplus (make-poly (car f)) (pctimes c (make-poly alg))) (car f) f))) (defmfun $splitfield (p var) (let ((varlist) (genvar) (genpairs) (*algvar) ($gcd '$algebraic)) (newsym var) (setq *algvar (caar (new-alg))) (setq p (psplit-field (cadr (ratf p)))) (cons '(mlist) (cons (pdis* (car p)) (mapcar 'rdis* (cdr p)))))) (let ((l (mapcar #'(lambda (q) (psplit-field1 (cdr q))) ($algebraic t)) (if (null (cdr l)) (car l) (do ((l l (cdr l)) (prim) (zeroes) (temp)) ((null l) (cons (or prim '|$splits in q|) zeroes)) (cond ((eq (caar l) 'linear) (setq zeroes (cons (cdar l) zeroes))) ((null prim) (setq prim (caar l) zeroes (nconc (cdar l) zeroes))) ((setq temp (primelmt (cons (car p) (cdr prim)) (cons (car p) (cdaar l)) *algvar) zeroes (nconc (mapcar #'(lambda (q) (ratgsubst (cadddr temp) (caaar l) q)) (cdar l)) (mapcar #'(lambda (q) (ratgsubst (caddr temp) (car prim) q)) zeroes)) prim (car temp)))))))) (defun plsolve (p) (ratreduce (pterm (cdr p) 0) (pminus (pterm (cdr p) 1)))) (defun psplit-field1 (p) (*bind* ((minpoly (cons *algvar (cdr p))) (zeroes) ($algebraic t) ($ratalgdenom t)) (if (equal (cadr p) 1) (return (cons 'linear (plsolve p)))) (do ((polys (list p) ) (nminpoly) (*nosplitf nil nil) (alpha (cons (make-poly (car minpoly)) 1))) ((null polys) (cons minpoly zeroes)) (push alpha zeroes) (putprop (car minpoly) (cdr minpoly) 'tellrat) (rplaca polys (car (rquotient (pctimes (cdr alpha) (car polys)) (pdifference (pctimes (cdr alpha) (pget (caar polys))) (car alpha))))) (setq polys (mapcan #'(lambda (q) linear factor (push (plsolve q) zeroes) ((list q)))) (mapcan #'(lambda (q) (let ((*ans) (*num 1) (*denom 1)) (nreverse (pfactoralg1 q minpoly 0)))) polys))) (when *nosplitf (setq nminpoly (car *nosplitf) *nosplitf (cdr *nosplitf)) (putprop *algvar (cdr nminpoly) 'tellrat) (let ((beta (plsolve (pgcd (cons (caar *nosplitf) (cdr minpoly)) (exchangevar (car *nosplitf) *algvar))))) (setq alpha (ratplus (cons (make-poly *algvar) 1) (rattimes (cons (- (cadr *nosplitf)) 1) beta t))) (setq zeroes (mapcar #'(lambda (q) (ratgsubst beta (car minpoly) q)) zeroes)) (setq polys (mapcar #'(lambda (q) (car (rgsubst beta (car minpoly) q))) polys)) (setq minpoly (cons *algvar (cdr nminpoly)))))))) (defun exchangevar (poly var) (let ((newvar (gensym)) (ovar (car poly))) (set newvar (1+ (eval ovar))) (pvsubst ovar newvar (pvsubst var ovar (pvsubst newvar var poly))))) (cond ((pcoefp p) expression for any var in p ((eq var (car p)) (cond ((pzerop val) (cons (pterm (cdr p) 0) 1)) ((do ((ld (cadr p) (car a)) (a (cdddr p) (cddr a)) (ans (cons (caddr p) 1) (ratplus (rattimes ans (ratexpt val (- ld (car a))) t) (cons (cadr a) 1)))) ((null a) (rattimes ans (ratexpt val ld) t)))))) ((pointergp var (car p)) (cons p 1)) (t (let ((newsym (gensym))) (set newsym (1+ (symbol-value (car p)))) (rgsubst val newsym (pvsubst newsym var p)))))) (defun ratgsubst (val var rat) (ratquotient (rgsubst val var (car rat)) (rgsubst val var (cdr rat)))) (defun algnorm (f p) (presult f p (car p))) (defmfun $algnorm (r p var) (let ((varlist (list var)) (genvar)) (setq r (ratf r) p (cadr (ratf p))) (rdis* (cons (algnorm (cadr r) p) (algnorm (cddr r) p))))) f must be sqfr , p is minpoly , fvar # pvar (*bind* ((pvar (car p))) new main var will be car of p (do ((i 0 (1+ i)) (dif (pdifference (make-poly fvar) (make-poly (car p)))) (f f (pgsubst dif fvar f)) (res)) ((and (eq (car f) (car p)) (setq res (primpart (algnorm f p))) (psqfrp res fvar)) (list res (putprop pvar (cdr p) 'tellrat) (pvsubst pvar (car p) f)) (car p) p i))))) (defun primelmt (a b gvar &aux ($algebraic nil)) a is a poly with 's in ) (let ((norm (sqfrnorm (cons gvar (cdr a)) b gvar)) (alpha) (beta) ($ratalgdenom t)) (rplaca norm (primpart (car norm))) (putprop gvar (cdar norm) 'tellrat) (setq $algebraic t beta (pgcd (cadddr norm) (pvsubst (caddr norm) (car b) (cadr norm)))) (setq beta (plsolve beta) alpha (ratplus (cons (make-poly gvar) 1) (rattimes (cons (- (cadddr (cdr norm))) 1) beta t))) (list (car b) 1 (- (cadddr (cdr norm))))) (defmfun $bdiscr (&rest args) (let ((varlist) (genvar)) (xcons (bdiscr (mapcar #'rform (butlast args)) (car (rform (car (last args))))) (list 'mrat 'simp varlist genvar)))) (defun bdiscr (l minp) (det (mapcar #'(lambda (q1) (mapcar #'(lambda (q2) (algtrace (ptimes q1 q2) minp)) l)) l)))
9d2ccdd086af3fc2c1048f5628ce87c515f57c0b019850a0ba5c3d990d6a89cc
TrustInSoft/tis-kernel
value_results.mli
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 . (* *) (* It 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. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) * This file will ultimately contain all the results computed by Value ( which must be moved out of Db . Value ) , both per stack and globally . (which must be moved out of Db.Value), both per stack and globally. *) open Cil_types val mark_kf_as_called: kernel_function -> unit val add_kf_caller: caller:kernel_function * stmt -> kernel_function -> unit val callees: stmt -> Kernel_function.Hptset.t * Returns the list of functions semantically called by the stmt . It takes into account recursive cloning It takes into account recursive cloning *) val callwise_terminating_instr: stmt -> Db.Value.callstack list * Db.Value.callstack list (** Returns the list of terminating and non-terminating callstacks. Returns ([], []) for dead code. *) val partition_terminating_instr: stmt -> Db.Value.callstack list * Db.Value.callstack list (** Returns the list of terminating callstacks and the list of non-terminating callstacks. Must be called *only* on statements that are instructions. *) val is_non_terminating_instr: stmt -> bool (** Returns [true] iff there exists executions of the statement that does not always fail/loop (for function calls). Must be called *only* on statements that are instructions. *) type state_per_stmt = Cvalue.Model.t Cil_datatype.Stmt.Hashtbl.t val merge_states_in_db: state_per_stmt Lazy.t -> Db.Value.callstack -> unit val merge_after_states_in_db: state_per_stmt Lazy.t -> Db.Value.callstack -> unit * { 2 Results } type results val get_results: unit -> results val set_results: results -> unit val merge: results -> results -> results val change_callstacks: (Value_callstack.callstack -> Value_callstack.callstack) -> results -> results * Change the callstacks for the results for which this is meaningful . For technical reasons , the top of the must currently be preserved . For technical reasons, the top of the callstack must currently be preserved. *) val add_wp_vertex: State_node.t -> unit val add_wp_edge: State_node.t -> State_node.t -> unit * Add a vertex or an edge to the whole - program graph in Db if Value_parameters . is set . Value_parameters.WholeProgramGraph is set. *) (* Local Variables: compile-command: "make -C ../../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/value/utils/value_results.mli
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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. ************************************************************************ * Returns the list of terminating and non-terminating callstacks. Returns ([], []) for dead code. * Returns the list of terminating callstacks and the list of non-terminating callstacks. Must be called *only* on statements that are instructions. * Returns [true] iff there exists executions of the statement that does not always fail/loop (for function calls). Must be called *only* on statements that are instructions. Local Variables: compile-command: "make -C ../../../.." End:
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . * This file will ultimately contain all the results computed by Value ( which must be moved out of Db . Value ) , both per stack and globally . (which must be moved out of Db.Value), both per stack and globally. *) open Cil_types val mark_kf_as_called: kernel_function -> unit val add_kf_caller: caller:kernel_function * stmt -> kernel_function -> unit val callees: stmt -> Kernel_function.Hptset.t * Returns the list of functions semantically called by the stmt . It takes into account recursive cloning It takes into account recursive cloning *) val callwise_terminating_instr: stmt -> Db.Value.callstack list * Db.Value.callstack list val partition_terminating_instr: stmt -> Db.Value.callstack list * Db.Value.callstack list val is_non_terminating_instr: stmt -> bool type state_per_stmt = Cvalue.Model.t Cil_datatype.Stmt.Hashtbl.t val merge_states_in_db: state_per_stmt Lazy.t -> Db.Value.callstack -> unit val merge_after_states_in_db: state_per_stmt Lazy.t -> Db.Value.callstack -> unit * { 2 Results } type results val get_results: unit -> results val set_results: results -> unit val merge: results -> results -> results val change_callstacks: (Value_callstack.callstack -> Value_callstack.callstack) -> results -> results * Change the callstacks for the results for which this is meaningful . For technical reasons , the top of the must currently be preserved . For technical reasons, the top of the callstack must currently be preserved. *) val add_wp_vertex: State_node.t -> unit val add_wp_edge: State_node.t -> State_node.t -> unit * Add a vertex or an edge to the whole - program graph in Db if Value_parameters . is set . Value_parameters.WholeProgramGraph is set. *)
102b784e3c904dcf8ff13a5d270b9132c68565ac983973204417497d003047bb
chiroptical/optics-by-example
Lib.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # module Lib where import Control.Lens import Data.Aeson import Data.Aeson.Lens import Data.Ord import qualified Data.Text as T import GHC.Generics import Text.RawString.QQ a = "42" ^? _Double b = "42" ^? _String jsonObject = [r| { "name": "Jack Sparrow", "rank": "Captain" } |] jsonArray = [r| [ "North", "South", "East", "West" ] |] c = jsonObject ^? _Object d = jsonArray ^? _Array blackPearl :: String blackPearl = [r| { "name": "Black Pearl", "crew": [ { "name": "Jack Sparrow", "rank": "Captain" }, { "name": "Will Turner", "rank": "First Mate" } ] } |] e = blackPearl ^? _Object . ix (T.pack "crew") . _Array . ix 0 . ix (T.pack "name") . _String f = blackPearl ^? key (T.pack "crew") . nth 0 . key (T.pack "name") . _String g = "[\"a\", \"b\", \"c\"]" ^@.. values . _String fleet :: String fleet = [r| [ { "name": "Black Pearl", "crew": [ { "name": "Jack Sparrow", "rank": "Captain" }, { "name": "Will Turner", "rank": "First Mate" } ] }, { "name": "Flying Dutchman", "crew": [ { "name": "Davy Jones", "rank": "Captain" }, { "name": "Bootstrap Bill", "rank": "First Mate" } ] } ] |] h = fleet ^.. values . key (T.pack "name") . _String i = fleet ^@.. values . reindexed (view (key (T.pack "name") . _String)) selfIndex <. (key (T.pack "crew") . values . key (T.pack "name") . _String) cargo :: String cargo = [r| { "emeralds": 327, "rubies": 480, "sapphires": 621, "opals": 92, "dubloons": 621 } |] j = cargo ^.. members . _Integer k = sumOf (members . _Integer) cargo l = cargo ^@.. members . _Integer m = maximumByOf (members . _Integer . withIndex) (comparing snd) cargo n = fleet ^.. values . key (T.pack "crew") . values . filteredBy (key (T.pack "rank") . only (_String # T.pack "Captain")) . key (T.pack "name") . _String data Creature = Creature { creatureName :: String, creatureSize :: Double } deriving stock (Generic, Show) deriving anyclass (ToJSON, FromJSON) makeLensesFor [ ("creatureName", "creatureNameL"), ("creatureSize", "creatureSizeL") ] ''Creature creatureSightings :: String creatureSightings = [r| { "Arctic": [ { "creatureName": "Giant Squid", "creatureSize": 45.2 } ], "Pacific": [ { "creatureName": "Kraken", "creatureSize": 124.4 }, { "creatureName": "Ogopogo", "creatureSize": 34.6 } ] } |] o = creatureSightings ^.. members . values . _JSON :: [Creature] p :: String p = _JSON # Creature "Kraken" 124.4 q = creatureSightings & members . values . _JSON @_ @Creature . creatureSizeL *~ 1.2
null
https://raw.githubusercontent.com/chiroptical/optics-by-example/3ee33546ee18c3a6f5510eec17a69d34e750198e/chapter15/src/Lib.hs
haskell
# LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # module Lib where import Control.Lens import Data.Aeson import Data.Aeson.Lens import Data.Ord import qualified Data.Text as T import GHC.Generics import Text.RawString.QQ a = "42" ^? _Double b = "42" ^? _String jsonObject = [r| { "name": "Jack Sparrow", "rank": "Captain" } |] jsonArray = [r| [ "North", "South", "East", "West" ] |] c = jsonObject ^? _Object d = jsonArray ^? _Array blackPearl :: String blackPearl = [r| { "name": "Black Pearl", "crew": [ { "name": "Jack Sparrow", "rank": "Captain" }, { "name": "Will Turner", "rank": "First Mate" } ] } |] e = blackPearl ^? _Object . ix (T.pack "crew") . _Array . ix 0 . ix (T.pack "name") . _String f = blackPearl ^? key (T.pack "crew") . nth 0 . key (T.pack "name") . _String g = "[\"a\", \"b\", \"c\"]" ^@.. values . _String fleet :: String fleet = [r| [ { "name": "Black Pearl", "crew": [ { "name": "Jack Sparrow", "rank": "Captain" }, { "name": "Will Turner", "rank": "First Mate" } ] }, { "name": "Flying Dutchman", "crew": [ { "name": "Davy Jones", "rank": "Captain" }, { "name": "Bootstrap Bill", "rank": "First Mate" } ] } ] |] h = fleet ^.. values . key (T.pack "name") . _String i = fleet ^@.. values . reindexed (view (key (T.pack "name") . _String)) selfIndex <. (key (T.pack "crew") . values . key (T.pack "name") . _String) cargo :: String cargo = [r| { "emeralds": 327, "rubies": 480, "sapphires": 621, "opals": 92, "dubloons": 621 } |] j = cargo ^.. members . _Integer k = sumOf (members . _Integer) cargo l = cargo ^@.. members . _Integer m = maximumByOf (members . _Integer . withIndex) (comparing snd) cargo n = fleet ^.. values . key (T.pack "crew") . values . filteredBy (key (T.pack "rank") . only (_String # T.pack "Captain")) . key (T.pack "name") . _String data Creature = Creature { creatureName :: String, creatureSize :: Double } deriving stock (Generic, Show) deriving anyclass (ToJSON, FromJSON) makeLensesFor [ ("creatureName", "creatureNameL"), ("creatureSize", "creatureSizeL") ] ''Creature creatureSightings :: String creatureSightings = [r| { "Arctic": [ { "creatureName": "Giant Squid", "creatureSize": 45.2 } ], "Pacific": [ { "creatureName": "Kraken", "creatureSize": 124.4 }, { "creatureName": "Ogopogo", "creatureSize": 34.6 } ] } |] o = creatureSightings ^.. members . values . _JSON :: [Creature] p :: String p = _JSON # Creature "Kraken" 124.4 q = creatureSightings & members . values . _JSON @_ @Creature . creatureSizeL *~ 1.2
68bf28a1c9f223507e02a58bb2cd6c9435a9bd710d6844f8b841952df2bdd67e
kitnil/dotfiles
gitlab.scm
(define-module (guile gitlab) #:use-module (gnu packages bash) #:use-module (gnu packages guile) #:use-module (gnu services configuration) #:use-module (guix build utils) #:use-module (guix gexp) #:use-module (guix modules) #:use-module (guix monads) #:use-module (guix packages) #:use-module (guix records) #:use-module (guix store) #:use-module (json builder) #:use-module (srfi srfi-1) #:export (home-gitlab-project-configuration terraform-gitlab terraform-gitlab-configuration)) (define (uglify-field-name field-name) "Convert symbol FIELD-NAME to a camel case string. @code{symbol-name} => \"@code{symbolName}\"." (let* ((str (string-delete #\? (symbol->string field-name))) (spl-str (string-split str #\-))) (string-join spl-str "_"))) (define (serialize-field field-name val) (cons (uglify-field-name field-name) val)) (define serialize-boolean serialize-field) (define serialize-string serialize-field) (define-configuration home-gitlab-project-configuration (name (string (configuration-missing-field 'home-gitlab-project-configuration 'name)) "Name of the project.") ;; (namespace-id ;; (string (configuration-missing-field 'home-gitlab-project-configuration 'namespace-id)) " Namespace ID . " ) (default-branch (string "master") "Default branch for the project.") (description (string (configuration-missing-field 'home-gitlab-project-configuration 'description)) "Description of the project.") (visibility-level (string "public") "Project access level.") (wiki-enabled? (boolean #f) "Enable wiki for the project.") (snippets-enabled? (boolean #f) "Enable snippets for the project.") (issues-enabled? (boolean #t) "Enable issue tracking for the project.") (container-registry-enabled? (boolean #f) "Enable container registry for the project.") (shared-runners-enabled? (boolean #f) "Enable shared runners for this project.") (request-access-enabled? (boolean #f) "Allow users to request member access.") (pipelines-enabled? (boolean #f) "Enable pipelines for the project.") (pages-access-level (string "public") "Pages access control.")) (define (serialize-gitlab-project-configuration config fields) "Similar to serialize-configuration from gnu/services/configuration.scm." (plain-file (string-append "gitlab-project-" (home-gitlab-project-configuration-name config) ".tf.json") (with-output-to-string (lambda () (scm->json `((resource (gitlab_project (,(home-gitlab-project-configuration-name config) ,@(map (lambda (field) ((configuration-field-serializer field) (configuration-field-name field) ((configuration-field-getter field) config))) fields))))) #:pretty #t))))) (define %terraform-configuration `((variable (GITLAB_TOKEN (type . "string"))) (provider (gitlab (token . "${var.GITLAB_TOKEN}") (base_url . "/"))))) (define-record-type* <terraform-gitlab-configuration> terraform-gitlab-configuration make-terraform-gitlab-configuration terraform-gitlab-configuration? (projects terraform-gitlab-configuration-projects) (state terraform-gitlab-configuration-state) (terraform-configuration terraform-gitlab-configuration-terraform-configuration (default %terraform-configuration))) (define (terraform-gitlab config) (mlet* %store-monad ((main.tf.json (text-file* "main.tf.json" (with-output-to-string (lambda () (scm->json (terraform-gitlab-configuration-terraform-configuration config)))))) (program -> (program-file "terraform-gitlab-program" (with-imported-modules '((guix build syscalls) (guix build utils)) #~(begin (use-modules (guix build syscalls) (guix build utils)) (define instance-dir (mkdtemp! "/tmp/terraform.XXXXXX")) (chdir instance-dir) (copy-file #$main.tf.json "main.tf.json") (for-each (lambda (file) (install-file file ".")) '#$(map (lambda (project) (serialize-gitlab-project-configuration project home-gitlab-project-configuration-fields)) (terraform-gitlab-configuration-projects config))) (invoke "terraform" "init") (invoke "terraform" "apply" #$(string-append "-state=" (terraform-gitlab-configuration-state config))) (delete-file-recursively instance-dir)))))) (gexp->derivation "terraform-gitlab" #~(symlink #$program #$output))))
null
https://raw.githubusercontent.com/kitnil/dotfiles/51519ac5e036761349cfa126e0226a9eb027f674/dotfiles/guile/gitlab.scm
scheme
(namespace-id (string (configuration-missing-field 'home-gitlab-project-configuration 'namespace-id))
(define-module (guile gitlab) #:use-module (gnu packages bash) #:use-module (gnu packages guile) #:use-module (gnu services configuration) #:use-module (guix build utils) #:use-module (guix gexp) #:use-module (guix modules) #:use-module (guix monads) #:use-module (guix packages) #:use-module (guix records) #:use-module (guix store) #:use-module (json builder) #:use-module (srfi srfi-1) #:export (home-gitlab-project-configuration terraform-gitlab terraform-gitlab-configuration)) (define (uglify-field-name field-name) "Convert symbol FIELD-NAME to a camel case string. @code{symbol-name} => \"@code{symbolName}\"." (let* ((str (string-delete #\? (symbol->string field-name))) (spl-str (string-split str #\-))) (string-join spl-str "_"))) (define (serialize-field field-name val) (cons (uglify-field-name field-name) val)) (define serialize-boolean serialize-field) (define serialize-string serialize-field) (define-configuration home-gitlab-project-configuration (name (string (configuration-missing-field 'home-gitlab-project-configuration 'name)) "Name of the project.") " Namespace ID . " ) (default-branch (string "master") "Default branch for the project.") (description (string (configuration-missing-field 'home-gitlab-project-configuration 'description)) "Description of the project.") (visibility-level (string "public") "Project access level.") (wiki-enabled? (boolean #f) "Enable wiki for the project.") (snippets-enabled? (boolean #f) "Enable snippets for the project.") (issues-enabled? (boolean #t) "Enable issue tracking for the project.") (container-registry-enabled? (boolean #f) "Enable container registry for the project.") (shared-runners-enabled? (boolean #f) "Enable shared runners for this project.") (request-access-enabled? (boolean #f) "Allow users to request member access.") (pipelines-enabled? (boolean #f) "Enable pipelines for the project.") (pages-access-level (string "public") "Pages access control.")) (define (serialize-gitlab-project-configuration config fields) "Similar to serialize-configuration from gnu/services/configuration.scm." (plain-file (string-append "gitlab-project-" (home-gitlab-project-configuration-name config) ".tf.json") (with-output-to-string (lambda () (scm->json `((resource (gitlab_project (,(home-gitlab-project-configuration-name config) ,@(map (lambda (field) ((configuration-field-serializer field) (configuration-field-name field) ((configuration-field-getter field) config))) fields))))) #:pretty #t))))) (define %terraform-configuration `((variable (GITLAB_TOKEN (type . "string"))) (provider (gitlab (token . "${var.GITLAB_TOKEN}") (base_url . "/"))))) (define-record-type* <terraform-gitlab-configuration> terraform-gitlab-configuration make-terraform-gitlab-configuration terraform-gitlab-configuration? (projects terraform-gitlab-configuration-projects) (state terraform-gitlab-configuration-state) (terraform-configuration terraform-gitlab-configuration-terraform-configuration (default %terraform-configuration))) (define (terraform-gitlab config) (mlet* %store-monad ((main.tf.json (text-file* "main.tf.json" (with-output-to-string (lambda () (scm->json (terraform-gitlab-configuration-terraform-configuration config)))))) (program -> (program-file "terraform-gitlab-program" (with-imported-modules '((guix build syscalls) (guix build utils)) #~(begin (use-modules (guix build syscalls) (guix build utils)) (define instance-dir (mkdtemp! "/tmp/terraform.XXXXXX")) (chdir instance-dir) (copy-file #$main.tf.json "main.tf.json") (for-each (lambda (file) (install-file file ".")) '#$(map (lambda (project) (serialize-gitlab-project-configuration project home-gitlab-project-configuration-fields)) (terraform-gitlab-configuration-projects config))) (invoke "terraform" "init") (invoke "terraform" "apply" #$(string-append "-state=" (terraform-gitlab-configuration-state config))) (delete-file-recursively instance-dir)))))) (gexp->derivation "terraform-gitlab" #~(symlink #$program #$output))))
fa137eee317d1870ec65621b5013d80fd2bc41a087ab2fcf937f0e9bb125a59b
camlspotter/ocaml-zippy-tutorial-in-japanese
w25.ml
let f = function | x when x = 1 -> x + 1 | x when x = 2 -> x + 20 | x when x = 3 -> x + 300
null
https://raw.githubusercontent.com/camlspotter/ocaml-zippy-tutorial-in-japanese/c6aeabc08b6e2289a0e66c5b94a89c6723d88a6a/t/warnings/w25.ml
ocaml
let f = function | x when x = 1 -> x + 1 | x when x = 2 -> x + 20 | x when x = 3 -> x + 300
f6f4cd60c4b7d6c9db08773a7cda85c5dbf746a327c8508758f8d912807e9a18
adventuring/tootsville.net
jack.lisp
;;;; -*- lisp -*- ;;; src / characters / named / jack.lisp is part of ;;; Copyright © 2008 - 2017 Bruce - Robert Pocock ; © 2018 - 2021 The Corporation for Inter - World Tourism and Adventuring ( ciwta.org ) . ;;; 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 ;;; </>. ;;; ;;; You can reach CIWTA at /, or write to us at: ;;; PO Box 23095 Oakland Park , FL 33307 - 3095 USA (in-package :Tootsville) (define-character Jack Holiday-Special)
null
https://raw.githubusercontent.com/adventuring/tootsville.net/985c11a91dd1a21b77d7378362d86cf1c031b22c/src/characters/named/jack.lisp
lisp
-*- lisp -*- © 2018 - 2021 The either version 3 of 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. License along with this program. If not, see </>. You can reach CIWTA at /, or write to us at:
src / characters / named / jack.lisp is part of Corporation for Inter - World Tourism and Adventuring ( ciwta.org ) . This program is Free Software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License the License , or ( at your option ) any later version . You should have received a copy of the GNU Affero General Public PO Box 23095 Oakland Park , FL 33307 - 3095 USA (in-package :Tootsville) (define-character Jack Holiday-Special)
bf251418150044f02b1808042cedd55d545c589b0cf7cf0dc5b34af2f5d4216a
xapi-project/message-switch
debug.ml
* Copyright ( C ) 2006 - 2009 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) 2006-2009 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. *) module Mutex = struct include Mutex (** execute the function f with the mutex hold *) let execute lock f = Mutex.lock lock ; let r = try f () with exn -> Mutex.unlock lock ; raise exn in Mutex.unlock lock ; r end let get_thread_id () = try Thread.id (Thread.self ()) with _ -> -1 module IntMap = Map.Make (Int) module ThreadLocalTable = struct type 'a t = {mutable tbl: 'a IntMap.t; m: Mutex.t} let make () = let tbl = IntMap.empty in let m = Mutex.create () in {tbl; m} let add t v = let id = get_thread_id () in Mutex.execute t.m (fun () -> t.tbl <- IntMap.add id v t.tbl) let remove t = let id = get_thread_id () in Mutex.execute t.m (fun () -> t.tbl <- IntMap.remove id t.tbl) let find t = let id = get_thread_id () in IntMap.find_opt id t.tbl end type task = {desc: string; client: string option} let tasks : task ThreadLocalTable.t = ThreadLocalTable.make () let names : string ThreadLocalTable.t = ThreadLocalTable.make () let gettimestring () = let time = Unix.gettimeofday () in let tm = Unix.gmtime time in let msec = time -. floor time in Printf.sprintf "%d%.2d%.2dT%.2d:%.2d:%.2d.%.3dZ|" (1900 + tm.Unix.tm_year) (tm.Unix.tm_mon + 1) tm.Unix.tm_mday tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec (int_of_float (1000.0 *. msec)) (** [escape str] efficiently escapes non-printable characters and in addition the backslash character. The function is efficient in the sense that it will allocate a new string only when necessary *) let escape = Astring.String.Ascii.escape let format include_time brand priority message = let id = get_thread_id () in let task, name = (* if the task's client is known, attach it to the task's name *) let name = match ThreadLocalTable.find names with Some x -> x | None -> "" in match ThreadLocalTable.find tasks with | None -> ("", name) | Some {desc; client= None} -> (desc, name) | Some {desc; client= Some client} -> (desc, Printf.sprintf "%s->%s" client name) in Printf.sprintf "[%s%5s||%d %s|%s|%s] %s" (if include_time then gettimestring () else "") priority id name task brand message let print_debug = ref false let log_to_stdout () = print_debug := true module BrandLevelPair = struct type t = string * Syslog.level let compare = Stdlib.compare end module BrandLevelPairSet = Set.Make (BrandLevelPair) let loglevel_m = Mutex.create () let logging_disabled_for = ref BrandLevelPairSet.empty let default_loglevel = Syslog.Debug let loglevel = ref default_loglevel let disabled_modules () = BrandLevelPairSet.elements !logging_disabled_for let is_disabled brand level = Syslog.is_masked ~threshold:!loglevel level || BrandLevelPairSet.mem (brand, level) !logging_disabled_for let facility = ref Syslog.Daemon let set_facility f = facility := f let get_facility () = !facility let output_log brand level priority s = if not (is_disabled brand level) then ( let msg = format false brand priority s in if !print_debug then Printf.printf "%s\n%!" (format true brand priority s) ; Syslog.log (get_facility ()) level (escape msg) ) let logs_reporter = We convert Logs level to our own type to allow output_log to correctly filter logs coming from libraries using Logs filter logs coming from libraries using Logs *) let logs_to_syslog_level = function In practice we only care about . Debug , Warning , Info , , because these are the ones we use in the log functions in Debug . Make these are the ones we use in the log functions in Debug.Make *) | Logs.Debug -> Syslog.Debug | Logs.Info -> Syslog.Info | Logs.Warning -> Syslog.Warning | Logs.Error -> Syslog.Err (* This is used by applications, not libraries - we should not get this in practice *) | Logs.App -> Syslog.Info in (* Ensure that logs from libraries will be displayed with the correct priority *) let logs_level_to_priority = function (* These string match the ones used by the logging functions in Debug.Make *) | Logs.Debug -> "debug" | Logs.Info -> "info" | Logs.Warning -> "warn" | Logs.Error -> "error" (* This is used by applications, not libraries - we should not get this in practice *) | Logs.App -> "app" in let report src level ~over k msgf = let formatter ?header ?tags fmt = ignore header ; ignore tags ; let buf = Buffer.create 80 in let buf_fmt = Format.formatter_of_buffer buf in let k _ = Format.pp_print_flush buf_fmt () ; let msg = Buffer.contents buf in (* We map the Logs source name to the "brand", so we have to use the name of the Logs source when enabling/disabling it *) let brand = Logs.Src.name src in output_log brand (logs_to_syslog_level level) (logs_level_to_priority level) msg ; over () ; k () in Format.kfprintf k buf_fmt fmt in msgf formatter in {Logs.report} let init_logs () = Logs.set_reporter logs_reporter ; [ output_log ] will do the actual filtering based on levels , but we only consider messages of level warning and above from libraries , to avoid calling [ output_log ] too often . consider messages of level warning and above from libraries, to avoid calling [output_log] too often. *) Logs.set_level (Some Logs.Warning) let rec split_c c str = try let i = String.index str c in String.sub str 0 i :: split_c c (String.sub str (i + 1) (String.length str - i - 1)) with Not_found -> [str] let log_backtrace_exn ?(level = Syslog.Err) ?(msg = "error") exn bt = We already got the backtrace in the ` bt ` argument when called from with_thread_associated . Log that , and remove ` exn ` from the backtraces table . If with_backtraces was not nested then looking at ` bt ` is the only way to get a proper backtrace , otherwise exiting from ` with_backtraces ` would 've removed the backtrace from the thread - local backtraces table , and we 'd always just log a message complaining about with_backtraces not being called , which is not true because it was . Log that, and remove `exn` from the backtraces table. If with_backtraces was not nested then looking at `bt` is the only way to get a proper backtrace, otherwise exiting from `with_backtraces` would've removed the backtrace from the thread-local backtraces table, and we'd always just log a message complaining about with_backtraces not being called, which is not true because it was. *) let bt' = Backtrace.remove exn in (* bt could be empty, but bt' would contain a non-empty warning, so compare 'bt' here *) let bt = if bt = Backtrace.empty then bt' else bt in let all = split_c '\n' Backtrace.(to_string_hum bt) in (* Write to the log line at a time *) output_log "backtrace" level msg (Printf.sprintf "Raised %s" (Printexc.to_string exn)) ; List.iter (output_log "backtrace" level msg) all let log_backtrace_internal ?level ?msg e _bt = Backtrace.is_important e ; log_backtrace_exn ?level ?msg e (Backtrace.remove e) let log_backtrace e bt = log_backtrace_internal e bt let with_thread_associated ?client desc f x = ThreadLocalTable.add tasks {desc; client} ; let result = Backtrace.with_backtraces (fun () -> try f x with e -> Backtrace.is_important e ; raise e) in ThreadLocalTable.remove tasks ; match result with | `Ok result -> result | `Error (exn, bt) -> (* This function is a top-level exception handler typically used on fresh threads. This is the last chance to do something with the backtrace *) output_log "backtrace" Syslog.Err "error" (Printf.sprintf "%s failed with exception %s" desc (Printexc.to_string exn)) ; log_backtrace_exn exn bt ; raise exn let with_thread_named name f x = ThreadLocalTable.add names name ; try let result = f x in ThreadLocalTable.remove names ; result with e -> Backtrace.is_important e ; ThreadLocalTable.remove names ; raise e module type BRAND = sig val name : string end let all_levels = [Syslog.Debug; Syslog.Info; Syslog.Warning; Syslog.Err; Syslog.Crit] let add_to_stoplist brand level = logging_disabled_for := BrandLevelPairSet.add (brand, level) !logging_disabled_for let disable ?level brand = let levels = match level with None -> all_levels | Some l -> [l] in Mutex.execute loglevel_m (fun () -> List.iter (add_to_stoplist brand) levels) let set_level level = Mutex.execute loglevel_m (fun () -> loglevel := level) module type DEBUG = sig val debug : ('a, unit, string, unit) format4 -> 'a val warn : ('a, unit, string, unit) format4 -> 'a val info : ('a, unit, string, unit) format4 -> 'a val error : ('a, unit, string, unit) format4 -> 'a val critical : ('a, unit, string, unit) format4 -> 'a val audit : ?raw:bool -> ('a, unit, string, string) format4 -> 'a val log_backtrace : unit -> unit val log_and_ignore_exn : (unit -> unit) -> unit end module Make = functor (Brand : BRAND) -> struct let output level priority (fmt : ('a, unit, string, 'b) format4) = Printf.kprintf (fun s -> if not (is_disabled Brand.name level) then output_log Brand.name level priority s) fmt let debug fmt = output Syslog.Debug "debug" fmt let warn fmt = output Syslog.Warning "warn" fmt let info fmt = output Syslog.Info "info" fmt let error fmt = output Syslog.Err "error" fmt let critical fmt = output Syslog.Crit "critical" fmt let audit ?(raw = false) (fmt : ('a, unit, string, 'b) format4) = Printf.kprintf (fun s -> let msg = if raw then s else format true Brand.name "audit" s in Syslog.log Syslog.Local6 Syslog.Info (escape msg) ; msg) fmt let log_backtrace () = let backtrace = Printexc.get_backtrace () in debug "%s" (String.escaped backtrace) let log_and_ignore_exn f = try f () with e -> log_backtrace_internal ~level:Syslog.Debug ~msg:"debug" e () end
null
https://raw.githubusercontent.com/xapi-project/message-switch/1d0d1aa45c01eba144ac2826d0d88bb663e33101/xapi-idl/lib/debug.ml
ocaml
* execute the function f with the mutex hold * [escape str] efficiently escapes non-printable characters and in addition the backslash character. The function is efficient in the sense that it will allocate a new string only when necessary if the task's client is known, attach it to the task's name This is used by applications, not libraries - we should not get this in practice Ensure that logs from libraries will be displayed with the correct priority These string match the ones used by the logging functions in Debug.Make This is used by applications, not libraries - we should not get this in practice We map the Logs source name to the "brand", so we have to use the name of the Logs source when enabling/disabling it bt could be empty, but bt' would contain a non-empty warning, so compare 'bt' here Write to the log line at a time This function is a top-level exception handler typically used on fresh threads. This is the last chance to do something with the backtrace
* Copyright ( C ) 2006 - 2009 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) 2006-2009 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. *) module Mutex = struct include Mutex let execute lock f = Mutex.lock lock ; let r = try f () with exn -> Mutex.unlock lock ; raise exn in Mutex.unlock lock ; r end let get_thread_id () = try Thread.id (Thread.self ()) with _ -> -1 module IntMap = Map.Make (Int) module ThreadLocalTable = struct type 'a t = {mutable tbl: 'a IntMap.t; m: Mutex.t} let make () = let tbl = IntMap.empty in let m = Mutex.create () in {tbl; m} let add t v = let id = get_thread_id () in Mutex.execute t.m (fun () -> t.tbl <- IntMap.add id v t.tbl) let remove t = let id = get_thread_id () in Mutex.execute t.m (fun () -> t.tbl <- IntMap.remove id t.tbl) let find t = let id = get_thread_id () in IntMap.find_opt id t.tbl end type task = {desc: string; client: string option} let tasks : task ThreadLocalTable.t = ThreadLocalTable.make () let names : string ThreadLocalTable.t = ThreadLocalTable.make () let gettimestring () = let time = Unix.gettimeofday () in let tm = Unix.gmtime time in let msec = time -. floor time in Printf.sprintf "%d%.2d%.2dT%.2d:%.2d:%.2d.%.3dZ|" (1900 + tm.Unix.tm_year) (tm.Unix.tm_mon + 1) tm.Unix.tm_mday tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec (int_of_float (1000.0 *. msec)) let escape = Astring.String.Ascii.escape let format include_time brand priority message = let id = get_thread_id () in let task, name = let name = match ThreadLocalTable.find names with Some x -> x | None -> "" in match ThreadLocalTable.find tasks with | None -> ("", name) | Some {desc; client= None} -> (desc, name) | Some {desc; client= Some client} -> (desc, Printf.sprintf "%s->%s" client name) in Printf.sprintf "[%s%5s||%d %s|%s|%s] %s" (if include_time then gettimestring () else "") priority id name task brand message let print_debug = ref false let log_to_stdout () = print_debug := true module BrandLevelPair = struct type t = string * Syslog.level let compare = Stdlib.compare end module BrandLevelPairSet = Set.Make (BrandLevelPair) let loglevel_m = Mutex.create () let logging_disabled_for = ref BrandLevelPairSet.empty let default_loglevel = Syslog.Debug let loglevel = ref default_loglevel let disabled_modules () = BrandLevelPairSet.elements !logging_disabled_for let is_disabled brand level = Syslog.is_masked ~threshold:!loglevel level || BrandLevelPairSet.mem (brand, level) !logging_disabled_for let facility = ref Syslog.Daemon let set_facility f = facility := f let get_facility () = !facility let output_log brand level priority s = if not (is_disabled brand level) then ( let msg = format false brand priority s in if !print_debug then Printf.printf "%s\n%!" (format true brand priority s) ; Syslog.log (get_facility ()) level (escape msg) ) let logs_reporter = We convert Logs level to our own type to allow output_log to correctly filter logs coming from libraries using Logs filter logs coming from libraries using Logs *) let logs_to_syslog_level = function In practice we only care about . Debug , Warning , Info , , because these are the ones we use in the log functions in Debug . Make these are the ones we use in the log functions in Debug.Make *) | Logs.Debug -> Syslog.Debug | Logs.Info -> Syslog.Info | Logs.Warning -> Syslog.Warning | Logs.Error -> Syslog.Err | Logs.App -> Syslog.Info in let logs_level_to_priority = function | Logs.Debug -> "debug" | Logs.Info -> "info" | Logs.Warning -> "warn" | Logs.Error -> "error" | Logs.App -> "app" in let report src level ~over k msgf = let formatter ?header ?tags fmt = ignore header ; ignore tags ; let buf = Buffer.create 80 in let buf_fmt = Format.formatter_of_buffer buf in let k _ = Format.pp_print_flush buf_fmt () ; let msg = Buffer.contents buf in let brand = Logs.Src.name src in output_log brand (logs_to_syslog_level level) (logs_level_to_priority level) msg ; over () ; k () in Format.kfprintf k buf_fmt fmt in msgf formatter in {Logs.report} let init_logs () = Logs.set_reporter logs_reporter ; [ output_log ] will do the actual filtering based on levels , but we only consider messages of level warning and above from libraries , to avoid calling [ output_log ] too often . consider messages of level warning and above from libraries, to avoid calling [output_log] too often. *) Logs.set_level (Some Logs.Warning) let rec split_c c str = try let i = String.index str c in String.sub str 0 i :: split_c c (String.sub str (i + 1) (String.length str - i - 1)) with Not_found -> [str] let log_backtrace_exn ?(level = Syslog.Err) ?(msg = "error") exn bt = We already got the backtrace in the ` bt ` argument when called from with_thread_associated . Log that , and remove ` exn ` from the backtraces table . If with_backtraces was not nested then looking at ` bt ` is the only way to get a proper backtrace , otherwise exiting from ` with_backtraces ` would 've removed the backtrace from the thread - local backtraces table , and we 'd always just log a message complaining about with_backtraces not being called , which is not true because it was . Log that, and remove `exn` from the backtraces table. If with_backtraces was not nested then looking at `bt` is the only way to get a proper backtrace, otherwise exiting from `with_backtraces` would've removed the backtrace from the thread-local backtraces table, and we'd always just log a message complaining about with_backtraces not being called, which is not true because it was. *) let bt' = Backtrace.remove exn in let bt = if bt = Backtrace.empty then bt' else bt in let all = split_c '\n' Backtrace.(to_string_hum bt) in output_log "backtrace" level msg (Printf.sprintf "Raised %s" (Printexc.to_string exn)) ; List.iter (output_log "backtrace" level msg) all let log_backtrace_internal ?level ?msg e _bt = Backtrace.is_important e ; log_backtrace_exn ?level ?msg e (Backtrace.remove e) let log_backtrace e bt = log_backtrace_internal e bt let with_thread_associated ?client desc f x = ThreadLocalTable.add tasks {desc; client} ; let result = Backtrace.with_backtraces (fun () -> try f x with e -> Backtrace.is_important e ; raise e) in ThreadLocalTable.remove tasks ; match result with | `Ok result -> result | `Error (exn, bt) -> output_log "backtrace" Syslog.Err "error" (Printf.sprintf "%s failed with exception %s" desc (Printexc.to_string exn)) ; log_backtrace_exn exn bt ; raise exn let with_thread_named name f x = ThreadLocalTable.add names name ; try let result = f x in ThreadLocalTable.remove names ; result with e -> Backtrace.is_important e ; ThreadLocalTable.remove names ; raise e module type BRAND = sig val name : string end let all_levels = [Syslog.Debug; Syslog.Info; Syslog.Warning; Syslog.Err; Syslog.Crit] let add_to_stoplist brand level = logging_disabled_for := BrandLevelPairSet.add (brand, level) !logging_disabled_for let disable ?level brand = let levels = match level with None -> all_levels | Some l -> [l] in Mutex.execute loglevel_m (fun () -> List.iter (add_to_stoplist brand) levels) let set_level level = Mutex.execute loglevel_m (fun () -> loglevel := level) module type DEBUG = sig val debug : ('a, unit, string, unit) format4 -> 'a val warn : ('a, unit, string, unit) format4 -> 'a val info : ('a, unit, string, unit) format4 -> 'a val error : ('a, unit, string, unit) format4 -> 'a val critical : ('a, unit, string, unit) format4 -> 'a val audit : ?raw:bool -> ('a, unit, string, string) format4 -> 'a val log_backtrace : unit -> unit val log_and_ignore_exn : (unit -> unit) -> unit end module Make = functor (Brand : BRAND) -> struct let output level priority (fmt : ('a, unit, string, 'b) format4) = Printf.kprintf (fun s -> if not (is_disabled Brand.name level) then output_log Brand.name level priority s) fmt let debug fmt = output Syslog.Debug "debug" fmt let warn fmt = output Syslog.Warning "warn" fmt let info fmt = output Syslog.Info "info" fmt let error fmt = output Syslog.Err "error" fmt let critical fmt = output Syslog.Crit "critical" fmt let audit ?(raw = false) (fmt : ('a, unit, string, 'b) format4) = Printf.kprintf (fun s -> let msg = if raw then s else format true Brand.name "audit" s in Syslog.log Syslog.Local6 Syslog.Info (escape msg) ; msg) fmt let log_backtrace () = let backtrace = Printexc.get_backtrace () in debug "%s" (String.escaped backtrace) let log_and_ignore_exn f = try f () with e -> log_backtrace_internal ~level:Syslog.Debug ~msg:"debug" e () end
64a4e1415cc12f0f48328f3e658fa41783af9d760b581170f713fd493949a9ed
danieljharvey/mimsa
ReplM.hs
# LANGUAGE DerivingStrategies # # LANGUAGE GeneralisedNewtypeDeriving # module Repl.ReplM ( ReplM (..), ReplState (..), runReplM, mapError, setStoredModule, getStoredModule, replMFromEither, replOutput, replDocOutput, ) where import Control.Monad.Catch import Control.Monad.Except import Control.Monad.Logger ( LoggingT, MonadLogger, filterLogger, runStdoutLoggingT, ) import Control.Monad.Reader import Control.Monad.State import qualified Data.Text.IO as T import Language.Mimsa.Core import Prettyprinter import Repl.Types -- | to allow us to do 'bindings' in the repl, -- we maintain a current Module and add to it newtype ReplState = ReplState { rsModule :: Module MonoType } -- | Although we are lucky and can keep much of our work outside of IO , we do need to do some Serious Business sometimes so here is a Monad to do it in newtype ReplM e a = ReplM { getReplM :: ExceptT e ( LoggingT ( ReaderT ReplConfig (StateT ReplState IO) ) ) a } deriving newtype ( Functor, Applicative, Monad, MonadIO, MonadReader ReplConfig, MonadState ReplState, MonadError e, MonadLogger, MonadThrow, MonadCatch, MonadMask ) -- | change error type mapError :: (e -> e') -> ReplM e a -> ReplM e' a mapError f = ReplM . withExceptT f . getReplM -- | run this big brave boy runReplM :: ReplConfig -> ReplM e a -> IO (Either e a) runReplM config app = let innerApp = runExceptT (getReplM app) emptyState = ReplState mempty in evalStateT ( runReaderT ( runStdoutLoggingT (logFilter config innerApp) ) config ) emptyState logFilter :: ReplConfig -> LoggingT m a -> LoggingT m a logFilter mc app = if rcShowLogs mc then app else filterLogger (\_ _ -> False) app -- | lift Either into ReplM replMFromEither :: Either e a -> ReplM e a replMFromEither = ReplM . liftEither -- | Output stuff for use in repl replOutput :: (Printer a) => a -> ReplM e () replOutput = liftIO . T.putStrLn . prettyPrint | Output a Doc from replDocOutput :: Doc a -> ReplM e () replDocOutput = liftIO . T.putStrLn . renderWithWidth 40 -- | we maintain a module in state, this allows us to update it setStoredModule :: Module MonoType -> ReplM e () setStoredModule newMod = modify (\s -> s {rsModule = newMod}) getStoredModule :: ReplM e (Module MonoType) getStoredModule = gets rsModule
null
https://raw.githubusercontent.com/danieljharvey/mimsa/564c32cc28d990c9e686f63533a9e30c3736aee4/repl/repl/Repl/ReplM.hs
haskell
| to allow us to do 'bindings' in the repl, we maintain a current Module and add to it | Although we are lucky and can keep much of our work | change error type | run this big brave boy | lift Either into ReplM | Output stuff for use in repl | we maintain a module in state, this allows us to update it
# LANGUAGE DerivingStrategies # # LANGUAGE GeneralisedNewtypeDeriving # module Repl.ReplM ( ReplM (..), ReplState (..), runReplM, mapError, setStoredModule, getStoredModule, replMFromEither, replOutput, replDocOutput, ) where import Control.Monad.Catch import Control.Monad.Except import Control.Monad.Logger ( LoggingT, MonadLogger, filterLogger, runStdoutLoggingT, ) import Control.Monad.Reader import Control.Monad.State import qualified Data.Text.IO as T import Language.Mimsa.Core import Prettyprinter import Repl.Types newtype ReplState = ReplState { rsModule :: Module MonoType } outside of IO , we do need to do some Serious Business sometimes so here is a Monad to do it in newtype ReplM e a = ReplM { getReplM :: ExceptT e ( LoggingT ( ReaderT ReplConfig (StateT ReplState IO) ) ) a } deriving newtype ( Functor, Applicative, Monad, MonadIO, MonadReader ReplConfig, MonadState ReplState, MonadError e, MonadLogger, MonadThrow, MonadCatch, MonadMask ) mapError :: (e -> e') -> ReplM e a -> ReplM e' a mapError f = ReplM . withExceptT f . getReplM runReplM :: ReplConfig -> ReplM e a -> IO (Either e a) runReplM config app = let innerApp = runExceptT (getReplM app) emptyState = ReplState mempty in evalStateT ( runReaderT ( runStdoutLoggingT (logFilter config innerApp) ) config ) emptyState logFilter :: ReplConfig -> LoggingT m a -> LoggingT m a logFilter mc app = if rcShowLogs mc then app else filterLogger (\_ _ -> False) app replMFromEither :: Either e a -> ReplM e a replMFromEither = ReplM . liftEither replOutput :: (Printer a) => a -> ReplM e () replOutput = liftIO . T.putStrLn . prettyPrint | Output a Doc from replDocOutput :: Doc a -> ReplM e () replDocOutput = liftIO . T.putStrLn . renderWithWidth 40 setStoredModule :: Module MonoType -> ReplM e () setStoredModule newMod = modify (\s -> s {rsModule = newMod}) getStoredModule :: ReplM e (Module MonoType) getStoredModule = gets rsModule
747389f24eb3bc0dce37ef3fe24f27f23a29fb818aa4b25934864e2c9a0ef64a
abailly/hevents
Persist.hs
{-# LANGUAGE DeriveGeneric #-} # LANGUAGE ImplicitParams # {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE AllowAmbiguousTypes # # LANGUAGE TypeFamilyDependencies # | An effect which combines a ` State ` and a ` Storage ` within IO monad module Hevents.Eff.Persist(Persist, makePersist, stopPersist, state) where import Control.Eff.Lift import Data.IORef import Data.Serialize import Data.Text (pack) import GHC.Generics import Hevents.Eff.Model import Hevents.Eff.State import Hevents.Eff.Store import Prelude hiding (length) data Persist m where Persist :: (Store IO s) => { state :: IORef m -- ^The persistent state managed by this effect , storeEngine :: s -- ^The low-level storage engine , errorHandler :: StoreError -> Error m -- ^How to interpret storage errors within the model } -> Persist m makePersist :: (Store IO s) => m -> s -> (StoreError -> Error m) -> IO (Persist m) makePersist m s h = do ref<- newIORef m return $ Persist { state = ref, storeEngine = s, errorHandler = h } stopPersist :: Persist m -> IO (Persist m) stopPersist p@Persist{..} = close storeEngine >> return p instance (Model m, Versionable (Event m)) => Registrar IO m (Persist m) where update p@Persist{..} (ApplyCommand c k) = lift (runCommand p c) >>= k update Persist{..} (GetState k) = lift (readIORef state) >>= k data CommandResult m = Success (Event m) | Failure (Error m) | Fatal StoreError deriving (Generic) instance (Show (Event m), Show (Error m)) => Show (CommandResult m) where show (Success e) = "[Success] " ++ show e show (Failure f) = "[Failure] " ++ show f show (Fatal e) = "[Fatal ] " ++ show e instance (Versionable (Event m), Versionable (Error m)) => Versionable (CommandResult m) instance (Serialize (Event m), Serialize (Error m)) => Serialize (CommandResult m) runCommand :: (Model m, Versionable (Event m)) => Persist m -> Command m -> IO (Either (Error m) (Event m)) runCommand Persist{..} command = store storeEngine pre post >>= return . handleResult where pre = do st <- readIORef state case st `act` command of OK e -> return $ Right e KO e -> return $ Left e post (Right (WriteSucceed ev )) = modifyIORef state (`apply` ev) >> return (Success ev) post (Right (OpFailed f)) = return $ Fatal (IOError $ pack f) post (Right _) = return $ Fatal (IOError "Something got wrong...") post (Left er) = return $ Failure er handleResult (WriteSucceed (Success e)) = Right e handleResult (WriteFailed (Failure er)) = Left er handleResult (WriteFailed (Fatal er)) = Left $ errorHandler er handleResult _ = Left $ errorHandler (IOError $ pack $ "Something got wrong while trying to store result of command")
null
https://raw.githubusercontent.com/abailly/hevents/d38789bf5ae787c35d496b72fe47419d965032de/src/Hevents/Eff/Persist.hs
haskell
# LANGUAGE DeriveGeneric # # LANGUAGE ScopedTypeVariables # ^The persistent state managed by this effect ^The low-level storage engine ^How to interpret storage errors within the model
# LANGUAGE ImplicitParams # # LANGUAGE AllowAmbiguousTypes # # LANGUAGE TypeFamilyDependencies # | An effect which combines a ` State ` and a ` Storage ` within IO monad module Hevents.Eff.Persist(Persist, makePersist, stopPersist, state) where import Control.Eff.Lift import Data.IORef import Data.Serialize import Data.Text (pack) import GHC.Generics import Hevents.Eff.Model import Hevents.Eff.State import Hevents.Eff.Store import Prelude hiding (length) data Persist m where Persist :: (Store IO s) => { state :: IORef m , storeEngine :: s , errorHandler :: StoreError -> Error m } -> Persist m makePersist :: (Store IO s) => m -> s -> (StoreError -> Error m) -> IO (Persist m) makePersist m s h = do ref<- newIORef m return $ Persist { state = ref, storeEngine = s, errorHandler = h } stopPersist :: Persist m -> IO (Persist m) stopPersist p@Persist{..} = close storeEngine >> return p instance (Model m, Versionable (Event m)) => Registrar IO m (Persist m) where update p@Persist{..} (ApplyCommand c k) = lift (runCommand p c) >>= k update Persist{..} (GetState k) = lift (readIORef state) >>= k data CommandResult m = Success (Event m) | Failure (Error m) | Fatal StoreError deriving (Generic) instance (Show (Event m), Show (Error m)) => Show (CommandResult m) where show (Success e) = "[Success] " ++ show e show (Failure f) = "[Failure] " ++ show f show (Fatal e) = "[Fatal ] " ++ show e instance (Versionable (Event m), Versionable (Error m)) => Versionable (CommandResult m) instance (Serialize (Event m), Serialize (Error m)) => Serialize (CommandResult m) runCommand :: (Model m, Versionable (Event m)) => Persist m -> Command m -> IO (Either (Error m) (Event m)) runCommand Persist{..} command = store storeEngine pre post >>= return . handleResult where pre = do st <- readIORef state case st `act` command of OK e -> return $ Right e KO e -> return $ Left e post (Right (WriteSucceed ev )) = modifyIORef state (`apply` ev) >> return (Success ev) post (Right (OpFailed f)) = return $ Fatal (IOError $ pack f) post (Right _) = return $ Fatal (IOError "Something got wrong...") post (Left er) = return $ Failure er handleResult (WriteSucceed (Success e)) = Right e handleResult (WriteFailed (Failure er)) = Left er handleResult (WriteFailed (Fatal er)) = Left $ errorHandler er handleResult _ = Left $ errorHandler (IOError $ pack $ "Something got wrong while trying to store result of command")
6d4982459025b7590cc8ac0638455d6ce499ff6305b197194f647fb820336d78
esl/ejabberd_tests
katt_helper.erl
%%============================================================================== Copyright 2014 Erlang Solutions Ltd. %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -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. %%============================================================================== -module(katt_helper). %% Suite configuration -export([init_per_suite/1, end_per_suite/1]). %% API -export([run/2, run/3]). -include_lib("common_test/include/ct.hrl"). %%-------------------------------------------------------------------- %% Suite configuration helpers %%-------------------------------------------------------------------- init_per_suite(Config) -> [{apps_started, start_apps([katt], [])} | Config]. end_per_suite(Config) -> [application:stop(App) || App <- ?config(apps_started, Config)], ok. run(BlueprintName, Config) -> run(BlueprintName, Config, []). run(BlueprintName, Config, Params) -> Blueprint = blueprint(BlueprintName, Config), Params1 = [{hostname, "localhost"}, {port, ct:get_config(ejabberd_metrics_rest_port)}], Params2 = Params ++ Params1, {TestResult, _, _, _, TransResults} = Result = katt:run(Blueprint, Params2), case TestResult of pass -> Result; fail -> FailedTrans = failed_transactions(TransResults), ct:pal("Failed transactions:~n~p~n", [FailedTrans]), ct:fail(katt_transactions_failed) end. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- start_apps([], Acc) -> Acc; start_apps([App|Tail]=All, Acc) -> case application:start(App) of ok -> start_apps(Tail, [App|Acc]); {error, {already_started, App}} -> start_apps(Tail, Acc); {error, {not_started, Dep}} -> start_apps([Dep|All], Acc) end. blueprint(Name, Config) -> File = atom_to_list(Name) ++ ".apib", filename:join([?config(data_dir, Config), File]). failed_transactions(Results) -> lists:filtermap(fun ({Description, _, _, _, {fail, Reason}}) -> {true, {Description, Reason}}; (_) -> false end, Results).
null
https://raw.githubusercontent.com/esl/ejabberd_tests/913fb0a5a8c1ab753eb35c1e1b491e8572633b54/tests/katt_helper.erl
erlang
============================================================================== 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. ============================================================================== Suite configuration API -------------------------------------------------------------------- Suite configuration helpers -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright 2014 Erlang Solutions Ltd. Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(katt_helper). -export([init_per_suite/1, end_per_suite/1]). -export([run/2, run/3]). -include_lib("common_test/include/ct.hrl"). init_per_suite(Config) -> [{apps_started, start_apps([katt], [])} | Config]. end_per_suite(Config) -> [application:stop(App) || App <- ?config(apps_started, Config)], ok. run(BlueprintName, Config) -> run(BlueprintName, Config, []). run(BlueprintName, Config, Params) -> Blueprint = blueprint(BlueprintName, Config), Params1 = [{hostname, "localhost"}, {port, ct:get_config(ejabberd_metrics_rest_port)}], Params2 = Params ++ Params1, {TestResult, _, _, _, TransResults} = Result = katt:run(Blueprint, Params2), case TestResult of pass -> Result; fail -> FailedTrans = failed_transactions(TransResults), ct:pal("Failed transactions:~n~p~n", [FailedTrans]), ct:fail(katt_transactions_failed) end. Internal functions start_apps([], Acc) -> Acc; start_apps([App|Tail]=All, Acc) -> case application:start(App) of ok -> start_apps(Tail, [App|Acc]); {error, {already_started, App}} -> start_apps(Tail, Acc); {error, {not_started, Dep}} -> start_apps([Dep|All], Acc) end. blueprint(Name, Config) -> File = atom_to_list(Name) ++ ".apib", filename:join([?config(data_dir, Config), File]). failed_transactions(Results) -> lists:filtermap(fun ({Description, _, _, _, {fail, Reason}}) -> {true, {Description, Reason}}; (_) -> false end, Results).
e29dc82dd00a320ed84e68fa368d58b2448aee5e186f55bc1f4980c587b49acb
tromp/ChessPositionRanking
Legality.hs
module Main where import System.Environment import Chess.Position import Data.Maybe import Data.Char import Data.List import qualified Data.Map as M import Data.Array -- the dark colored squares darkSquares :: [Square] darkSquares = filter isDark boardSquares where isDark c = let (y,x) = c `divMod` 8 in odd x /= odd y -- spare room for promotions spareProms :: Diagram -> (Int, String) spareProms diag = let nkSymbols = "PQRBNpqrbn" -- non king squares zerocnts = zip nkSymbols (repeat 0) cnts = M.fromListWith (+) $ zerocnts ++ zip (elems diag) (repeat 1) nkcnts = map (cnts M.!) nkSymbols [wp,wq,wr,wb,wn,bp,bq,br,bb,bn] = nkcnts darkcnts = M.fromListWith (+) $ zerocnts ++ zip (map (diag!) darkSquares) (repeat 1) (pwb,pbb) = (bishopProms wb (darkcnts M.! 'B'), bishopProms bb (darkcnts M.! 'b')) where bishopProms tot dark = if dark > 0 && tot-dark > 0 then tot-2 else tot-1 wproms = sum . map (max 0) $ [wq-1,wr-2,pwb,wn-2] bproms = sum . map (max 0) $ [bq-1,br-2,pbb,bn-2] tot = 2 + sum nkcnts -- add kings back wx = 15 - sum (take 5 nkcnts) bx = 15 - sum (drop 5 nkcnts) wpx = 8 - wp - wproms -- white pawns captured bpx = 8 - bp - bproms -- black pawns captured caps = 32 - tot maxuwp = bpx + caps - wproms maxubp = wpx + caps - bproms minopp = wp - maxuwp nOppFiles = length . filter (not . null) . mkOpps $ diag spare = if wpx >= 0 && bpx >= 0 then nOppFiles - minopp else -1 stats = "\t wx " ++ show wx ++ " wp " ++ show wp ++ " wpr " ++ show wproms ++ " wpx " ++ show wpx ++ " maxuwp " ++ show maxuwp ++ " minopp " ++ show minopp ++ "\t bx " ++ show bx ++ " bp " ++ show bp ++ " bpr " ++ show bproms ++ " bpx " ++ show bpx ++ " maxubp " ++ show maxubp ++ " minopp " ++ show minopp in (spare, stats) -- list opponent pieces checking target coord checks :: Diagram -> Square -> [(Symbol, (Int, Int))] checks diag king = let (ky, kx) = king `divMod` 8 onW = isUpper (diag!king) dP = if onW then [(-1,-1),(1,-1)] else [(1,1),(-1,1)] dN = [(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2),(1,-2),(2,-1)] dBQ = [(1,1),(-1,1),(-1,-1),(1,-1)] dRQ = [(1,0),(0,1),(-1,0),(0,-1)] toSquare (x,y) = y * 8 + x inRange x = x >= 0 && x < 8 onBoard (x,y) = inRange x && inRange y ray (dx,dy) = map (\xy -> (diag!toSquare xy, xy)) . takeWhile onBoard . map (\i -> (kx+i*dx, ky+i*dy)) $ [1..] neray = filter ((/= emptySymbol) . fst) . ray -- non empty ray toOpp = if onW then toLower else toUpper in [ x | (x@(sq,_):_) <- map ray dP , sq == toOpp 'p'] ++ [ x | (x@(sq,_):_) <- map ray dN , sq == toOpp 'n'] ++ [ x | (x@(sq,_):_) <- map neray dBQ, sq == toOpp 'b' || sq == toOpp 'q'] ++ [ x | (x@(sq,_):_) <- map neray dRQ, sq == toOpp 'r' || sq == toOpp 'q'] -- research legality research :: Position -> String research (Position { diagram = diag, sideToMove = stm, castlings = c, enPassant = ep }) = let [wk, bk] = map (\sq -> fst . fromJust . find (\(i,x)-> x==sq) . assocs $ diag) "Kk" wtm = stm == 'w' (ktm,kntm) = if wtm then (wk,bk) else (bk,wk) -- to move or not to move [(yktm, xktm), (ykntm, xkntm)] = map (`divMod` 8) [ktm, kntm] adjacentKings = abs (xktm - xkntm) <= 1 && abs (yktm - ykntm) <= 1 (checksOnTM, checksOnNTM) = (checks diag ktm, checks diag kntm) (tmInCheck, ntmInCheck) = (not (null checksOnTM), not (null checksOnNTM)) checkingpcs = sort . map (toLower . fst) $ checksOnTM [(x0,y0),(x1,y1)] = map (\(_,(x,y)) -> (x-xktm, y-yktm)) checksOnTM (innerProd, taxiCab) = (x0*x1 + y0*y1, sum (map abs [x0,y0,x1,y1])) (sharpAngle, rightAngle) = (innerProd > 0, innerProd == 0) minDist = M.fromList [("bb",99),("bn",7),("bp",99),("bq",5),("br",5),("nn",99),("np",99),("nq",6),("nr",6),("pp",99),("pq",5),("pr",5),("qq",99),("qr",5),("rr",99)] discoverable = taxiCab >= minDist M.! checkingpcs promRowCheckers = filter (\(_,(_,y)) -> y == if wtm then 7 else 0) checksOnTM kDistToPromRow = if wtm then 7-yktm else yktm (slack, stats) = spareProms diag promRowLegal = case length promRowCheckers of 0 -> sharpAngle && discoverable 1 -> (rightAngle && taxiCab > 2 && kDistToPromRow <= 1 && slack > 0) || (sharpAngle && (discoverable || kDistToPromRow == 1)) 2 -> sharpAngle && (discoverable || (kDistToPromRow == 2 && slack > 0)) doubleCheck = if checkingpcs == "nn" then "Illegal Double Knight Check" else if promRowLegal then ("Discovered Double Check" ++ stats) else "Illegal Double Check" in if adjacentKings then "Illegal Adjacent Kings" else if tmInCheck && ntmInCheck then "Illegal Both Kings in Check" else if ntmInCheck then "Illegal Side not to move in Check" else if length checkingpcs > 2 then "Illegal Triple Check" else if slack < 0 then ("Illegal Bishops Too Monochromatic" ++ stats) else if length checkingpcs == 2 then doubleCheck else (if length checkingpcs == 1 then "Single Check" else "No Checks") ++ stats main = do let legality = map (\fen -> fen ++ "\t " ++ research (readFEN fen)) getContents >>= mapM_ putStrLn . legality . filter (not . null) . lines
null
https://raw.githubusercontent.com/tromp/ChessPositionRanking/b0ecf6ba7041bfe05302780ba3a3421ff0e26c1a/src/Legality.hs
haskell
the dark colored squares spare room for promotions non king squares add kings back white pawns captured black pawns captured list opponent pieces checking target coord non empty ray research legality to move or not to move
module Main where import System.Environment import Chess.Position import Data.Maybe import Data.Char import Data.List import qualified Data.Map as M import Data.Array darkSquares :: [Square] darkSquares = filter isDark boardSquares where isDark c = let (y,x) = c `divMod` 8 in odd x /= odd y spareProms :: Diagram -> (Int, String) spareProms diag = let zerocnts = zip nkSymbols (repeat 0) cnts = M.fromListWith (+) $ zerocnts ++ zip (elems diag) (repeat 1) nkcnts = map (cnts M.!) nkSymbols [wp,wq,wr,wb,wn,bp,bq,br,bb,bn] = nkcnts darkcnts = M.fromListWith (+) $ zerocnts ++ zip (map (diag!) darkSquares) (repeat 1) (pwb,pbb) = (bishopProms wb (darkcnts M.! 'B'), bishopProms bb (darkcnts M.! 'b')) where bishopProms tot dark = if dark > 0 && tot-dark > 0 then tot-2 else tot-1 wproms = sum . map (max 0) $ [wq-1,wr-2,pwb,wn-2] bproms = sum . map (max 0) $ [bq-1,br-2,pbb,bn-2] wx = 15 - sum (take 5 nkcnts) bx = 15 - sum (drop 5 nkcnts) caps = 32 - tot maxuwp = bpx + caps - wproms maxubp = wpx + caps - bproms minopp = wp - maxuwp nOppFiles = length . filter (not . null) . mkOpps $ diag spare = if wpx >= 0 && bpx >= 0 then nOppFiles - minopp else -1 stats = "\t wx " ++ show wx ++ " wp " ++ show wp ++ " wpr " ++ show wproms ++ " wpx " ++ show wpx ++ " maxuwp " ++ show maxuwp ++ " minopp " ++ show minopp ++ "\t bx " ++ show bx ++ " bp " ++ show bp ++ " bpr " ++ show bproms ++ " bpx " ++ show bpx ++ " maxubp " ++ show maxubp ++ " minopp " ++ show minopp in (spare, stats) checks :: Diagram -> Square -> [(Symbol, (Int, Int))] checks diag king = let (ky, kx) = king `divMod` 8 onW = isUpper (diag!king) dP = if onW then [(-1,-1),(1,-1)] else [(1,1),(-1,1)] dN = [(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2),(1,-2),(2,-1)] dBQ = [(1,1),(-1,1),(-1,-1),(1,-1)] dRQ = [(1,0),(0,1),(-1,0),(0,-1)] toSquare (x,y) = y * 8 + x inRange x = x >= 0 && x < 8 onBoard (x,y) = inRange x && inRange y ray (dx,dy) = map (\xy -> (diag!toSquare xy, xy)) . takeWhile onBoard . map (\i -> (kx+i*dx, ky+i*dy)) $ [1..] toOpp = if onW then toLower else toUpper in [ x | (x@(sq,_):_) <- map ray dP , sq == toOpp 'p'] ++ [ x | (x@(sq,_):_) <- map ray dN , sq == toOpp 'n'] ++ [ x | (x@(sq,_):_) <- map neray dBQ, sq == toOpp 'b' || sq == toOpp 'q'] ++ [ x | (x@(sq,_):_) <- map neray dRQ, sq == toOpp 'r' || sq == toOpp 'q'] research :: Position -> String research (Position { diagram = diag, sideToMove = stm, castlings = c, enPassant = ep }) = let [wk, bk] = map (\sq -> fst . fromJust . find (\(i,x)-> x==sq) . assocs $ diag) "Kk" wtm = stm == 'w' [(yktm, xktm), (ykntm, xkntm)] = map (`divMod` 8) [ktm, kntm] adjacentKings = abs (xktm - xkntm) <= 1 && abs (yktm - ykntm) <= 1 (checksOnTM, checksOnNTM) = (checks diag ktm, checks diag kntm) (tmInCheck, ntmInCheck) = (not (null checksOnTM), not (null checksOnNTM)) checkingpcs = sort . map (toLower . fst) $ checksOnTM [(x0,y0),(x1,y1)] = map (\(_,(x,y)) -> (x-xktm, y-yktm)) checksOnTM (innerProd, taxiCab) = (x0*x1 + y0*y1, sum (map abs [x0,y0,x1,y1])) (sharpAngle, rightAngle) = (innerProd > 0, innerProd == 0) minDist = M.fromList [("bb",99),("bn",7),("bp",99),("bq",5),("br",5),("nn",99),("np",99),("nq",6),("nr",6),("pp",99),("pq",5),("pr",5),("qq",99),("qr",5),("rr",99)] discoverable = taxiCab >= minDist M.! checkingpcs promRowCheckers = filter (\(_,(_,y)) -> y == if wtm then 7 else 0) checksOnTM kDistToPromRow = if wtm then 7-yktm else yktm (slack, stats) = spareProms diag promRowLegal = case length promRowCheckers of 0 -> sharpAngle && discoverable 1 -> (rightAngle && taxiCab > 2 && kDistToPromRow <= 1 && slack > 0) || (sharpAngle && (discoverable || kDistToPromRow == 1)) 2 -> sharpAngle && (discoverable || (kDistToPromRow == 2 && slack > 0)) doubleCheck = if checkingpcs == "nn" then "Illegal Double Knight Check" else if promRowLegal then ("Discovered Double Check" ++ stats) else "Illegal Double Check" in if adjacentKings then "Illegal Adjacent Kings" else if tmInCheck && ntmInCheck then "Illegal Both Kings in Check" else if ntmInCheck then "Illegal Side not to move in Check" else if length checkingpcs > 2 then "Illegal Triple Check" else if slack < 0 then ("Illegal Bishops Too Monochromatic" ++ stats) else if length checkingpcs == 2 then doubleCheck else (if length checkingpcs == 1 then "Single Check" else "No Checks") ++ stats main = do let legality = map (\fen -> fen ++ "\t " ++ research (readFEN fen)) getContents >>= mapM_ putStrLn . legality . filter (not . null) . lines
f050ba6f75467b3124c6ebdae999a099fecc0aea87e5a56f97d9ea8d9c55d5da
haskell-hvr/token-bucket
TokenBucket.hs
# LANGUAGE CPP # -- | This module provides rate-limiting facilities built on top of the lazy bucket algorithm heavily inspired by < -limiting-at-webscale-lazy-leaky-buckets " Rate Limiting at Webscale : Lazy Leaky Buckets " > -- See also Wikipedia 's < Token Bucket > article for general information about token bucket algorithms and their properties . module Control.Concurrent.TokenBucket ( -- * The 'TokenBucket' type TokenBucket , newTokenBucket -- * Operations on 'TokenBucket' -- | The following operations take two parameters , a burst - size and an average token rate . -- -- === Average token rate -- -- The average rate is expressed as inverse rate in terms of microseconds - per - token ( i.e. one token every -- @n@ microseconds). This representation exposes the time -- granularity of the underlying implementation using integer -- arithmetic. -- -- So in order to convert a token-rate @r@ expressed in tokens - per - second ( i.e. @Hertz@ ) to microseconds - per - token the -- simple function below can be used: -- -- @ -- toInvRate :: Double -> Word64 toInvRate r = round ( 1e6 / r ) -- @ -- An inverse - rate @0@ denotes an infinite average rate , which -- will let token allocation always succeed (regardless of the -- burst-size parameter). -- -- === Burst size -- -- The burst-size parameter denotes the depth of the token -- bucket, and allows for temporarily exceeding the average -- token rate. The burst-size parameter should be at least as -- large as the maximum amount of tokens that need to be -- allocated at once, since an allocation-size smaller than the -- current burst-size will always fail unless an infinite token -- rate is used. , tokenBucketTryAlloc , tokenBucketTryAlloc1 , tokenBucketWait ) where import Control.Concurrent import Control.Exception import Control.Monad import Data.IORef #if !defined(USE_CBITS) import Data.Time.Clock.POSIX (getPOSIXTime) #endif import Data.Word (Word64) -- | Abstract type containing the token bucket state newtype TokenBucket = TB (IORef TBData) data TBData = TBData !Word64 !PosixTimeUsecs deriving Show type PosixTimeUsecs = Word64 -- getTBData :: TokenBucket -> IO TBData -- getTBData (TB lbd) = readIORef lbd #if defined(USE_CBITS) foreign import ccall unsafe "hs_token_bucket_get_posix_time_usecs" getPosixTimeUsecs :: IO PosixTimeUsecs #else getPosixTimeUsecs :: IO PosixTimeUsecs getPosixTimeUsecs = fmap (floor . (*1e6)) getPOSIXTime #endif -- | Create new 'TokenBucket' instance newTokenBucket :: IO TokenBucket newTokenBucket = do now <- getPosixTimeUsecs lbd <- newIORef $! TBData 0 now evaluate (TB lbd) -- | Attempt to allocate a given amount of tokens from the 'TokenBucket' -- -- This operation either succeeds in allocating the requested amount -- of tokens (and returns 'True'), or else, if allocation fails the -- 'TokenBucket' remains in its previous allocation state. tokenBucketTryAlloc :: TokenBucket -> Word64 -- ^ burst-size (tokens) ^ avg . inverse rate ( usec / token ) -> Word64 -- ^ amount of tokens to allocate -> IO Bool -- ^ 'True' if allocation succeeded tokenBucketTryAlloc _ _ 0 _ = return True -- infinitive rate, no-op tokenBucketTryAlloc _ burst _ alloc | alloc > burst = return False tokenBucketTryAlloc (TB lbref) burst invRate alloc = do now <- getPosixTimeUsecs atomicModifyIORef' lbref (go now) where go now (TBData lvl ts) | lvl'' > burst = (TBData lvl' ts', False) | otherwise = (TBData lvl'' ts', True) where lvl' = lvl ∸ dl (dl,dtRem) = dt `quotRem` invRate dt = now ∸ ts ts' = now ∸ dtRem lvl'' = lvl' ∔ alloc -- | Try to allocate a single token from the token bucket. -- -- Returns 0 if successful (i.e. a token was successfully allocated from -- the token bucket). -- -- On failure, i.e. if token bucket budget was exhausted, the minimum -- non-zero amount of microseconds to wait till allocation /may/ -- succeed is returned. -- -- This function does not block. See 'tokenBucketWait' for wrapper -- around this function which blocks until a token could be allocated. tokenBucketTryAlloc1 :: TokenBucket -> Word64 -- ^ burst-size (tokens) ^ avg . inverse rate ( usec / token ) ^ retry - time ( usecs ) tokenBucketTryAlloc1 _ _ 0 = return 0 -- infinite rate, no-op tokenBucketTryAlloc1 (TB lbref) burst invRate = do now <- getPosixTimeUsecs atomicModifyIORef' lbref (go now) where go now (TBData lvl ts) | lvl'' > burst = (TBData lvl' ts', invRate-dtRem) | otherwise = (TBData lvl'' ts', 0) where lvl' = lvl ∸ dl (dl,dtRem) = dt `quotRem` invRate dt = now ∸ ts ts' = now ∸ dtRem lvl'' = lvl' ∔ 1 -- | Blocking wrapper around 'tokenBucketTryAlloc1'. Uses 'threadDelay' when blocking. -- -- This is effectively implemented as -- -- @ -- 'tokenBucketWait' tb burst invRate = do -- delay <- 'tokenBucketTryAlloc1' tb burst invRate -- unless (delay == 0) $ do -- threadDelay (fromIntegral delay) -- 'tokenBucketWait' tb burst invRate -- @ tokenBucketWait :: TokenBucket -> Word64 -- ^ burst-size (tokens) ^ avg . inverse rate ( usec / token ) -> IO () tokenBucketWait tb burst invRate = do delay <- tokenBucketTryAlloc1 tb burst invRate unless (delay == 0) $ do threadDelay (fromIntegral delay) tokenBucketWait tb burst invRate -- saturated arithmetic helpers (∸), (∔) :: Word64 -> Word64 -> Word64 x ∸ y = if x>y then x-y else 0 {-# INLINE (∸) #-} x ∔ y = let s=x+y in if x <= s then s else maxBound # INLINE ( ∔ ) #
null
https://raw.githubusercontent.com/haskell-hvr/token-bucket/2a274b8445f0ac100198cae7d5be401bd647df03/src/Control/Concurrent/TokenBucket.hs
haskell
| This module provides rate-limiting facilities built on top of the lazy bucket algorithm heavily inspired by * The 'TokenBucket' type * Operations on 'TokenBucket' === Average token rate The average rate is expressed as inverse rate in terms of @n@ microseconds). This representation exposes the time granularity of the underlying implementation using integer arithmetic. So in order to convert a token-rate @r@ expressed in simple function below can be used: @ toInvRate :: Double -> Word64 @ will let token allocation always succeed (regardless of the burst-size parameter). === Burst size The burst-size parameter denotes the depth of the token bucket, and allows for temporarily exceeding the average token rate. The burst-size parameter should be at least as large as the maximum amount of tokens that need to be allocated at once, since an allocation-size smaller than the current burst-size will always fail unless an infinite token rate is used. | Abstract type containing the token bucket state getTBData :: TokenBucket -> IO TBData getTBData (TB lbd) = readIORef lbd | Create new 'TokenBucket' instance | Attempt to allocate a given amount of tokens from the 'TokenBucket' This operation either succeeds in allocating the requested amount of tokens (and returns 'True'), or else, if allocation fails the 'TokenBucket' remains in its previous allocation state. ^ burst-size (tokens) ^ amount of tokens to allocate ^ 'True' if allocation succeeded infinitive rate, no-op | Try to allocate a single token from the token bucket. Returns 0 if successful (i.e. a token was successfully allocated from the token bucket). On failure, i.e. if token bucket budget was exhausted, the minimum non-zero amount of microseconds to wait till allocation /may/ succeed is returned. This function does not block. See 'tokenBucketWait' for wrapper around this function which blocks until a token could be allocated. ^ burst-size (tokens) infinite rate, no-op | Blocking wrapper around 'tokenBucketTryAlloc1'. Uses 'threadDelay' when blocking. This is effectively implemented as @ 'tokenBucketWait' tb burst invRate = do delay <- 'tokenBucketTryAlloc1' tb burst invRate unless (delay == 0) $ do threadDelay (fromIntegral delay) 'tokenBucketWait' tb burst invRate @ ^ burst-size (tokens) saturated arithmetic helpers # INLINE (∸) #
# LANGUAGE CPP # < -limiting-at-webscale-lazy-leaky-buckets " Rate Limiting at Webscale : Lazy Leaky Buckets " > See also Wikipedia 's < Token Bucket > article for general information about token bucket algorithms and their properties . module Control.Concurrent.TokenBucket TokenBucket , newTokenBucket | The following operations take two parameters , a burst - size and an average token rate . microseconds - per - token ( i.e. one token every tokens - per - second ( i.e. @Hertz@ ) to microseconds - per - token the toInvRate r = round ( 1e6 / r ) An inverse - rate @0@ denotes an infinite average rate , which , tokenBucketTryAlloc , tokenBucketTryAlloc1 , tokenBucketWait ) where import Control.Concurrent import Control.Exception import Control.Monad import Data.IORef #if !defined(USE_CBITS) import Data.Time.Clock.POSIX (getPOSIXTime) #endif import Data.Word (Word64) newtype TokenBucket = TB (IORef TBData) data TBData = TBData !Word64 !PosixTimeUsecs deriving Show type PosixTimeUsecs = Word64 #if defined(USE_CBITS) foreign import ccall unsafe "hs_token_bucket_get_posix_time_usecs" getPosixTimeUsecs :: IO PosixTimeUsecs #else getPosixTimeUsecs :: IO PosixTimeUsecs getPosixTimeUsecs = fmap (floor . (*1e6)) getPOSIXTime #endif newTokenBucket :: IO TokenBucket newTokenBucket = do now <- getPosixTimeUsecs lbd <- newIORef $! TBData 0 now evaluate (TB lbd) tokenBucketTryAlloc :: TokenBucket ^ avg . inverse rate ( usec / token ) tokenBucketTryAlloc _ burst _ alloc | alloc > burst = return False tokenBucketTryAlloc (TB lbref) burst invRate alloc = do now <- getPosixTimeUsecs atomicModifyIORef' lbref (go now) where go now (TBData lvl ts) | lvl'' > burst = (TBData lvl' ts', False) | otherwise = (TBData lvl'' ts', True) where lvl' = lvl ∸ dl (dl,dtRem) = dt `quotRem` invRate dt = now ∸ ts ts' = now ∸ dtRem lvl'' = lvl' ∔ alloc tokenBucketTryAlloc1 :: TokenBucket ^ avg . inverse rate ( usec / token ) ^ retry - time ( usecs ) tokenBucketTryAlloc1 (TB lbref) burst invRate = do now <- getPosixTimeUsecs atomicModifyIORef' lbref (go now) where go now (TBData lvl ts) | lvl'' > burst = (TBData lvl' ts', invRate-dtRem) | otherwise = (TBData lvl'' ts', 0) where lvl' = lvl ∸ dl (dl,dtRem) = dt `quotRem` invRate dt = now ∸ ts ts' = now ∸ dtRem lvl'' = lvl' ∔ 1 tokenBucketWait :: TokenBucket ^ avg . inverse rate ( usec / token ) -> IO () tokenBucketWait tb burst invRate = do delay <- tokenBucketTryAlloc1 tb burst invRate unless (delay == 0) $ do threadDelay (fromIntegral delay) tokenBucketWait tb burst invRate (∸), (∔) :: Word64 -> Word64 -> Word64 x ∸ y = if x>y then x-y else 0 x ∔ y = let s=x+y in if x <= s then s else maxBound # INLINE ( ∔ ) #
d9bb23192219c177db4f72d5c6ddf5920a391ed1ff038a64ae0ceba684f37f40
input-output-hk/cardano-sl
Focus.hs
# LANGUAGE RecordWildCards # module Statistics.Focus ( Focus (..) , focusF ) where import Control.Foldl (Fold (..)) import Data.Set (Set) import qualified Data.Set as S import qualified Data.Text as T import JSONLog import Pos.Infra.Util.JsonLog.Events (JLBlock (..), JLEvent (..), JLTxR (..)) import Prelude (id) import Types import Universum data Focus = Received !(Maybe Text) | InCreatedBlock !BlockHash | InAdoptedBlock !BlockHash deriving Show focusF :: TxHash -> Fold IndexedJLTimedEvent [(Timestamp, NodeId, Focus)] focusF tx = f <$> allF <*> blocksF where f :: [(Timestamp, NodeId, Focus)] -> Set BlockHash -> [(Timestamp, NodeId, Focus)] f xs s = filter g xs where g :: (Timestamp, NodeId, Focus) -> Bool g (_, _, x) = case x of (Received _) -> True (InCreatedBlock h) -> S.member h s (InAdoptedBlock h) -> S.member h s allF :: Fold IndexedJLTimedEvent [(Timestamp, NodeId, Focus)] allF = reverse <$> Fold step [] id where step :: [(Timestamp, NodeId, Focus)] -> IndexedJLTimedEvent -> [(Timestamp, NodeId, Focus)] step xs IndexedJLTimedEvent{..} = case ijlEvent of (JLCreatedBlock JLBlock{..}) -> (ijlTimestamp, ijlNode, InCreatedBlock jlHash) : xs (JLAdoptedBlock h) -> (ijlTimestamp, ijlNode, InAdoptedBlock h) : xs (JLTxReceived JLTxR{..}) -> if jlrTxId == tx then (ijlTimestamp, ijlNode, Received jlrError) : xs else xs _ -> xs blocksF :: Fold IndexedJLTimedEvent (Set BlockHash) blocksF = Fold step S.empty id where step :: Set BlockHash -> IndexedJLTimedEvent -> Set BlockHash step s IndexedJLTimedEvent{..} = case ijlEvent of (JLCreatedBlock JLBlock{..}) -> if tx `elem` [T.take 16 tx' | tx' <- jlTxs] then S.insert jlHash s else s _ -> s
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/tools/post-mortem/src/Statistics/Focus.hs
haskell
# LANGUAGE RecordWildCards # module Statistics.Focus ( Focus (..) , focusF ) where import Control.Foldl (Fold (..)) import Data.Set (Set) import qualified Data.Set as S import qualified Data.Text as T import JSONLog import Pos.Infra.Util.JsonLog.Events (JLBlock (..), JLEvent (..), JLTxR (..)) import Prelude (id) import Types import Universum data Focus = Received !(Maybe Text) | InCreatedBlock !BlockHash | InAdoptedBlock !BlockHash deriving Show focusF :: TxHash -> Fold IndexedJLTimedEvent [(Timestamp, NodeId, Focus)] focusF tx = f <$> allF <*> blocksF where f :: [(Timestamp, NodeId, Focus)] -> Set BlockHash -> [(Timestamp, NodeId, Focus)] f xs s = filter g xs where g :: (Timestamp, NodeId, Focus) -> Bool g (_, _, x) = case x of (Received _) -> True (InCreatedBlock h) -> S.member h s (InAdoptedBlock h) -> S.member h s allF :: Fold IndexedJLTimedEvent [(Timestamp, NodeId, Focus)] allF = reverse <$> Fold step [] id where step :: [(Timestamp, NodeId, Focus)] -> IndexedJLTimedEvent -> [(Timestamp, NodeId, Focus)] step xs IndexedJLTimedEvent{..} = case ijlEvent of (JLCreatedBlock JLBlock{..}) -> (ijlTimestamp, ijlNode, InCreatedBlock jlHash) : xs (JLAdoptedBlock h) -> (ijlTimestamp, ijlNode, InAdoptedBlock h) : xs (JLTxReceived JLTxR{..}) -> if jlrTxId == tx then (ijlTimestamp, ijlNode, Received jlrError) : xs else xs _ -> xs blocksF :: Fold IndexedJLTimedEvent (Set BlockHash) blocksF = Fold step S.empty id where step :: Set BlockHash -> IndexedJLTimedEvent -> Set BlockHash step s IndexedJLTimedEvent{..} = case ijlEvent of (JLCreatedBlock JLBlock{..}) -> if tx `elem` [T.take 16 tx' | tx' <- jlTxs] then S.insert jlHash s else s _ -> s
396e5ee8b43c64d8f070bde46033c6f51f716658e9198cbee77f1c6b297a5785
jrm-code-project/LISP-Machine
dump-storage.lisp
-*- Mode : LISP ; Package : SYSTEM - INTERNALS ; Base:8 ; : ZL -*- (defun dump-storage (start) (do ((adr (%pointer start) (1+ adr)) info) (()) (format t "~&~10o: " adr) (setq info (nth-value 1 (lam:xpointer-info adr))) (cond ((= info 2) (format t "~15a " (nth (%p-cdr-code adr) q-cdr-codes)) (cond ((= (%p-data-type adr) dtp-header) (format t "~25a " (nth (%p-ldb %%header-type-field adr) q-header-types))) (t (format t "~25a " (nth (%p-data-type adr) q-data-types)))) (format t "~10o" (%p-pointer adr)) ) (t (format t "Unboxed: ") (send standard-output :tyo (%p-ldb (byte 8 0) adr)) (send standard-output :tyo (%p-ldb (byte 8 8) adr)) (send standard-output :tyo (%p-ldb (byte 8 16.) adr)) (send standard-output :tyo (%p-ldb (byte 8 24.) adr)) )) (send standard-input :tyi) ))
null
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/pace/hacks/dump-storage.lisp
lisp
Package : SYSTEM - INTERNALS ; Base:8 ; : ZL -*-
(defun dump-storage (start) (do ((adr (%pointer start) (1+ adr)) info) (()) (format t "~&~10o: " adr) (setq info (nth-value 1 (lam:xpointer-info adr))) (cond ((= info 2) (format t "~15a " (nth (%p-cdr-code adr) q-cdr-codes)) (cond ((= (%p-data-type adr) dtp-header) (format t "~25a " (nth (%p-ldb %%header-type-field adr) q-header-types))) (t (format t "~25a " (nth (%p-data-type adr) q-data-types)))) (format t "~10o" (%p-pointer adr)) ) (t (format t "Unboxed: ") (send standard-output :tyo (%p-ldb (byte 8 0) adr)) (send standard-output :tyo (%p-ldb (byte 8 8) adr)) (send standard-output :tyo (%p-ldb (byte 8 16.) adr)) (send standard-output :tyo (%p-ldb (byte 8 24.) adr)) )) (send standard-input :tyi) ))
c462ef84d8a6e85ef41c52a0ae12f01cf3a638c72d0f6f5baf2c30e06b5b38ff
mrb/graaaph
examples.clj
(ns graaaph.core-examples (:use graaaph.core) (:require [clojure.core.logic :as l])) (def data {:simple "def a;'ok';end" :args "class Dude; def initialize(cool=nil); @cool = cool; end; end; d = Dude.new(:cool);" :class-variable "class Dude; @@cool = \"dude\"; def speak; @@cool; end; end" :dup-method "class Dude; def a; \"first\"; end; def a; \"second\"; end; end" :for-loop "for i in (1..10) do; p i; end" :symbol-to_proc "[1,2,3].map(&:to_s)" :simple-map "[1,2,3].map{|x| x.to_s}" :openstruct "OpenStruct.new" :add "1+1"}) (def ruby-code "class Dude def awesome 'first awesome' end # def cool 'not awesome' end # def awesome 'second awesome' end # def bro end # def bro end end") (view-ruby-ast ruby-code) (defn get-duplicate-method-names [ruby-code] (let [nodes (parse-ruby-code ruby-code) defnnodes (l/run* [q] (l/fresh [a b c d n e] (l/== a nodes) (nodetypeo a "DEFNNODE" c) (nodenameo c n e) (l/== e q)))] defnnodes)) (get-duplicate-method-names ruby-code) (ruby-code-zipper ruby-code) (zipper-to-source (ruby-code-zipper ruby-code)) (-> (ruby-code-zipper (:add data)) z/down z/down z/down z/node) (parse-ruby-code (:add data)) (def n (-> (ruby-code-zipper "1") z/next z/next z/node)) (l/run* [q] (l/== q (parse-ruby-code ruby-code))) nodeattro now works on * one * node (l/run* [q] (l/fresh [node] (l/== node (first (parse-ruby-code ruby-code))) (nodeattro node :name q))) get only the names w/ mapo (l/run* [q] (l/fresh [nodes] (l/== nodes (parse-ruby-code ruby-code)) (mapo nodes #(nodeattro %1 :name %2) q))) ;; filter out nodes w/o names (l/run* [q] (l/fresh [nodes] (l/== nodes (parse-ruby-code ruby-code)) (filtero nodes (fn [node] (l/fresh [value] (nodeattro node :name value) (l/!= value nil))) q))) ;; extract names (l/run* [q] (l/fresh [nodes nodes'] (l/== nodes (parse-ruby-code ruby-code)) (filtero nodes (fn [node] (l/fresh [value] (nodeattro node :type "DEFNNODE") (nodeattro node :name value) (l/!= value nil))) nodes') (mapo nodes' #(nodeattro %1 :name %2) q))) ;; dupeo names (l/run* [q] (l/fresh [nodes nodes' dupes] (l/== nodes (parse-ruby-code ruby-code)) (filtero nodes (fn [node] (l/fresh [value] (nodeattro node :type "DEFNNODE") (nodeattro node :name value) (l/!= value nil))) nodes') (mapo nodes' #(nodeattro %1 :name %2) dupes) (dupeo dupes q)))
null
https://raw.githubusercontent.com/mrb/graaaph/d2e23081fde21d93ef49e12f87f0c02bfe4e31a8/examples/examples.clj
clojure
filter out nodes w/o names extract names dupeo names
(ns graaaph.core-examples (:use graaaph.core) (:require [clojure.core.logic :as l])) (def data {:simple "def a;'ok';end" :args "class Dude; def initialize(cool=nil); @cool = cool; end; end; d = Dude.new(:cool);" :class-variable "class Dude; @@cool = \"dude\"; def speak; @@cool; end; end" :dup-method "class Dude; def a; \"first\"; end; def a; \"second\"; end; end" :for-loop "for i in (1..10) do; p i; end" :symbol-to_proc "[1,2,3].map(&:to_s)" :simple-map "[1,2,3].map{|x| x.to_s}" :openstruct "OpenStruct.new" :add "1+1"}) (def ruby-code "class Dude def awesome 'first awesome' end # def cool 'not awesome' end # def awesome 'second awesome' end # def bro end # def bro end end") (view-ruby-ast ruby-code) (defn get-duplicate-method-names [ruby-code] (let [nodes (parse-ruby-code ruby-code) defnnodes (l/run* [q] (l/fresh [a b c d n e] (l/== a nodes) (nodetypeo a "DEFNNODE" c) (nodenameo c n e) (l/== e q)))] defnnodes)) (get-duplicate-method-names ruby-code) (ruby-code-zipper ruby-code) (zipper-to-source (ruby-code-zipper ruby-code)) (-> (ruby-code-zipper (:add data)) z/down z/down z/down z/node) (parse-ruby-code (:add data)) (def n (-> (ruby-code-zipper "1") z/next z/next z/node)) (l/run* [q] (l/== q (parse-ruby-code ruby-code))) nodeattro now works on * one * node (l/run* [q] (l/fresh [node] (l/== node (first (parse-ruby-code ruby-code))) (nodeattro node :name q))) get only the names w/ mapo (l/run* [q] (l/fresh [nodes] (l/== nodes (parse-ruby-code ruby-code)) (mapo nodes #(nodeattro %1 :name %2) q))) (l/run* [q] (l/fresh [nodes] (l/== nodes (parse-ruby-code ruby-code)) (filtero nodes (fn [node] (l/fresh [value] (nodeattro node :name value) (l/!= value nil))) q))) (l/run* [q] (l/fresh [nodes nodes'] (l/== nodes (parse-ruby-code ruby-code)) (filtero nodes (fn [node] (l/fresh [value] (nodeattro node :type "DEFNNODE") (nodeattro node :name value) (l/!= value nil))) nodes') (mapo nodes' #(nodeattro %1 :name %2) q))) (l/run* [q] (l/fresh [nodes nodes' dupes] (l/== nodes (parse-ruby-code ruby-code)) (filtero nodes (fn [node] (l/fresh [value] (nodeattro node :type "DEFNNODE") (nodeattro node :name value) (l/!= value nil))) nodes') (mapo nodes' #(nodeattro %1 :name %2) dupes) (dupeo dupes q)))
e9b51935543f3b5b74bb1ec93b4e956152d8dbf8c52254f329b9005c46a3fb61
litxio/streamly-cassava
Csv.hs
# LANGUAGE FlexibleContexts , MultiParamTypeClasses , OverloadedStrings , ScopedTypeVariables , LambdaCase # ScopedTypeVariables, LambdaCase #-} | Module : Streamly . Csv Description : Cassava support for the streamly library Copyright : ( c ) License : BSD 3 - clause Maintainer : Stream CSV data in\/out using [ Cassava]( / package / cassava ) . Adapted from [ streaming - cassava]( / package / streaming - cassava ) . For efficiency , operates on streams of strict ByteString chunks @(i.e . S.IsStream t = > t m ByteString)@ rather than directly on streams of Word8 . The ' chunkStream ' function is useful for generating an input stream from a ' Handle ' . Example usage : > import Streamly > import qualified Streamly . Prelude as S > import Streamly . Csv ( decode , encode , chunkStream ) > import System . IO > import qualified Data . Csv as Csv > import qualified Data . ByteString as BS > import Data . Vector ( Vector ) > > do > h < - openFile " testfile.csv " ReadMode > let chunks = chunkStream h ( 64 * 1024 ) > . HasHeader chunks : : S.SerialT IO ( Vector BS.ByteString ) > withFile " dest.csv " WriteMode $ \ho - > > S.mapM _ ( ho ) $ encode Nothing recs Module : Streamly.Csv Description : Cassava support for the streamly library Copyright : (c) Richard Warfield License : BSD 3-clause Maintainer : Stream CSV data in\/out using [Cassava](). Adapted from [streaming-cassava](-cassava). For efficiency, operates on streams of strict ByteString chunks @(i.e. S.IsStream t => t m ByteString)@ rather than directly on streams of Word8. The 'chunkStream' function is useful for generating an input stream from a 'Handle'. Example usage: > import Streamly > import qualified Streamly.Prelude as S > import Streamly.Csv (decode, encode, chunkStream) > import System.IO > import qualified Data.Csv as Csv > import qualified Data.ByteString as BS > import Data.Vector (Vector) > > do > h <- openFile "testfile.csv" ReadMode > let chunks = chunkStream h (64*1024) > recs = decode Csv.HasHeader chunks :: S.SerialT IO (Vector BS.ByteString) > withFile "dest.csv" WriteMode $ \ho -> > S.mapM_ (BS.hPut ho) $ encode Nothing recs -} module Streamly.Csv ( -- * Decoding decode , decodeWith , decodeWithErrors , CsvParseException (..) , chunkStream -- ** Named decoding , decodeByName , decodeByNameWith , decodeByNameWithErrors -- * Encoding , encode , encodeDefault , encodeWith -- ** Named encoding , encodeByName , encodeByNameDefault , encodeByNameWith -- * Re-exports , FromRecord (..) , FromNamedRecord (..) , ToRecord (..) , ToNamedRecord (..) , DefaultOrdered (..) , HasHeader (..) , Header , header , Name , DecodeOptions(..) , defaultDecodeOptions , EncodeOptions(..) , defaultEncodeOptions ) where import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Streamly.Prelude as S import Data.Csv (DecodeOptions(..), DefaultOrdered(..), EncodeOptions(..), FromNamedRecord(..), FromRecord(..), Header, Name, ToNamedRecord(..), ToRecord(..), defaultDecodeOptions, defaultEncodeOptions, encIncludeHeader, header) import Data.Csv.Incremental (HasHeader(..), HeaderParser(..), Parser(..)) import qualified Data.Csv.Incremental as CI import System.IO (Handle) import Control.Exception (Exception(..)) import Control.Monad.Catch (MonadThrow(..)) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Word (Word8) import Data.Bifunctor (first) import Data.Maybe (fromMaybe) import Data.String (IsString(..)) import Data.Typeable (Typeable) -------------------------------------------------------------------------------- -- | Use 'defaultOptions' for decoding the provided CSV. decode :: (S.IsStream t, S.MonadAsync m, FromRecord a) => HasHeader -> t m BS.ByteString -> t m a decode = decodeWith defaultDecodeOptions -- | Return back a stream of values from the provided CSV, stopping at the first error . -- -- If you wish to instead ignore errors, consider using -- 'decodeWithErrors' with 'S.mapMaybe' -- -- Any remaining input is discarded. decodeWith :: (S.IsStream t, S.MonadAsync m, FromRecord a) => DecodeOptions -> HasHeader -> t m BS.ByteString -> t m a decodeWith opts hdr chunks = getValues (decodeWithErrors opts hdr chunks) -- >>= either (throwError . fst) return -- | Return back a stream with an attempt at type conversion, and -- either the previous result or any overall parsing errors with the -- remainder of the input. decodeWithErrors :: (S.IsStream t, Monad m, FromRecord a, MonadThrow m) => DecodeOptions -> HasHeader -> t m BS.ByteString -> t m (Either CsvParseException a) decodeWithErrors opts = runParser . CI.decodeWith opts runParser :: forall t a m. (S.IsStream t, Monad m, MonadThrow m) => Parser a -> t m BS.ByteString -> t m (Either CsvParseException a) runParser p chunked = S.concatMap fst $ S.scanlM' continue (pure (S.nil, const p)) $ S.cons BS.empty chunked where continue :: (t m (Either CsvParseException a), BS.ByteString -> Parser a) -> BS.ByteString -> m (t m (Either CsvParseException a), BS.ByteString -> Parser a) continue (_, p) chunk = case p chunk of Fail bs err -> throwM (CsvParseException err) Many es get -> return (withEach es, get) Done es -> return (withEach es, p) withEach = S.fromList . map (first CsvParseException) chunkStream :: (S.IsStream t, S.MonadAsync m) => Handle -> Int -> t m BS.ByteString chunkStream h chunkSize = loop where loop = S.takeWhile (not . BS.null) $ liftIO (BS.hGetSome h chunkSize) `S.consM` loop -------------------------------------------------------------------------------- -- | Use 'defaultOptions' for decoding the provided CSV. decodeByName :: (S.MonadAsync m, FromNamedRecord a) => S.SerialT m BS.ByteString -> S.SerialT m a decodeByName = decodeByNameWith defaultDecodeOptions -- | Return back a stream of values from the provided CSV, stopping at the first error . -- -- A header is required to determine the order of columns, but then -- discarded. -- -- If you wish to instead ignore errors, consider using -- 'decodeByNameWithErrors' with 'S.mapMaybe' -- -- Any remaining input is discarded. decodeByNameWith :: (S.MonadAsync m, FromNamedRecord a) => DecodeOptions -> S.SerialT m BS.ByteString -> S.SerialT m a decodeByNameWith opts bs = getValues (decodeByNameWithErrors opts bs) -- >>= either (throwError . fst) return -- | Return back a stream with an attempt at type conversion, but -- where the order of columns doesn't have to match the order of -- fields of your actual type. -- -- This requires\/assumes a header in the CSV stream, which is -- discarded after parsing. -- decodeByNameWithErrors :: forall m a. (Monad m, MonadThrow m, FromNamedRecord a) => DecodeOptions -> S.SerialT m BS.ByteString -> S.SerialT m (Either CsvParseException a) decodeByNameWithErrors opts chunked = do (p, rest) <- S.fromEffect $ extractParser (const $ CI.decodeByNameWith opts) $ S.cons BS.empty chunked runParser p rest where extractParser :: (BS.ByteString -> HeaderParser (Parser a)) -> S.SerialT m BS.ByteString -> m (Parser a, S.SerialT m BS.ByteString) extractParser p chunks = S.uncons chunks >>= \case Just (hed, rest) -> case p hed of FailH bs err -> throwM (CsvParseException err) PartialH get -> extractParser get rest DoneH _ p -> return (p, rest) Nothing -> throwM $ CsvParseException "Unexpected end of input stream" -- -------------------------------------------------------------------------------- -- -- -- | Encode a stream of values with the default options. -- -- -- -- Optionally prefix the stream with headers (the 'header' function -- -- may be useful). encode :: (S.IsStream t, ToRecord a, Monad m) => Maybe Header -> t m a -> t m BS.ByteString encode = encodeWith defaultEncodeOptions -- | Encode a stream of values with the default options and a derived -- header prefixed. encodeDefault :: forall a t m. (S.IsStream t, ToRecord a, DefaultOrdered a, Monad m) => t m a -> t m BS.ByteString encodeDefault = encode (Just (headerOrder (undefined :: a))) -- | Encode a stream of values with the provided options. -- -- Optionally prefix the stream with headers (the 'header' function -- may be useful). encodeWith :: (S.IsStream t, ToRecord a, Monad m) => EncodeOptions -> Maybe Header -> t m a -> t m BS.ByteString encodeWith opts mhdr = S.concatMap S.fromList . addHeaders . S.map enc where addHeaders = maybe id (S.cons . enc) mhdr enc :: (ToRecord v) => v -> [BS.ByteString] enc = BSL.toChunks . CI.encodeWith opts . CI.encodeRecord -------------------------------------------------------------------------------- -- | Use the default ordering to encode all fields\/columns. encodeByNameDefault :: forall a t m. (S.IsStream t, DefaultOrdered a, ToNamedRecord a, Monad m) => t m a -> t m BS.ByteString encodeByNameDefault = encodeByName (headerOrder (undefined :: a)) -- | Select the columns that you wish to encode from your data -- structure using default options (which currently includes -- printing the header). encodeByName :: (S.IsStream t, ToNamedRecord a, Monad m) => Header -> t m a -> t m BS.ByteString encodeByName = encodeByNameWith defaultEncodeOptions -- | Select the columns that you wish to encode from your data -- structure. -- -- Header printing respects 'encIncludeheader'. encodeByNameWith :: (S.IsStream t, ToNamedRecord a, Monad m) => EncodeOptions -> Header -> t m a -> t m BS.ByteString encodeByNameWith opts hdr = S.concatMap S.fromList . addHeaders . S.map enc where opts' = opts { encIncludeHeader = False } addHeaders | encIncludeHeader opts = S.cons . BSL.toChunks . CI.encodeWith opts' . CI.encodeRecord $ hdr | otherwise = id enc = BSL.toChunks . CI.encodeByNameWith opts' hdr . CI.encodeNamedRecord -------------------------------------------------------------------------------- getValues :: (S.IsStream t, S.MonadAsync m, Exception e) => t m (Either e a) -> t m a getValues = S.mapM (either throwM return) newtype CsvParseException = CsvParseException String deriving (Eq, Show, Typeable) instance IsString CsvParseException where fromString = CsvParseException instance Exception CsvParseException where displayException (CsvParseException e) = "Error parsing csv: " ++ e
null
https://raw.githubusercontent.com/litxio/streamly-cassava/8dae3d9568461b7dc5c55681a16f0ae45100cac3/src/Streamly/Csv.hs
haskell
* Decoding ** Named decoding * Encoding ** Named encoding * Re-exports ------------------------------------------------------------------------------ | Use 'defaultOptions' for decoding the provided CSV. | Return back a stream of values from the provided CSV, stopping at If you wish to instead ignore errors, consider using 'decodeWithErrors' with 'S.mapMaybe' Any remaining input is discarded. >>= either (throwError . fst) return | Return back a stream with an attempt at type conversion, and either the previous result or any overall parsing errors with the remainder of the input. ------------------------------------------------------------------------------ | Use 'defaultOptions' for decoding the provided CSV. | Return back a stream of values from the provided CSV, stopping at A header is required to determine the order of columns, but then discarded. If you wish to instead ignore errors, consider using 'decodeByNameWithErrors' with 'S.mapMaybe' Any remaining input is discarded. >>= either (throwError . fst) return | Return back a stream with an attempt at type conversion, but where the order of columns doesn't have to match the order of fields of your actual type. This requires\/assumes a header in the CSV stream, which is discarded after parsing. -------------------------------------------------------------------------------- -- | Encode a stream of values with the default options. -- -- Optionally prefix the stream with headers (the 'header' function -- may be useful). | Encode a stream of values with the default options and a derived header prefixed. | Encode a stream of values with the provided options. Optionally prefix the stream with headers (the 'header' function may be useful). ------------------------------------------------------------------------------ | Use the default ordering to encode all fields\/columns. | Select the columns that you wish to encode from your data structure using default options (which currently includes printing the header). | Select the columns that you wish to encode from your data structure. Header printing respects 'encIncludeheader'. ------------------------------------------------------------------------------
# LANGUAGE FlexibleContexts , MultiParamTypeClasses , OverloadedStrings , ScopedTypeVariables , LambdaCase # ScopedTypeVariables, LambdaCase #-} | Module : Streamly . Csv Description : Cassava support for the streamly library Copyright : ( c ) License : BSD 3 - clause Maintainer : Stream CSV data in\/out using [ Cassava]( / package / cassava ) . Adapted from [ streaming - cassava]( / package / streaming - cassava ) . For efficiency , operates on streams of strict ByteString chunks @(i.e . S.IsStream t = > t m ByteString)@ rather than directly on streams of Word8 . The ' chunkStream ' function is useful for generating an input stream from a ' Handle ' . Example usage : > import Streamly > import qualified Streamly . Prelude as S > import Streamly . Csv ( decode , encode , chunkStream ) > import System . IO > import qualified Data . Csv as Csv > import qualified Data . ByteString as BS > import Data . Vector ( Vector ) > > do > h < - openFile " testfile.csv " ReadMode > let chunks = chunkStream h ( 64 * 1024 ) > . HasHeader chunks : : S.SerialT IO ( Vector BS.ByteString ) > withFile " dest.csv " WriteMode $ \ho - > > S.mapM _ ( ho ) $ encode Nothing recs Module : Streamly.Csv Description : Cassava support for the streamly library Copyright : (c) Richard Warfield License : BSD 3-clause Maintainer : Stream CSV data in\/out using [Cassava](). Adapted from [streaming-cassava](-cassava). For efficiency, operates on streams of strict ByteString chunks @(i.e. S.IsStream t => t m ByteString)@ rather than directly on streams of Word8. The 'chunkStream' function is useful for generating an input stream from a 'Handle'. Example usage: > import Streamly > import qualified Streamly.Prelude as S > import Streamly.Csv (decode, encode, chunkStream) > import System.IO > import qualified Data.Csv as Csv > import qualified Data.ByteString as BS > import Data.Vector (Vector) > > do > h <- openFile "testfile.csv" ReadMode > let chunks = chunkStream h (64*1024) > recs = decode Csv.HasHeader chunks :: S.SerialT IO (Vector BS.ByteString) > withFile "dest.csv" WriteMode $ \ho -> > S.mapM_ (BS.hPut ho) $ encode Nothing recs -} module Streamly.Csv decode , decodeWith , decodeWithErrors , CsvParseException (..) , chunkStream , decodeByName , decodeByNameWith , decodeByNameWithErrors , encode , encodeDefault , encodeWith , encodeByName , encodeByNameDefault , encodeByNameWith , FromRecord (..) , FromNamedRecord (..) , ToRecord (..) , ToNamedRecord (..) , DefaultOrdered (..) , HasHeader (..) , Header , header , Name , DecodeOptions(..) , defaultDecodeOptions , EncodeOptions(..) , defaultEncodeOptions ) where import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Streamly.Prelude as S import Data.Csv (DecodeOptions(..), DefaultOrdered(..), EncodeOptions(..), FromNamedRecord(..), FromRecord(..), Header, Name, ToNamedRecord(..), ToRecord(..), defaultDecodeOptions, defaultEncodeOptions, encIncludeHeader, header) import Data.Csv.Incremental (HasHeader(..), HeaderParser(..), Parser(..)) import qualified Data.Csv.Incremental as CI import System.IO (Handle) import Control.Exception (Exception(..)) import Control.Monad.Catch (MonadThrow(..)) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Word (Word8) import Data.Bifunctor (first) import Data.Maybe (fromMaybe) import Data.String (IsString(..)) import Data.Typeable (Typeable) decode :: (S.IsStream t, S.MonadAsync m, FromRecord a) => HasHeader -> t m BS.ByteString -> t m a decode = decodeWith defaultDecodeOptions the first error . decodeWith :: (S.IsStream t, S.MonadAsync m, FromRecord a) => DecodeOptions -> HasHeader -> t m BS.ByteString -> t m a decodeWith opts hdr chunks = getValues (decodeWithErrors opts hdr chunks) decodeWithErrors :: (S.IsStream t, Monad m, FromRecord a, MonadThrow m) => DecodeOptions -> HasHeader -> t m BS.ByteString -> t m (Either CsvParseException a) decodeWithErrors opts = runParser . CI.decodeWith opts runParser :: forall t a m. (S.IsStream t, Monad m, MonadThrow m) => Parser a -> t m BS.ByteString -> t m (Either CsvParseException a) runParser p chunked = S.concatMap fst $ S.scanlM' continue (pure (S.nil, const p)) $ S.cons BS.empty chunked where continue :: (t m (Either CsvParseException a), BS.ByteString -> Parser a) -> BS.ByteString -> m (t m (Either CsvParseException a), BS.ByteString -> Parser a) continue (_, p) chunk = case p chunk of Fail bs err -> throwM (CsvParseException err) Many es get -> return (withEach es, get) Done es -> return (withEach es, p) withEach = S.fromList . map (first CsvParseException) chunkStream :: (S.IsStream t, S.MonadAsync m) => Handle -> Int -> t m BS.ByteString chunkStream h chunkSize = loop where loop = S.takeWhile (not . BS.null) $ liftIO (BS.hGetSome h chunkSize) `S.consM` loop decodeByName :: (S.MonadAsync m, FromNamedRecord a) => S.SerialT m BS.ByteString -> S.SerialT m a decodeByName = decodeByNameWith defaultDecodeOptions the first error . decodeByNameWith :: (S.MonadAsync m, FromNamedRecord a) => DecodeOptions -> S.SerialT m BS.ByteString -> S.SerialT m a decodeByNameWith opts bs = getValues (decodeByNameWithErrors opts bs) decodeByNameWithErrors :: forall m a. (Monad m, MonadThrow m, FromNamedRecord a) => DecodeOptions -> S.SerialT m BS.ByteString -> S.SerialT m (Either CsvParseException a) decodeByNameWithErrors opts chunked = do (p, rest) <- S.fromEffect $ extractParser (const $ CI.decodeByNameWith opts) $ S.cons BS.empty chunked runParser p rest where extractParser :: (BS.ByteString -> HeaderParser (Parser a)) -> S.SerialT m BS.ByteString -> m (Parser a, S.SerialT m BS.ByteString) extractParser p chunks = S.uncons chunks >>= \case Just (hed, rest) -> case p hed of FailH bs err -> throwM (CsvParseException err) PartialH get -> extractParser get rest DoneH _ p -> return (p, rest) Nothing -> throwM $ CsvParseException "Unexpected end of input stream" encode :: (S.IsStream t, ToRecord a, Monad m) => Maybe Header -> t m a -> t m BS.ByteString encode = encodeWith defaultEncodeOptions encodeDefault :: forall a t m. (S.IsStream t, ToRecord a, DefaultOrdered a, Monad m) => t m a -> t m BS.ByteString encodeDefault = encode (Just (headerOrder (undefined :: a))) encodeWith :: (S.IsStream t, ToRecord a, Monad m) => EncodeOptions -> Maybe Header -> t m a -> t m BS.ByteString encodeWith opts mhdr = S.concatMap S.fromList . addHeaders . S.map enc where addHeaders = maybe id (S.cons . enc) mhdr enc :: (ToRecord v) => v -> [BS.ByteString] enc = BSL.toChunks . CI.encodeWith opts . CI.encodeRecord encodeByNameDefault :: forall a t m. (S.IsStream t, DefaultOrdered a, ToNamedRecord a, Monad m) => t m a -> t m BS.ByteString encodeByNameDefault = encodeByName (headerOrder (undefined :: a)) encodeByName :: (S.IsStream t, ToNamedRecord a, Monad m) => Header -> t m a -> t m BS.ByteString encodeByName = encodeByNameWith defaultEncodeOptions encodeByNameWith :: (S.IsStream t, ToNamedRecord a, Monad m) => EncodeOptions -> Header -> t m a -> t m BS.ByteString encodeByNameWith opts hdr = S.concatMap S.fromList . addHeaders . S.map enc where opts' = opts { encIncludeHeader = False } addHeaders | encIncludeHeader opts = S.cons . BSL.toChunks . CI.encodeWith opts' . CI.encodeRecord $ hdr | otherwise = id enc = BSL.toChunks . CI.encodeByNameWith opts' hdr . CI.encodeNamedRecord getValues :: (S.IsStream t, S.MonadAsync m, Exception e) => t m (Either e a) -> t m a getValues = S.mapM (either throwM return) newtype CsvParseException = CsvParseException String deriving (Eq, Show, Typeable) instance IsString CsvParseException where fromString = CsvParseException instance Exception CsvParseException where displayException (CsvParseException e) = "Error parsing csv: " ++ e
e27f962e9383ad4cb3140f11a9bc0957d2fbdd403de85b80befe1ccbcc4f550f
Vaguery/klapaucius
random_scalars.clj
(ns push.type.module.random-scalars (:require [push.instructions.dsl :as d] [push.instructions.core :as i] [clojure.math.numeric-tower :as n] [push.type.core :as t] )) (def integer-uniform (i/build-instruction integer-uniform "`:integer-uniform` pops the top `:scalar` value, and pushes a uniform random integer (typecase from a uniform number on the range `[0.0, :arg)`). If the scalar is negative, a negative result is returned; if the argument is out of bounds (larger than Long/MAX_VALUE), an `:error` is pushed instead of a value." (d/consume-top-of :scalar :as :arg) (d/calculate [:arg] #(< (n/abs %1) Long/MAX_VALUE) :as :valid) (d/calculate [:valid :arg] #(when %1 (long (rand %2))) :as :result) (d/calculate [:valid] #(when-not %1 ":integer-uniform argument out of range") :as :warning) (d/return-item :result) (d/record-an-error :from :warning))) (def float-uniform (i/build-instruction float-uniform "`:float-uniform` pops the top `:scalar` value, and pushes a random double uniformly sampled from the range [0,:f). If the float is negative, a negative result is returned." (d/consume-top-of :scalar :as :arg) (d/calculate [:arg] #(< (n/abs %1) Double/MAX_VALUE) :as :valid) (d/calculate [:valid :arg] #(when %1 (rand %2)) :as :result) (d/calculate [:valid] #(when-not %1 ":float-uniform argument out of range") :as :warning) (d/return-item :result) (d/record-an-error :from :warning))) (def boolean-faircoin (i/build-instruction boolean-faircoin "`:boolean-faircoin` pushes a random `:boolean` value, with equal probability `true` or `false`." (d/calculate [] #(< (rand) 0.5) :as :result) (d/return-item :result))) ;;;;;;;;;;;;;;;;; (def random-scalars-module ( -> (t/make-module :random-scalars :attributes #{:numeric :random}) (t/attach-instruction , integer-uniform) (t/attach-instruction , float-uniform) (t/attach-instruction , boolean-faircoin) ))
null
https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/src/push/type/module/random_scalars.clj
clojure
(ns push.type.module.random-scalars (:require [push.instructions.dsl :as d] [push.instructions.core :as i] [clojure.math.numeric-tower :as n] [push.type.core :as t] )) (def integer-uniform (i/build-instruction integer-uniform "`:integer-uniform` pops the top `:scalar` value, and pushes a uniform random integer (typecase from a uniform number on the range `[0.0, :arg)`). If the scalar is negative, a negative result is returned; if the argument is out of bounds (larger than Long/MAX_VALUE), an `:error` is pushed instead of a value." (d/consume-top-of :scalar :as :arg) (d/calculate [:arg] #(< (n/abs %1) Long/MAX_VALUE) :as :valid) (d/calculate [:valid :arg] #(when %1 (long (rand %2))) :as :result) (d/calculate [:valid] #(when-not %1 ":integer-uniform argument out of range") :as :warning) (d/return-item :result) (d/record-an-error :from :warning))) (def float-uniform (i/build-instruction float-uniform "`:float-uniform` pops the top `:scalar` value, and pushes a random double uniformly sampled from the range [0,:f). If the float is negative, a negative result is returned." (d/consume-top-of :scalar :as :arg) (d/calculate [:arg] #(< (n/abs %1) Double/MAX_VALUE) :as :valid) (d/calculate [:valid :arg] #(when %1 (rand %2)) :as :result) (d/calculate [:valid] #(when-not %1 ":float-uniform argument out of range") :as :warning) (d/return-item :result) (d/record-an-error :from :warning))) (def boolean-faircoin (i/build-instruction boolean-faircoin "`:boolean-faircoin` pushes a random `:boolean` value, with equal probability `true` or `false`." (d/calculate [] #(< (rand) 0.5) :as :result) (d/return-item :result))) (def random-scalars-module ( -> (t/make-module :random-scalars :attributes #{:numeric :random}) (t/attach-instruction , integer-uniform) (t/attach-instruction , float-uniform) (t/attach-instruction , boolean-faircoin) ))
ab32992a08042c425cec13187cb3b10f7120490bc9e4c389d56b8578a799cefe
kelamg/HtDP2e-workthrough
ex196.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex196) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/batch-io) (define LOCATION "/usr/share/dict/words") ; A Dictionary is a List-of-strings. (define AS-LIST (read-lines LOCATION)) A Letter is one of the following 1Strings : ; – "a" ; – ... ; – "z" ; or, equivalently, a member? of this list: (define LETTERS (explode "abcdefghijklmnopqrstuvwxyz")) (define-struct lcount (letter count)) A LetterCount is a structure : ;; (make-lcount Letter N) ;; interp. (make-lcount s n) means s appears as the first letter of a word n times A LLC is one of : ;; - '() - ( cons LetterCount LLC ) A LoL ( list of letters ) is one of : ;; - '() ;; - (cons Letter LoL) ;; Any -> Boolean ;; produces true if s is a Letter (check-expect (letter? 1) #f) (check-expect (letter? (list "a" "z")) #f) (check-expect (letter? "az") #f) (check-expect (letter? "a") #t) (check-expect (letter? "z") #t) (define (letter? s) (member? s LETTERS)) (define DICT (list "antelope" "assimilate" "bravo" "class" "orthogonal" "padantic" "quasi" "trope" "set" "ventriloquist" "vindictive" "violence" "vilify" "vapid" "wallow" "zealous")) (define LLC1 (list (make-lcount "a" 2) (make-lcount "b" 1) (make-lcount "c" 1) (make-lcount "o" 1) (make-lcount "p" 1) (make-lcount "q" 1) (make-lcount "t" 1) (make-lcount "s" 1) (make-lcount "v" 5) (make-lcount "w" 1) (make-lcount "z" 1))) LoL Dictionary - > LLC ;; produces a list of lcount for all letters in dict (check-expect (count-by-letter '() DICT) '()) (check-expect (count-by-letter (list "v") DICT) (list (make-lcount "v" 5))) (check-expect (count-by-letter (list "a" "b" "c") DICT) (list (make-lcount "a" 2) (make-lcount "b" 1) (make-lcount "c" 1))) (define (count-by-letter lol dict) (cond [(empty? lol) '()] [else (cons (make-lcount (first lol) (starts-with# (first lol) dict)) (count-by-letter (rest lol) dict))])) ;; Letter Dictionary -> N ;; counts how many words in dict that start with l (check-expect (starts-with# "a" '()) 0) (check-expect (starts-with# "b" DICT) 1) (check-expect (starts-with# "a" DICT) 2) (check-expect (starts-with# "v" DICT) 5) (define (starts-with# l dict) (cond [(empty? dict) 0] [else (if (starts-with? l (first dict)) (add1 (starts-with# l (rest dict))) (starts-with# l (rest dict)))])) ;; 1String String -> Boolean produces true if s starts with 1s (check-expect (starts-with? "a" "ant") #t) (check-expect (starts-with? "1" "ant") #f) (define (starts-with? 1s s) (string=? 1s (substring s 0 1))) ;; Once your function is designed, determine how many words ;; appear for all letters in your computer’s dictionary. (count-by-letter LETTERS AS-LIST)
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Arbitrarily-Large-Data/ex196.rkt
racket
about the language level of this file in a form that our tools can easily process. A Dictionary is a List-of-strings. – "a" – ... – "z" or, equivalently, a member? of this list: (make-lcount Letter N) interp. (make-lcount s n) means s appears as the - '() - '() - (cons Letter LoL) Any -> Boolean produces true if s is a Letter produces a list of lcount for all letters in dict Letter Dictionary -> N counts how many words in dict that start with l 1String String -> Boolean Once your function is designed, determine how many words appear for all letters in your computer’s dictionary.
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex196) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/batch-io) (define LOCATION "/usr/share/dict/words") (define AS-LIST (read-lines LOCATION)) A Letter is one of the following 1Strings : (define LETTERS (explode "abcdefghijklmnopqrstuvwxyz")) (define-struct lcount (letter count)) A LetterCount is a structure : first letter of a word n times A LLC is one of : - ( cons LetterCount LLC ) A LoL ( list of letters ) is one of : (check-expect (letter? 1) #f) (check-expect (letter? (list "a" "z")) #f) (check-expect (letter? "az") #f) (check-expect (letter? "a") #t) (check-expect (letter? "z") #t) (define (letter? s) (member? s LETTERS)) (define DICT (list "antelope" "assimilate" "bravo" "class" "orthogonal" "padantic" "quasi" "trope" "set" "ventriloquist" "vindictive" "violence" "vilify" "vapid" "wallow" "zealous")) (define LLC1 (list (make-lcount "a" 2) (make-lcount "b" 1) (make-lcount "c" 1) (make-lcount "o" 1) (make-lcount "p" 1) (make-lcount "q" 1) (make-lcount "t" 1) (make-lcount "s" 1) (make-lcount "v" 5) (make-lcount "w" 1) (make-lcount "z" 1))) LoL Dictionary - > LLC (check-expect (count-by-letter '() DICT) '()) (check-expect (count-by-letter (list "v") DICT) (list (make-lcount "v" 5))) (check-expect (count-by-letter (list "a" "b" "c") DICT) (list (make-lcount "a" 2) (make-lcount "b" 1) (make-lcount "c" 1))) (define (count-by-letter lol dict) (cond [(empty? lol) '()] [else (cons (make-lcount (first lol) (starts-with# (first lol) dict)) (count-by-letter (rest lol) dict))])) (check-expect (starts-with# "a" '()) 0) (check-expect (starts-with# "b" DICT) 1) (check-expect (starts-with# "a" DICT) 2) (check-expect (starts-with# "v" DICT) 5) (define (starts-with# l dict) (cond [(empty? dict) 0] [else (if (starts-with? l (first dict)) (add1 (starts-with# l (rest dict))) (starts-with# l (rest dict)))])) produces true if s starts with 1s (check-expect (starts-with? "a" "ant") #t) (check-expect (starts-with? "1" "ant") #f) (define (starts-with? 1s s) (string=? 1s (substring s 0 1))) (count-by-letter LETTERS AS-LIST)
198442563a797b3c137dfa89dd02daeb47cb500b1cdc1f9c6aafc9dd76d40b00
Zulu-Inuoe/clution
initialize.lisp
;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*- ;;; ;;; --- Error conditions and checking ;;; (in-package :static-vectors) (declaim (inline check-initialization-arguments)) (defun check-initialization-arguments (initial-element-p initial-contents-p) (when (and initial-element-p initial-contents-p) ;; FIXME: signal ARGUMENT-LIST-ERROR (error "MAKE-STATIC-VECTOR: You must not specify both ~ :INITIAL-ELEMENT and :INITIAL-CONTENTS"))) (declaim (inline check-initial-element)) (defun check-initial-element (element-type initial-element) (when (not (typep initial-element element-type)) FIXME : signal SUBTYPE - ERROR (error "MAKE-STATIC-VECTOR: The type of :INITIAL-ELEMENT ~S is not a subtype ~ of the array's :ELEMENT-TYPE ~S" initial-element element-type))) (declaim (inline check-initial-contents)) (defun check-initial-contents (length initial-contents) (let ((initial-contents-length (length initial-contents))) (when (/= length initial-contents-length) ;; FIXME: signal TYPE-ERROR (error "MAKE-STATIC-VECTOR: There are ~A elements in the :INITIAL-CONTENTS, ~ but requested vector length is ~A." initial-contents-length length)))) (defun check-arguments (length element-type initial-element initial-element-p initial-contents initial-contents-p) (check-initialization-arguments initial-element-p initial-contents-p) (check-type length non-negative-fixnum) (when initial-element-p (check-initial-element element-type initial-element)) (when initial-contents-p (check-initial-contents length initial-contents))) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +static-vectors-are-garbage-collected+ #+(or ecl lispworks) t #-(or ecl lispworks) nil)) (defmacro free-vector-on-error ((vector) &body body) (if +static-vectors-are-garbage-collected+ `(progn ,@body) `(unwind-protect-case () (progn ,@body) (:abort (free-static-vector ,vector))))) (defmacro the* (type form) `(#+sbcl sb-ext:truly-the #-sbcl cl:the ,type ,form)) (declaim (inline %initialize-vector)) (defun %initialize-vector (vector length element-type initial-element initial-element-p initial-contents initial-contents-p) These two are kept because the compiler - macro uses them to check for the validity ;; of the INITIAL-ELEMENT and INITIAL-CONTENTS (declare (ignore length element-type)) (cond (initial-element-p (free-vector-on-error (vector) (fill vector initial-element))) (initial-contents-p (free-vector-on-error (vector) (replace vector initial-contents)))) vector) (define-compiler-macro %initialize-vector (&whole form &environment env vector length element-type initial-element initial-element-p initial-contents initial-contents-p) (cond ((and (constantp initial-element-p env) (eval-constant initial-element-p env)) (once-only (vector) `(free-vector-on-error (,vector) ,@(if (and (constantp element-type env) (constantp initial-element env)) (check-initial-element (eval-constant element-type env) initial-element) `((check-initial-element ,element-type ,initial-element))) (fill ,vector ,initial-element) ,vector))) ((and (constantp initial-contents-p env) (eval-constant initial-contents-p env)) (once-only (vector) `(free-vector-on-error (,vector) ,@(if (and (constantp length env) (constantp initial-contents env)) (check-initial-contents length (eval-constant initial-contents env)) `((check-initial-contents ,length ,initial-contents))) (replace ,vector ,initial-contents) ,vector))) (t form)))
null
https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/static-vectors-v1.8.3/src/initialize.lisp
lisp
-*- Mode: Lisp; indent-tabs-mode: nil -*- --- Error conditions and checking FIXME: signal ARGUMENT-LIST-ERROR FIXME: signal TYPE-ERROR of the INITIAL-ELEMENT and INITIAL-CONTENTS
(in-package :static-vectors) (declaim (inline check-initialization-arguments)) (defun check-initialization-arguments (initial-element-p initial-contents-p) (when (and initial-element-p initial-contents-p) (error "MAKE-STATIC-VECTOR: You must not specify both ~ :INITIAL-ELEMENT and :INITIAL-CONTENTS"))) (declaim (inline check-initial-element)) (defun check-initial-element (element-type initial-element) (when (not (typep initial-element element-type)) FIXME : signal SUBTYPE - ERROR (error "MAKE-STATIC-VECTOR: The type of :INITIAL-ELEMENT ~S is not a subtype ~ of the array's :ELEMENT-TYPE ~S" initial-element element-type))) (declaim (inline check-initial-contents)) (defun check-initial-contents (length initial-contents) (let ((initial-contents-length (length initial-contents))) (when (/= length initial-contents-length) (error "MAKE-STATIC-VECTOR: There are ~A elements in the :INITIAL-CONTENTS, ~ but requested vector length is ~A." initial-contents-length length)))) (defun check-arguments (length element-type initial-element initial-element-p initial-contents initial-contents-p) (check-initialization-arguments initial-element-p initial-contents-p) (check-type length non-negative-fixnum) (when initial-element-p (check-initial-element element-type initial-element)) (when initial-contents-p (check-initial-contents length initial-contents))) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +static-vectors-are-garbage-collected+ #+(or ecl lispworks) t #-(or ecl lispworks) nil)) (defmacro free-vector-on-error ((vector) &body body) (if +static-vectors-are-garbage-collected+ `(progn ,@body) `(unwind-protect-case () (progn ,@body) (:abort (free-static-vector ,vector))))) (defmacro the* (type form) `(#+sbcl sb-ext:truly-the #-sbcl cl:the ,type ,form)) (declaim (inline %initialize-vector)) (defun %initialize-vector (vector length element-type initial-element initial-element-p initial-contents initial-contents-p) These two are kept because the compiler - macro uses them to check for the validity (declare (ignore length element-type)) (cond (initial-element-p (free-vector-on-error (vector) (fill vector initial-element))) (initial-contents-p (free-vector-on-error (vector) (replace vector initial-contents)))) vector) (define-compiler-macro %initialize-vector (&whole form &environment env vector length element-type initial-element initial-element-p initial-contents initial-contents-p) (cond ((and (constantp initial-element-p env) (eval-constant initial-element-p env)) (once-only (vector) `(free-vector-on-error (,vector) ,@(if (and (constantp element-type env) (constantp initial-element env)) (check-initial-element (eval-constant element-type env) initial-element) `((check-initial-element ,element-type ,initial-element))) (fill ,vector ,initial-element) ,vector))) ((and (constantp initial-contents-p env) (eval-constant initial-contents-p env)) (once-only (vector) `(free-vector-on-error (,vector) ,@(if (and (constantp length env) (constantp initial-contents env)) (check-initial-contents length (eval-constant initial-contents env)) `((check-initial-contents ,length ,initial-contents))) (replace ,vector ,initial-contents) ,vector))) (t form)))
af6ab9b2e075a76e00848c84e6f23004a89b846f9f8c50626a4b24c61a7316a3
mzp/coq-for-ipad
marshal.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1997 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../../LICENSE. *) (* *) (***********************************************************************) $ I d : marshal.ml 9547 2010 - 01 - 22 12:48:24Z doligez $ type extern_flags = No_sharing | Closures external to_string: 'a -> extern_flags list -> string = "caml_output_value_to_string" let to_channel chan v flags = output_string chan (to_string v flags) external to_buffer_unsafe: string -> int -> int -> 'a -> extern_flags list -> int = "caml_output_value_to_buffer" let to_buffer buff ofs len v flags = if ofs < 0 || len < 0 || ofs + len > String.length buff then invalid_arg "Marshal.to_buffer: substring out of bounds" else to_buffer_unsafe buff ofs len v flags let to_buffer' ~buf ~pos ~len v ~mode = to_buffer buf pos len v mode external from_string_unsafe: string -> int -> 'a = "caml_input_value_from_string" external data_size_unsafe: string -> int -> int = "caml_marshal_data_size" let header_size = 20 let data_size buff ofs = if ofs < 0 || ofs > String.length buff - header_size then invalid_arg "Marshal.data_size" else data_size_unsafe buff ofs let total_size buff ofs = header_size + data_size buff ofs let from_string buff ofs = if ofs < 0 || ofs > String.length buff - header_size then invalid_arg "Marshal.from_size" else begin let len = data_size_unsafe buff ofs in if ofs > String.length buff - (header_size + len) then invalid_arg "Marshal.from_string" else from_string_unsafe buff ofs end let from_channel = Pervasives.input_value
null
https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/otherlibs/threads/marshal.ml
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../../LICENSE. *********************************************************************
, projet Cristal , INRIA Rocquencourt Copyright 1997 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ I d : marshal.ml 9547 2010 - 01 - 22 12:48:24Z doligez $ type extern_flags = No_sharing | Closures external to_string: 'a -> extern_flags list -> string = "caml_output_value_to_string" let to_channel chan v flags = output_string chan (to_string v flags) external to_buffer_unsafe: string -> int -> int -> 'a -> extern_flags list -> int = "caml_output_value_to_buffer" let to_buffer buff ofs len v flags = if ofs < 0 || len < 0 || ofs + len > String.length buff then invalid_arg "Marshal.to_buffer: substring out of bounds" else to_buffer_unsafe buff ofs len v flags let to_buffer' ~buf ~pos ~len v ~mode = to_buffer buf pos len v mode external from_string_unsafe: string -> int -> 'a = "caml_input_value_from_string" external data_size_unsafe: string -> int -> int = "caml_marshal_data_size" let header_size = 20 let data_size buff ofs = if ofs < 0 || ofs > String.length buff - header_size then invalid_arg "Marshal.data_size" else data_size_unsafe buff ofs let total_size buff ofs = header_size + data_size buff ofs let from_string buff ofs = if ofs < 0 || ofs > String.length buff - header_size then invalid_arg "Marshal.from_size" else begin let len = data_size_unsafe buff ofs in if ofs > String.length buff - (header_size + len) then invalid_arg "Marshal.from_string" else from_string_unsafe buff ofs end let from_channel = Pervasives.input_value
507594a43f623611915a9fa752c2f29c5520aabf1804545d4ab05d0f57cc9d91
bcbio/bcbio.variation.recall
variantcontext.clj
(ns bcbio.variation.variantcontext "Helper functions to retrieve information from htsjdk VariantContext objects, which represent variant data stored in VCF files." (:import [htsjdk.samtools.reference ReferenceSequenceFileFactory] [htsjdk.tribble AbstractFeatureReader] [htsjdk.variant.vcf VCFCodec VCFUtils VCFHeader VCFFilterHeaderLine] [htsjdk.variant.variantcontext VariantContextBuilder GenotypeBuilder GenotypesContext] [htsjdk.variant.variantcontext.writer VariantContextWriterBuilder Options] [picard.sam CreateSequenceDictionary] [java.util EnumSet]) (:use [clojure.set :only [intersection union]] [lazymap.core :only [lazy-hash-map]] [ordered.set :only [ordered-set]]) (:require [clojure.java.io :as io] [clojure.string :as string] [bcbio.run.fsp :as fsp] [bcbio.run.itx :as itx] [bcbio.variation.ensemble.prep :as eprep])) # # Represent VariantContext objects ;; ;; Provide simple map-based access to important attributes of VariantContexts . There are 3 useful levels of abstraction : ;; ;; - VariantContext: Details about a variation. This captures a single line in a VCF file ;; - Genotype: An individual genotype for a sample, at a variant position. ;; - Allele: The actual alleles at a genotype. (defn from-genotype "Represent a sample genotype including alleles. :genotype stores the original java genotype object for direct access." [g] (lazy-hash-map :sample-name (.getSampleName g) :qual (.getPhredScaledQual g) :type (-> g .getType .name) :phased? (.isPhased g) :attributes (merge {"DP" (.getDP g) "AD" (vec (.getAD g)) "GQ" (.getGQ g) "PL" (vec (.getPL g))} (into {} (.getExtendedAttributes g))) :alleles (vec (.getAlleles g)) :genotype g)) (defn from-vc "Provide a top level map of information from a variant context. :vc stores the original java VariantContext object for direct access." [vc] (lazy-hash-map :chr (.getChr vc) :start (.getStart vc) :end (.getEnd vc) :id (when (.hasID vc) (.getID vc)) :ref-allele (clojure.string/upper-case (.getDisplayString (.getReference vc))) :alt-alleles (vec (map #(-> % .getDisplayString clojure.string/upper-case) (.getAlternateAlleles vc))) :type (-> vc .getType .name) :filters (set (.getFilters vc)) :attributes (into {} (.getAttributes vc)) :qual (.getPhredScaledQual vc) :num-samples (.getNSamples vc) :genotypes (map from-genotype (-> vc .getGenotypes .toArray vec)) :vc vc)) # # Parsing VCF files (defn create-ref-dict "Create reference dictionaries required by GATK and Picard. Requires samtools command to create *.fai if missing, since code to create these is no longer present in GATK." [ref-file] (let [dict-file (str (fsp/file-root ref-file) ".dict")] (when (itx/needs-run? dict-file) (.instanceMain (CreateSequenceDictionary.) (into-array [(str "r=" ref-file) (str "o=" dict-file)]))) dict-file)) (defn get-seq-dict "Retrieve Picard sequence dictionary from FASTA reference file." [ref-file] (create-ref-dict ref-file) (-> (io/file ref-file) ReferenceSequenceFileFactory/getReferenceSequenceFile .getSequenceDictionary)) (defn get-vcf-source "Create a Tribble FeatureSource for VCF file, using bgzipped tabix indexed VCFs." ([in-file] (eprep/bgzip-index-vcf in-file) (AbstractFeatureReader/getFeatureReader in-file (VCFCodec.) false)) ([in-file ref-file] (get-vcf-source in-file))) (defn get-vcf-iterator "Create an iterator over VCF VariantContexts." ([in-file] (.iterator (get-vcf-source in-file))) ([in-file ref-file] (get-vcf-iterator in-file))) (defn variants-in-region "Retrieve variants located in potentially multiple variant files" ([retriever vc] (variants-in-region retriever (:chr vc) (:start vc) (:end vc))) ([retriever space start end] (letfn [(get-vcs-in-source [[source fname]] (with-open [vcf-iter (.query source space (max 1 start) end)] (doall (map #(assoc (from-vc %) :fname fname) (iterator-seq vcf-iter)))))] (mapcat get-vcs-in-source (map vector (:sources retriever) (:fnames retriever)))))) (defrecord VariantRetriever [sources fnames] java.io.Closeable (close [_] (doseq [x sources] (.close x)))) (defn get-vcf-retriever "Indexed variant file retrieval for zero to multiple files with clean handle closing." [ref & vcf-files] (let [fnames (remove nil? vcf-files)] (VariantRetriever. (map #(get-vcf-source % ref) fnames) fnames))) (defn parse-vcf "Lazy iterator of VariantContext information from VCF file." [vcf-source] (map from-vc (iterator-seq (.iterator vcf-source)))) # # Writing VCF files (defn get-vcf-header "Retrieve header from input VCF file." [vcf-file] (with-open [vcf-reader (AbstractFeatureReader/getFeatureReader vcf-file (VCFCodec.) false)] (.getHeader vcf-reader))) (defn get-vcf-samples "Retrieve samples from a VCF header" [vcf-file] (map str (.getGenotypeSamples (get-vcf-header vcf-file)))) (defn vc-add-attr "Add an attribute to the current VariantContext" [vc key val] (-> (VariantContextBuilder. vc) (.attributes (assoc (into {} (.getAttributes vc)) key val)) .make)) (defn- header-w-md "Update a header with new INFO and FILTER metadata." [new-md header] (VCFHeader. (apply ordered-set (concat (.getMetaDataInInputOrder header) new-md)) (.getGenotypeSamples header))) (defn merge-headers [& merge-files] (fn [_ header] (VCFHeader. (VCFUtils/smartMergeHeaders (cons header (map get-vcf-header merge-files)) true) (.getGenotypeSamples header)))) (defn write-vcf-w-template "Write VCF output files starting with an original input template VCF. Handles writing to multiple VCF files simultaneously with the different file handles represented as keywords. This allows lazy splitting of VCF files: `vc-iter` is a lazy sequence of `(writer-keyword variant-context)`. `out-file-map` is a map of writer-keywords to output filenames." [tmpl-file out-file-map vc-iter & {:keys [header-update-fn new-md]}] (letfn [(make-vcf-writer [f] (-> (VariantContextWriterBuilder. ) (.setOutputFile f) (.setOption Options/INDEX_ON_THE_FLY) (.setOption Options/ALLOW_MISSING_FIELDS_IN_HEADER) .build)) (convert-to-output [info] [(if (and (coll? info) (= 2 (count info))) (first info) :out) (if (coll? info) (last info) info)])] (itx/with-tx-files [tx-out-files out-file-map (keys out-file-map) [".idx" ".tbi"]] (let [tmpl-header (get-vcf-header tmpl-file) writer-map (zipmap (keys tx-out-files) (map make-vcf-writer (vals tx-out-files)))] (doseq [[key out-vcf] writer-map] (.writeHeader out-vcf (cond->> tmpl-header header-update-fn (header-update-fn key) new-md (header-w-md new-md)))) (doseq [[fkey item] (map convert-to-output vc-iter)] (let [ready-vc (if (and (map? item) (contains? item :vc)) (:vc item) item)] (when-not (nil? ready-vc) (.add (get writer-map fkey) ready-vc)))) (doseq [x (vals writer-map)] (.close x)))))) ;; ## Utilities (defn remove-filter "Remove filter from a variant context." [vc] (-> (VariantContextBuilder. vc) .passFilters .make))
null
https://raw.githubusercontent.com/bcbio/bcbio.variation.recall/b7aa436dcb558535f87d004ba0abc5d7bc380b70/src/bcbio/variation/variantcontext.clj
clojure
Provide simple map-based access to important attributes of - VariantContext: Details about a variation. This captures a - Genotype: An individual genotype for a sample, at a variant position. - Allele: The actual alleles at a genotype. ## Utilities
(ns bcbio.variation.variantcontext "Helper functions to retrieve information from htsjdk VariantContext objects, which represent variant data stored in VCF files." (:import [htsjdk.samtools.reference ReferenceSequenceFileFactory] [htsjdk.tribble AbstractFeatureReader] [htsjdk.variant.vcf VCFCodec VCFUtils VCFHeader VCFFilterHeaderLine] [htsjdk.variant.variantcontext VariantContextBuilder GenotypeBuilder GenotypesContext] [htsjdk.variant.variantcontext.writer VariantContextWriterBuilder Options] [picard.sam CreateSequenceDictionary] [java.util EnumSet]) (:use [clojure.set :only [intersection union]] [lazymap.core :only [lazy-hash-map]] [ordered.set :only [ordered-set]]) (:require [clojure.java.io :as io] [clojure.string :as string] [bcbio.run.fsp :as fsp] [bcbio.run.itx :as itx] [bcbio.variation.ensemble.prep :as eprep])) # # Represent VariantContext objects VariantContexts . There are 3 useful levels of abstraction : single line in a VCF file (defn from-genotype "Represent a sample genotype including alleles. :genotype stores the original java genotype object for direct access." [g] (lazy-hash-map :sample-name (.getSampleName g) :qual (.getPhredScaledQual g) :type (-> g .getType .name) :phased? (.isPhased g) :attributes (merge {"DP" (.getDP g) "AD" (vec (.getAD g)) "GQ" (.getGQ g) "PL" (vec (.getPL g))} (into {} (.getExtendedAttributes g))) :alleles (vec (.getAlleles g)) :genotype g)) (defn from-vc "Provide a top level map of information from a variant context. :vc stores the original java VariantContext object for direct access." [vc] (lazy-hash-map :chr (.getChr vc) :start (.getStart vc) :end (.getEnd vc) :id (when (.hasID vc) (.getID vc)) :ref-allele (clojure.string/upper-case (.getDisplayString (.getReference vc))) :alt-alleles (vec (map #(-> % .getDisplayString clojure.string/upper-case) (.getAlternateAlleles vc))) :type (-> vc .getType .name) :filters (set (.getFilters vc)) :attributes (into {} (.getAttributes vc)) :qual (.getPhredScaledQual vc) :num-samples (.getNSamples vc) :genotypes (map from-genotype (-> vc .getGenotypes .toArray vec)) :vc vc)) # # Parsing VCF files (defn create-ref-dict "Create reference dictionaries required by GATK and Picard. Requires samtools command to create *.fai if missing, since code to create these is no longer present in GATK." [ref-file] (let [dict-file (str (fsp/file-root ref-file) ".dict")] (when (itx/needs-run? dict-file) (.instanceMain (CreateSequenceDictionary.) (into-array [(str "r=" ref-file) (str "o=" dict-file)]))) dict-file)) (defn get-seq-dict "Retrieve Picard sequence dictionary from FASTA reference file." [ref-file] (create-ref-dict ref-file) (-> (io/file ref-file) ReferenceSequenceFileFactory/getReferenceSequenceFile .getSequenceDictionary)) (defn get-vcf-source "Create a Tribble FeatureSource for VCF file, using bgzipped tabix indexed VCFs." ([in-file] (eprep/bgzip-index-vcf in-file) (AbstractFeatureReader/getFeatureReader in-file (VCFCodec.) false)) ([in-file ref-file] (get-vcf-source in-file))) (defn get-vcf-iterator "Create an iterator over VCF VariantContexts." ([in-file] (.iterator (get-vcf-source in-file))) ([in-file ref-file] (get-vcf-iterator in-file))) (defn variants-in-region "Retrieve variants located in potentially multiple variant files" ([retriever vc] (variants-in-region retriever (:chr vc) (:start vc) (:end vc))) ([retriever space start end] (letfn [(get-vcs-in-source [[source fname]] (with-open [vcf-iter (.query source space (max 1 start) end)] (doall (map #(assoc (from-vc %) :fname fname) (iterator-seq vcf-iter)))))] (mapcat get-vcs-in-source (map vector (:sources retriever) (:fnames retriever)))))) (defrecord VariantRetriever [sources fnames] java.io.Closeable (close [_] (doseq [x sources] (.close x)))) (defn get-vcf-retriever "Indexed variant file retrieval for zero to multiple files with clean handle closing." [ref & vcf-files] (let [fnames (remove nil? vcf-files)] (VariantRetriever. (map #(get-vcf-source % ref) fnames) fnames))) (defn parse-vcf "Lazy iterator of VariantContext information from VCF file." [vcf-source] (map from-vc (iterator-seq (.iterator vcf-source)))) # # Writing VCF files (defn get-vcf-header "Retrieve header from input VCF file." [vcf-file] (with-open [vcf-reader (AbstractFeatureReader/getFeatureReader vcf-file (VCFCodec.) false)] (.getHeader vcf-reader))) (defn get-vcf-samples "Retrieve samples from a VCF header" [vcf-file] (map str (.getGenotypeSamples (get-vcf-header vcf-file)))) (defn vc-add-attr "Add an attribute to the current VariantContext" [vc key val] (-> (VariantContextBuilder. vc) (.attributes (assoc (into {} (.getAttributes vc)) key val)) .make)) (defn- header-w-md "Update a header with new INFO and FILTER metadata." [new-md header] (VCFHeader. (apply ordered-set (concat (.getMetaDataInInputOrder header) new-md)) (.getGenotypeSamples header))) (defn merge-headers [& merge-files] (fn [_ header] (VCFHeader. (VCFUtils/smartMergeHeaders (cons header (map get-vcf-header merge-files)) true) (.getGenotypeSamples header)))) (defn write-vcf-w-template "Write VCF output files starting with an original input template VCF. Handles writing to multiple VCF files simultaneously with the different file handles represented as keywords. This allows lazy splitting of VCF files: `vc-iter` is a lazy sequence of `(writer-keyword variant-context)`. `out-file-map` is a map of writer-keywords to output filenames." [tmpl-file out-file-map vc-iter & {:keys [header-update-fn new-md]}] (letfn [(make-vcf-writer [f] (-> (VariantContextWriterBuilder. ) (.setOutputFile f) (.setOption Options/INDEX_ON_THE_FLY) (.setOption Options/ALLOW_MISSING_FIELDS_IN_HEADER) .build)) (convert-to-output [info] [(if (and (coll? info) (= 2 (count info))) (first info) :out) (if (coll? info) (last info) info)])] (itx/with-tx-files [tx-out-files out-file-map (keys out-file-map) [".idx" ".tbi"]] (let [tmpl-header (get-vcf-header tmpl-file) writer-map (zipmap (keys tx-out-files) (map make-vcf-writer (vals tx-out-files)))] (doseq [[key out-vcf] writer-map] (.writeHeader out-vcf (cond->> tmpl-header header-update-fn (header-update-fn key) new-md (header-w-md new-md)))) (doseq [[fkey item] (map convert-to-output vc-iter)] (let [ready-vc (if (and (map? item) (contains? item :vc)) (:vc item) item)] (when-not (nil? ready-vc) (.add (get writer-map fkey) ready-vc)))) (doseq [x (vals writer-map)] (.close x)))))) (defn remove-filter "Remove filter from a variant context." [vc] (-> (VariantContextBuilder. vc) .passFilters .make))