_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
55e9594d2de0281177045e526a207682ed88f70ee6598d8569d5f7b233449fb0
nextjournal/clerk-demo
zipper_with_scars.clj
# Clojure Zippers with Scars à la ;; _Building scars into clojure zipper library to go up and back down at the previous location._ (ns zipper-with-scars {:nextjournal.clerk/visibility {:code :fold} :nextjournal.clerk/no-cache true} (:require [clojure.zip :as zip] [arrowic.core :as a] [nextjournal.clerk :as clerk] [nextjournal.clerk.viewer :as v] [clojure.string :as str]) (:import (clojure.lang Seqable))) ;; I recently stumbled into a parsing scenario where a stream of tokens is folded onto a zipper. ;; Some of these tokens would just push a new child at the current location while ;; others would also need to vary the shape some ancestor node. Now the issue with `clojure.zip/up` followed by a ` clojure.zip/down ` is that it goes back to _ the first _ ( or leftmost ) of the child nodes . ;; ;; Can we build a function to actually _go back_ to the previous lower location ;; without say, storing some left offset while going up or using a non-core zipper library? ;; Mr. to the rescue here ! It turns out ;; the [original zipper paper](/~huet/PUBLIC/zip.pdf) has a memo-version of the up and down functions. Let's use Clerk viewers to illustrate how they work. ;; ;; Admittedly, the story with scars is just an excuse to test some animated zipper viewers in Clerk. To that end some machinery follows, unfold at your own peril. ^{::clerk/visibility {:result :hide}} (do (defn loc-seq [zloc] this sorts nodes so that children seqs are displayed in the correct order by (try (doall (concat (reverse (take-while some? (next (iterate zip/prev zloc)))) (cons zloc (take-while (complement zip/end?) (next (iterate zip/next zloc)))))) (catch Throwable e (throw (ex-info "Cant seq at loc" {:zloc zloc} e))))) (def ->name (comp :name zip/node)) (defn pnode [zloc] (some-> zloc (get 1) :pnodes peek)) (def empty-graph {:vertices #{} :edges []}) (defn add-v [g zloc] (update g :vertices conj (->name zloc))) (defn add-e [g zloc] (let [parent-name (-> zloc pnode :name)] (cond-> g parent-name (update :edges conj [parent-name (-> zloc zip/node :name)])))) (defn ->graph [zloc] (reduce #(-> %1 (add-e %2) (add-v %2)) (assoc empty-graph :current? #{(->name zloc)}) (loc-seq zloc))) (defn insert-vtx [{:keys [current?]} name] (doto (a/insert-vertex! name :font-color "black" :fill-color (if (current? name) "#ec4899" "#a855f7") :perimeter-spacing 1 :spacing-bottom 1 :spacing-left 1 :font-size 20 :font-style 1) (.. getGeometry (setWidth 40)) (.. getGeometry (setHeight 40)))) (defn ->svg [{:as g :keys [vertices edges]}] (a/as-svg (a/with-graph (a/create-graph) (let [vmap (zipmap vertices (map (partial insert-vtx g) vertices))] (doseq [[v1 v2] edges] (a/insert-edge! (vmap v1) (vmap v2) :end-arrow false :rounded true :stroke-width "3" :stroke-color "#7c3aed")))))) (def zipper? (every-pred vector? (comp #{2} count) (comp map? first) (comp (some-fn nil? :changed? :ppath :pnodes) second))) (def zip-location-viewer {:transform-fn (comp nextjournal.clerk.viewer/html (v/update-val #(-> % ->graph ->svg))) :pred zipper?}) (def zip-reel-viewer {:pred (every-pred zipper? (comp :cut? meta)) :transform-fn (comp v/mark-presented (v/update-val (comp #(mapv (comp ->svg ->graph) %) :frames meta))) :render-fn '(fn [frames] (let [!state (nextjournal.clerk.render.hooks/use-state {:reel? false :idx 0 :tmr nil}) frame-count (count frames)] (let [{:keys [reel? idx tmr]} @!state] (cond (and reel? (not tmr)) (swap! !state assoc :tmr (js/setInterval (fn [_] (swap! !state update :idx (comp #(mod % frame-count) inc))) 500)) (and (not reel?) tmr) (do (js/clearInterval tmr) (swap! !state assoc :tmr nil :idx 0))) [:div.flex.items-left [:div.flex.mr-5 {:style {:font-size "1.5rem"}} [:div.cursor-pointer {:on-click #(swap! !state update :reel? not)} ({true "⏹" false "▶️"} reel?)]] [nextjournal.clerk.viewer/html (frames (if reel? idx (dec frame-count)))]])))}) (defn reset-reel [zloc] (vary-meta zloc assoc :frames [] :cut? false)) (defn add-frame [zloc] (vary-meta zloc update :frames (fnil conj []) zloc)) (defn cut [zloc] (vary-meta zloc assoc :cut? true)) (defmacro zmov-> [subj & ops] (list* '-> subj `reset-reel `add-frame (concat (interpose `add-frame ops) [`add-frame `cut]))) (clerk/add-viewers! [zip-reel-viewer zip-location-viewer])) {::clerk/visibility {:code :show :result :hide}} (def ->zip (partial zip/zipper map? :content #(assoc %1 :content %2))) (defn ->node [name] {:name name}) {::clerk/visibility {:result :show}} ;; In code cells below, you may read `zmov->` as clojure's own threading macro: ;; the resulting values are the same while metadata is being varied to contain intermediate "frames". (def tree (zmov-> (->zip (->node 'a)) (zip/append-child (->node 'b)) (zip/append-child (->node 'c)) zip/down zip/right (zip/append-child (->node 'd)) (zip/append-child (->node 'e)) (zip/append-child (->node 'f)) zip/up)) ;; So given a location (def loc (zmov-> tree zip/down zip/right zip/down zip/right zip/right)) ;; we'd go up, edit and go back down (zmov-> loc zip/up (zip/edit assoc :name "☹︎︎") zip/down) ;; losing the position we had. This is the scenario pictured by the author: ;; > When an algorithm has frequent operations which necessitate going up in the tree, ;;and down again at the same position, it is a loss of time (and space, and garbage collecting time, etc) ;;to close the sections in the meantime. It may be advantageous ;;to leave “scars” in the structure allowing direct access to the memorized visited ;;positions. Thus we replace the (non-empty) sections by triples memorizing a tree ;;and its siblings: ;; _ * * The Zipper * * J. Functional Programming 1 ( 1 ): 1–000 , January 1993 _ ;; Let 's now stick to the rules : reuse Clojure 's own data structures while adding a " memorized " functionality . ;; A Scar is a seq that remembers who's left and right of a given point (deftype Scar [left node right] Seqable (seq [_] (concat left (cons node right)))) ;; and we're plugging it in the original up and down function definitions: ^{::clerk/visibility {:code :hide :result :hide}} (.addMethod ^clojure.lang.MultiFn print-method Scar (get-method print-method clojure.lang.ISeq)) (defn zip-up-memo [[node path :as loc]] (let [{:keys [pnodes ppath l r]} path] (when pnodes (with-meta [(zip/make-node loc (peek pnodes) (->Scar l node r)) (when ppath (assoc ppath :changed? true))] (meta loc))))) (defn zip-down-memo [[node path :as loc]] (when (zip/branch? loc) (let [children (zip/children loc)] (with-meta [(.node children) {:l (.-left children) :ppath path :pnodes (if path (conj (:pnodes path) node)) :r (.-right children)}] (meta loc))))) ;; so now we can go up, edit, go back at the previous location (zmov-> loc zip-up-memo (zip/edit assoc :name "☻") zip-down-memo) ;; same works with repeated applications of memo movements (zmov-> loc zip-up-memo zip-up-memo (zip/edit assoc :name "☻") zip-down-memo zip-down-memo) ;; up and down memo is compatible with other zipper operations (zmov-> loc zip-up-memo (zip/insert-left (->node '▶)) (zip/insert-right (->node '◀)) zip-down-memo) ;; or move away from the remembered position, go back to it, go back memo (zmov-> loc zip-up-memo zip/left zip/right zip-down-memo) ;; let's get a final crazy reel. (zmov-> (->node 'a) ->zip (zip/append-child (->node 'b)) (zip/append-child (->node 'c)) zip/down (zip/edit update :name str/capitalize) zip/right (zip/append-child (->node 'd)) (zip/append-child (->node 'e)) (zip/insert-child (->node 'f)) zip/down (zip/insert-child (->node 'g)) (zip/insert-child (->node 'h)) zip/down zip/right zip/remove zip/remove zip/remove) ^{::clerk/visibility {:result :hide}} (comment (clerk/clear-cache!) (macroexpand '(zmov-> tree zip/up zip/down)) *e)
null
https://raw.githubusercontent.com/nextjournal/clerk-demo/e004b275b98f677d30724b234285da22c16980fa/notebooks/zipper_with_scars.clj
clojure
_Building scars into clojure zipper library to go up and back down at the previous location._ I recently stumbled into a parsing scenario where a stream of tokens is folded onto a zipper. Some of these tokens would just push a new child at the current location while others would also need to vary the shape some ancestor node. Now the issue with `clojure.zip/up` followed Can we build a function to actually _go back_ to the previous lower location without say, storing some left offset while going up or using a non-core zipper library? the [original zipper paper](/~huet/PUBLIC/zip.pdf) has a memo-version of the up and down functions. Let's use Clerk viewers to illustrate how they work. Admittedly, the story with scars is just an excuse to test some animated zipper viewers in Clerk. To that end some machinery follows, unfold at your own peril. In code cells below, you may read `zmov->` as clojure's own threading macro: the resulting values are the same while metadata is being varied to contain intermediate "frames". So given a location we'd go up, edit and go back down losing the position we had. This is the scenario pictured by the author: > When an algorithm has frequent operations which necessitate going up in the tree, and down again at the same position, it is a loss of time (and space, and garbage collecting time, etc) to close the sections in the meantime. It may be advantageous to leave “scars” in the structure allowing direct access to the memorized visited positions. Thus we replace the (non-empty) sections by triples memorizing a tree and its siblings: A Scar is a seq that remembers who's left and right of a given point and we're plugging it in the original up and down function definitions: so now we can go up, edit, go back at the previous location same works with repeated applications of memo movements up and down memo is compatible with other zipper operations or move away from the remembered position, go back to it, go back memo let's get a final crazy reel.
# Clojure Zippers with Scars à la (ns zipper-with-scars {:nextjournal.clerk/visibility {:code :fold} :nextjournal.clerk/no-cache true} (:require [clojure.zip :as zip] [arrowic.core :as a] [nextjournal.clerk :as clerk] [nextjournal.clerk.viewer :as v] [clojure.string :as str]) (:import (clojure.lang Seqable))) by a ` clojure.zip/down ` is that it goes back to _ the first _ ( or leftmost ) of the child nodes . Mr. to the rescue here ! It turns out ^{::clerk/visibility {:result :hide}} (do (defn loc-seq [zloc] this sorts nodes so that children seqs are displayed in the correct order by (try (doall (concat (reverse (take-while some? (next (iterate zip/prev zloc)))) (cons zloc (take-while (complement zip/end?) (next (iterate zip/next zloc)))))) (catch Throwable e (throw (ex-info "Cant seq at loc" {:zloc zloc} e))))) (def ->name (comp :name zip/node)) (defn pnode [zloc] (some-> zloc (get 1) :pnodes peek)) (def empty-graph {:vertices #{} :edges []}) (defn add-v [g zloc] (update g :vertices conj (->name zloc))) (defn add-e [g zloc] (let [parent-name (-> zloc pnode :name)] (cond-> g parent-name (update :edges conj [parent-name (-> zloc zip/node :name)])))) (defn ->graph [zloc] (reduce #(-> %1 (add-e %2) (add-v %2)) (assoc empty-graph :current? #{(->name zloc)}) (loc-seq zloc))) (defn insert-vtx [{:keys [current?]} name] (doto (a/insert-vertex! name :font-color "black" :fill-color (if (current? name) "#ec4899" "#a855f7") :perimeter-spacing 1 :spacing-bottom 1 :spacing-left 1 :font-size 20 :font-style 1) (.. getGeometry (setWidth 40)) (.. getGeometry (setHeight 40)))) (defn ->svg [{:as g :keys [vertices edges]}] (a/as-svg (a/with-graph (a/create-graph) (let [vmap (zipmap vertices (map (partial insert-vtx g) vertices))] (doseq [[v1 v2] edges] (a/insert-edge! (vmap v1) (vmap v2) :end-arrow false :rounded true :stroke-width "3" :stroke-color "#7c3aed")))))) (def zipper? (every-pred vector? (comp #{2} count) (comp map? first) (comp (some-fn nil? :changed? :ppath :pnodes) second))) (def zip-location-viewer {:transform-fn (comp nextjournal.clerk.viewer/html (v/update-val #(-> % ->graph ->svg))) :pred zipper?}) (def zip-reel-viewer {:pred (every-pred zipper? (comp :cut? meta)) :transform-fn (comp v/mark-presented (v/update-val (comp #(mapv (comp ->svg ->graph) %) :frames meta))) :render-fn '(fn [frames] (let [!state (nextjournal.clerk.render.hooks/use-state {:reel? false :idx 0 :tmr nil}) frame-count (count frames)] (let [{:keys [reel? idx tmr]} @!state] (cond (and reel? (not tmr)) (swap! !state assoc :tmr (js/setInterval (fn [_] (swap! !state update :idx (comp #(mod % frame-count) inc))) 500)) (and (not reel?) tmr) (do (js/clearInterval tmr) (swap! !state assoc :tmr nil :idx 0))) [:div.flex.items-left [:div.flex.mr-5 {:style {:font-size "1.5rem"}} [:div.cursor-pointer {:on-click #(swap! !state update :reel? not)} ({true "⏹" false "▶️"} reel?)]] [nextjournal.clerk.viewer/html (frames (if reel? idx (dec frame-count)))]])))}) (defn reset-reel [zloc] (vary-meta zloc assoc :frames [] :cut? false)) (defn add-frame [zloc] (vary-meta zloc update :frames (fnil conj []) zloc)) (defn cut [zloc] (vary-meta zloc assoc :cut? true)) (defmacro zmov-> [subj & ops] (list* '-> subj `reset-reel `add-frame (concat (interpose `add-frame ops) [`add-frame `cut]))) (clerk/add-viewers! [zip-reel-viewer zip-location-viewer])) {::clerk/visibility {:code :show :result :hide}} (def ->zip (partial zip/zipper map? :content #(assoc %1 :content %2))) (defn ->node [name] {:name name}) {::clerk/visibility {:result :show}} (def tree (zmov-> (->zip (->node 'a)) (zip/append-child (->node 'b)) (zip/append-child (->node 'c)) zip/down zip/right (zip/append-child (->node 'd)) (zip/append-child (->node 'e)) (zip/append-child (->node 'f)) zip/up)) (def loc (zmov-> tree zip/down zip/right zip/down zip/right zip/right)) (zmov-> loc zip/up (zip/edit assoc :name "☹︎︎") zip/down) _ * * The Zipper * * J. Functional Programming 1 ( 1 ): 1–000 , January 1993 _ Let 's now stick to the rules : reuse Clojure 's own data structures while adding a " memorized " functionality . (deftype Scar [left node right] Seqable (seq [_] (concat left (cons node right)))) ^{::clerk/visibility {:code :hide :result :hide}} (.addMethod ^clojure.lang.MultiFn print-method Scar (get-method print-method clojure.lang.ISeq)) (defn zip-up-memo [[node path :as loc]] (let [{:keys [pnodes ppath l r]} path] (when pnodes (with-meta [(zip/make-node loc (peek pnodes) (->Scar l node r)) (when ppath (assoc ppath :changed? true))] (meta loc))))) (defn zip-down-memo [[node path :as loc]] (when (zip/branch? loc) (let [children (zip/children loc)] (with-meta [(.node children) {:l (.-left children) :ppath path :pnodes (if path (conj (:pnodes path) node)) :r (.-right children)}] (meta loc))))) (zmov-> loc zip-up-memo (zip/edit assoc :name "☻") zip-down-memo) (zmov-> loc zip-up-memo zip-up-memo (zip/edit assoc :name "☻") zip-down-memo zip-down-memo) (zmov-> loc zip-up-memo (zip/insert-left (->node '▶)) (zip/insert-right (->node '◀)) zip-down-memo) (zmov-> loc zip-up-memo zip/left zip/right zip-down-memo) (zmov-> (->node 'a) ->zip (zip/append-child (->node 'b)) (zip/append-child (->node 'c)) zip/down (zip/edit update :name str/capitalize) zip/right (zip/append-child (->node 'd)) (zip/append-child (->node 'e)) (zip/insert-child (->node 'f)) zip/down (zip/insert-child (->node 'g)) (zip/insert-child (->node 'h)) zip/down zip/right zip/remove zip/remove zip/remove) ^{::clerk/visibility {:result :hide}} (comment (clerk/clear-cache!) (macroexpand '(zmov-> tree zip/up zip/down)) *e)
e4668494aa6b7bc5703f8028abd514483daba11776e02ee789eaf4ed90733836
tsoding/HyperNerd
OrgMode.hs
{-# LANGUAGE OverloadedStrings #-} module OrgMode ( renderTable ) where import Data.List import qualified Data.Text as T charEscapeList :: String charEscapeList = "|" renderTable :: [T.Text] -> [[T.Text]] -> T.Text renderTable header rows = T.unlines ([renderRow header, "|-"] <> map (renderRow . normalizeRow) rows) where normalizeRow row = take (length header) (row ++ repeat "") renderRow :: [T.Text] -> T.Text renderRow columns = "|" <> T.concat (intersperse "|" $ map escapeColumn columns) <> "|" escapeColumn :: T.Text -> T.Text escapeColumn = T.filter $ not . (`elem` charEscapeList)
null
https://raw.githubusercontent.com/tsoding/HyperNerd/5322580483c5c05179bc455a6f94566d398bccdf/src/OrgMode.hs
haskell
# LANGUAGE OverloadedStrings #
module OrgMode ( renderTable ) where import Data.List import qualified Data.Text as T charEscapeList :: String charEscapeList = "|" renderTable :: [T.Text] -> [[T.Text]] -> T.Text renderTable header rows = T.unlines ([renderRow header, "|-"] <> map (renderRow . normalizeRow) rows) where normalizeRow row = take (length header) (row ++ repeat "") renderRow :: [T.Text] -> T.Text renderRow columns = "|" <> T.concat (intersperse "|" $ map escapeColumn columns) <> "|" escapeColumn :: T.Text -> T.Text escapeColumn = T.filter $ not . (`elem` charEscapeList)
ca1acd96f0e809756a1982fe6dfe915a38f447c74945ed4dc69afb6bb0a16675
RichiH/git-annex
Repair.hs
git - annex command - - Copyright 2013 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2013 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Command.Repair where import Command import qualified Annex import qualified Git.Repair import qualified Annex.Branch import qualified Git.Ref import Git.Types import Annex.Version cmd :: Command cmd = noCommit $ dontCheck repoExists $ command "repair" SectionMaintenance "recover broken git repository" paramNothing (withParams seek) seek :: CmdParams -> CommandSeek seek = withNothing start start :: CommandStart start = next $ next $ runRepair =<< Annex.getState Annex.force runRepair :: Bool -> Annex Bool runRepair forced = do (ok, modifiedbranches) <- inRepo $ Git.Repair.runRepair isAnnexSyncBranch forced -- This command can be run in git repos not using git-annex, -- so avoid git annex branch stuff in that case. whenM (isJust <$> getVersion) $ repairAnnexBranch modifiedbranches return ok After git repository repair , the .git / annex / index file could - still be broken , by pointing to bad objects , or might just be corrupt on - its own . Since this index file is not used to stage things - for long durations of time , it can safely be deleted if it is broken . - - Otherwise , if the git - annex branch was modified by the repair , - commit the index file to the git - annex branch . - This way , if the git - annex branch got rewound to an old version by - the repository repair , or was completely deleted , this will get it back - to a good state . Note that in the unlikely case where the git - annex - branch was rewound to a state that , had new changes from elsewhere not - yet reflected in the index , this does properly merge those into the - index before committing . - still be broken, by pointing to bad objects, or might just be corrupt on - its own. Since this index file is not used to stage things - for long durations of time, it can safely be deleted if it is broken. - - Otherwise, if the git-annex branch was modified by the repair, - commit the index file to the git-annex branch. - This way, if the git-annex branch got rewound to an old version by - the repository repair, or was completely deleted, this will get it back - to a good state. Note that in the unlikely case where the git-annex - branch was rewound to a state that, had new changes from elsewhere not - yet reflected in the index, this does properly merge those into the - index before committing. -} repairAnnexBranch :: [Branch] -> Annex () repairAnnexBranch modifiedbranches | Annex.Branch.fullname `elem` modifiedbranches = ifM okindex ( commitindex , do nukeindex missingbranch ) | otherwise = ifM okindex ( noop , do nukeindex ifM (null <$> inRepo (Git.Ref.matching [Annex.Branch.fullname])) ( missingbranch , liftIO $ putStrLn "No data was lost." ) ) where okindex = Annex.Branch.withIndex $ inRepo Git.Repair.checkIndex commitindex = do Annex.Branch.forceCommit "committing index after git repository repair" liftIO $ putStrLn "Successfully recovered the git-annex branch using .git/annex/index" nukeindex = do inRepo $ nukeFile . gitAnnexIndex liftIO $ putStrLn "Had to delete the .git/annex/index file as it was corrupt." missingbranch = liftIO $ putStrLn "Since the git-annex branch is not up-to-date anymore. It would be a very good idea to run: git annex fsck --fast" trackingOrSyncBranch :: Ref -> Bool trackingOrSyncBranch b = Git.Repair.isTrackingBranch b || isAnnexSyncBranch b isAnnexSyncBranch :: Ref -> Bool isAnnexSyncBranch b = "refs/synced/" `isPrefixOf` fromRef b
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Command/Repair.hs
haskell
This command can be run in git repos not using git-annex, so avoid git annex branch stuff in that case.
git - annex command - - Copyright 2013 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2013 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Command.Repair where import Command import qualified Annex import qualified Git.Repair import qualified Annex.Branch import qualified Git.Ref import Git.Types import Annex.Version cmd :: Command cmd = noCommit $ dontCheck repoExists $ command "repair" SectionMaintenance "recover broken git repository" paramNothing (withParams seek) seek :: CmdParams -> CommandSeek seek = withNothing start start :: CommandStart start = next $ next $ runRepair =<< Annex.getState Annex.force runRepair :: Bool -> Annex Bool runRepair forced = do (ok, modifiedbranches) <- inRepo $ Git.Repair.runRepair isAnnexSyncBranch forced whenM (isJust <$> getVersion) $ repairAnnexBranch modifiedbranches return ok After git repository repair , the .git / annex / index file could - still be broken , by pointing to bad objects , or might just be corrupt on - its own . Since this index file is not used to stage things - for long durations of time , it can safely be deleted if it is broken . - - Otherwise , if the git - annex branch was modified by the repair , - commit the index file to the git - annex branch . - This way , if the git - annex branch got rewound to an old version by - the repository repair , or was completely deleted , this will get it back - to a good state . Note that in the unlikely case where the git - annex - branch was rewound to a state that , had new changes from elsewhere not - yet reflected in the index , this does properly merge those into the - index before committing . - still be broken, by pointing to bad objects, or might just be corrupt on - its own. Since this index file is not used to stage things - for long durations of time, it can safely be deleted if it is broken. - - Otherwise, if the git-annex branch was modified by the repair, - commit the index file to the git-annex branch. - This way, if the git-annex branch got rewound to an old version by - the repository repair, or was completely deleted, this will get it back - to a good state. Note that in the unlikely case where the git-annex - branch was rewound to a state that, had new changes from elsewhere not - yet reflected in the index, this does properly merge those into the - index before committing. -} repairAnnexBranch :: [Branch] -> Annex () repairAnnexBranch modifiedbranches | Annex.Branch.fullname `elem` modifiedbranches = ifM okindex ( commitindex , do nukeindex missingbranch ) | otherwise = ifM okindex ( noop , do nukeindex ifM (null <$> inRepo (Git.Ref.matching [Annex.Branch.fullname])) ( missingbranch , liftIO $ putStrLn "No data was lost." ) ) where okindex = Annex.Branch.withIndex $ inRepo Git.Repair.checkIndex commitindex = do Annex.Branch.forceCommit "committing index after git repository repair" liftIO $ putStrLn "Successfully recovered the git-annex branch using .git/annex/index" nukeindex = do inRepo $ nukeFile . gitAnnexIndex liftIO $ putStrLn "Had to delete the .git/annex/index file as it was corrupt." missingbranch = liftIO $ putStrLn "Since the git-annex branch is not up-to-date anymore. It would be a very good idea to run: git annex fsck --fast" trackingOrSyncBranch :: Ref -> Bool trackingOrSyncBranch b = Git.Repair.isTrackingBranch b || isAnnexSyncBranch b isAnnexSyncBranch :: Ref -> Bool isAnnexSyncBranch b = "refs/synced/" `isPrefixOf` fromRef b
0195683ac9b58b6c02ddd6504ed3efef98495631d35e78faac83c1ea66002500
let-def/menhir
parserAux.ml
(**************************************************************************) (* *) Menhir (* *) , INRIA Rocquencourt , PPS , Université Paris Diderot (* *) Copyright 2005 - 2008 Institut National de Recherche en Informatique (* et en Automatique. All rights reserved. This file is distributed *) under the terms of the Q Public License version 1.0 , with the change (* described in file LICENSE. *) (* *) (**************************************************************************) open Positions open Syntax let current_token_precedence = let c = ref 0 in fun pos1 pos2 -> incr c; PrecedenceLevel (Error.get_filemark (), !c, pos1, pos2) let current_reduce_precedence = let c = ref 0 in fun () -> incr c; PrecedenceLevel (Error.get_filemark (), !c, Lexing.dummy_pos, Lexing.dummy_pos) module IdSet = Set.Make (struct type t = identifier located let compare id1 id2 = compare (value id1) (value id2) end) let defined_identifiers ((ido, _) : producer) accu = Option.fold IdSet.add ido accu let defined_identifiers (producers : producer list) = List.fold_right defined_identifiers producers IdSet.empty let check_production_group right_hand_sides pos1 pos2 action = begin match right_hand_sides with | [] -> assert false | ((producers : producer list), _, _, _) :: right_hand_sides -> let ids = defined_identifiers producers in List.iter (fun (producers, _, _, _) -> let ids' = defined_identifiers producers in try let id = IdSet.choose (IdSet.union (IdSet.diff ids ids') (IdSet.diff ids' ids)) in Error.error [Positions.position id] "Two productions that share a semantic action must define\n\ exactly the same identifiers." with Not_found -> () ) right_hand_sides end; begin if List.length right_hand_sides > 1 && Action.use_dollar action then Error.signal (Positions.two pos1 pos2) "A semantic action that is shared between several productions must\n\ not use the $i notation -- semantic values must be named instead." end let override pos o1 o2 = match o1, o2 with | Some _, Some _ -> Error.signal [ pos ] "This production carries two %prec declarations."; o2 | None, Some _ -> o2 | _, None -> o1
null
https://raw.githubusercontent.com/let-def/menhir/e8ba7bef219acd355798072c42abbd11335ecf09/src/parserAux.ml
ocaml
************************************************************************ et en Automatique. All rights reserved. This file is distributed described in file LICENSE. ************************************************************************
Menhir , INRIA Rocquencourt , PPS , Université Paris Diderot Copyright 2005 - 2008 Institut National de Recherche en Informatique under the terms of the Q Public License version 1.0 , with the change open Positions open Syntax let current_token_precedence = let c = ref 0 in fun pos1 pos2 -> incr c; PrecedenceLevel (Error.get_filemark (), !c, pos1, pos2) let current_reduce_precedence = let c = ref 0 in fun () -> incr c; PrecedenceLevel (Error.get_filemark (), !c, Lexing.dummy_pos, Lexing.dummy_pos) module IdSet = Set.Make (struct type t = identifier located let compare id1 id2 = compare (value id1) (value id2) end) let defined_identifiers ((ido, _) : producer) accu = Option.fold IdSet.add ido accu let defined_identifiers (producers : producer list) = List.fold_right defined_identifiers producers IdSet.empty let check_production_group right_hand_sides pos1 pos2 action = begin match right_hand_sides with | [] -> assert false | ((producers : producer list), _, _, _) :: right_hand_sides -> let ids = defined_identifiers producers in List.iter (fun (producers, _, _, _) -> let ids' = defined_identifiers producers in try let id = IdSet.choose (IdSet.union (IdSet.diff ids ids') (IdSet.diff ids' ids)) in Error.error [Positions.position id] "Two productions that share a semantic action must define\n\ exactly the same identifiers." with Not_found -> () ) right_hand_sides end; begin if List.length right_hand_sides > 1 && Action.use_dollar action then Error.signal (Positions.two pos1 pos2) "A semantic action that is shared between several productions must\n\ not use the $i notation -- semantic values must be named instead." end let override pos o1 o2 = match o1, o2 with | Some _, Some _ -> Error.signal [ pos ] "This production carries two %prec declarations."; o2 | None, Some _ -> o2 | _, None -> o1
3c119384b7a0874a7247cd5a5d25581bd11b4c9e57b881184f05dea027849068
juspay/atlas
DriverQuote.hs
# LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE QuasiQuotes # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # OPTIONS_GHC -Wno - orphans # | Copyright 2022 Juspay Technologies Pvt 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 : Storage . Tabular . DriverQuote Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt 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 : Storage.Tabular.DriverQuote Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Storage.Tabular.DriverQuote where import Beckn.Prelude import Beckn.Storage.Esqueleto import Beckn.Types.Common (Meters (..), Seconds (..)) import Beckn.Types.Id import qualified Domain.Types.DriverQuote as Domain import qualified Domain.Types.Vehicle.Variant as Variant import Storage.Tabular.Person (PersonTId) import qualified Storage.Tabular.SearchRequest as SReq derivePersistField "Domain.DriverQuoteStatus" derivePersistField "Variant.Variant" mkPersist defaultSqlSettings [defaultQQ| DriverQuoteT sql=driver_quote id Text status Domain.DriverQuoteStatus searchRequestId SReq.SearchRequestTId driverId PersonTId baseFare Double extraFareSelected Double Maybe vehicleVariant Variant.Variant distanceToPickup Int durationToPickup Double validTill UTCTime createdAt UTCTime updatedAt UTCTime Primary id deriving Generic |] instance TEntityKey DriverQuoteT where type DomainKey DriverQuoteT = Id Domain.DriverQuote fromKey (DriverQuoteTKey _id) = Id _id toKey (Id id) = DriverQuoteTKey id instance TEntity DriverQuoteT Domain.DriverQuote where fromTEntity entity = do let DriverQuoteT {..} = entityVal entity return $ Domain.DriverQuote { id = Id id, searchRequestId = fromKey searchRequestId, driverId = fromKey driverId, distanceToPickup = Meters distanceToPickup, durationToPickup = Seconds $ floor durationToPickup, .. } toTType Domain.DriverQuote {..} = DriverQuoteT { id = getId id, searchRequestId = toKey searchRequestId, driverId = toKey driverId, distanceToPickup = getMeters distanceToPickup, durationToPickup = fromIntegral $ getSeconds durationToPickup, .. } toTEntity a = Entity (toKey a.id) $ toTType a
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/driver-offer-bpp/src/Storage/Tabular/DriverQuote.hs
haskell
# LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE QuasiQuotes # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # OPTIONS_GHC -Wno - orphans # | Copyright 2022 Juspay Technologies Pvt 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 : Storage . Tabular . DriverQuote Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt 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 : Storage.Tabular.DriverQuote Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Storage.Tabular.DriverQuote where import Beckn.Prelude import Beckn.Storage.Esqueleto import Beckn.Types.Common (Meters (..), Seconds (..)) import Beckn.Types.Id import qualified Domain.Types.DriverQuote as Domain import qualified Domain.Types.Vehicle.Variant as Variant import Storage.Tabular.Person (PersonTId) import qualified Storage.Tabular.SearchRequest as SReq derivePersistField "Domain.DriverQuoteStatus" derivePersistField "Variant.Variant" mkPersist defaultSqlSettings [defaultQQ| DriverQuoteT sql=driver_quote id Text status Domain.DriverQuoteStatus searchRequestId SReq.SearchRequestTId driverId PersonTId baseFare Double extraFareSelected Double Maybe vehicleVariant Variant.Variant distanceToPickup Int durationToPickup Double validTill UTCTime createdAt UTCTime updatedAt UTCTime Primary id deriving Generic |] instance TEntityKey DriverQuoteT where type DomainKey DriverQuoteT = Id Domain.DriverQuote fromKey (DriverQuoteTKey _id) = Id _id toKey (Id id) = DriverQuoteTKey id instance TEntity DriverQuoteT Domain.DriverQuote where fromTEntity entity = do let DriverQuoteT {..} = entityVal entity return $ Domain.DriverQuote { id = Id id, searchRequestId = fromKey searchRequestId, driverId = fromKey driverId, distanceToPickup = Meters distanceToPickup, durationToPickup = Seconds $ floor durationToPickup, .. } toTType Domain.DriverQuote {..} = DriverQuoteT { id = getId id, searchRequestId = toKey searchRequestId, driverId = toKey driverId, distanceToPickup = getMeters distanceToPickup, durationToPickup = fromIntegral $ getSeconds durationToPickup, .. } toTEntity a = Entity (toKey a.id) $ toTType a
c406e90f555add0856d8dde668bbd19cb423fd73b0d4322ce4d58adfacd75006
hyperfiddle/electric
binding_flat.cljc
(ns contrib.clojurex ;(:refer-clojure :exclude [binding]) (:require [hyperfiddle.rcf :refer [tests]]) #?(:cljs (:require-macros [contrib.clojurex :refer [binding-pyramid]]))) (defn binding-pyramid* [bindings body] (let [[s expr & xs] bindings] (if (seq xs) ; don't qualify - for Photon CLJS compatibility ? `(~'binding [~s ~expr] ~(binding-pyramid* xs body)) `(~'binding [~s ~expr] ~@body)))) (defmacro binding-pyramid [bindings & body] (binding-pyramid* bindings body)) (tests (macroexpand-1 '(binding-pyramid [a 1 b (inc a)] (inc b)))” := '(binding [a 1] (binding [b (inc a)] (inc b))) (def ^:dynamic a) (def ^:dynamic b) (binding-pyramid [a 1 b (inc a)] (inc b)) := 3) (ns dustin.y2022.binding2 (:require [clojure.walk :refer [macroexpand-all]] [hyperfiddle.rcf :refer [tests]])) (comment (defmacro binding2 [bindings & body] (loop [[[s expr :as x] & xs] (partition 2 bindings)] `(binding [~s ~expr] ~(if (seq xs) (recur xs) ~@body))))) (defmacro binding2 [bindings & body] (let [[s expr & xs] bindings] `(binding [~s ~expr] ~(if (seq xs) `(binding2 ~xs ~@body) `(do ~@body))))) (defmacro binding2 [bindings & body] (let [[s expr & xs] bindings] (if (seq xs) `(binding [~s ~expr] (binding2 ~xs ~@body)) `(binding [~s ~expr] ~@body)))) (defmacro binding2 [bindings & body] (let [[s expr & xs] bindings] (if (seq xs) `(binding [~s ~expr] ~`(binding2 ~xs ~@body)) `(binding [~s ~expr] ~@body)))) (defn binding2* [bindings body] (let [[s expr & xs] bindings] (if (seq xs) `(binding [~s ~expr] ~(binding2* xs body)) `(binding [~s ~expr] ~@body)))) (defmacro binding2 [bindings & body] (binding2* bindings body)) (tests (macroexpand-1 '(binding2 [a 1 b (inc a)] (inc b))) := '(binding [a 1] (binding [b (inc a)] (inc b))) (def ^:dynamic a) (def ^:dynamic b) (binding2 [a 1 b (inc a)] (inc b)) := 3 ) (comment `(do ~`a) )
null
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2022/binding_flat.cljc
clojure
(:refer-clojure :exclude [binding]) don't qualify - for Photon CLJS compatibility ?
(ns contrib.clojurex (:require [hyperfiddle.rcf :refer [tests]]) #?(:cljs (:require-macros [contrib.clojurex :refer [binding-pyramid]]))) (defn binding-pyramid* [bindings body] (let [[s expr & xs] bindings] (if (seq xs) `(~'binding [~s ~expr] ~(binding-pyramid* xs body)) `(~'binding [~s ~expr] ~@body)))) (defmacro binding-pyramid [bindings & body] (binding-pyramid* bindings body)) (tests (macroexpand-1 '(binding-pyramid [a 1 b (inc a)] (inc b)))” := '(binding [a 1] (binding [b (inc a)] (inc b))) (def ^:dynamic a) (def ^:dynamic b) (binding-pyramid [a 1 b (inc a)] (inc b)) := 3) (ns dustin.y2022.binding2 (:require [clojure.walk :refer [macroexpand-all]] [hyperfiddle.rcf :refer [tests]])) (comment (defmacro binding2 [bindings & body] (loop [[[s expr :as x] & xs] (partition 2 bindings)] `(binding [~s ~expr] ~(if (seq xs) (recur xs) ~@body))))) (defmacro binding2 [bindings & body] (let [[s expr & xs] bindings] `(binding [~s ~expr] ~(if (seq xs) `(binding2 ~xs ~@body) `(do ~@body))))) (defmacro binding2 [bindings & body] (let [[s expr & xs] bindings] (if (seq xs) `(binding [~s ~expr] (binding2 ~xs ~@body)) `(binding [~s ~expr] ~@body)))) (defmacro binding2 [bindings & body] (let [[s expr & xs] bindings] (if (seq xs) `(binding [~s ~expr] ~`(binding2 ~xs ~@body)) `(binding [~s ~expr] ~@body)))) (defn binding2* [bindings body] (let [[s expr & xs] bindings] (if (seq xs) `(binding [~s ~expr] ~(binding2* xs body)) `(binding [~s ~expr] ~@body)))) (defmacro binding2 [bindings & body] (binding2* bindings body)) (tests (macroexpand-1 '(binding2 [a 1 b (inc a)] (inc b))) := '(binding [a 1] (binding [b (inc a)] (inc b))) (def ^:dynamic a) (def ^:dynamic b) (binding2 [a 1 b (inc a)] (inc b)) := 3 ) (comment `(do ~`a) )
96f1390448bce17242001aa74ca4dbd5127ef1fa316ce3ebfde6aaabed40488f
jordillonch/eggs
example_game_world.erl
%% eggs (Erlang Generic Game Server) %% Copyright ( C ) 2012 - 2013 < llonch.jordi at gmail dot com > %% %% This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the %% License, or (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU Affero General Public License for more details. %% You should have received a copy of the GNU Affero General Public License %% along with this program. If not, see </>. -module(example_game_world). -behaviour(eggs_world_simple_area). %% API -export([initialize/1, destroy/1]). -export([frozen/2, running/2, run/1, froze/1, stop/1]). -export([get/2, set/2, set/3, entity_add/3, entity_remove/2, entity_move/3, entity_add_handler/3, entity_remove_handler/3, get_entities_list/1]). -spec initialize({_,_}) -> {'ok',_}. initialize({GameServerPid, WorldSupPid}) -> AreaSpecs = [{x, 0}, {y, 0}, {width, 1000}, {height, 1000}], {ok, WorldEntity} = eggs_world_simple_area:initialize({GameServerPid, WorldSupPid, ?MODULE, AreaSpecs}), {ok, WorldEntity}. -spec destroy(_) -> any(). destroy(World) -> eggs_world_simple_area:destroy(World). -spec run(_) -> any(). run(World) -> eggs_world_simple_area:run(World). -spec froze(_) -> any(). froze(World) -> eggs_world_simple_area:froze(World). -spec frozen({_,_},_) -> {'next_state','frozen',_}. frozen({_Event, _Message}, World) -> {next_state, frozen, World}. -spec running({_,_},_) -> {'next_state','running',_}. running({_Event, _Message}, World) -> {next_state, running, World}. %% entity -spec get(_,_) -> any(). get(World, Property) -> eggs_world_simple_area:get(World, Property). -spec set(_,_) -> any(). set(World, Values) -> eggs_world_simple_area:set(World, Values). -spec set(_,_,_) -> any(). set(World, Property, Value) -> eggs_world_simple_area:set(World, Property, Value). -spec entity_add(_,_,_) -> any(). entity_add(World, Entity, Coords) -> eggs_world_simple_area:entity_add(World, Entity, Coords). -spec entity_remove(_,_) -> any(). entity_remove(World, Entity) -> eggs_world_simple_area:entity_remove(World, Entity). -spec entity_move(_,_,_) -> any(). entity_move(World, Entity, Coords) -> eggs_world_simple_area:entity_move(World, Entity, Coords). -spec entity_add_handler(_,_,_) -> any(). entity_add_handler(World, Entity, Handler) -> eggs_world_simple_area:entity_add_handler(World, Entity, Handler). -spec entity_remove_handler(_,_,_) -> any(). entity_remove_handler(World, Entity, Handler) -> eggs_world_simple_area:entity_remove_handler(World, Entity, Handler). -spec get_entities_list(_) -> any(). get_entities_list(World) -> eggs_world_simple_area:get_entities_list(World). -spec stop(_) -> 'ok'. stop(_World) -> ok. %% %% API -export([initialize/1 , initialize/2 , is_active/0 , get/2 , set/2 , set/3 , frozen/2 ] ) . %% %% initialize(GameServerPid) -> %% eggs_world:initialize({GameServerPid, ?MODULE}). %% %% %% %% entity %% initialize(_, _) -> initialize(none ) . %% initialize(_) -> %% %% entity WorldEntityInit = eggs_entity : initialize(?MODULE , [ { width , 1000 } , { height , 1000 } , { split_width , 10 } , { split_height , 10 } ] ) , %% %% trait active WorldEntity = eggs_trait_world : initialize(?MODULE , WorldEntityInit , frozen ) , WorldEntity . %% is_active ( ) - > true . %% %% get(World, Property) -> %% eggs_entity:base_get(World, Property). %% %% set(World, Values) -> %% eggs_entity:base_set(World, Values). %% set(World, Property, Value) -> %% eggs_entity:base_set(World, Property, Value). %% %% %% trait active handlers %% frozen(Message, World) -> %% lager:debug("World frozen: ~p", [Message]), %% {next_state, frozen, World}.
null
https://raw.githubusercontent.com/jordillonch/eggs/e20ccd5093952ec967458bb2d50d5acf82e69063/apps/eggs_example_game/src/example_game_world.erl
erlang
eggs (Erlang Generic Game Server) This program is free software: you can redistribute it and/or modify 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. along with this program. If not, see </>. API entity %% API initialize(GameServerPid) -> eggs_world:initialize({GameServerPid, ?MODULE}). %% entity initialize(_, _) -> initialize(_) -> %% entity %% trait active get(World, Property) -> eggs_entity:base_get(World, Property). set(World, Values) -> eggs_entity:base_set(World, Values). set(World, Property, Value) -> eggs_entity:base_set(World, Property, Value). %% trait active handlers frozen(Message, World) -> lager:debug("World frozen: ~p", [Message]), {next_state, frozen, World}.
Copyright ( C ) 2012 - 2013 < llonch.jordi at gmail dot com > it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the You should have received a copy of the GNU Affero General Public License -module(example_game_world). -behaviour(eggs_world_simple_area). -export([initialize/1, destroy/1]). -export([frozen/2, running/2, run/1, froze/1, stop/1]). -export([get/2, set/2, set/3, entity_add/3, entity_remove/2, entity_move/3, entity_add_handler/3, entity_remove_handler/3, get_entities_list/1]). -spec initialize({_,_}) -> {'ok',_}. initialize({GameServerPid, WorldSupPid}) -> AreaSpecs = [{x, 0}, {y, 0}, {width, 1000}, {height, 1000}], {ok, WorldEntity} = eggs_world_simple_area:initialize({GameServerPid, WorldSupPid, ?MODULE, AreaSpecs}), {ok, WorldEntity}. -spec destroy(_) -> any(). destroy(World) -> eggs_world_simple_area:destroy(World). -spec run(_) -> any(). run(World) -> eggs_world_simple_area:run(World). -spec froze(_) -> any(). froze(World) -> eggs_world_simple_area:froze(World). -spec frozen({_,_},_) -> {'next_state','frozen',_}. frozen({_Event, _Message}, World) -> {next_state, frozen, World}. -spec running({_,_},_) -> {'next_state','running',_}. running({_Event, _Message}, World) -> {next_state, running, World}. -spec get(_,_) -> any(). get(World, Property) -> eggs_world_simple_area:get(World, Property). -spec set(_,_) -> any(). set(World, Values) -> eggs_world_simple_area:set(World, Values). -spec set(_,_,_) -> any(). set(World, Property, Value) -> eggs_world_simple_area:set(World, Property, Value). -spec entity_add(_,_,_) -> any(). entity_add(World, Entity, Coords) -> eggs_world_simple_area:entity_add(World, Entity, Coords). -spec entity_remove(_,_) -> any(). entity_remove(World, Entity) -> eggs_world_simple_area:entity_remove(World, Entity). -spec entity_move(_,_,_) -> any(). entity_move(World, Entity, Coords) -> eggs_world_simple_area:entity_move(World, Entity, Coords). -spec entity_add_handler(_,_,_) -> any(). entity_add_handler(World, Entity, Handler) -> eggs_world_simple_area:entity_add_handler(World, Entity, Handler). -spec entity_remove_handler(_,_,_) -> any(). entity_remove_handler(World, Entity, Handler) -> eggs_world_simple_area:entity_remove_handler(World, Entity, Handler). -spec get_entities_list(_) -> any(). get_entities_list(World) -> eggs_world_simple_area:get_entities_list(World). -spec stop(_) -> 'ok'. stop(_World) -> ok. -export([initialize/1 , initialize/2 , is_active/0 , get/2 , set/2 , set/3 , frozen/2 ] ) . initialize(none ) . WorldEntityInit = eggs_entity : initialize(?MODULE , [ { width , 1000 } , { height , 1000 } , { split_width , 10 } , { split_height , 10 } ] ) , WorldEntity = eggs_trait_world : initialize(?MODULE , WorldEntityInit , frozen ) , WorldEntity . is_active ( ) - > true .
c31c2d38e2220bc9adec549cc6df419044ccaf1772a99728d200dfbc006ce2b8
brendanhay/amazonka
ImprovementSummary.hs
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . -- | -- Module : Amazonka.WellArchitected.Types.ImprovementSummary Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) module Amazonka.WellArchitected.Types.ImprovementSummary where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude import Amazonka.WellArchitected.Types.ChoiceImprovementPlan import Amazonka.WellArchitected.Types.Risk -- | An improvement summary of a lens review in a workload. -- -- /See:/ 'newImprovementSummary' smart constructor. data ImprovementSummary = ImprovementSummary' { improvementPlanUrl :: Prelude.Maybe Prelude.Text, -- | The improvement plan details. improvementPlans :: Prelude.Maybe [ChoiceImprovementPlan], pillarId :: Prelude.Maybe Prelude.Text, questionId :: Prelude.Maybe Prelude.Text, questionTitle :: Prelude.Maybe Prelude.Text, risk :: Prelude.Maybe Risk } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) -- | -- Create a value of 'ImprovementSummary' with all optional fields omitted. -- Use < -lens generic - lens > or < optics > to modify other optional fields . -- -- The following record fields are available, with the corresponding lenses provided -- for backwards compatibility: -- -- 'improvementPlanUrl', 'improvementSummary_improvementPlanUrl' - Undocumented member. -- ' improvementPlans ' , ' improvementSummary_improvementPlans ' - The improvement plan details . -- -- 'pillarId', 'improvementSummary_pillarId' - Undocumented member. -- -- 'questionId', 'improvementSummary_questionId' - Undocumented member. -- -- 'questionTitle', 'improvementSummary_questionTitle' - Undocumented member. -- -- 'risk', 'improvementSummary_risk' - Undocumented member. newImprovementSummary :: ImprovementSummary newImprovementSummary = ImprovementSummary' { improvementPlanUrl = Prelude.Nothing, improvementPlans = Prelude.Nothing, pillarId = Prelude.Nothing, questionId = Prelude.Nothing, questionTitle = Prelude.Nothing, risk = Prelude.Nothing } -- | Undocumented member. improvementSummary_improvementPlanUrl :: Lens.Lens' ImprovementSummary (Prelude.Maybe Prelude.Text) improvementSummary_improvementPlanUrl = Lens.lens (\ImprovementSummary' {improvementPlanUrl} -> improvementPlanUrl) (\s@ImprovementSummary' {} a -> s {improvementPlanUrl = a} :: ImprovementSummary) -- | The improvement plan details. improvementSummary_improvementPlans :: Lens.Lens' ImprovementSummary (Prelude.Maybe [ChoiceImprovementPlan]) improvementSummary_improvementPlans = Lens.lens (\ImprovementSummary' {improvementPlans} -> improvementPlans) (\s@ImprovementSummary' {} a -> s {improvementPlans = a} :: ImprovementSummary) Prelude.. Lens.mapping Lens.coerced -- | Undocumented member. improvementSummary_pillarId :: Lens.Lens' ImprovementSummary (Prelude.Maybe Prelude.Text) improvementSummary_pillarId = Lens.lens (\ImprovementSummary' {pillarId} -> pillarId) (\s@ImprovementSummary' {} a -> s {pillarId = a} :: ImprovementSummary) -- | Undocumented member. improvementSummary_questionId :: Lens.Lens' ImprovementSummary (Prelude.Maybe Prelude.Text) improvementSummary_questionId = Lens.lens (\ImprovementSummary' {questionId} -> questionId) (\s@ImprovementSummary' {} a -> s {questionId = a} :: ImprovementSummary) -- | Undocumented member. improvementSummary_questionTitle :: Lens.Lens' ImprovementSummary (Prelude.Maybe Prelude.Text) improvementSummary_questionTitle = Lens.lens (\ImprovementSummary' {questionTitle} -> questionTitle) (\s@ImprovementSummary' {} a -> s {questionTitle = a} :: ImprovementSummary) -- | Undocumented member. improvementSummary_risk :: Lens.Lens' ImprovementSummary (Prelude.Maybe Risk) improvementSummary_risk = Lens.lens (\ImprovementSummary' {risk} -> risk) (\s@ImprovementSummary' {} a -> s {risk = a} :: ImprovementSummary) instance Data.FromJSON ImprovementSummary where parseJSON = Data.withObject "ImprovementSummary" ( \x -> ImprovementSummary' Prelude.<$> (x Data..:? "ImprovementPlanUrl") Prelude.<*> ( x Data..:? "ImprovementPlans" Data..!= Prelude.mempty ) Prelude.<*> (x Data..:? "PillarId") Prelude.<*> (x Data..:? "QuestionId") Prelude.<*> (x Data..:? "QuestionTitle") Prelude.<*> (x Data..:? "Risk") ) instance Prelude.Hashable ImprovementSummary where hashWithSalt _salt ImprovementSummary' {..} = _salt `Prelude.hashWithSalt` improvementPlanUrl `Prelude.hashWithSalt` improvementPlans `Prelude.hashWithSalt` pillarId `Prelude.hashWithSalt` questionId `Prelude.hashWithSalt` questionTitle `Prelude.hashWithSalt` risk instance Prelude.NFData ImprovementSummary where rnf ImprovementSummary' {..} = Prelude.rnf improvementPlanUrl `Prelude.seq` Prelude.rnf improvementPlans `Prelude.seq` Prelude.rnf pillarId `Prelude.seq` Prelude.rnf questionId `Prelude.seq` Prelude.rnf questionTitle `Prelude.seq` Prelude.rnf risk
null
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-wellarchitected/gen/Amazonka/WellArchitected/Types/ImprovementSummary.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Module : Amazonka.WellArchitected.Types.ImprovementSummary Stability : auto-generated | An improvement summary of a lens review in a workload. /See:/ 'newImprovementSummary' smart constructor. | The improvement plan details. | Create a value of 'ImprovementSummary' with all optional fields omitted. The following record fields are available, with the corresponding lenses provided for backwards compatibility: 'improvementPlanUrl', 'improvementSummary_improvementPlanUrl' - Undocumented member. 'pillarId', 'improvementSummary_pillarId' - Undocumented member. 'questionId', 'improvementSummary_questionId' - Undocumented member. 'questionTitle', 'improvementSummary_questionTitle' - Undocumented member. 'risk', 'improvementSummary_risk' - Undocumented member. | Undocumented member. | The improvement plan details. | Undocumented member. | Undocumented member. | Undocumented member. | Undocumented member.
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Amazonka.WellArchitected.Types.ImprovementSummary where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude import Amazonka.WellArchitected.Types.ChoiceImprovementPlan import Amazonka.WellArchitected.Types.Risk data ImprovementSummary = ImprovementSummary' { improvementPlanUrl :: Prelude.Maybe Prelude.Text, improvementPlans :: Prelude.Maybe [ChoiceImprovementPlan], pillarId :: Prelude.Maybe Prelude.Text, questionId :: Prelude.Maybe Prelude.Text, questionTitle :: Prelude.Maybe Prelude.Text, risk :: Prelude.Maybe Risk } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) Use < -lens generic - lens > or < optics > to modify other optional fields . ' improvementPlans ' , ' improvementSummary_improvementPlans ' - The improvement plan details . newImprovementSummary :: ImprovementSummary newImprovementSummary = ImprovementSummary' { improvementPlanUrl = Prelude.Nothing, improvementPlans = Prelude.Nothing, pillarId = Prelude.Nothing, questionId = Prelude.Nothing, questionTitle = Prelude.Nothing, risk = Prelude.Nothing } improvementSummary_improvementPlanUrl :: Lens.Lens' ImprovementSummary (Prelude.Maybe Prelude.Text) improvementSummary_improvementPlanUrl = Lens.lens (\ImprovementSummary' {improvementPlanUrl} -> improvementPlanUrl) (\s@ImprovementSummary' {} a -> s {improvementPlanUrl = a} :: ImprovementSummary) improvementSummary_improvementPlans :: Lens.Lens' ImprovementSummary (Prelude.Maybe [ChoiceImprovementPlan]) improvementSummary_improvementPlans = Lens.lens (\ImprovementSummary' {improvementPlans} -> improvementPlans) (\s@ImprovementSummary' {} a -> s {improvementPlans = a} :: ImprovementSummary) Prelude.. Lens.mapping Lens.coerced improvementSummary_pillarId :: Lens.Lens' ImprovementSummary (Prelude.Maybe Prelude.Text) improvementSummary_pillarId = Lens.lens (\ImprovementSummary' {pillarId} -> pillarId) (\s@ImprovementSummary' {} a -> s {pillarId = a} :: ImprovementSummary) improvementSummary_questionId :: Lens.Lens' ImprovementSummary (Prelude.Maybe Prelude.Text) improvementSummary_questionId = Lens.lens (\ImprovementSummary' {questionId} -> questionId) (\s@ImprovementSummary' {} a -> s {questionId = a} :: ImprovementSummary) improvementSummary_questionTitle :: Lens.Lens' ImprovementSummary (Prelude.Maybe Prelude.Text) improvementSummary_questionTitle = Lens.lens (\ImprovementSummary' {questionTitle} -> questionTitle) (\s@ImprovementSummary' {} a -> s {questionTitle = a} :: ImprovementSummary) improvementSummary_risk :: Lens.Lens' ImprovementSummary (Prelude.Maybe Risk) improvementSummary_risk = Lens.lens (\ImprovementSummary' {risk} -> risk) (\s@ImprovementSummary' {} a -> s {risk = a} :: ImprovementSummary) instance Data.FromJSON ImprovementSummary where parseJSON = Data.withObject "ImprovementSummary" ( \x -> ImprovementSummary' Prelude.<$> (x Data..:? "ImprovementPlanUrl") Prelude.<*> ( x Data..:? "ImprovementPlans" Data..!= Prelude.mempty ) Prelude.<*> (x Data..:? "PillarId") Prelude.<*> (x Data..:? "QuestionId") Prelude.<*> (x Data..:? "QuestionTitle") Prelude.<*> (x Data..:? "Risk") ) instance Prelude.Hashable ImprovementSummary where hashWithSalt _salt ImprovementSummary' {..} = _salt `Prelude.hashWithSalt` improvementPlanUrl `Prelude.hashWithSalt` improvementPlans `Prelude.hashWithSalt` pillarId `Prelude.hashWithSalt` questionId `Prelude.hashWithSalt` questionTitle `Prelude.hashWithSalt` risk instance Prelude.NFData ImprovementSummary where rnf ImprovementSummary' {..} = Prelude.rnf improvementPlanUrl `Prelude.seq` Prelude.rnf improvementPlans `Prelude.seq` Prelude.rnf pillarId `Prelude.seq` Prelude.rnf questionId `Prelude.seq` Prelude.rnf questionTitle `Prelude.seq` Prelude.rnf risk
4da39373025360e201198acfb22b92b6829ef9dea1cce9e6c7fb18af10f84a42
nikodemus/raylisp
normal.lisp
by Nikodemus Siivola < > , 2009 . ;;;; ;;;; 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 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 :raylisp) ;;;; SURFACE NORMAL PERTURBATION (defclass normal (transformable) ((height :initarg :height :initform 1.0 :reader normal-height))) (defmethod normal-height :around ((normal normal)) (coerce (call-next-method) 'single-float)) (declaim (ftype (function (t matrix) perturbation-function) compute-perturbation-function)) (defgeneric compute-perturbation-function (normal matrix)) (defmethod compute-perturbation-function :around (normal matrix) (check-function-type (call-next-method) 'perturbation-function)) (defmethod compute-perturbation-function :around ((normal transformable) matrix) (call-next-method normal (matrix* matrix (transform-of normal)))) (define-named-lambda perturbation-lambda vec ((result vec) (normal vec) (point vec)) :safe nil) (defmethod compute-perturbation-function ((normal null) matrix) (perturbation-lambda smooth-normal (result normal point) (declare (ignore result point)) normal))
null
https://raw.githubusercontent.com/nikodemus/raylisp/f79f61c6df283baad265dfdc207d798b63ca19a9/kernel/normal.lisp
lisp
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files including without limitation the rights to use, copy, modify, merge, subject to the following conditions: EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. SURFACE NORMAL PERTURBATION
by Nikodemus Siivola < > , 2009 . ( the " Software " ) , to deal in the Software without restriction , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , (in-package :raylisp) (defclass normal (transformable) ((height :initarg :height :initform 1.0 :reader normal-height))) (defmethod normal-height :around ((normal normal)) (coerce (call-next-method) 'single-float)) (declaim (ftype (function (t matrix) perturbation-function) compute-perturbation-function)) (defgeneric compute-perturbation-function (normal matrix)) (defmethod compute-perturbation-function :around (normal matrix) (check-function-type (call-next-method) 'perturbation-function)) (defmethod compute-perturbation-function :around ((normal transformable) matrix) (call-next-method normal (matrix* matrix (transform-of normal)))) (define-named-lambda perturbation-lambda vec ((result vec) (normal vec) (point vec)) :safe nil) (defmethod compute-perturbation-function ((normal null) matrix) (perturbation-lambda smooth-normal (result normal point) (declare (ignore result point)) normal))
c9d91e9a04aded50be6b2f1bccc8d0cd1b6a8062db097721863b57f92ca5a7f8
xapi-project/xen-api
db_rpc_common_v1.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. *) * / unmarshall functions for relevant types to XMLRPC open Db_cache_types exception DB_remote_marshall_error let marshall_2strings (x, y) = XMLRPC.To.array [XMLRPC.To.string x; XMLRPC.To.string y] let unmarshall_2strings xml = match XMLRPC.From.array (fun x -> x) xml with | [x1; x2] -> (XMLRPC.From.string x1, XMLRPC.From.string x2) | _ -> raise DB_remote_marshall_error let marshall_4strings (x, y, w, z) = XMLRPC.To.array [ XMLRPC.To.string x ; XMLRPC.To.string y ; XMLRPC.To.string w ; XMLRPC.To.string z ] let unmarshall_4strings xml = match XMLRPC.From.array (fun x -> x) xml with | [x1; x2; x3; x4] -> ( XMLRPC.From.string x1 , XMLRPC.From.string x2 , XMLRPC.From.string x3 , XMLRPC.From.string x4 ) | _ -> raise DB_remote_marshall_error let marshall_3strings (x, y, w) = XMLRPC.To.array [XMLRPC.To.string x; XMLRPC.To.string y; XMLRPC.To.string w] let unmarshall_3strings xml = match XMLRPC.From.array (fun x -> x) xml with | [x1; x2; x3] -> (XMLRPC.From.string x1, XMLRPC.From.string x2, XMLRPC.From.string x3) | _ -> raise DB_remote_marshall_error let marshall_stringlist sl = XMLRPC.To.array (List.map XMLRPC.To.string sl) let unmarshall_stringlist xml = List.map XMLRPC.From.string (XMLRPC.From.array (fun x -> x) xml) let marshall_stringstringlist ssl = XMLRPC.To.array (List.map marshall_2strings ssl) let unmarshall_stringstringlist xml = List.map unmarshall_2strings (XMLRPC.From.array (fun x -> x) xml) let marshall_stringopt x = match x with | None -> XMLRPC.To.array [] | Some x -> XMLRPC.To.array [XMLRPC.To.string x] let unmarshall_stringopt xml = match XMLRPC.From.array (fun x -> x) xml with | [] -> None | [xml] -> Some (XMLRPC.From.string xml) | _ -> raise DB_remote_marshall_error let marshall_expr x = Db_filter.xml_of_expr x let unmarshall_expr xml = Db_filter.expr_of_xml xml let marshall_structured_op x = let str = match x with | AddSet -> "addset" | RemoveSet -> "removeset" | AddMap -> "addmap" | RemoveMap -> "removemap" | AddMapLegacy -> "addmap" (* Nb, we always use 'non-legacy' mode for remote access *) in XMLRPC.To.string str let unmarshall_structured_op xml = match XMLRPC.From.string xml with | "addset" -> AddSet | "removeset" -> RemoveSet | "addmap" -> AddMap | "removemap" -> RemoveMap | _ -> raise DB_remote_marshall_error let marshall_where_rec r = XMLRPC.To.array [ XMLRPC.To.string r.table ; XMLRPC.To.string r.return ; XMLRPC.To.string r.where_field ; XMLRPC.To.string r.where_value ] let unmarshall_where_rec xml = match XMLRPC.From.array (fun x -> x) xml with | [t; r; wf; wv] -> { table= XMLRPC.From.string t ; return= XMLRPC.From.string r ; where_field= XMLRPC.From.string wf ; where_value= XMLRPC.From.string wv } | _ -> raise DB_remote_marshall_error let marshall_unit () = XMLRPC.To.string "" let unmarshall_unit xml = match XMLRPC.From.string xml with | "" -> () | _ -> raise DB_remote_marshall_error (* get_table_from_ref *) let marshall_get_table_from_ref_args s = XMLRPC.To.string s let unmarshall_get_table_from_ref_args xml = XMLRPC.From.string xml let marshall_get_table_from_ref_response so = marshall_stringopt so let unmarshall_get_table_from_ref_response so = unmarshall_stringopt so (* is_valid_ref *) let marshall_is_valid_ref_args s = XMLRPC.To.string s let unmarshall_is_valid_ref_args xml = XMLRPC.From.string xml let marshall_is_valid_ref_response b = XMLRPC.To.boolean b let unmarshall_is_valid_ref_response xml = XMLRPC.From.boolean xml (* read_refs *) let marshall_read_refs_args s = XMLRPC.To.string s let unmarshall_read_refs_args s = XMLRPC.From.string s let marshall_read_refs_response sl = marshall_stringlist sl let unmarshall_read_refs_response xml = unmarshall_stringlist xml (* read_field_where *) let marshall_read_field_where_args w = marshall_where_rec w let unmarshall_read_field_where_args xml = unmarshall_where_rec xml let marshall_read_field_where_response sl = marshall_stringlist sl let unmarshall_read_field_where_response xml = unmarshall_stringlist xml (* db_get_by_uuid *) let marshall_db_get_by_uuid_args (s1, s2) = marshall_2strings (s1, s2) let unmarshall_db_get_by_uuid_args xml = unmarshall_2strings xml let marshall_db_get_by_uuid_response s = XMLRPC.To.string s let unmarshall_db_get_by_uuid_response xml = XMLRPC.From.string xml (* db_get_by_name_label *) let marshall_db_get_by_name_label_args (s1, s2) = marshall_2strings (s1, s2) let unmarshall_db_get_by_name_label_args xml = unmarshall_2strings xml let marshall_db_get_by_name_label_response sl = marshall_stringlist sl let unmarshall_db_get_by_name_label_response xml = unmarshall_stringlist xml create_row let marshall_create_row_args (s1, ssl, s2) = XMLRPC.To.array [ XMLRPC.To.string s1 ; XMLRPC.To.array (List.map marshall_2strings ssl) ; XMLRPC.To.string s2 ] let unmarshall_create_row_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s1_xml; ssl_xml; s2_xml] -> ( XMLRPC.From.string s1_xml , List.map unmarshall_2strings (XMLRPC.From.array (fun x -> x) ssl_xml) , XMLRPC.From.string s2_xml ) | _ -> raise DB_remote_marshall_error let marshall_create_row_response () = marshall_unit () let unmarshall_create_row_response xml = unmarshall_unit xml (* delete_row *) let marshall_delete_row_args (s1, s2) = XMLRPC.To.array [XMLRPC.To.string s1; XMLRPC.To.string s2] let unmarshall_delete_row_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s1_xml; s2_xml] -> (XMLRPC.From.string s1_xml, XMLRPC.From.string s2_xml) | _ -> raise DB_remote_marshall_error let marshall_delete_row_response () = marshall_unit () let unmarshall_delete_row_response xml = unmarshall_unit xml (* write_field *) let marshall_write_field_args (s1, s2, s3, s4) = XMLRPC.To.array (List.map XMLRPC.To.string [s1; s2; s3; s4]) let unmarshall_write_field_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s1x; s2x; s3x; s4x] -> ( XMLRPC.From.string s1x , XMLRPC.From.string s2x , XMLRPC.From.string s3x , XMLRPC.From.string s4x ) | _ -> raise DB_remote_marshall_error let marshall_write_field_response () = marshall_unit () let unmarshall_write_field_response xml = unmarshall_unit xml (* read_field *) let marshall_read_field_args (s1, s2, s3) = XMLRPC.To.array (List.map XMLRPC.To.string [s1; s2; s3]) let unmarshall_read_field_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s1x; s2x; s3x] -> (XMLRPC.From.string s1x, XMLRPC.From.string s2x, XMLRPC.From.string s3x) | _ -> raise DB_remote_marshall_error let marshall_read_field_response s = XMLRPC.To.string s let unmarshall_read_field_response xml = XMLRPC.From.string xml (* find_refs_with_filter *) let marshall_find_refs_with_filter_args (s, e) = XMLRPC.To.array [XMLRPC.To.string s; marshall_expr e] let unmarshall_find_refs_with_filter_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s; e] -> (XMLRPC.From.string s, unmarshall_expr e) | _ -> raise DB_remote_marshall_error let marshall_find_refs_with_filter_response sl = marshall_stringlist sl let unmarshall_find_refs_with_filter_response xml = unmarshall_stringlist xml (* process_structured_field *) let marshall_process_structured_field_args (ss, s1, s2, s3, op) = XMLRPC.To.array [ marshall_2strings ss ; XMLRPC.To.string s1 ; XMLRPC.To.string s2 ; XMLRPC.To.string s3 ; marshall_structured_op op ] let unmarshall_process_structured_field_args xml = match XMLRPC.From.array (fun x -> x) xml with | [ss_xml; s1_xml; s2_xml; s3_xml; op_xml] -> ( unmarshall_2strings ss_xml , XMLRPC.From.string s1_xml , XMLRPC.From.string s2_xml , XMLRPC.From.string s3_xml , unmarshall_structured_op op_xml ) | _ -> raise DB_remote_marshall_error let marshall_process_structured_field_response () = marshall_unit () let unmarshall_process_structured_field_response xml = unmarshall_unit xml (* read_record *) let marshall_read_record_args = marshall_2strings let unmarshall_read_record_args = unmarshall_2strings let marshall_read_record_response (ssl, ssll) = XMLRPC.To.array [ XMLRPC.To.array (List.map marshall_2strings ssl) ; XMLRPC.To.array (List.map (fun (s, sl) -> XMLRPC.To.array [ XMLRPC.To.string s ; XMLRPC.To.array (List.map XMLRPC.To.string sl) ] ) ssll ) ] let unmarshall_read_record_response xml = match XMLRPC.From.array (fun x -> x) xml with | [ssl_xml; ssll_xml] -> ( List.map unmarshall_2strings (XMLRPC.From.array (fun x -> x) ssl_xml) , List.map (fun xml -> match XMLRPC.From.array (fun x -> x) xml with | [s_xml; sl_xml] -> (XMLRPC.From.string s_xml, unmarshall_stringlist sl_xml) | _ -> raise DB_remote_marshall_error ) (XMLRPC.From.array (fun x -> x) ssll_xml) ) | _ -> raise DB_remote_marshall_error (* read_records_where *) let marshall_read_records_where_args (s, e) = XMLRPC.To.array [XMLRPC.To.string s; marshall_expr e] let unmarshall_read_records_where_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s_xml; expr_xml] -> (XMLRPC.From.string s_xml, unmarshall_expr expr_xml) | _ -> raise DB_remote_marshall_error let marshall_read_records_where_response refs_and_recs_list = XMLRPC.To.array (List.map (fun (ref, record) -> XMLRPC.To.array [XMLRPC.To.string ref; marshall_read_record_response record] ) refs_and_recs_list ) let unmarshall_read_records_where_response xml = match XMLRPC.From.array (fun x -> x) xml with | xml_refs_and_recs_list -> List.map (fun xml_ref_and_rec -> match XMLRPC.From.array (fun x -> x) xml_ref_and_rec with | [ref_xml; rec_xml] -> ( XMLRPC.From.string ref_xml , unmarshall_read_record_response rec_xml ) | _ -> raise DB_remote_marshall_error ) xml_refs_and_recs_list
null
https://raw.githubusercontent.com/xapi-project/xen-api/47fae74032aa6ade0fc12e867c530eaf2a96bf75/ocaml/database/db_rpc_common_v1.ml
ocaml
Nb, we always use 'non-legacy' mode for remote access get_table_from_ref is_valid_ref read_refs read_field_where db_get_by_uuid db_get_by_name_label delete_row write_field read_field find_refs_with_filter process_structured_field read_record read_records_where
* 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. *) * / unmarshall functions for relevant types to XMLRPC open Db_cache_types exception DB_remote_marshall_error let marshall_2strings (x, y) = XMLRPC.To.array [XMLRPC.To.string x; XMLRPC.To.string y] let unmarshall_2strings xml = match XMLRPC.From.array (fun x -> x) xml with | [x1; x2] -> (XMLRPC.From.string x1, XMLRPC.From.string x2) | _ -> raise DB_remote_marshall_error let marshall_4strings (x, y, w, z) = XMLRPC.To.array [ XMLRPC.To.string x ; XMLRPC.To.string y ; XMLRPC.To.string w ; XMLRPC.To.string z ] let unmarshall_4strings xml = match XMLRPC.From.array (fun x -> x) xml with | [x1; x2; x3; x4] -> ( XMLRPC.From.string x1 , XMLRPC.From.string x2 , XMLRPC.From.string x3 , XMLRPC.From.string x4 ) | _ -> raise DB_remote_marshall_error let marshall_3strings (x, y, w) = XMLRPC.To.array [XMLRPC.To.string x; XMLRPC.To.string y; XMLRPC.To.string w] let unmarshall_3strings xml = match XMLRPC.From.array (fun x -> x) xml with | [x1; x2; x3] -> (XMLRPC.From.string x1, XMLRPC.From.string x2, XMLRPC.From.string x3) | _ -> raise DB_remote_marshall_error let marshall_stringlist sl = XMLRPC.To.array (List.map XMLRPC.To.string sl) let unmarshall_stringlist xml = List.map XMLRPC.From.string (XMLRPC.From.array (fun x -> x) xml) let marshall_stringstringlist ssl = XMLRPC.To.array (List.map marshall_2strings ssl) let unmarshall_stringstringlist xml = List.map unmarshall_2strings (XMLRPC.From.array (fun x -> x) xml) let marshall_stringopt x = match x with | None -> XMLRPC.To.array [] | Some x -> XMLRPC.To.array [XMLRPC.To.string x] let unmarshall_stringopt xml = match XMLRPC.From.array (fun x -> x) xml with | [] -> None | [xml] -> Some (XMLRPC.From.string xml) | _ -> raise DB_remote_marshall_error let marshall_expr x = Db_filter.xml_of_expr x let unmarshall_expr xml = Db_filter.expr_of_xml xml let marshall_structured_op x = let str = match x with | AddSet -> "addset" | RemoveSet -> "removeset" | AddMap -> "addmap" | RemoveMap -> "removemap" | AddMapLegacy -> "addmap" in XMLRPC.To.string str let unmarshall_structured_op xml = match XMLRPC.From.string xml with | "addset" -> AddSet | "removeset" -> RemoveSet | "addmap" -> AddMap | "removemap" -> RemoveMap | _ -> raise DB_remote_marshall_error let marshall_where_rec r = XMLRPC.To.array [ XMLRPC.To.string r.table ; XMLRPC.To.string r.return ; XMLRPC.To.string r.where_field ; XMLRPC.To.string r.where_value ] let unmarshall_where_rec xml = match XMLRPC.From.array (fun x -> x) xml with | [t; r; wf; wv] -> { table= XMLRPC.From.string t ; return= XMLRPC.From.string r ; where_field= XMLRPC.From.string wf ; where_value= XMLRPC.From.string wv } | _ -> raise DB_remote_marshall_error let marshall_unit () = XMLRPC.To.string "" let unmarshall_unit xml = match XMLRPC.From.string xml with | "" -> () | _ -> raise DB_remote_marshall_error let marshall_get_table_from_ref_args s = XMLRPC.To.string s let unmarshall_get_table_from_ref_args xml = XMLRPC.From.string xml let marshall_get_table_from_ref_response so = marshall_stringopt so let unmarshall_get_table_from_ref_response so = unmarshall_stringopt so let marshall_is_valid_ref_args s = XMLRPC.To.string s let unmarshall_is_valid_ref_args xml = XMLRPC.From.string xml let marshall_is_valid_ref_response b = XMLRPC.To.boolean b let unmarshall_is_valid_ref_response xml = XMLRPC.From.boolean xml let marshall_read_refs_args s = XMLRPC.To.string s let unmarshall_read_refs_args s = XMLRPC.From.string s let marshall_read_refs_response sl = marshall_stringlist sl let unmarshall_read_refs_response xml = unmarshall_stringlist xml let marshall_read_field_where_args w = marshall_where_rec w let unmarshall_read_field_where_args xml = unmarshall_where_rec xml let marshall_read_field_where_response sl = marshall_stringlist sl let unmarshall_read_field_where_response xml = unmarshall_stringlist xml let marshall_db_get_by_uuid_args (s1, s2) = marshall_2strings (s1, s2) let unmarshall_db_get_by_uuid_args xml = unmarshall_2strings xml let marshall_db_get_by_uuid_response s = XMLRPC.To.string s let unmarshall_db_get_by_uuid_response xml = XMLRPC.From.string xml let marshall_db_get_by_name_label_args (s1, s2) = marshall_2strings (s1, s2) let unmarshall_db_get_by_name_label_args xml = unmarshall_2strings xml let marshall_db_get_by_name_label_response sl = marshall_stringlist sl let unmarshall_db_get_by_name_label_response xml = unmarshall_stringlist xml create_row let marshall_create_row_args (s1, ssl, s2) = XMLRPC.To.array [ XMLRPC.To.string s1 ; XMLRPC.To.array (List.map marshall_2strings ssl) ; XMLRPC.To.string s2 ] let unmarshall_create_row_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s1_xml; ssl_xml; s2_xml] -> ( XMLRPC.From.string s1_xml , List.map unmarshall_2strings (XMLRPC.From.array (fun x -> x) ssl_xml) , XMLRPC.From.string s2_xml ) | _ -> raise DB_remote_marshall_error let marshall_create_row_response () = marshall_unit () let unmarshall_create_row_response xml = unmarshall_unit xml let marshall_delete_row_args (s1, s2) = XMLRPC.To.array [XMLRPC.To.string s1; XMLRPC.To.string s2] let unmarshall_delete_row_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s1_xml; s2_xml] -> (XMLRPC.From.string s1_xml, XMLRPC.From.string s2_xml) | _ -> raise DB_remote_marshall_error let marshall_delete_row_response () = marshall_unit () let unmarshall_delete_row_response xml = unmarshall_unit xml let marshall_write_field_args (s1, s2, s3, s4) = XMLRPC.To.array (List.map XMLRPC.To.string [s1; s2; s3; s4]) let unmarshall_write_field_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s1x; s2x; s3x; s4x] -> ( XMLRPC.From.string s1x , XMLRPC.From.string s2x , XMLRPC.From.string s3x , XMLRPC.From.string s4x ) | _ -> raise DB_remote_marshall_error let marshall_write_field_response () = marshall_unit () let unmarshall_write_field_response xml = unmarshall_unit xml let marshall_read_field_args (s1, s2, s3) = XMLRPC.To.array (List.map XMLRPC.To.string [s1; s2; s3]) let unmarshall_read_field_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s1x; s2x; s3x] -> (XMLRPC.From.string s1x, XMLRPC.From.string s2x, XMLRPC.From.string s3x) | _ -> raise DB_remote_marshall_error let marshall_read_field_response s = XMLRPC.To.string s let unmarshall_read_field_response xml = XMLRPC.From.string xml let marshall_find_refs_with_filter_args (s, e) = XMLRPC.To.array [XMLRPC.To.string s; marshall_expr e] let unmarshall_find_refs_with_filter_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s; e] -> (XMLRPC.From.string s, unmarshall_expr e) | _ -> raise DB_remote_marshall_error let marshall_find_refs_with_filter_response sl = marshall_stringlist sl let unmarshall_find_refs_with_filter_response xml = unmarshall_stringlist xml let marshall_process_structured_field_args (ss, s1, s2, s3, op) = XMLRPC.To.array [ marshall_2strings ss ; XMLRPC.To.string s1 ; XMLRPC.To.string s2 ; XMLRPC.To.string s3 ; marshall_structured_op op ] let unmarshall_process_structured_field_args xml = match XMLRPC.From.array (fun x -> x) xml with | [ss_xml; s1_xml; s2_xml; s3_xml; op_xml] -> ( unmarshall_2strings ss_xml , XMLRPC.From.string s1_xml , XMLRPC.From.string s2_xml , XMLRPC.From.string s3_xml , unmarshall_structured_op op_xml ) | _ -> raise DB_remote_marshall_error let marshall_process_structured_field_response () = marshall_unit () let unmarshall_process_structured_field_response xml = unmarshall_unit xml let marshall_read_record_args = marshall_2strings let unmarshall_read_record_args = unmarshall_2strings let marshall_read_record_response (ssl, ssll) = XMLRPC.To.array [ XMLRPC.To.array (List.map marshall_2strings ssl) ; XMLRPC.To.array (List.map (fun (s, sl) -> XMLRPC.To.array [ XMLRPC.To.string s ; XMLRPC.To.array (List.map XMLRPC.To.string sl) ] ) ssll ) ] let unmarshall_read_record_response xml = match XMLRPC.From.array (fun x -> x) xml with | [ssl_xml; ssll_xml] -> ( List.map unmarshall_2strings (XMLRPC.From.array (fun x -> x) ssl_xml) , List.map (fun xml -> match XMLRPC.From.array (fun x -> x) xml with | [s_xml; sl_xml] -> (XMLRPC.From.string s_xml, unmarshall_stringlist sl_xml) | _ -> raise DB_remote_marshall_error ) (XMLRPC.From.array (fun x -> x) ssll_xml) ) | _ -> raise DB_remote_marshall_error let marshall_read_records_where_args (s, e) = XMLRPC.To.array [XMLRPC.To.string s; marshall_expr e] let unmarshall_read_records_where_args xml = match XMLRPC.From.array (fun x -> x) xml with | [s_xml; expr_xml] -> (XMLRPC.From.string s_xml, unmarshall_expr expr_xml) | _ -> raise DB_remote_marshall_error let marshall_read_records_where_response refs_and_recs_list = XMLRPC.To.array (List.map (fun (ref, record) -> XMLRPC.To.array [XMLRPC.To.string ref; marshall_read_record_response record] ) refs_and_recs_list ) let unmarshall_read_records_where_response xml = match XMLRPC.From.array (fun x -> x) xml with | xml_refs_and_recs_list -> List.map (fun xml_ref_and_rec -> match XMLRPC.From.array (fun x -> x) xml_ref_and_rec with | [ref_xml; rec_xml] -> ( XMLRPC.From.string ref_xml , unmarshall_read_record_response rec_xml ) | _ -> raise DB_remote_marshall_error ) xml_refs_and_recs_list
e2466e1cd87b4c02b30af9bd9942e21b3fd7942dbbcdcca1bf1eeba4c6562d97
facebook/duckling
Corpus.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.IS.Corpus ( corpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types context :: Context context = testContext{locale = makeLocale IS Nothing} corpus :: Corpus corpus = (context, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "0" , "núll" , "null" ] , examples (NumeralValue 1) [ "1" , "einn" ] , examples (NumeralValue 2) [ "tveir" ] , examples (NumeralValue 3) [ "þrír" ] , examples (NumeralValue 4) [ "fjórir" ] , examples (NumeralValue 5) [ "fimm" ] , examples (NumeralValue 6) [ "sex" ] , examples (NumeralValue 7) [ "sjö" ] , examples (NumeralValue 8) [ "átta" ] , examples (NumeralValue 9) [ "níu" ] , examples (NumeralValue 10) [ "tíu" ] , examples (NumeralValue 11) [ "ellefu" ] , examples (NumeralValue 15) [ "fimmtán" ] , examples (NumeralValue 17) [ "sautján" ] , examples (NumeralValue 20) [ "20" , "tuttugu" ] ]
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Numeral/IS/Corpus.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. # LANGUAGE OverloadedStrings #
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.Numeral.IS.Corpus ( corpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types context :: Context context = testContext{locale = makeLocale IS Nothing} corpus :: Corpus corpus = (context, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "0" , "núll" , "null" ] , examples (NumeralValue 1) [ "1" , "einn" ] , examples (NumeralValue 2) [ "tveir" ] , examples (NumeralValue 3) [ "þrír" ] , examples (NumeralValue 4) [ "fjórir" ] , examples (NumeralValue 5) [ "fimm" ] , examples (NumeralValue 6) [ "sex" ] , examples (NumeralValue 7) [ "sjö" ] , examples (NumeralValue 8) [ "átta" ] , examples (NumeralValue 9) [ "níu" ] , examples (NumeralValue 10) [ "tíu" ] , examples (NumeralValue 11) [ "ellefu" ] , examples (NumeralValue 15) [ "fimmtán" ] , examples (NumeralValue 17) [ "sautján" ] , examples (NumeralValue 20) [ "20" , "tuttugu" ] ]
6412c0c3c1db652793abe6345bb42213ce8463fd5fff99b0a813f842f744cdd3
ghilesZ/picasso
colors.ml
type t = int * int * int let rgb r g b = (r, g, b) let red = (255, 0, 0) let green = (0, 255, 0) let blue = (0, 0, 255) let white = (255, 255, 255) let black = (0, 0, 0)
null
https://raw.githubusercontent.com/ghilesZ/picasso/520e5dbfa12ad6e7db5f1c5eb40c18812ff099f3/src/colors.ml
ocaml
type t = int * int * int let rgb r g b = (r, g, b) let red = (255, 0, 0) let green = (0, 255, 0) let blue = (0, 0, 255) let white = (255, 255, 255) let black = (0, 0, 0)
bcd3171f16cedaa2b98de3babe37409fc4faeed658082a11d865ce651fa31843
inria-parkas/sundialsml
cvsFoodWeb_ASAi_kry.ml
* ----------------------------------------------------------------- * $ Revision : 1.4 $ * $ Date : 2011/11/23 23:53:02 $ * ----------------------------------------------------------------- * Programmer(s ): @ LLNL * ----------------------------------------------------------------- * OCaml port : , , Jun 2014 . * ----------------------------------------------------------------- * This program solves a stiff ODE system that arises from a system * of partial differential equations . The PDE system is a food web * population model , with predator - prey interaction and diffusion on * the unit square in two dimensions . The dependent variable vector * is the following : * * 1 2 ns * c = ( c , c , ... , c ) * * and the PDEs are as follows : * * i i i * dc /dt = d(i)*(c + c ) + f ( x , y , c ) ( i=1, ... ,ns ) * xx yy i * * where * * i ns j * f ( x , y , c ) = c * ( b(i ) + sum a(i , j)*c ) . * i j=1 * * The number of species is ns = 2*np , with the first np being prey * and the last np being predators . The coefficients a(i , j ) , b(i ) , * d(i ) are : * * a(i , i ) = -a ( all i ) * a(i , j ) = -g ( i < = np , j > np ) * a(i , j ) = e ( i > np , j < = np ) * b(i ) = b*(1 + alpha*x*y ) ( i < = np ) * b(i ) = -b*(1 + alpha*x*y ) ( i > np ) * d(i ) = Dprey ( i < = np ) * d(i ) i > np ) * * The spatial domain is the unit square . The final time is 10 . * The boundary conditions are : normal derivative = 0 . * A polynomial in x and y is used to set the initial conditions . * * The PDEs are discretized by central differencing on an MX by MY * mesh . The resulting ODE system is stiff . * * The ODE system is solved by CVODES using Newton iteration and * the CVSPGMR linear solver ( scaled preconditioned GMRES ) . * * The preconditioner matrix used is the product of two matrices : * ( 1 ) A matrix , only defined implicitly , based on a fixed number * of Gauss - Seidel iterations using the diffusion terms only . * ( 2 ) A block - diagonal matrix based on the partial derivatives of * the interaction terms f only , using block - grouping ( computing * only a subset of the ns by ns blocks ) . * * Additionally , CVODES integrates backwards in time the * the semi - discrete form of the adjoint PDE : * d(lambda)/dt = - D^T ( lambda_xx + ) * - F_c^T lambda - g_c^T * with homogeneous Neumann boundary conditions and final * conditions are the following : * lambda(x , y , t = t_final ) = 0.0 * whose solution at t = 0 represents the sensitivity of * G = int_0^t_final int_x int _ y g(t , c ) dx dy dt * with respect to the initial conditions of the original problem . * * In this example , * g(t , c ) = c(ISPEC ) , with ISPEC defined below . * * During the forward run , CVODES also computes G as * G = phi(t_final ) * where * d(phi)/dt = int_x int _ y g(t , c ) dx dy * and the 2 - D integral is evaluated with Simpson 's rule . * ----------------------------------------------------------------- * Reference : and , Reduced Storage * Matrix Methods in Stiff ODE Systems , J. Appl . Math . & Comp . , 31 * ( 1989 ) , pp . 40 - 91 . Also available as National * Laboratory Report UCRL-95088 , Rev. 1 , June 1987 . * ----------------------------------------------------------------- * ----------------------------------------------------------------- * $Revision: 1.4 $ * $Date: 2011/11/23 23:53:02 $ * ----------------------------------------------------------------- * Programmer(s): Radu Serban @ LLNL * ----------------------------------------------------------------- * OCaml port: Timothy Bourke, Inria, Jun 2014. * ----------------------------------------------------------------- * This program solves a stiff ODE system that arises from a system * of partial differential equations. The PDE system is a food web * population model, with predator-prey interaction and diffusion on * the unit square in two dimensions. The dependent variable vector * is the following: * * 1 2 ns * c = (c , c , ..., c ) * * and the PDEs are as follows: * * i i i * dc /dt = d(i)*(c + c ) + f (x,y,c) (i=1,...,ns) * xx yy i * * where * * i ns j * f (x,y,c) = c *(b(i) + sum a(i,j)*c ). * i j=1 * * The number of species is ns = 2*np, with the first np being prey * and the last np being predators. The coefficients a(i,j), b(i), * d(i) are: * * a(i,i) = -a (all i) * a(i,j) = -g (i <= np, j > np) * a(i,j) = e (i > np, j <= np) * b(i) = b*(1 + alpha*x*y) (i <= np) * b(i) = -b*(1 + alpha*x*y) (i > np) * d(i) = Dprey (i <= np) * d(i) = Dpred (i > np) * * The spatial domain is the unit square. The final time is 10. * The boundary conditions are: normal derivative = 0. * A polynomial in x and y is used to set the initial conditions. * * The PDEs are discretized by central differencing on an MX by MY * mesh. The resulting ODE system is stiff. * * The ODE system is solved by CVODES using Newton iteration and * the CVSPGMR linear solver (scaled preconditioned GMRES). * * The preconditioner matrix used is the product of two matrices: * (1) A matrix, only defined implicitly, based on a fixed number * of Gauss-Seidel iterations using the diffusion terms only. * (2) A block-diagonal matrix based on the partial derivatives of * the interaction terms f only, using block-grouping (computing * only a subset of the ns by ns blocks). * * Additionally, CVODES integrates backwards in time the * the semi-discrete form of the adjoint PDE: * d(lambda)/dt = - D^T ( lambda_xx + lambda_yy ) * - F_c^T lambda - g_c^T * with homogeneous Neumann boundary conditions and final * conditions are the following: * lambda(x,y,t=t_final) = 0.0 * whose solution at t = 0 represents the sensitivity of * G = int_0^t_final int_x int _y g(t,c) dx dy dt * with respect to the initial conditions of the original problem. * * In this example, * g(t,c) = c(ISPEC), with ISPEC defined below. * * During the forward run, CVODES also computes G as * G = phi(t_final) * where * d(phi)/dt = int_x int _y g(t,c) dx dy * and the 2-D integral is evaluated with Simpson's rule. * ----------------------------------------------------------------- * Reference: Peter N. Brown and Alan C. Hindmarsh, Reduced Storage * Matrix Methods in Stiff ODE Systems, J. Appl. Math. & Comp., 31 * (1989), pp. 40-91. Also available as Lawrence Livermore National * Laboratory Report UCRL-95088, Rev. 1, June 1987. * ----------------------------------------------------------------- *) open Sundials module Adj = Cvodes.Adjoint module Densemat = Matrix.ArrayDense open Bigarray let unwrap = Nvector.unwrap let sundials_gte500 = let n, _, _ = Sundials_configuration.sundials_version in n >= 5 let printf = Printf.printf let sqr x = x *. x let nvwrmsnorm = Nvector_serial.DataOps.wrmsnorm let nvlinearsum = Nvector_serial.DataOps.linearsum (* Problem Specification Constants *) let aa = 1.0 (* aa = a *) let ee = 1e4 (* ee = e *) let gg = 0.5e-6 (* gg = g *) let bb = 1.0 (* bb = b *) let dprey = 1.0 let dpred = 0.5 let alph = 1.0 let np = 3 let ns = (2*np) (* Method Constants *) let mx = 20 let my = 20 let mxns = mx*ns let ax = 1.0 let ay = 1.0 let dx = ax/.float (mx-1) let dy = ay/.float (my-1) let mp = ns let mq = mx*my let mxmp = mx*mp let ngx = 2 let ngy = 2 let ngrp = ngx*ngy let itmax = 5 (* CVodeInit Constants *) let neq = (ns*mx*my) let t0 = 0.0 let rtol = 1e-5 let atol = 1e-5 (* Output Constants *) let tout = 10.0 (* Note: The value for species i at mesh point (j,k) is stored in *) (* component number (i-1) + j*NS + k*NS*MX of an N_Vector, *) where 1 < = i < = NS , 0 < = j < MX , 0 < = k < MY . (* Structure for user data *) type web_data = { p : Densemat.t array; pivot : LintArray.t array; ns : int; mxns : int; mp : int; mq : int; mx : int; my : int; ngrp : int; ngx : int; ngy : int; mxmp : int; jgx : int array; jgy : int array; jigx : int array; jigy : int array; jxr : int array; jyr : int array; acoef : float array array; bcoef : float array; diff : float array; cox : float array; coy : float array; dx : float; dy : float; srur : float; fsave : RealArray.t; fbsave : RealArray.t; tmp : RealArray.t; rewt : Nvector_serial.t; rewtb : Nvector_serial.t; mutable cvode_mem : Nvector_serial.kind Cvode.serial_session option; mutable cvode_memb : Nvector_serial.kind Adj.serial_bsession option; } Adjoint calculation constants G = int_t int_x ) dy dx dt check points every NSTEPS steps let ispec = 6 (* species # in objective *) (* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- *) (* Small Vector Kernels *) let v_sum_prods n (u : RealArray.t) uoffs p (q : RealArray.t) qoffs (v : float array)(w : RealArray.t) woffs = for i = 0 to n - 1 do u.{uoffs + i} <- p.(i) *. q.{qoffs + i} +. v.(i) *. w.{woffs + i} done let v_inc_by_prod n (u : RealArray.t) uoffs (v : float array) (w : RealArray.t) woffs = for i = 0 to n - 1 do u.{uoffs + i} <- u.{uoffs + i} +. v.(i) *. w.{woffs + i} done let v_prod n (u : RealArray.t) uoffs (v : float array) (w : RealArray.t) woffs = for i = 0 to n - 1 do u.{uoffs + i} <- v.(i) *. w.{woffs + i} done let v_zero n u offs = for i = 0 to n - 1 do u.{offs + i} <- 0.0 done * This routine sets arrays jg , jig , and jr describing * a uniform partition of ( 0,1,2, ... ,m-1 ) into ng groups . * The arrays set are : * jg = length ng+1 array of group boundaries . * Group ig has indices j = ... ,jg[ig+1]-1 . * jig = length m array of group indices vs node index . * Node index j is in group jig[j ] . * jr = length ng array of indices representing the groups . * The index for group ig is j = jr[ig ] . * This routine sets arrays jg, jig, and jr describing * a uniform partition of (0,1,2,...,m-1) into ng groups. * The arrays set are: * jg = length ng+1 array of group boundaries. * Group ig has indices j = jg[ig],...,jg[ig+1]-1. * jig = length m array of group indices vs node index. * Node index j is in group jig[j]. * jr = length ng array of indices representing the groups. * The index for group ig is j = jr[ig]. *) let set_groups m ng jg jig jr = let mper = m / ng in (* does integer division *) for ig = 0 to ng - 1 do jg.(ig) <- ig * mper done; jg.(ng) <- m; let ngm1 = ng - 1 in let len1 = ngm1 * mper in for j = 0 to len1 - 1 do jig.(j) <- j / mper done; for j = len1 to m - 1 do jig.(j) <- ngm1 done; for ig = 0 to ngm1 - 1 do jr.(ig) <- ((2 * ig + 1) * mper - 1) / 2; done; jr.(ngm1) <- (ngm1 * mper + m - 1) / 2 (* Allocate space for user data structure *) let alloc_user_data () = let r = { p = Array.init ngrp (fun _ -> Densemat.create ns ns); pivot = Array.init ngrp (fun _ -> LintArray.create ns); ns = ns; mxns = mxns; mp = mp; mq = mq; mx = mx; my = my; ngrp = ngrp; ngx = ngx; ngy = ngy; mxmp = mxmp; jgx = Array.make (ngx + 1) 0; jgy = Array.make (ngy + 1) 0; jigx = Array.make mx 0; jigy = Array.make my 0; jxr = Array.make ngx 0; jyr = Array.make ngy 0; acoef = Array.make_matrix ns ns 0.0; bcoef = Array.make ns 0.0; diff = Array.make ns 0.0; cox = Array.make ns 0.0; coy = Array.make ns 0.0; dx = dx; dy = dy; srur = sqrt Config.unit_roundoff; fsave = RealArray.create neq; fbsave = RealArray.create neq; tmp = RealArray.create neq; rewt = Nvector_serial.make (neq + 1) 0.0; The original C code uses rewt for forward solving where the length is neq + 1 and also for backward solving where the length is neq ( it relies on the fact that nvwrmsnorm takes the length from its first argument , and not its second ) . This is not possible in the OCaml interface which checks nvectors for compatibility , i.e. , serial nvectors must have the same length . neq + 1 and also for backward solving where the length is neq (it relies on the fact that nvwrmsnorm takes the length from its first argument, and not its second). This is not possible in the OCaml interface which checks nvectors for compatibility, i.e., serial nvectors must have the same length. *) rewtb = Nvector_serial.make neq 0.0; cvode_mem = None; cvode_memb = None; } in let acoef = r.acoef and bcoef = r.bcoef and diff = r.diff and cox = r.cox and coy = r.coy in for j = 0 to np - 1 do for i = 0 to np - 1 do acoef.(np + i).(j) <- ee; acoef.(i).(np + j) <- -. gg done; acoef.(j).(j) <- -. aa; acoef.(np + j).(np + j) <- -. aa; bcoef.(j) <- bb; bcoef.(np + j) <- -. bb; diff.(j) <- dprey; diff.(np + j) <- dpred done; let sqr_dx = sqr dx in let sqr_dy = sqr dy in for i = 0 to ns - 1 do cox.(i) <- diff.(i) /. sqr_dx; coy.(i) <- diff.(i) /. sqr_dy done; r Initialize user data structure let init_user_data wdata = set_groups mx ngx wdata.jgx wdata.jigx wdata.jxr; set_groups my ngy wdata.jgy wdata.jigy wdata.jyr (* This routine computes and loads the vector of initial values. *) let cinit wdata (cdata : RealArray.t) = let ns = wdata.ns and mxns = wdata.mxns and dx = wdata.dx and dy = wdata.dy in let x_factor = 4.0 /. sqr ax and y_factor = 4.0 /. sqr ay in for jy = 0 to my - 1 do let y = float jy *. dy in let argy = sqr (y_factor *. y *. (ay -. y)) in let iyoff = mxns * jy in for jx = 0 to mx - 1 do let x = float jx *. dx in let argx = sqr (x_factor *. x *. (ax -. x)) in let ioff = iyoff + ns * jx in for i = 1 to ns do let ici = ioff + i - 1 in cdata.{ici} <- 10.0 +. float i *. argx *. argy done done done; Initialize quadrature variable to zero cdata.{neq} <- 0.0 * This routine computes the interaction rates for the species * c_1 , ... , ( stored in c[0], ... ,c[ns-1 ] ) , at one spatial point * and at time t. * This routine computes the interaction rates for the species * c_1, ... ,c_ns (stored in c[0],...,c[ns-1]), at one spatial point * and at time t. *) let web_rates wdata x y ((c : RealArray.t), c_off) ((rate : RealArray.t), rate_off) = let acoef = wdata.acoef and bcoef = wdata.bcoef in for i = rate_off to rate_off + ns - 1 do rate.{i} <- 0.0 done; for i = 0 to ns - 1 do for j = 0 to ns - 1 do let c = c.{c_off + j} in rate.{rate_off + i} <- rate.{rate_off + i} +. c *. acoef.(i).(j) done done; let fac = 1.0 +. alph *. x *. y in for i = 0 to ns - 1 do rate.{rate_off + i} <- c.{c_off + i} *. (bcoef.(i) *. fac +. rate.{rate_off + i}) done (* This routine computes the interaction rates for the backward problem *) let web_rates_b wdata x y ((c : RealArray.t), c_off) ((cB : RealArray.t), cB_off) ((rate : RealArray.t), rate_off) ((rateB : RealArray.t), rateB_off) = let ns = wdata.ns and acoef = wdata.acoef and bcoef = wdata.bcoef in let fac = 1.0 +. alph *. x *. y in for i = 0 to ns - 1 do rate.{rate_off + i} <- bcoef.(i) *. fac done; for j = 0 to ns - 1 do for i = 0 to ns - 1 do rate.{rate_off + i} <- rate.{rate_off + i} +. acoef.(i).(j) *. c.{c_off + j} done done; for i = 0 to ns - 1 do rateB.{rateB_off + i} <- cB.{cB_off + i} *. rate.{rate_off + i}; rate.{rate_off + i} <- c.{c_off + i} *. rate.{rate_off + i} done; for j = 0 to ns - 1 do for i = 0 to ns - 1 do rateB.{rateB_off + i} <- rateB.{rateB_off + i} +. acoef.(j).(i) *. c.{c_off + j} *. cB.{cB_off + j} done done * This routine computes one block of the interaction terms of the * system , namely block ( jx , jy ) , for use in preconditioning . * Here jx and jy count from 0 . * This routine computes one block of the interaction terms of the * system, namely block (jx,jy), for use in preconditioning. * Here jx and jy count from 0. *) let fblock wdata _ cdata jx jy cdotdata = let iblok = jx + jy * wdata.mx and y = float jy *. wdata.dy and x = float jx *. wdata.dx in let ic = wdata.ns * iblok in web_rates wdata x y (cdata, ic) (cdotdata, 0) * This routine performs iterations to compute an * approximation to ( P - inverse)*z , where P = I - gamma*Jd , and * represents the diffusion contributions to the Jacobian . * The answer is stored in z on return , and x is a temporary vector . * The dimensions below assume a global constant NS > = ns . * Some inner loops of length ns are implemented with the small * vector kernels v_sum_prods , v_prod , v_inc_by_prod . * This routine performs ITMAX=5 Gauss-Seidel iterations to compute an * approximation to (P-inverse)*z, where P = I - gamma*Jd, and * Jd represents the diffusion contributions to the Jacobian. * The answer is stored in z on return, and x is a temporary vector. * The dimensions below assume a global constant NS >= ns. * Some inner loops of length ns are implemented with the small * vector kernels v_sum_prods, v_prod, v_inc_by_prod. *) let gs_iter wdata = let beta = Array.make ns 0.0 and beta2 = Array.make ns 0.0 and cof1 = Array.make ns 0.0 and gam = Array.make ns 0.0 and gam2 = Array.make ns 0.0 in fun gamma zd xd -> let ns = wdata.ns and mx = wdata.mx and my = wdata.my and mxns = wdata.mxns and cox = wdata.cox and coy = wdata.coy in Write matrix as P = D - L - U. Load local arrays beta , beta2 , gam , gam2 , and cof1 . Load local arrays beta, beta2, gam, gam2, and cof1. *) for i = 0 to ns - 1 do let temp = 1.0 /. (1.0 +. 2.0 *. gamma *. (cox.(i) +. coy.(i))) in beta.(i) <- gamma *. cox.(i) *. temp; beta2.(i) <- 2.0 *. beta.(i); gam.(i) <- gamma *. coy.(i) *. temp; gam2.(i) <- 2.0 *. gam.(i); cof1.(i) <- temp done; Begin iteration loop . Load vector x with ( D - inverse)*z for first iteration . Load vector x with (D-inverse)*z for first iteration. *) for jy = 0 to my - 1 do let iyoff = mxns * jy in for jx = 0 to mx - 1 do let ic = iyoff + ns*jx in v_prod ns xd ic cof1 zd ic (* x[ic+i] = cof1[i]z[ic+i] *) done done; Array1.fill zd 0.0; (* Looping point for iterations. *) for iter = 1 to itmax do Calculate ( D - inverse)*U*x if not the first iteration . if (iter > 1) then for jy = 0 to my - 1 do let iyoff = mxns * jy in for jx = 0 to mx - 1 do (* order of loops matters *) let ic = iyoff + ns * jx and x_loc = if jx = 0 then 0 else if jx = mx - 1 then 2 else 1 and y_loc = if jy = 0 then 0 else if jy = my - 1 then 2 else 1 in match (3 * y_loc + x_loc) with | 0 -> jx = = 0 , jy = = 0 (* x[ic+i] = beta2[i]x[ic+ns+i] + gam2[i]x[ic+mxns+i] *) v_sum_prods ns xd ic beta2 xd (ic + ns) gam2 xd (ic + mxns) | 1 -> 1 < = jx < = mx-2 , jy = = 0 (* x[ic+i] = beta[i]x[ic+ns+i] + gam2[i]x[ic+mxns+i] *) v_sum_prods ns xd ic beta xd (ic + ns) gam2 xd (ic + mxns) | 2 -> jx = = mx-1 , jy = = 0 (* x[ic+i] = gam2[i]x[ic+mxns+i] *) v_prod ns xd ic gam2 xd (ic + mxns) | 3 -> jx = = 0 , 1 < = jy < = my-2 (* x[ic+i] = beta2[i]x[ic+ns+i] + gam[i]x[ic+mxns+i] *) v_sum_prods ns xd ic beta2 xd (ic + ns) gam xd (ic + mxns) | 4 -> 1 < = jx < = mx-2 , 1 < = jy < = my-2 (* x[ic+i] = beta[i]x[ic+ns+i] + gam[i]x[ic+mxns+i] *) v_sum_prods ns xd ic beta xd (ic + ns) gam xd (ic + mxns) | 5 -> jx = = mx-1 , 1 < = jy < = my-2 (* x[ic+i] = gam[i]x[ic+mxns+i] *) v_prod ns xd ic gam xd (ic + mxns) | 6 -> (* jx == 0, jy == my-1 *) (* x[ic+i] = beta2[i]x[ic+ns+i] *) v_prod ns xd ic beta2 xd (ic + ns) | 7 -> 1 < = jx < = mx-2 , jy = = my-1 (* x[ic+i] = beta[i]x[ic+ns+i] *) v_prod ns xd ic beta xd (ic + ns) | 8 -> (* jx == mx-1, jy == my-1 *) x[ic+i ] = 0.0 v_zero ns xd ic | _ -> assert false done end if ( iter > 1 ) (* Overwrite x with [(I - (D-inverse)*L)-inverse]*x. *) for jy = 0 to my - 1 do let iyoff = mxns * jy in for jx = 0 to mx - 1 do (* order of loops matters *) let ic = iyoff + ns * jx and x_loc = if jx = 0 then 0 else if jx = mx - 1 then 2 else 1 and y_loc = if jy = 0 then 0 else if jy = my - 1 then 2 else 1 in match (3 * y_loc + x_loc) with | 0 -> jx = = 0 , jy = = 0 () | 1 -> 1 < = jx < = mx-2 , jy = = 0 (* x[ic+i] += beta[i]x[ic-ns+i] *) v_inc_by_prod ns xd ic beta xd (ic - ns) | 2 -> jx = = mx-1 , jy = = 0 (* x[ic+i] += beta2[i]x[ic-ns+i] *) v_inc_by_prod ns xd ic beta2 xd (ic - ns) | 3 -> jx = = 0 , 1 < = jy < = my-2 (* x[ic+i] += gam[i]x[ic-mxns+i] *) v_inc_by_prod ns xd ic gam xd (ic - mxns) | 4 -> 1 < = jx < = mx-2 , 1 < = jy < = my-2 (* x[ic+i] += beta[i]x[ic-ns+i] + gam[i]x[ic-mxns+i] *) v_inc_by_prod ns xd ic beta xd (ic - ns); v_inc_by_prod ns xd ic gam xd (ic - mxns) | 5 -> jx = = mx-1 , 1 < = jy < = my-2 (* x[ic+i] += beta2[i]x[ic-ns+i] + gam[i]x[ic-mxns+i] *) v_inc_by_prod ns xd ic beta2 xd (ic - ns); v_inc_by_prod ns xd ic gam xd (ic - mxns) | 6 -> (* jx == 0, jy == my-1 *) (* x[ic+i] += gam2[i]x[ic-mxns+i] *) v_inc_by_prod ns xd ic gam2 xd (ic - mxns) | 7 -> 1 < = jx < = mx-2 , jy = = my-1 (* x[ic+i] += beta[i]x[ic-ns+i] + gam2[i]x[ic-mxns+i] *) v_inc_by_prod ns xd ic beta xd (ic - ns); v_inc_by_prod ns xd ic gam2 xd (ic - mxns) | 8 -> (* jx == mx-1, jy == my-1 *) (* x[ic+i] += beta2[i]x[ic-ns+i] + gam2[i]x[ic-mxns+i] *) v_inc_by_prod ns xd ic beta2 xd (ic - ns); v_inc_by_prod ns xd ic gam2 xd (ic - mxns) | _ -> assert false done done; (* Add increment x to z : z <- z+x *) nvlinearsum 1.0 zd 1.0 xd zd done (* Print maximum sensitivity of G for each species *) let print_output wdata (cdata : RealArray.t) ns mxns = let x = ref 0.0 and y = ref 0.0 in for i=1 to ns do let cmax = ref 0.0 in for jy=my-1 downto 0 do for jx=0 to mx - 1 do let cij = cdata.{(i-1) + jx*ns + jy*mxns} in if abs_float(cij) > !cmax then begin cmax := cij; x := float jx *. wdata.dx; y := float jy *. wdata.dy end done done; printf "\nMaximum sensitivity with respect to I.C. of species %d\n" i; printf " lambda max = %e\n" !cmax; printf "at\n"; printf " x = %e\n y = %e\n" !x !y done (* Compute double space integral *) let double_intgr (cdata : RealArray.t) i wdata = let ns = wdata.ns and mx = wdata.mx and my = wdata.my and mxns = wdata.mxns and dx = wdata.dx and dy = wdata.dy in let jy = 0 in let intgr_x = ref cdata.{(i-1) + jy*mxns} in for jx = 1 to mx-2 do intgr_x := !intgr_x +. 2.0 *. cdata.{(i-1) + jx*ns + jy*mxns} done; intgr_x := !intgr_x +. cdata.{(i-1) + (mx-1)*ns + jy*mxns}; intgr_x := !intgr_x *. 0.5 *. dx; let intgr_xy = ref !intgr_x in for jy = 1 to my-2 do intgr_x := cdata.{(i-1)+jy*mxns}; for jx = 1 to mx-2 do intgr_x := !intgr_x +. 2.0 *. cdata.{(i-1) + jx*ns + jy*mxns} done; intgr_x := !intgr_x +. cdata.{(i-1) + (mx-1)*ns + jy*mxns}; intgr_x := !intgr_x *. 0.5 *. dx; intgr_xy := !intgr_xy +. 2.0 *. !intgr_x done; let jy = my-1 in intgr_x := cdata.{(i-1) + jy*mxns}; for jx = 1 to mx-2 do intgr_x := !intgr_x +. 2.0 *. cdata.{(i-1) + jx*ns + jy*mxns} done; intgr_x := !intgr_x +. cdata.{(i-1) + (mx-1)*ns + jy*mxns}; intgr_x := !intgr_x *. 0.5 *. dx; intgr_xy := !intgr_xy +. !intgr_x; intgr_xy := !intgr_xy *. 0.5 *. dy; !intgr_xy (* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY CVODES *-------------------------------------------------------------------- *) * This routine computes the right - hand side of the ODE system and * returns it in cdot . The interaction rates are computed by calls to WebRates , * and these are saved in fsave for use in preconditioning . * This routine computes the right-hand side of the ODE system and * returns it in cdot. The interaction rates are computed by calls to WebRates, * and these are saved in fsave for use in preconditioning. *) let f wdata _ (cdata : RealArray.t) (cdotdata : RealArray.t) = let ns = wdata.ns and fsave = wdata.fsave and cox = wdata.cox and coy = wdata.coy and mxns = wdata.mxns and dx = wdata.dx and dy = wdata.dy in for jy = 0 to my - 1 do let y = float jy *. dy in let iyoff = mxns*jy in let idyu = if jy = my - 1 then - mxns else mxns in let idyl = if jy = 0 then - mxns else mxns in for jx = 0 to mx - 1 do let x = float jx *. dx in let ic = iyoff + ns * jx in Get interaction rates at one point ( x , y ) . web_rates wdata x y (cdata, ic) (fsave, ic); let idxu = if jx = mx - 1 then -ns else ns in let idxl = if jx = 0 then -ns else ns in for i = 1 to ns do let ici = ic + i - 1 in (* Do differencing in y. *) let dcyli = cdata.{ici} -. cdata.{ici - idyl} in let dcyui = cdata.{ici + idyu} -. cdata.{ici} in (* Do differencing in x. *) let dcxli = cdata.{ici} -. cdata.{ici - idxl} in let dcxui = cdata.{ici + idxu} -. cdata.{ici} in (* Collect terms and load cdot elements. *) cdotdata.{ici} <- coy.(i - 1) *. (dcyui -. dcyli) +. cox.(i - 1) *. (dcxui -. dcxli) +. fsave.{ici} done done done; Quadrature equation ( species 1 ) cdotdata.{neq} <- double_intgr cdata ispec wdata * This routine generates the block - diagonal part of the Jacobian * corresponding to the interaction rates , multiplies by -gamma , adds * the identity matrix , and calls denseGETRF to do the LU decomposition of * each diagonal block . The computation of the diagonal blocks uses * the preset block and grouping information . One block per group is * computed . The Jacobian elements are generated by difference * quotients using calls to the routine fblock . * * This routine can be regarded as a prototype for the general case * of a block - diagonal preconditioner . The blocks are of size mp , and * there are = ngx*ngy blocks computed in the block - grouping scheme . * This routine generates the block-diagonal part of the Jacobian * corresponding to the interaction rates, multiplies by -gamma, adds * the identity matrix, and calls denseGETRF to do the LU decomposition of * each diagonal block. The computation of the diagonal blocks uses * the preset block and grouping information. One block per group is * computed. The Jacobian elements are generated by difference * quotients using calls to the routine fblock. * * This routine can be regarded as a prototype for the general case * of a block-diagonal preconditioner. The blocks are of size mp, and * there are ngrp=ngx*ngy blocks computed in the block-grouping scheme. *) let precond wdata jacarg _ gamma = let { Cvode.jac_t = t; Cvode.jac_y = cdata; Cvode.jac_fy = fc } = jacarg in let f1 = wdata.tmp in let cvode_mem = match wdata.cvode_mem with | Some c -> c | None -> assert false and rewtdata = unwrap wdata.rewt in Cvode.get_err_weights cvode_mem wdata.rewt; let uround = Config.unit_roundoff and p = wdata.p and pivot = wdata.pivot and jxr = wdata.jxr and jyr = wdata.jyr and mp = wdata.mp and srur = wdata.srur and ngx = wdata.ngx and ngy = wdata.ngy and mxmp = wdata.mxmp and fsave = wdata.fsave in Make mp calls to fblock to approximate each diagonal block of Jacobian . Here , fsave contains the base value of the rate vector and r0 is a minimum increment factor for the difference quotient . Here, fsave contains the base value of the rate vector and r0 is a minimum increment factor for the difference quotient. *) let fac = nvwrmsnorm fc rewtdata in let r0 = 1000.0 *. abs_float gamma *. uround *. float (neq + 1) *. fac in let r0 = if r0 = 0.0 then 1.0 else r0 in for igy = 0 to ngy - 1 do let jy = jyr.(igy) in let if00 = jy * mxmp in for igx = 0 to ngx - 1 do let jx = jxr.(igx) in let if0 = if00 + jx * mp in let ig = igx + igy * ngx in (* Generate ig-th diagonal block *) let pdata = RealArray2.unwrap p.(ig) in for j = 0 to mp - 1 do Generate the jth column as a difference quotient let jj = if0 + j in let save = cdata.{jj} in let r = max (srur *. abs_float save) (r0 /. rewtdata.{jj}) in cdata.{jj} <- cdata.{jj} +. r; fblock wdata t cdata jx jy f1; let fac = -. gamma /. r in for i = 0 to mp - 1 do pdata.{j, i} <- (f1.{i} -. fsave.{if0 + i}) *. fac done; cdata.{jj} <- save done done done; Add identity matrix and do LU decompositions on blocks . let f ig p_ig = Densemat.add_identity p_ig; Densemat.getrf p_ig pivot.(ig) in Array.iteri f p; true * This routine applies two inverse preconditioner matrices * to the vector r , using the interaction - only block - diagonal Jacobian * with block - grouping , denoted , and Gauss - Seidel applied to the * diffusion contribution to the Jacobian , denoted Jd . * It first calls for a Gauss - Seidel approximation to * ( ( I - gamma*Jd)-inverse)*r , and stores the result in z. * Then it computes ( ( I - gamma*Jr)-inverse)*z , using LU factors of the * blocks in P , and pivot information in pivot , and returns the result in z. * This routine applies two inverse preconditioner matrices * to the vector r, using the interaction-only block-diagonal Jacobian * with block-grouping, denoted Jr, and Gauss-Seidel applied to the * diffusion contribution to the Jacobian, denoted Jd. * It first calls GSIter for a Gauss-Seidel approximation to * ((I - gamma*Jd)-inverse)*r, and stores the result in z. * Then it computes ((I - gamma*Jr)-inverse)*z, using LU factors of the * blocks in P, and pivot information in pivot, and returns the result in z. *) let psolve wdata _ solve_arg (z : RealArray.t) = let { Cvode.Spils.rhs = r; Cvode.Spils.gamma = gamma } = solve_arg in Array1.blit r z; call for Gauss - Seidel iterations gs_iter wdata gamma z wdata.tmp; (* Do backsolves for inverse of block-diagonal preconditioner factor *) let p = wdata.p and pivot = wdata.pivot and mx = wdata.mx and my = wdata.my and ngx = wdata.ngx and mp = wdata.mp and jigx = wdata.jigx and jigy = wdata.jigy in let iv = ref 0 in for jy = 0 to my - 1 do let igy = jigy.(jy) in for jx = 0 to mx - 1 do let igx = jigx.(jx) in let ig = igx + igy * ngx in Densemat.getrs' p.(ig) pivot.(ig) z !iv; iv := !iv + mp done done; (* Solve for the quadrature variable *) z.{neq} <- r.{neq} +. gamma *. double_intgr z ispec wdata * This routine computes the right - hand side of the adjoint ODE system and * returns it in cBdot . The interaction rates are computed by calls to WebRates , * and these are saved in fsave for use in preconditioning . The adjoint * interaction rates are computed by calls to WebRatesB. * This routine computes the right-hand side of the adjoint ODE system and * returns it in cBdot. The interaction rates are computed by calls to WebRates, * and these are saved in fsave for use in preconditioning. The adjoint * interaction rates are computed by calls to WebRatesB. *) let fB : web_data -> RealArray.t Adj.brhsfn_no_sens = fun wdata args cBdotdata -> let cdata = args.Adj.y and cBdata = args.Adj.yb in let mxns = wdata.mxns and ns = wdata.ns and fsave = wdata.fsave and fBsave = wdata.fbsave and cox = wdata.cox and coy = wdata.coy and dx = wdata.dx and dy = wdata.dy in let gu = RealArray.make ns 0.0 in gu.{ispec-1} <- 1.0; for jy = 0 to my - 1 do let y = float jy *. dy and iyoff = mxns*jy and idyu = if jy = my-1 then -mxns else mxns and idyl = if jy = 0 then -mxns else mxns in for jx = 0 to mx - 1 do let x = float jx *. dx and ic = iyoff + ns*jx in Get interaction rates at one point ( x , y ) . web_rates_b wdata x y (cdata, ic) (cBdata, ic) (fsave, ic) (fBsave, ic); let idxu = if jx = mx-1 then -ns else ns and idxl = if jx = 0 then -ns else ns in for i = 1 to ns do let ici = ic + i-1 in (* Do differencing in y. *) let dcyli = cBdata.{ici} -. cBdata.{ici - idyl} in let dcyui = cBdata.{ici + idyu} -. cBdata.{ici} in (* Do differencing in x. *) let dcxli = cBdata.{ici} -. cBdata.{ici - idxl} in let dcxui = cBdata.{ici + idxu} -. cBdata.{ici} in (* Collect terms and load cdot elements. *) cBdotdata.{ici} <- -. coy.(i-1)*.(dcyui -. dcyli) -. cox.(i-1)*.(dcxui -. dcxli) -. fBsave.{ici} -. gu.{i-1} done done done Preconditioner setup function for the backward problem let precondb wdata jacarg _ gamma = let open Adj in let { jac_t = t; jac_y = cdata; jac_fyb = fcBdata; _ } = jacarg in let f1 = wdata.tmp in let cvode_mem = match wdata.cvode_memb with | Some c -> c | None -> assert false and rewtdata = unwrap wdata.rewtb in Adj.get_err_weights cvode_mem wdata.rewtb; let uround = Config.unit_roundoff and p = wdata.p and pivot = wdata.pivot and jxr = wdata.jxr and jyr = wdata.jyr and mp = wdata.mp and srur = wdata.srur and ngx = wdata.ngx and ngy = wdata.ngy and mxmp = wdata.mxmp and fsave = wdata.fsave in Make mp calls to fblock to approximate each diagonal block of Jacobian . Here , fsave contains the base value of the rate vector and r0 is a minimum increment factor for the difference quotient . Here, fsave contains the base value of the rate vector and r0 is a minimum increment factor for the difference quotient. *) let fac = nvwrmsnorm fcBdata rewtdata in let r0 = 1000.0 *. abs_float gamma *. uround *. float neq *. fac in let r0 = if r0 = 0.0 then 1.0 else r0 in for igy = 0 to ngy - 1 do let jy = jyr.(igy) in let if00 = jy * mxmp in for igx = 0 to ngx - 1 do let jx = jxr.(igx) in let if0 = if00 + jx * mp in let ig = igx + igy * ngx in (* Generate ig-th diagonal block *) let pdata = RealArray2.unwrap p.(ig) in for j = 0 to mp - 1 do Generate the jth column as a difference quotient let jj = if0 + j in let save = cdata.{jj} in let r = max (srur *. abs_float save) (r0 /. rewtdata.{jj}) in cdata.{jj} <- cdata.{jj} +. r; fblock wdata t cdata jx jy f1; let fac = gamma /. r in for i = 0 to mp - 1 do pdata.{i, j} <- (f1.{i} -. fsave.{if0 + i}) *. fac done; cdata.{jj} <- save done done done; Add identity matrix and do LU decompositions on blocks . let f ig p_ig = Densemat.add_identity p_ig; Densemat.getrf p_ig pivot.(ig) in Array.iteri f p; true Preconditioner solve function for the backward problem let psolveb wdata = let cache = RealArray.create ns in fun _ solve_arg z -> let { Adj.Spils.rhs = r; Adj.Spils.gamma = gamma } = solve_arg in Array1.blit r z; call for Gauss - Seidel iterations ( same routine but with gamma=-gamma ) (same routine but with gamma=-gamma) *) gs_iter wdata (-.gamma) z wdata.tmp; (* Do backsolves for inverse of block-diagonal preconditioner factor *) let p = wdata.p and pivot = wdata.pivot and mx = wdata.mx and my = wdata.my and ngx = wdata.ngx and mp = wdata.mp and jigx = wdata.jigx and jigy = wdata.jigy in let iv = ref 0 in for jy = 0 to my - 1 do let igy = jigy.(jy) in for jx = 0 to mx - 1 do let igx = jigx.(jx) in let ig = igx + igy * ngx in faster to cache and copy in / out than to Bigarray.Array1.sub ... for i=0 to ns - 1 do cache.{i} <- z.{!iv + i} done; Densemat.getrs p.(ig) pivot.(ig) cache; for i=0 to ns - 1 do z.{!iv + i} <- cache.{i} done; iv := !iv + mp done done (* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- *) let main () = let abstol, reltol = atol, rtol and abstolb, reltolb = atol, rtol in Allocate and initialize user data let wdata = alloc_user_data () in init_user_data wdata; (* Set-up forward problem *) Initializations let c = Nvector_serial.make (neq + 1) 0.0 in cinit wdata (unwrap c); Call CVodeCreate / CVodeInit for forward run Call CVSpgmr for forward run (match Config.sundials_version with | 2,5,_ -> printf "\nCreate and allocate CVODE memory for forward run\n" | _ -> printf "\nCreate and allocate CVODES memory for forward run\n"); flush stdout; let cvode_mem = Cvode.(init BDF (SStolerances (reltol, abstol)) ~lsolver:Spils.(solver (spgmr c) (prec_left ~setup:(precond wdata) (psolve wdata))) (f wdata) t0 c) in wdata.cvode_mem <- Some cvode_mem; (* Used in Precond *) (* Call CVodeSetMaxNumSteps to set the maximum number of steps the * solver will take in an attempt to reach the next output time * during forward integration. *) if sundials_gte500 then Cvode.set_max_num_steps cvode_mem 2500; (* Set-up adjoint calculations *) printf "\nAllocate global memory\n"; Adj.init cvode_mem nsteps Adj.IHermite; (* Perform forward run *) printf "\nForward integration\n"; flush stdout; let _, ncheck, _ = Adj.forward_normal cvode_mem tout c in printf "\nncheck = %d\n" ncheck; printf "\n G = int_t int_x int_y c%d(t,x,y) dx dy dt = %f \n\n" ispec (unwrap c).{neq}; (* Set-up backward problem *) (* Allocate cB *) Initialize cB = 0 let cB = Nvector_serial.make neq 0.0 in Create and allocate CVODES memory for backward run (* Call CVSpgmr *) printf "\nCreate and allocate CVODES memory for backward run\n"; flush stdout; let cvode_memb = Adj.(init_backward cvode_mem Cvode.BDF (SStolerances (reltolb, abstolb)) ~lsolver:Spils.(solver (spgmr cB) (prec_left ~setup:(precondb wdata) (psolveb wdata))) (NoSens (fB wdata)) tout cB) in Adj.set_max_num_steps cvode_memb 1000; wdata.cvode_memb <- Some cvode_memb; (* Perform backward integration *) printf "\nBackward integration\n"; Adj.backward_normal cvode_mem t0; flush stdout; let _ = Adj.get cvode_memb cB in print_output wdata (unwrap cB) ns mxns (* Check environment variables for extra arguments. *) let reps = try int_of_string (Unix.getenv "NUM_REPS") with Not_found | Failure _ -> 1 let gc_at_end = try int_of_string (Unix.getenv "GC_AT_END") <> 0 with Not_found | Failure _ -> false let gc_each_rep = try int_of_string (Unix.getenv "GC_EACH_REP") <> 0 with Not_found | Failure _ -> false (* Entry point *) let _ = for _ = 1 to reps do main (); if gc_each_rep then Gc.compact () done; if gc_at_end then Gc.compact ()
null
https://raw.githubusercontent.com/inria-parkas/sundialsml/a1848318cac2e340c32ddfd42671bef07b1390db/examples/cvodes/serial/cvsFoodWeb_ASAi_kry.ml
ocaml
Problem Specification Constants aa = a ee = e gg = g bb = b Method Constants CVodeInit Constants Output Constants Note: The value for species i at mesh point (j,k) is stored in component number (i-1) + j*NS + k*NS*MX of an N_Vector, Structure for user data species # in objective *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- Small Vector Kernels does integer division Allocate space for user data structure This routine computes and loads the vector of initial values. This routine computes the interaction rates for the backward problem x[ic+i] = cof1[i]z[ic+i] Looping point for iterations. order of loops matters x[ic+i] = beta2[i]x[ic+ns+i] + gam2[i]x[ic+mxns+i] x[ic+i] = beta[i]x[ic+ns+i] + gam2[i]x[ic+mxns+i] x[ic+i] = gam2[i]x[ic+mxns+i] x[ic+i] = beta2[i]x[ic+ns+i] + gam[i]x[ic+mxns+i] x[ic+i] = beta[i]x[ic+ns+i] + gam[i]x[ic+mxns+i] x[ic+i] = gam[i]x[ic+mxns+i] jx == 0, jy == my-1 x[ic+i] = beta2[i]x[ic+ns+i] x[ic+i] = beta[i]x[ic+ns+i] jx == mx-1, jy == my-1 Overwrite x with [(I - (D-inverse)*L)-inverse]*x. order of loops matters x[ic+i] += beta[i]x[ic-ns+i] x[ic+i] += beta2[i]x[ic-ns+i] x[ic+i] += gam[i]x[ic-mxns+i] x[ic+i] += beta[i]x[ic-ns+i] + gam[i]x[ic-mxns+i] x[ic+i] += beta2[i]x[ic-ns+i] + gam[i]x[ic-mxns+i] jx == 0, jy == my-1 x[ic+i] += gam2[i]x[ic-mxns+i] x[ic+i] += beta[i]x[ic-ns+i] + gam2[i]x[ic-mxns+i] jx == mx-1, jy == my-1 x[ic+i] += beta2[i]x[ic-ns+i] + gam2[i]x[ic-mxns+i] Add increment x to z : z <- z+x Print maximum sensitivity of G for each species Compute double space integral *-------------------------------------------------------------------- * FUNCTIONS CALLED BY CVODES *-------------------------------------------------------------------- Do differencing in y. Do differencing in x. Collect terms and load cdot elements. Generate ig-th diagonal block Do backsolves for inverse of block-diagonal preconditioner factor Solve for the quadrature variable Do differencing in y. Do differencing in x. Collect terms and load cdot elements. Generate ig-th diagonal block Do backsolves for inverse of block-diagonal preconditioner factor *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- Set-up forward problem Used in Precond Call CVodeSetMaxNumSteps to set the maximum number of steps the * solver will take in an attempt to reach the next output time * during forward integration. Set-up adjoint calculations Perform forward run Set-up backward problem Allocate cB Call CVSpgmr Perform backward integration Check environment variables for extra arguments. Entry point
* ----------------------------------------------------------------- * $ Revision : 1.4 $ * $ Date : 2011/11/23 23:53:02 $ * ----------------------------------------------------------------- * Programmer(s ): @ LLNL * ----------------------------------------------------------------- * OCaml port : , , Jun 2014 . * ----------------------------------------------------------------- * This program solves a stiff ODE system that arises from a system * of partial differential equations . The PDE system is a food web * population model , with predator - prey interaction and diffusion on * the unit square in two dimensions . The dependent variable vector * is the following : * * 1 2 ns * c = ( c , c , ... , c ) * * and the PDEs are as follows : * * i i i * dc /dt = d(i)*(c + c ) + f ( x , y , c ) ( i=1, ... ,ns ) * xx yy i * * where * * i ns j * f ( x , y , c ) = c * ( b(i ) + sum a(i , j)*c ) . * i j=1 * * The number of species is ns = 2*np , with the first np being prey * and the last np being predators . The coefficients a(i , j ) , b(i ) , * d(i ) are : * * a(i , i ) = -a ( all i ) * a(i , j ) = -g ( i < = np , j > np ) * a(i , j ) = e ( i > np , j < = np ) * b(i ) = b*(1 + alpha*x*y ) ( i < = np ) * b(i ) = -b*(1 + alpha*x*y ) ( i > np ) * d(i ) = Dprey ( i < = np ) * d(i ) i > np ) * * The spatial domain is the unit square . The final time is 10 . * The boundary conditions are : normal derivative = 0 . * A polynomial in x and y is used to set the initial conditions . * * The PDEs are discretized by central differencing on an MX by MY * mesh . The resulting ODE system is stiff . * * The ODE system is solved by CVODES using Newton iteration and * the CVSPGMR linear solver ( scaled preconditioned GMRES ) . * * The preconditioner matrix used is the product of two matrices : * ( 1 ) A matrix , only defined implicitly , based on a fixed number * of Gauss - Seidel iterations using the diffusion terms only . * ( 2 ) A block - diagonal matrix based on the partial derivatives of * the interaction terms f only , using block - grouping ( computing * only a subset of the ns by ns blocks ) . * * Additionally , CVODES integrates backwards in time the * the semi - discrete form of the adjoint PDE : * d(lambda)/dt = - D^T ( lambda_xx + ) * - F_c^T lambda - g_c^T * with homogeneous Neumann boundary conditions and final * conditions are the following : * lambda(x , y , t = t_final ) = 0.0 * whose solution at t = 0 represents the sensitivity of * G = int_0^t_final int_x int _ y g(t , c ) dx dy dt * with respect to the initial conditions of the original problem . * * In this example , * g(t , c ) = c(ISPEC ) , with ISPEC defined below . * * During the forward run , CVODES also computes G as * G = phi(t_final ) * where * d(phi)/dt = int_x int _ y g(t , c ) dx dy * and the 2 - D integral is evaluated with Simpson 's rule . * ----------------------------------------------------------------- * Reference : and , Reduced Storage * Matrix Methods in Stiff ODE Systems , J. Appl . Math . & Comp . , 31 * ( 1989 ) , pp . 40 - 91 . Also available as National * Laboratory Report UCRL-95088 , Rev. 1 , June 1987 . * ----------------------------------------------------------------- * ----------------------------------------------------------------- * $Revision: 1.4 $ * $Date: 2011/11/23 23:53:02 $ * ----------------------------------------------------------------- * Programmer(s): Radu Serban @ LLNL * ----------------------------------------------------------------- * OCaml port: Timothy Bourke, Inria, Jun 2014. * ----------------------------------------------------------------- * This program solves a stiff ODE system that arises from a system * of partial differential equations. The PDE system is a food web * population model, with predator-prey interaction and diffusion on * the unit square in two dimensions. The dependent variable vector * is the following: * * 1 2 ns * c = (c , c , ..., c ) * * and the PDEs are as follows: * * i i i * dc /dt = d(i)*(c + c ) + f (x,y,c) (i=1,...,ns) * xx yy i * * where * * i ns j * f (x,y,c) = c *(b(i) + sum a(i,j)*c ). * i j=1 * * The number of species is ns = 2*np, with the first np being prey * and the last np being predators. The coefficients a(i,j), b(i), * d(i) are: * * a(i,i) = -a (all i) * a(i,j) = -g (i <= np, j > np) * a(i,j) = e (i > np, j <= np) * b(i) = b*(1 + alpha*x*y) (i <= np) * b(i) = -b*(1 + alpha*x*y) (i > np) * d(i) = Dprey (i <= np) * d(i) = Dpred (i > np) * * The spatial domain is the unit square. The final time is 10. * The boundary conditions are: normal derivative = 0. * A polynomial in x and y is used to set the initial conditions. * * The PDEs are discretized by central differencing on an MX by MY * mesh. The resulting ODE system is stiff. * * The ODE system is solved by CVODES using Newton iteration and * the CVSPGMR linear solver (scaled preconditioned GMRES). * * The preconditioner matrix used is the product of two matrices: * (1) A matrix, only defined implicitly, based on a fixed number * of Gauss-Seidel iterations using the diffusion terms only. * (2) A block-diagonal matrix based on the partial derivatives of * the interaction terms f only, using block-grouping (computing * only a subset of the ns by ns blocks). * * Additionally, CVODES integrates backwards in time the * the semi-discrete form of the adjoint PDE: * d(lambda)/dt = - D^T ( lambda_xx + lambda_yy ) * - F_c^T lambda - g_c^T * with homogeneous Neumann boundary conditions and final * conditions are the following: * lambda(x,y,t=t_final) = 0.0 * whose solution at t = 0 represents the sensitivity of * G = int_0^t_final int_x int _y g(t,c) dx dy dt * with respect to the initial conditions of the original problem. * * In this example, * g(t,c) = c(ISPEC), with ISPEC defined below. * * During the forward run, CVODES also computes G as * G = phi(t_final) * where * d(phi)/dt = int_x int _y g(t,c) dx dy * and the 2-D integral is evaluated with Simpson's rule. * ----------------------------------------------------------------- * Reference: Peter N. Brown and Alan C. Hindmarsh, Reduced Storage * Matrix Methods in Stiff ODE Systems, J. Appl. Math. & Comp., 31 * (1989), pp. 40-91. Also available as Lawrence Livermore National * Laboratory Report UCRL-95088, Rev. 1, June 1987. * ----------------------------------------------------------------- *) open Sundials module Adj = Cvodes.Adjoint module Densemat = Matrix.ArrayDense open Bigarray let unwrap = Nvector.unwrap let sundials_gte500 = let n, _, _ = Sundials_configuration.sundials_version in n >= 5 let printf = Printf.printf let sqr x = x *. x let nvwrmsnorm = Nvector_serial.DataOps.wrmsnorm let nvlinearsum = Nvector_serial.DataOps.linearsum let dprey = 1.0 let dpred = 0.5 let alph = 1.0 let np = 3 let ns = (2*np) let mx = 20 let my = 20 let mxns = mx*ns let ax = 1.0 let ay = 1.0 let dx = ax/.float (mx-1) let dy = ay/.float (my-1) let mp = ns let mq = mx*my let mxmp = mx*mp let ngx = 2 let ngy = 2 let ngrp = ngx*ngy let itmax = 5 let neq = (ns*mx*my) let t0 = 0.0 let rtol = 1e-5 let atol = 1e-5 let tout = 10.0 where 1 < = i < = NS , 0 < = j < MX , 0 < = k < MY . type web_data = { p : Densemat.t array; pivot : LintArray.t array; ns : int; mxns : int; mp : int; mq : int; mx : int; my : int; ngrp : int; ngx : int; ngy : int; mxmp : int; jgx : int array; jgy : int array; jigx : int array; jigy : int array; jxr : int array; jyr : int array; acoef : float array array; bcoef : float array; diff : float array; cox : float array; coy : float array; dx : float; dy : float; srur : float; fsave : RealArray.t; fbsave : RealArray.t; tmp : RealArray.t; rewt : Nvector_serial.t; rewtb : Nvector_serial.t; mutable cvode_mem : Nvector_serial.kind Cvode.serial_session option; mutable cvode_memb : Nvector_serial.kind Adj.serial_bsession option; } Adjoint calculation constants G = int_t int_x ) dy dx dt check points every NSTEPS steps let v_sum_prods n (u : RealArray.t) uoffs p (q : RealArray.t) qoffs (v : float array)(w : RealArray.t) woffs = for i = 0 to n - 1 do u.{uoffs + i} <- p.(i) *. q.{qoffs + i} +. v.(i) *. w.{woffs + i} done let v_inc_by_prod n (u : RealArray.t) uoffs (v : float array) (w : RealArray.t) woffs = for i = 0 to n - 1 do u.{uoffs + i} <- u.{uoffs + i} +. v.(i) *. w.{woffs + i} done let v_prod n (u : RealArray.t) uoffs (v : float array) (w : RealArray.t) woffs = for i = 0 to n - 1 do u.{uoffs + i} <- v.(i) *. w.{woffs + i} done let v_zero n u offs = for i = 0 to n - 1 do u.{offs + i} <- 0.0 done * This routine sets arrays jg , jig , and jr describing * a uniform partition of ( 0,1,2, ... ,m-1 ) into ng groups . * The arrays set are : * jg = length ng+1 array of group boundaries . * Group ig has indices j = ... ,jg[ig+1]-1 . * jig = length m array of group indices vs node index . * Node index j is in group jig[j ] . * jr = length ng array of indices representing the groups . * The index for group ig is j = jr[ig ] . * This routine sets arrays jg, jig, and jr describing * a uniform partition of (0,1,2,...,m-1) into ng groups. * The arrays set are: * jg = length ng+1 array of group boundaries. * Group ig has indices j = jg[ig],...,jg[ig+1]-1. * jig = length m array of group indices vs node index. * Node index j is in group jig[j]. * jr = length ng array of indices representing the groups. * The index for group ig is j = jr[ig]. *) let set_groups m ng jg jig jr = for ig = 0 to ng - 1 do jg.(ig) <- ig * mper done; jg.(ng) <- m; let ngm1 = ng - 1 in let len1 = ngm1 * mper in for j = 0 to len1 - 1 do jig.(j) <- j / mper done; for j = len1 to m - 1 do jig.(j) <- ngm1 done; for ig = 0 to ngm1 - 1 do jr.(ig) <- ((2 * ig + 1) * mper - 1) / 2; done; jr.(ngm1) <- (ngm1 * mper + m - 1) / 2 let alloc_user_data () = let r = { p = Array.init ngrp (fun _ -> Densemat.create ns ns); pivot = Array.init ngrp (fun _ -> LintArray.create ns); ns = ns; mxns = mxns; mp = mp; mq = mq; mx = mx; my = my; ngrp = ngrp; ngx = ngx; ngy = ngy; mxmp = mxmp; jgx = Array.make (ngx + 1) 0; jgy = Array.make (ngy + 1) 0; jigx = Array.make mx 0; jigy = Array.make my 0; jxr = Array.make ngx 0; jyr = Array.make ngy 0; acoef = Array.make_matrix ns ns 0.0; bcoef = Array.make ns 0.0; diff = Array.make ns 0.0; cox = Array.make ns 0.0; coy = Array.make ns 0.0; dx = dx; dy = dy; srur = sqrt Config.unit_roundoff; fsave = RealArray.create neq; fbsave = RealArray.create neq; tmp = RealArray.create neq; rewt = Nvector_serial.make (neq + 1) 0.0; The original C code uses rewt for forward solving where the length is neq + 1 and also for backward solving where the length is neq ( it relies on the fact that nvwrmsnorm takes the length from its first argument , and not its second ) . This is not possible in the OCaml interface which checks nvectors for compatibility , i.e. , serial nvectors must have the same length . neq + 1 and also for backward solving where the length is neq (it relies on the fact that nvwrmsnorm takes the length from its first argument, and not its second). This is not possible in the OCaml interface which checks nvectors for compatibility, i.e., serial nvectors must have the same length. *) rewtb = Nvector_serial.make neq 0.0; cvode_mem = None; cvode_memb = None; } in let acoef = r.acoef and bcoef = r.bcoef and diff = r.diff and cox = r.cox and coy = r.coy in for j = 0 to np - 1 do for i = 0 to np - 1 do acoef.(np + i).(j) <- ee; acoef.(i).(np + j) <- -. gg done; acoef.(j).(j) <- -. aa; acoef.(np + j).(np + j) <- -. aa; bcoef.(j) <- bb; bcoef.(np + j) <- -. bb; diff.(j) <- dprey; diff.(np + j) <- dpred done; let sqr_dx = sqr dx in let sqr_dy = sqr dy in for i = 0 to ns - 1 do cox.(i) <- diff.(i) /. sqr_dx; coy.(i) <- diff.(i) /. sqr_dy done; r Initialize user data structure let init_user_data wdata = set_groups mx ngx wdata.jgx wdata.jigx wdata.jxr; set_groups my ngy wdata.jgy wdata.jigy wdata.jyr let cinit wdata (cdata : RealArray.t) = let ns = wdata.ns and mxns = wdata.mxns and dx = wdata.dx and dy = wdata.dy in let x_factor = 4.0 /. sqr ax and y_factor = 4.0 /. sqr ay in for jy = 0 to my - 1 do let y = float jy *. dy in let argy = sqr (y_factor *. y *. (ay -. y)) in let iyoff = mxns * jy in for jx = 0 to mx - 1 do let x = float jx *. dx in let argx = sqr (x_factor *. x *. (ax -. x)) in let ioff = iyoff + ns * jx in for i = 1 to ns do let ici = ioff + i - 1 in cdata.{ici} <- 10.0 +. float i *. argx *. argy done done done; Initialize quadrature variable to zero cdata.{neq} <- 0.0 * This routine computes the interaction rates for the species * c_1 , ... , ( stored in c[0], ... ,c[ns-1 ] ) , at one spatial point * and at time t. * This routine computes the interaction rates for the species * c_1, ... ,c_ns (stored in c[0],...,c[ns-1]), at one spatial point * and at time t. *) let web_rates wdata x y ((c : RealArray.t), c_off) ((rate : RealArray.t), rate_off) = let acoef = wdata.acoef and bcoef = wdata.bcoef in for i = rate_off to rate_off + ns - 1 do rate.{i} <- 0.0 done; for i = 0 to ns - 1 do for j = 0 to ns - 1 do let c = c.{c_off + j} in rate.{rate_off + i} <- rate.{rate_off + i} +. c *. acoef.(i).(j) done done; let fac = 1.0 +. alph *. x *. y in for i = 0 to ns - 1 do rate.{rate_off + i} <- c.{c_off + i} *. (bcoef.(i) *. fac +. rate.{rate_off + i}) done let web_rates_b wdata x y ((c : RealArray.t), c_off) ((cB : RealArray.t), cB_off) ((rate : RealArray.t), rate_off) ((rateB : RealArray.t), rateB_off) = let ns = wdata.ns and acoef = wdata.acoef and bcoef = wdata.bcoef in let fac = 1.0 +. alph *. x *. y in for i = 0 to ns - 1 do rate.{rate_off + i} <- bcoef.(i) *. fac done; for j = 0 to ns - 1 do for i = 0 to ns - 1 do rate.{rate_off + i} <- rate.{rate_off + i} +. acoef.(i).(j) *. c.{c_off + j} done done; for i = 0 to ns - 1 do rateB.{rateB_off + i} <- cB.{cB_off + i} *. rate.{rate_off + i}; rate.{rate_off + i} <- c.{c_off + i} *. rate.{rate_off + i} done; for j = 0 to ns - 1 do for i = 0 to ns - 1 do rateB.{rateB_off + i} <- rateB.{rateB_off + i} +. acoef.(j).(i) *. c.{c_off + j} *. cB.{cB_off + j} done done * This routine computes one block of the interaction terms of the * system , namely block ( jx , jy ) , for use in preconditioning . * Here jx and jy count from 0 . * This routine computes one block of the interaction terms of the * system, namely block (jx,jy), for use in preconditioning. * Here jx and jy count from 0. *) let fblock wdata _ cdata jx jy cdotdata = let iblok = jx + jy * wdata.mx and y = float jy *. wdata.dy and x = float jx *. wdata.dx in let ic = wdata.ns * iblok in web_rates wdata x y (cdata, ic) (cdotdata, 0) * This routine performs iterations to compute an * approximation to ( P - inverse)*z , where P = I - gamma*Jd , and * represents the diffusion contributions to the Jacobian . * The answer is stored in z on return , and x is a temporary vector . * The dimensions below assume a global constant NS > = ns . * Some inner loops of length ns are implemented with the small * vector kernels v_sum_prods , v_prod , v_inc_by_prod . * This routine performs ITMAX=5 Gauss-Seidel iterations to compute an * approximation to (P-inverse)*z, where P = I - gamma*Jd, and * Jd represents the diffusion contributions to the Jacobian. * The answer is stored in z on return, and x is a temporary vector. * The dimensions below assume a global constant NS >= ns. * Some inner loops of length ns are implemented with the small * vector kernels v_sum_prods, v_prod, v_inc_by_prod. *) let gs_iter wdata = let beta = Array.make ns 0.0 and beta2 = Array.make ns 0.0 and cof1 = Array.make ns 0.0 and gam = Array.make ns 0.0 and gam2 = Array.make ns 0.0 in fun gamma zd xd -> let ns = wdata.ns and mx = wdata.mx and my = wdata.my and mxns = wdata.mxns and cox = wdata.cox and coy = wdata.coy in Write matrix as P = D - L - U. Load local arrays beta , beta2 , gam , gam2 , and cof1 . Load local arrays beta, beta2, gam, gam2, and cof1. *) for i = 0 to ns - 1 do let temp = 1.0 /. (1.0 +. 2.0 *. gamma *. (cox.(i) +. coy.(i))) in beta.(i) <- gamma *. cox.(i) *. temp; beta2.(i) <- 2.0 *. beta.(i); gam.(i) <- gamma *. coy.(i) *. temp; gam2.(i) <- 2.0 *. gam.(i); cof1.(i) <- temp done; Begin iteration loop . Load vector x with ( D - inverse)*z for first iteration . Load vector x with (D-inverse)*z for first iteration. *) for jy = 0 to my - 1 do let iyoff = mxns * jy in for jx = 0 to mx - 1 do let ic = iyoff + ns*jx in done done; Array1.fill zd 0.0; for iter = 1 to itmax do Calculate ( D - inverse)*U*x if not the first iteration . if (iter > 1) then for jy = 0 to my - 1 do let iyoff = mxns * jy in let ic = iyoff + ns * jx and x_loc = if jx = 0 then 0 else if jx = mx - 1 then 2 else 1 and y_loc = if jy = 0 then 0 else if jy = my - 1 then 2 else 1 in match (3 * y_loc + x_loc) with | 0 -> jx = = 0 , jy = = 0 v_sum_prods ns xd ic beta2 xd (ic + ns) gam2 xd (ic + mxns) | 1 -> 1 < = jx < = mx-2 , jy = = 0 v_sum_prods ns xd ic beta xd (ic + ns) gam2 xd (ic + mxns) | 2 -> jx = = mx-1 , jy = = 0 v_prod ns xd ic gam2 xd (ic + mxns) | 3 -> jx = = 0 , 1 < = jy < = my-2 v_sum_prods ns xd ic beta2 xd (ic + ns) gam xd (ic + mxns) | 4 -> 1 < = jx < = mx-2 , 1 < = jy < = my-2 v_sum_prods ns xd ic beta xd (ic + ns) gam xd (ic + mxns) | 5 -> jx = = mx-1 , 1 < = jy < = my-2 v_prod ns xd ic gam xd (ic + mxns) | 6 -> v_prod ns xd ic beta2 xd (ic + ns) | 7 -> 1 < = jx < = mx-2 , jy = = my-1 v_prod ns xd ic beta xd (ic + ns) | 8 -> x[ic+i ] = 0.0 v_zero ns xd ic | _ -> assert false done end if ( iter > 1 ) for jy = 0 to my - 1 do let iyoff = mxns * jy in let ic = iyoff + ns * jx and x_loc = if jx = 0 then 0 else if jx = mx - 1 then 2 else 1 and y_loc = if jy = 0 then 0 else if jy = my - 1 then 2 else 1 in match (3 * y_loc + x_loc) with | 0 -> jx = = 0 , jy = = 0 () | 1 -> 1 < = jx < = mx-2 , jy = = 0 v_inc_by_prod ns xd ic beta xd (ic - ns) | 2 -> jx = = mx-1 , jy = = 0 v_inc_by_prod ns xd ic beta2 xd (ic - ns) | 3 -> jx = = 0 , 1 < = jy < = my-2 v_inc_by_prod ns xd ic gam xd (ic - mxns) | 4 -> 1 < = jx < = mx-2 , 1 < = jy < = my-2 v_inc_by_prod ns xd ic beta xd (ic - ns); v_inc_by_prod ns xd ic gam xd (ic - mxns) | 5 -> jx = = mx-1 , 1 < = jy < = my-2 v_inc_by_prod ns xd ic beta2 xd (ic - ns); v_inc_by_prod ns xd ic gam xd (ic - mxns) | 6 -> v_inc_by_prod ns xd ic gam2 xd (ic - mxns) | 7 -> 1 < = jx < = mx-2 , jy = = my-1 v_inc_by_prod ns xd ic beta xd (ic - ns); v_inc_by_prod ns xd ic gam2 xd (ic - mxns) | 8 -> v_inc_by_prod ns xd ic beta2 xd (ic - ns); v_inc_by_prod ns xd ic gam2 xd (ic - mxns) | _ -> assert false done done; nvlinearsum 1.0 zd 1.0 xd zd done let print_output wdata (cdata : RealArray.t) ns mxns = let x = ref 0.0 and y = ref 0.0 in for i=1 to ns do let cmax = ref 0.0 in for jy=my-1 downto 0 do for jx=0 to mx - 1 do let cij = cdata.{(i-1) + jx*ns + jy*mxns} in if abs_float(cij) > !cmax then begin cmax := cij; x := float jx *. wdata.dx; y := float jy *. wdata.dy end done done; printf "\nMaximum sensitivity with respect to I.C. of species %d\n" i; printf " lambda max = %e\n" !cmax; printf "at\n"; printf " x = %e\n y = %e\n" !x !y done let double_intgr (cdata : RealArray.t) i wdata = let ns = wdata.ns and mx = wdata.mx and my = wdata.my and mxns = wdata.mxns and dx = wdata.dx and dy = wdata.dy in let jy = 0 in let intgr_x = ref cdata.{(i-1) + jy*mxns} in for jx = 1 to mx-2 do intgr_x := !intgr_x +. 2.0 *. cdata.{(i-1) + jx*ns + jy*mxns} done; intgr_x := !intgr_x +. cdata.{(i-1) + (mx-1)*ns + jy*mxns}; intgr_x := !intgr_x *. 0.5 *. dx; let intgr_xy = ref !intgr_x in for jy = 1 to my-2 do intgr_x := cdata.{(i-1)+jy*mxns}; for jx = 1 to mx-2 do intgr_x := !intgr_x +. 2.0 *. cdata.{(i-1) + jx*ns + jy*mxns} done; intgr_x := !intgr_x +. cdata.{(i-1) + (mx-1)*ns + jy*mxns}; intgr_x := !intgr_x *. 0.5 *. dx; intgr_xy := !intgr_xy +. 2.0 *. !intgr_x done; let jy = my-1 in intgr_x := cdata.{(i-1) + jy*mxns}; for jx = 1 to mx-2 do intgr_x := !intgr_x +. 2.0 *. cdata.{(i-1) + jx*ns + jy*mxns} done; intgr_x := !intgr_x +. cdata.{(i-1) + (mx-1)*ns + jy*mxns}; intgr_x := !intgr_x *. 0.5 *. dx; intgr_xy := !intgr_xy +. !intgr_x; intgr_xy := !intgr_xy *. 0.5 *. dy; !intgr_xy * This routine computes the right - hand side of the ODE system and * returns it in cdot . The interaction rates are computed by calls to WebRates , * and these are saved in fsave for use in preconditioning . * This routine computes the right-hand side of the ODE system and * returns it in cdot. The interaction rates are computed by calls to WebRates, * and these are saved in fsave for use in preconditioning. *) let f wdata _ (cdata : RealArray.t) (cdotdata : RealArray.t) = let ns = wdata.ns and fsave = wdata.fsave and cox = wdata.cox and coy = wdata.coy and mxns = wdata.mxns and dx = wdata.dx and dy = wdata.dy in for jy = 0 to my - 1 do let y = float jy *. dy in let iyoff = mxns*jy in let idyu = if jy = my - 1 then - mxns else mxns in let idyl = if jy = 0 then - mxns else mxns in for jx = 0 to mx - 1 do let x = float jx *. dx in let ic = iyoff + ns * jx in Get interaction rates at one point ( x , y ) . web_rates wdata x y (cdata, ic) (fsave, ic); let idxu = if jx = mx - 1 then -ns else ns in let idxl = if jx = 0 then -ns else ns in for i = 1 to ns do let ici = ic + i - 1 in let dcyli = cdata.{ici} -. cdata.{ici - idyl} in let dcyui = cdata.{ici + idyu} -. cdata.{ici} in let dcxli = cdata.{ici} -. cdata.{ici - idxl} in let dcxui = cdata.{ici + idxu} -. cdata.{ici} in cdotdata.{ici} <- coy.(i - 1) *. (dcyui -. dcyli) +. cox.(i - 1) *. (dcxui -. dcxli) +. fsave.{ici} done done done; Quadrature equation ( species 1 ) cdotdata.{neq} <- double_intgr cdata ispec wdata * This routine generates the block - diagonal part of the Jacobian * corresponding to the interaction rates , multiplies by -gamma , adds * the identity matrix , and calls denseGETRF to do the LU decomposition of * each diagonal block . The computation of the diagonal blocks uses * the preset block and grouping information . One block per group is * computed . The Jacobian elements are generated by difference * quotients using calls to the routine fblock . * * This routine can be regarded as a prototype for the general case * of a block - diagonal preconditioner . The blocks are of size mp , and * there are = ngx*ngy blocks computed in the block - grouping scheme . * This routine generates the block-diagonal part of the Jacobian * corresponding to the interaction rates, multiplies by -gamma, adds * the identity matrix, and calls denseGETRF to do the LU decomposition of * each diagonal block. The computation of the diagonal blocks uses * the preset block and grouping information. One block per group is * computed. The Jacobian elements are generated by difference * quotients using calls to the routine fblock. * * This routine can be regarded as a prototype for the general case * of a block-diagonal preconditioner. The blocks are of size mp, and * there are ngrp=ngx*ngy blocks computed in the block-grouping scheme. *) let precond wdata jacarg _ gamma = let { Cvode.jac_t = t; Cvode.jac_y = cdata; Cvode.jac_fy = fc } = jacarg in let f1 = wdata.tmp in let cvode_mem = match wdata.cvode_mem with | Some c -> c | None -> assert false and rewtdata = unwrap wdata.rewt in Cvode.get_err_weights cvode_mem wdata.rewt; let uround = Config.unit_roundoff and p = wdata.p and pivot = wdata.pivot and jxr = wdata.jxr and jyr = wdata.jyr and mp = wdata.mp and srur = wdata.srur and ngx = wdata.ngx and ngy = wdata.ngy and mxmp = wdata.mxmp and fsave = wdata.fsave in Make mp calls to fblock to approximate each diagonal block of Jacobian . Here , fsave contains the base value of the rate vector and r0 is a minimum increment factor for the difference quotient . Here, fsave contains the base value of the rate vector and r0 is a minimum increment factor for the difference quotient. *) let fac = nvwrmsnorm fc rewtdata in let r0 = 1000.0 *. abs_float gamma *. uround *. float (neq + 1) *. fac in let r0 = if r0 = 0.0 then 1.0 else r0 in for igy = 0 to ngy - 1 do let jy = jyr.(igy) in let if00 = jy * mxmp in for igx = 0 to ngx - 1 do let jx = jxr.(igx) in let if0 = if00 + jx * mp in let ig = igx + igy * ngx in let pdata = RealArray2.unwrap p.(ig) in for j = 0 to mp - 1 do Generate the jth column as a difference quotient let jj = if0 + j in let save = cdata.{jj} in let r = max (srur *. abs_float save) (r0 /. rewtdata.{jj}) in cdata.{jj} <- cdata.{jj} +. r; fblock wdata t cdata jx jy f1; let fac = -. gamma /. r in for i = 0 to mp - 1 do pdata.{j, i} <- (f1.{i} -. fsave.{if0 + i}) *. fac done; cdata.{jj} <- save done done done; Add identity matrix and do LU decompositions on blocks . let f ig p_ig = Densemat.add_identity p_ig; Densemat.getrf p_ig pivot.(ig) in Array.iteri f p; true * This routine applies two inverse preconditioner matrices * to the vector r , using the interaction - only block - diagonal Jacobian * with block - grouping , denoted , and Gauss - Seidel applied to the * diffusion contribution to the Jacobian , denoted Jd . * It first calls for a Gauss - Seidel approximation to * ( ( I - gamma*Jd)-inverse)*r , and stores the result in z. * Then it computes ( ( I - gamma*Jr)-inverse)*z , using LU factors of the * blocks in P , and pivot information in pivot , and returns the result in z. * This routine applies two inverse preconditioner matrices * to the vector r, using the interaction-only block-diagonal Jacobian * with block-grouping, denoted Jr, and Gauss-Seidel applied to the * diffusion contribution to the Jacobian, denoted Jd. * It first calls GSIter for a Gauss-Seidel approximation to * ((I - gamma*Jd)-inverse)*r, and stores the result in z. * Then it computes ((I - gamma*Jr)-inverse)*z, using LU factors of the * blocks in P, and pivot information in pivot, and returns the result in z. *) let psolve wdata _ solve_arg (z : RealArray.t) = let { Cvode.Spils.rhs = r; Cvode.Spils.gamma = gamma } = solve_arg in Array1.blit r z; call for Gauss - Seidel iterations gs_iter wdata gamma z wdata.tmp; let p = wdata.p and pivot = wdata.pivot and mx = wdata.mx and my = wdata.my and ngx = wdata.ngx and mp = wdata.mp and jigx = wdata.jigx and jigy = wdata.jigy in let iv = ref 0 in for jy = 0 to my - 1 do let igy = jigy.(jy) in for jx = 0 to mx - 1 do let igx = jigx.(jx) in let ig = igx + igy * ngx in Densemat.getrs' p.(ig) pivot.(ig) z !iv; iv := !iv + mp done done; z.{neq} <- r.{neq} +. gamma *. double_intgr z ispec wdata * This routine computes the right - hand side of the adjoint ODE system and * returns it in cBdot . The interaction rates are computed by calls to WebRates , * and these are saved in fsave for use in preconditioning . The adjoint * interaction rates are computed by calls to WebRatesB. * This routine computes the right-hand side of the adjoint ODE system and * returns it in cBdot. The interaction rates are computed by calls to WebRates, * and these are saved in fsave for use in preconditioning. The adjoint * interaction rates are computed by calls to WebRatesB. *) let fB : web_data -> RealArray.t Adj.brhsfn_no_sens = fun wdata args cBdotdata -> let cdata = args.Adj.y and cBdata = args.Adj.yb in let mxns = wdata.mxns and ns = wdata.ns and fsave = wdata.fsave and fBsave = wdata.fbsave and cox = wdata.cox and coy = wdata.coy and dx = wdata.dx and dy = wdata.dy in let gu = RealArray.make ns 0.0 in gu.{ispec-1} <- 1.0; for jy = 0 to my - 1 do let y = float jy *. dy and iyoff = mxns*jy and idyu = if jy = my-1 then -mxns else mxns and idyl = if jy = 0 then -mxns else mxns in for jx = 0 to mx - 1 do let x = float jx *. dx and ic = iyoff + ns*jx in Get interaction rates at one point ( x , y ) . web_rates_b wdata x y (cdata, ic) (cBdata, ic) (fsave, ic) (fBsave, ic); let idxu = if jx = mx-1 then -ns else ns and idxl = if jx = 0 then -ns else ns in for i = 1 to ns do let ici = ic + i-1 in let dcyli = cBdata.{ici} -. cBdata.{ici - idyl} in let dcyui = cBdata.{ici + idyu} -. cBdata.{ici} in let dcxli = cBdata.{ici} -. cBdata.{ici - idxl} in let dcxui = cBdata.{ici + idxu} -. cBdata.{ici} in cBdotdata.{ici} <- -. coy.(i-1)*.(dcyui -. dcyli) -. cox.(i-1)*.(dcxui -. dcxli) -. fBsave.{ici} -. gu.{i-1} done done done Preconditioner setup function for the backward problem let precondb wdata jacarg _ gamma = let open Adj in let { jac_t = t; jac_y = cdata; jac_fyb = fcBdata; _ } = jacarg in let f1 = wdata.tmp in let cvode_mem = match wdata.cvode_memb with | Some c -> c | None -> assert false and rewtdata = unwrap wdata.rewtb in Adj.get_err_weights cvode_mem wdata.rewtb; let uround = Config.unit_roundoff and p = wdata.p and pivot = wdata.pivot and jxr = wdata.jxr and jyr = wdata.jyr and mp = wdata.mp and srur = wdata.srur and ngx = wdata.ngx and ngy = wdata.ngy and mxmp = wdata.mxmp and fsave = wdata.fsave in Make mp calls to fblock to approximate each diagonal block of Jacobian . Here , fsave contains the base value of the rate vector and r0 is a minimum increment factor for the difference quotient . Here, fsave contains the base value of the rate vector and r0 is a minimum increment factor for the difference quotient. *) let fac = nvwrmsnorm fcBdata rewtdata in let r0 = 1000.0 *. abs_float gamma *. uround *. float neq *. fac in let r0 = if r0 = 0.0 then 1.0 else r0 in for igy = 0 to ngy - 1 do let jy = jyr.(igy) in let if00 = jy * mxmp in for igx = 0 to ngx - 1 do let jx = jxr.(igx) in let if0 = if00 + jx * mp in let ig = igx + igy * ngx in let pdata = RealArray2.unwrap p.(ig) in for j = 0 to mp - 1 do Generate the jth column as a difference quotient let jj = if0 + j in let save = cdata.{jj} in let r = max (srur *. abs_float save) (r0 /. rewtdata.{jj}) in cdata.{jj} <- cdata.{jj} +. r; fblock wdata t cdata jx jy f1; let fac = gamma /. r in for i = 0 to mp - 1 do pdata.{i, j} <- (f1.{i} -. fsave.{if0 + i}) *. fac done; cdata.{jj} <- save done done done; Add identity matrix and do LU decompositions on blocks . let f ig p_ig = Densemat.add_identity p_ig; Densemat.getrf p_ig pivot.(ig) in Array.iteri f p; true Preconditioner solve function for the backward problem let psolveb wdata = let cache = RealArray.create ns in fun _ solve_arg z -> let { Adj.Spils.rhs = r; Adj.Spils.gamma = gamma } = solve_arg in Array1.blit r z; call for Gauss - Seidel iterations ( same routine but with gamma=-gamma ) (same routine but with gamma=-gamma) *) gs_iter wdata (-.gamma) z wdata.tmp; let p = wdata.p and pivot = wdata.pivot and mx = wdata.mx and my = wdata.my and ngx = wdata.ngx and mp = wdata.mp and jigx = wdata.jigx and jigy = wdata.jigy in let iv = ref 0 in for jy = 0 to my - 1 do let igy = jigy.(jy) in for jx = 0 to mx - 1 do let igx = jigx.(jx) in let ig = igx + igy * ngx in faster to cache and copy in / out than to Bigarray.Array1.sub ... for i=0 to ns - 1 do cache.{i} <- z.{!iv + i} done; Densemat.getrs p.(ig) pivot.(ig) cache; for i=0 to ns - 1 do z.{!iv + i} <- cache.{i} done; iv := !iv + mp done done let main () = let abstol, reltol = atol, rtol and abstolb, reltolb = atol, rtol in Allocate and initialize user data let wdata = alloc_user_data () in init_user_data wdata; Initializations let c = Nvector_serial.make (neq + 1) 0.0 in cinit wdata (unwrap c); Call CVodeCreate / CVodeInit for forward run Call CVSpgmr for forward run (match Config.sundials_version with | 2,5,_ -> printf "\nCreate and allocate CVODE memory for forward run\n" | _ -> printf "\nCreate and allocate CVODES memory for forward run\n"); flush stdout; let cvode_mem = Cvode.(init BDF (SStolerances (reltol, abstol)) ~lsolver:Spils.(solver (spgmr c) (prec_left ~setup:(precond wdata) (psolve wdata))) (f wdata) t0 c) in if sundials_gte500 then Cvode.set_max_num_steps cvode_mem 2500; printf "\nAllocate global memory\n"; Adj.init cvode_mem nsteps Adj.IHermite; printf "\nForward integration\n"; flush stdout; let _, ncheck, _ = Adj.forward_normal cvode_mem tout c in printf "\nncheck = %d\n" ncheck; printf "\n G = int_t int_x int_y c%d(t,x,y) dx dy dt = %f \n\n" ispec (unwrap c).{neq}; Initialize cB = 0 let cB = Nvector_serial.make neq 0.0 in Create and allocate CVODES memory for backward run printf "\nCreate and allocate CVODES memory for backward run\n"; flush stdout; let cvode_memb = Adj.(init_backward cvode_mem Cvode.BDF (SStolerances (reltolb, abstolb)) ~lsolver:Spils.(solver (spgmr cB) (prec_left ~setup:(precondb wdata) (psolveb wdata))) (NoSens (fB wdata)) tout cB) in Adj.set_max_num_steps cvode_memb 1000; wdata.cvode_memb <- Some cvode_memb; printf "\nBackward integration\n"; Adj.backward_normal cvode_mem t0; flush stdout; let _ = Adj.get cvode_memb cB in print_output wdata (unwrap cB) ns mxns let reps = try int_of_string (Unix.getenv "NUM_REPS") with Not_found | Failure _ -> 1 let gc_at_end = try int_of_string (Unix.getenv "GC_AT_END") <> 0 with Not_found | Failure _ -> false let gc_each_rep = try int_of_string (Unix.getenv "GC_EACH_REP") <> 0 with Not_found | Failure _ -> false let _ = for _ = 1 to reps do main (); if gc_each_rep then Gc.compact () done; if gc_at_end then Gc.compact ()
436c2c715dffeda5ee5e23b2f10e83f1c3532e17b0fd2282a306e4628e2c3f82
walkie/Hagl
Game.hs
# LANGUAGE FlexibleContexts , FlexibleInstances , PatternGuards , TypeFamilies , UndecidableInstances # FlexibleInstances, PatternGuards, TypeFamilies, UndecidableInstances #-} | All games in Hagl can be reduced to one of two kinds of game trees . -- Each node in a game tree consists of a game state and an action to -- perform (e.g. a player must make a decision). Edges between nodes -- are determined by moves. For `Discrete` game trees, the edges are -- given explicitly as a list. For `Continuous` game trees, the edges -- are defined implicitly by a function. Games end when a `Payoff` -- node is reached. module Hagl.Game where import Data.Maybe (fromMaybe) import qualified Data.Tree as DT (Tree(..), drawTree) import Hagl.List import Hagl.Payoff -- -- * Games -- -- | A game has several associated types describing whether the game -- is discrete or continuous, what type of state it maintains, and -- the type of moves on edges. The function `gameTree` is used -- to get the game tree representation of this game, which is used internally by Hagl for execution and analysis . class GameTree (TreeType g) => Game g where -- The type of the corresponding game tree--either `Discrete` or `Continuous`. type TreeType g :: * -> * -> * | The type of state maintained throughout the game ( use @()@ for stateless games ) . type State g -- | The type of moves that may be played during the game. type Move g -- | A representation of this game as a game tree. gameTree :: g -> (TreeType g) (State g) (Move g) | Captures all games whose ` TreeType ` is ` Discrete ` . Do not instantiate -- this class directly! class (Game g, TreeType g ~ Discrete) => DiscreteGame g instance (Game g, TreeType g ~ Discrete) => DiscreteGame g | Captures all games whose ` TreeType ` is ` Continuous ` . Do not instantiate -- this class directly! class (Game g, TreeType g ~ Continuous) => ContinuousGame g instance (Game g, TreeType g ~ Continuous) => ContinuousGame g -- -- * Nodes and actions -- -- | A node consists of a game state and an action to perform. type Node s mv = (s, Action mv) -- | The action to perform at a given node. data Action mv = -- | A decision by the indicated player. Decision PlayerID -- | A move based on a probability distribution. This corresponds to moves by Chance or Nature in game theory texts . | Chance (Dist mv) -- | A terminating payoff node. | Payoff Payoff deriving Eq -- | The state at a given node. nodeState :: Node s mv -> s nodeState = fst -- | The action at a given node. nodeAction :: Node s mv -> Action mv nodeAction = snd instance Show mv => Show (Action mv) where show (Decision p) = "Player " ++ show p show (Chance d) = "Chance " ++ show d show (Payoff p) = showPayoffAsList p -- -- * Game trees -- -- | A location in a game tree consists of a node and some representation of -- outbound edges. class GameTree t where -- | The state and action of this location. treeNode :: t s mv -> Node s mv -- | An implicit representation of the outbound edges. treeMove :: Eq mv => t s mv -> mv -> Maybe (t s mv) -- | The state at a given tree node. treeState :: GameTree t => t s mv -> s treeState = nodeState . treeNode -- | The action at a given tree node. treeAction :: GameTree t => t s mv -> Action mv treeAction = nodeAction . treeNode -- | Get the PlayerID corresponding to a decision node. playerID :: GameTree t => t s mv -> Maybe PlayerID playerID t = case treeAction t of Decision p -> Just p _ -> Nothing -- ** Discrete game trees -- -- | A discrete game tree provides a finite list of outbound edges from -- each location, providing a discrete and finite list of available moves. data Discrete s mv = Discrete { -- | The game state and action associated with this location. dtreeNode :: Node s mv, -- | The outbound edges. dtreeEdges :: [Edge s mv] } deriving Eq | An edge represents a single transition from one location in a discrete -- game tree to another, via a move. type Edge s mv = (mv, Discrete s mv) -- | The move assicated with an edge. edgeMove :: Edge s mv -> mv edgeMove = fst -- | The destination of an edge. edgeDest :: Edge s mv -> Discrete s mv edgeDest = snd -- | The available moves from a given location. movesFrom :: Discrete s mv -> [mv] movesFrom = map edgeMove . dtreeEdges -- | The highest numbered player in this finite game tree. maxPlayer :: Discrete s mv -> Int maxPlayer t = maximum $ map (fromMaybe 0 . playerID) (dfs t) -- | The immediate children of a node. children :: Discrete s mv -> [Discrete s mv] children = map edgeDest . dtreeEdges -- | Get a particular child node by following the edge labeled with mv. child :: Eq mv => mv -> Discrete s mv -> Discrete s mv child mv t | Just t' <- lookup mv (dtreeEdges t) = t' child _ _ = error "GameTree.child: invalid move" instance GameTree Discrete where treeNode = dtreeNode treeMove t m = lookup m (dtreeEdges t) instance Game (Discrete s mv) where type TreeType (Discrete s mv) = Discrete type State (Discrete s mv) = s type Move (Discrete s mv) = mv gameTree = id -- ** Continuous game trees -- -- | The edges of a continuous game tree are defined by a transition function -- from moves to children, supporting a potentially infinite or continuous -- set of available moves. data Continuous s mv = Continuous { -- | The game state and action associated with this location. ctreeNode :: Node s mv, -- | The transition function. ctreeMove :: mv -> Maybe (Continuous s mv) } instance GameTree Continuous where treeNode = ctreeNode treeMove = ctreeMove instance Game (Continuous s mv) where type TreeType (Continuous s mv) = Continuous type State (Continuous s mv) = s type Move (Continuous s mv) = mv gameTree = id -- * -- | Nodes in BFS order . bfs :: Discrete s mv -> [Discrete s mv] bfs t = bfs' [t] where bfs' [] = [] bfs' ns = ns ++ bfs' (concatMap children ns) -- | Nodes in DFS order. dfs :: Discrete s mv -> [Discrete s mv] dfs t = t : concatMap dfs (children t) -- -- * Pretty printing -- -- | A nice string representation of a game tree. drawTree :: Show mv => Discrete s mv -> String drawTree = condense . DT.drawTree . tree "" where condense = unlines . filter empty . lines empty = not . all (\c -> c == ' ' || c == '|') tree s t@(Discrete (_,a) _) = DT.Node (s ++ show a) [tree (show m ++ " -> ") t | (m,t) <- dtreeEdges t] instance Show mv => Show (Discrete s mv) where show = drawTree instance Show mv => Show (Continuous s mv) where show = show . treeAction
null
https://raw.githubusercontent.com/walkie/Hagl/ac1edda51c53d2b683c4ada3f1c3d4d14a285d38/src/Hagl/Game.hs
haskell
Each node in a game tree consists of a game state and an action to perform (e.g. a player must make a decision). Edges between nodes are determined by moves. For `Discrete` game trees, the edges are given explicitly as a list. For `Continuous` game trees, the edges are defined implicitly by a function. Games end when a `Payoff` node is reached. * Games | A game has several associated types describing whether the game is discrete or continuous, what type of state it maintains, and the type of moves on edges. The function `gameTree` is used to get the game tree representation of this game, which is used The type of the corresponding game tree--either `Discrete` or `Continuous`. | The type of moves that may be played during the game. | A representation of this game as a game tree. this class directly! this class directly! * Nodes and actions | A node consists of a game state and an action to perform. | The action to perform at a given node. | A decision by the indicated player. | A move based on a probability distribution. This corresponds to | A terminating payoff node. | The state at a given node. | The action at a given node. * Game trees | A location in a game tree consists of a node and some representation of outbound edges. | The state and action of this location. | An implicit representation of the outbound edges. | The state at a given tree node. | The action at a given tree node. | Get the PlayerID corresponding to a decision node. ** Discrete game trees | A discrete game tree provides a finite list of outbound edges from each location, providing a discrete and finite list of available moves. | The game state and action associated with this location. | The outbound edges. game tree to another, via a move. | The move assicated with an edge. | The destination of an edge. | The available moves from a given location. | The highest numbered player in this finite game tree. | The immediate children of a node. | Get a particular child node by following the edge labeled with mv. ** Continuous game trees | The edges of a continuous game tree are defined by a transition function from moves to children, supporting a potentially infinite or continuous set of available moves. | The game state and action associated with this location. | The transition function. | Nodes in DFS order. * Pretty printing | A nice string representation of a game tree.
# LANGUAGE FlexibleContexts , FlexibleInstances , PatternGuards , TypeFamilies , UndecidableInstances # FlexibleInstances, PatternGuards, TypeFamilies, UndecidableInstances #-} | All games in Hagl can be reduced to one of two kinds of game trees . module Hagl.Game where import Data.Maybe (fromMaybe) import qualified Data.Tree as DT (Tree(..), drawTree) import Hagl.List import Hagl.Payoff internally by Hagl for execution and analysis . class GameTree (TreeType g) => Game g where type TreeType g :: * -> * -> * | The type of state maintained throughout the game ( use @()@ for stateless games ) . type State g type Move g gameTree :: g -> (TreeType g) (State g) (Move g) | Captures all games whose ` TreeType ` is ` Discrete ` . Do not instantiate class (Game g, TreeType g ~ Discrete) => DiscreteGame g instance (Game g, TreeType g ~ Discrete) => DiscreteGame g | Captures all games whose ` TreeType ` is ` Continuous ` . Do not instantiate class (Game g, TreeType g ~ Continuous) => ContinuousGame g instance (Game g, TreeType g ~ Continuous) => ContinuousGame g type Node s mv = (s, Action mv) data Action mv = Decision PlayerID moves by Chance or Nature in game theory texts . | Chance (Dist mv) | Payoff Payoff deriving Eq nodeState :: Node s mv -> s nodeState = fst nodeAction :: Node s mv -> Action mv nodeAction = snd instance Show mv => Show (Action mv) where show (Decision p) = "Player " ++ show p show (Chance d) = "Chance " ++ show d show (Payoff p) = showPayoffAsList p class GameTree t where treeNode :: t s mv -> Node s mv treeMove :: Eq mv => t s mv -> mv -> Maybe (t s mv) treeState :: GameTree t => t s mv -> s treeState = nodeState . treeNode treeAction :: GameTree t => t s mv -> Action mv treeAction = nodeAction . treeNode playerID :: GameTree t => t s mv -> Maybe PlayerID playerID t = case treeAction t of Decision p -> Just p _ -> Nothing data Discrete s mv = Discrete { dtreeNode :: Node s mv, dtreeEdges :: [Edge s mv] } deriving Eq | An edge represents a single transition from one location in a discrete type Edge s mv = (mv, Discrete s mv) edgeMove :: Edge s mv -> mv edgeMove = fst edgeDest :: Edge s mv -> Discrete s mv edgeDest = snd movesFrom :: Discrete s mv -> [mv] movesFrom = map edgeMove . dtreeEdges maxPlayer :: Discrete s mv -> Int maxPlayer t = maximum $ map (fromMaybe 0 . playerID) (dfs t) children :: Discrete s mv -> [Discrete s mv] children = map edgeDest . dtreeEdges child :: Eq mv => mv -> Discrete s mv -> Discrete s mv child mv t | Just t' <- lookup mv (dtreeEdges t) = t' child _ _ = error "GameTree.child: invalid move" instance GameTree Discrete where treeNode = dtreeNode treeMove t m = lookup m (dtreeEdges t) instance Game (Discrete s mv) where type TreeType (Discrete s mv) = Discrete type State (Discrete s mv) = s type Move (Discrete s mv) = mv gameTree = id data Continuous s mv = Continuous { ctreeNode :: Node s mv, ctreeMove :: mv -> Maybe (Continuous s mv) } instance GameTree Continuous where treeNode = ctreeNode treeMove = ctreeMove instance Game (Continuous s mv) where type TreeType (Continuous s mv) = Continuous type State (Continuous s mv) = s type Move (Continuous s mv) = mv gameTree = id * | Nodes in BFS order . bfs :: Discrete s mv -> [Discrete s mv] bfs t = bfs' [t] where bfs' [] = [] bfs' ns = ns ++ bfs' (concatMap children ns) dfs :: Discrete s mv -> [Discrete s mv] dfs t = t : concatMap dfs (children t) drawTree :: Show mv => Discrete s mv -> String drawTree = condense . DT.drawTree . tree "" where condense = unlines . filter empty . lines empty = not . all (\c -> c == ' ' || c == '|') tree s t@(Discrete (_,a) _) = DT.Node (s ++ show a) [tree (show m ++ " -> ") t | (m,t) <- dtreeEdges t] instance Show mv => Show (Discrete s mv) where show = drawTree instance Show mv => Show (Continuous s mv) where show = show . treeAction
8d3b258d13128cbbd04dea2489a5565f9f25cccb373ba63ccaecb51219d36341
ushitora-anqou/alqo
room_database.erl
-module(room_database). -behaviour(gen_server). -export([ start_link/0, stop/0, create_room/1, get_current_state/1, set_current_state/2 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:call(?MODULE, stop). create_room(InitialRoomState) -> gen_server:call(?MODULE, {create, InitialRoomState}). get_current_state(RoomID) -> case ets:lookup(?MODULE, RoomID) of [] -> undefined; [{_, State}] -> State end. set_current_state(RoomID, RoomNewState) -> gen_server:call(?MODULE, {set_current_state, RoomID, RoomNewState}). GEN_SERVER init(_) -> ?MODULE = ets:new(?MODULE, [set, named_table, protected]), {ok, ?MODULE}. handle_call({create, RoomState}, _From, State) -> RoomID = list_to_binary(uuid:uuid_to_string(uuid:get_v4(), nodash)), XXX assume does not duplicate true = ets:insert_new(?MODULE, {RoomID, RoomState}), {reply, RoomID, State}; handle_call({set_current_state, RoomID, RoomNewState}, _From, State) -> ets:insert(?MODULE, {RoomID, RoomNewState}), {reply, ok, State}; handle_call(stop, _From, State) -> ets:delete(?MODULE), {stop, normal, ok, State}; handle_call(_Event, _From, State) -> {noreply, State}. handle_cast(_Event, State) -> {noreply, State}. handle_info(_Event, State) -> {noreply, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_Reason, _State) -> ok. Internal functions
null
https://raw.githubusercontent.com/ushitora-anqou/alqo/9900172d765100dec40c00a7aec3c2dc971956f1/src/room_database.erl
erlang
-module(room_database). -behaviour(gen_server). -export([ start_link/0, stop/0, create_room/1, get_current_state/1, set_current_state/2 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:call(?MODULE, stop). create_room(InitialRoomState) -> gen_server:call(?MODULE, {create, InitialRoomState}). get_current_state(RoomID) -> case ets:lookup(?MODULE, RoomID) of [] -> undefined; [{_, State}] -> State end. set_current_state(RoomID, RoomNewState) -> gen_server:call(?MODULE, {set_current_state, RoomID, RoomNewState}). GEN_SERVER init(_) -> ?MODULE = ets:new(?MODULE, [set, named_table, protected]), {ok, ?MODULE}. handle_call({create, RoomState}, _From, State) -> RoomID = list_to_binary(uuid:uuid_to_string(uuid:get_v4(), nodash)), XXX assume does not duplicate true = ets:insert_new(?MODULE, {RoomID, RoomState}), {reply, RoomID, State}; handle_call({set_current_state, RoomID, RoomNewState}, _From, State) -> ets:insert(?MODULE, {RoomID, RoomNewState}), {reply, ok, State}; handle_call(stop, _From, State) -> ets:delete(?MODULE), {stop, normal, ok, State}; handle_call(_Event, _From, State) -> {noreply, State}. handle_cast(_Event, State) -> {noreply, State}. handle_info(_Event, State) -> {noreply, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_Reason, _State) -> ok. Internal functions
ec7c595f923bf3e0d7675f82c106bfbfaf128ad34c8b6e185715f05cd5e3ee9e
input-output-hk/cardano-addresses
GenerateSpec.hs
# LANGUAGE FlexibleContexts # module Command.RecoveryPhrase.GenerateSpec ( spec ) where import Prelude import Test.Hspec ( Spec, SpecWith, it, shouldBe, shouldContain ) import Test.Utils ( cli, describeCmd ) spec :: Spec spec = describeCmd ["recovery-phrase", "generate"] $ do specDefaultSize mapM_ specSpecificSize [9,12,15,18,21,24] mapM_ specInvalidSize ["15.5","3","6","14","abc","👌","0","~!@#%","-1000","1000"] specDefaultSize :: SpecWith () specDefaultSize = it "ø; default size" $ do out <- cli ["recovery-phrase", "generate"] mempty length (words out) `shouldBe` 24 specSpecificSize :: Int -> SpecWith () specSpecificSize n = it ("--size=" <> show n <> "; valid size") $ do out <- cli ["recovery-phrase", "generate", "--size", show n] "" length (words out) `shouldBe` n specInvalidSize :: String -> SpecWith () specInvalidSize x = it ("--size=" <> x <> "; invalid size") $ do (out, err) <- cli ["recovery-phrase", "generate", "--size", x] "" out `shouldBe` "" err `shouldContain` "Invalid mnemonic size. Expected one of: 9, 12, 15, 18, 21, 24."
null
https://raw.githubusercontent.com/input-output-hk/cardano-addresses/41971b6bc29d6d69cd258ee78253af8da4b414f4/command-line/test/Command/RecoveryPhrase/GenerateSpec.hs
haskell
# LANGUAGE FlexibleContexts # module Command.RecoveryPhrase.GenerateSpec ( spec ) where import Prelude import Test.Hspec ( Spec, SpecWith, it, shouldBe, shouldContain ) import Test.Utils ( cli, describeCmd ) spec :: Spec spec = describeCmd ["recovery-phrase", "generate"] $ do specDefaultSize mapM_ specSpecificSize [9,12,15,18,21,24] mapM_ specInvalidSize ["15.5","3","6","14","abc","👌","0","~!@#%","-1000","1000"] specDefaultSize :: SpecWith () specDefaultSize = it "ø; default size" $ do out <- cli ["recovery-phrase", "generate"] mempty length (words out) `shouldBe` 24 specSpecificSize :: Int -> SpecWith () specSpecificSize n = it ("--size=" <> show n <> "; valid size") $ do out <- cli ["recovery-phrase", "generate", "--size", show n] "" length (words out) `shouldBe` n specInvalidSize :: String -> SpecWith () specInvalidSize x = it ("--size=" <> x <> "; invalid size") $ do (out, err) <- cli ["recovery-phrase", "generate", "--size", x] "" out `shouldBe` "" err `shouldContain` "Invalid mnemonic size. Expected one of: 9, 12, 15, 18, 21, 24."
5b467612974f1b048089a87aa8c9b2af673a2911f52e22caf641261d9c5e2ce8
iustin/corydalis
Image.hs
Copyright ( C ) 2013 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 < / > . Copyright (C) 2013 Iustin Pop 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 </>. -} # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoCPP # # LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TupleSections # # LANGUAGE TypeFamilies # module Handler.Image ( getImageR ) where import Exif import Handler.Utils import Handler.Widgets import Import import Pics getImageR :: Text -> ImageName -> Handler Html getImageR folder iname = do dir <- getFolder folder img <- getFolderImage dir iname params <- getParams let images = pdTimeSort dir tkey = imageTimeKey img flags = if flagsSoftMaster (imgFlags img) then "soft master"::Text else "(none)" lens = exifLens exif exif = imgExif img defaultLayout $ do setHtmlTitle $ "image " <> folder <> "/" <> unImageName (imgName img) $(widgetFile "image")
null
https://raw.githubusercontent.com/iustin/corydalis/43f8bf004904847fad43c428a9e1b20e67da964d/src/Handler/Image.hs
haskell
# LANGUAGE TemplateHaskell #
Copyright ( C ) 2013 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 < / > . Copyright (C) 2013 Iustin Pop 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 </>. -} # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoCPP # # LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # # LANGUAGE TupleSections # # LANGUAGE TypeFamilies # module Handler.Image ( getImageR ) where import Exif import Handler.Utils import Handler.Widgets import Import import Pics getImageR :: Text -> ImageName -> Handler Html getImageR folder iname = do dir <- getFolder folder img <- getFolderImage dir iname params <- getParams let images = pdTimeSort dir tkey = imageTimeKey img flags = if flagsSoftMaster (imgFlags img) then "soft master"::Text else "(none)" lens = exifLens exif exif = imgExif img defaultLayout $ do setHtmlTitle $ "image " <> folder <> "/" <> unImageName (imgName img) $(widgetFile "image")
38dbe0651dabc73c34ac6c56d6240634dcb21885e360ad5713c5e242ac3ed5c8
cjay/vulkyrie
Memory.hs
{-# LANGUAGE StrictData #-} # LANGUAGE DuplicateRecordFields # module Vulkyrie.Vulkan.Memory ( findMemoryType , MemTypeIndex(..) , MemoryLoc(..) , allocBindImageMem , allocBindBufferMem , MemoryPool , createMemoryPool , allocMem ) where import Control.Monad import Control.Monad.Primitive import Data.Bits import qualified Data.Map.Strict as Map import Data.Map.Strict (Map) import qualified Data.Set as Set import Data.Set (Set) import qualified Data.Vector.Mutable as MVector import Data.Vector.Mutable (MVector) import Graphics.Vulkan import Graphics.Vulkan.Core_1_0 import Graphics.Vulkan.Marshal.Create import Graphics.Vulkan.Marshal.Create.DataFrame import Numeric.DataFrame ( ixOff ) import UnliftIO.Exception import Vulkyrie.Program import Vulkyrie.Program.Foreign import Vulkyrie.Resource import Data.Maybe import Safe (headMay) import Data.Foldable (toList) import Data.Foldable (foldl') iterateMaybe :: forall a. (a -> Maybe a) -> Maybe a -> [a] iterateMaybe f ma = maybe [] go ma where go a = a : maybe [] go (f a) rawAlloc :: VkDevice -> MemTypeIndex -> VkDeviceSize -> Prog r VkDeviceMemory rawAlloc dev (MemTypeIndex memTypeIndex) size = do let allocInfo = createVk @VkMemoryAllocateInfo $ set @"sType" VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO &* set @"pNext" VK_NULL &* set @"allocationSize" size &* set @"memoryTypeIndex" memTypeIndex withVkPtr allocInfo $ \aiPtr -> allocaPeek $ runVk . vkAllocateMemory dev aiPtr VK_NULL rawFree :: VkDevice -> VkDeviceMemory -> Prog r () rawFree dev mem = liftIO $ vkFreeMemory dev mem VK_NULL newtype MemTypeIndex = MemTypeIndex Word32 -- | Return an index of a memory type for a device findMemoryType :: VkPhysicalDeviceMemoryProperties -> Word32 -- ^ type filter bitfield -> VkMemoryPropertyFlags -- ^ desired memory properties -> Prog r MemTypeIndex findMemoryType memProps typeFilter properties = do let mtCount = getField @"memoryTypeCount" memProps memTypes = getVec @"memoryTypes" memProps go i | i == mtCount = throwString "Failed to find suitable memory type!" | otherwise = tryType i tryType i = if testBit typeFilter (fromIntegral i) && ( getField @"propertyFlags" (ixOff (fromIntegral i) memTypes) .&. properties ) == properties then return $ MemTypeIndex i else go (i+1) go 0 data MemoryLoc = MemoryLoc { memory :: VkDeviceMemory , memoryOffset :: VkDeviceSize , memorySize :: VkDeviceSize , allocSize :: VkDeviceSize } TODO unify with allocBindBufferMem allocBindImageMem :: MemoryPool -> VkMemoryPropertyFlags -> VkImage -> Resource MemoryLoc allocBindImageMem memPool@MemoryPool{dev, memProps} propFlags image = Resource $ do memRequirements <- allocaPeek $ \reqsPtr -> liftIO $ vkGetImageMemoryRequirements dev image reqsPtr memType <- findMemoryType memProps (getField @"memoryTypeBits" memRequirements) propFlags loc@MemoryLoc{memory, memoryOffset} <- auto $ allocMem memPool memType (getField @"size" memRequirements) (getField @"alignment" memRequirements) runVk $ vkBindImageMemory dev image memory memoryOffset return loc allocBindBufferMem :: MemoryPool -> VkMemoryPropertyFlags -> VkBuffer -> Resource MemoryLoc allocBindBufferMem memPool@MemoryPool{dev, memProps} propFlags buffer = Resource $ do memRequirements <- allocaPeek $ \reqsPtr -> liftIO $ vkGetBufferMemoryRequirements dev buffer reqsPtr memType <- findMemoryType memProps (getField @"memoryTypeBits" memRequirements) propFlags loc@MemoryLoc{memory, memoryOffset} <- auto $ allocMem memPool memType (getField @"size" memRequirements) (getField @"alignment" memRequirements) runVk $ vkBindBufferMemory dev buffer memory memoryOffset return loc TODO determine best size at runtime memoryChunkSize :: VkDeviceSize memoryChunkSize = 128 * 1024 * 1024 -- | Best-fit sub-allocating memory pool. Not thread-safe. -- Helps with low maxMemoryAllocationCount and time -- across smaller allocations. data MemoryPool = MemoryPool { dev :: VkDevice , memProps :: VkPhysicalDeviceMemoryProperties , bufferImageGranularity :: VkDeviceSize , pools :: MVector (PrimState IO) MemPool ^ one vector entry for each memory type index } createMemoryPool :: VkPhysicalDevice -> VkDevice -> Resource MemoryPool createMemoryPool pdev dev = Resource $ do memProps <- allocaPeek $ liftIO . vkGetPhysicalDeviceMemoryProperties pdev let memTypeCount = getField @"memoryTypeCount" memProps devProps <- allocaPeek $ \propsPtr -> liftIO $ vkGetPhysicalDeviceProperties pdev propsPtr let limits = getField @"limits" devProps let bufferImageGranularity = getField @"bufferImageGranularity" limits pools <- liftIO $ MVector.new $ fromIntegral memTypeCount forM_ [0..(memTypeCount - 1)] $ \index -> do let pool = makeMemPool dev (MemTypeIndex index) liftIO $ MVector.write pools (fromIntegral index) pool onDestroy $ forM_ [0..(memTypeCount - 1)] $ \index -> do pool <- liftIO $ MVector.read pools (fromIntegral index) destroyMemPool pool pure MemoryPool{..} allocMem :: MemoryPool -> MemTypeIndex -> VkDeviceSize -- ^ requested size in bytes -> VkDeviceSize -- ^ requested alignment -> MetaResource MemoryLoc allocMem MemoryPool{..} (MemTypeIndex memTypeIndex) requestSize requestAlignment = -- For real world bufferImageGranularity see -- . In order to respect the granularity , Vulkan Memory Allocator keeps track of -- all allocations in its data structures and checks neighboring allocations -- for their linearity when allocating. Simply bumping the alignment makes this unnecessary . On modern hardware with a granularity of 1024 this should lead to only about 512 bytes of loss on average per allocation . Only on some older NVidia hardware it would be 16 KB loss . -- No exceptions to this alignment can be made, even if you happen to know -- that the neighboring allocations are known to be linear/non-linear, because -- neighbors could be freed and reallocated with different linearity. So -- either the info about neighbors is always available to check, or the -- alignment has to be always respected. -- To avoid the loss, you could sub-allocate from a MemoryLoc and chose to -- only place non-linear/linear memory resources there. let alignment = max requestAlignment bufferImageGranularity in metaResource (\loc -> do let index = fromIntegral memTypeIndex pool <- liftIO $ MVector.read pools index pool' <- free pool loc liftIO $ MVector.write pools index pool' ) (do let index = fromIntegral memTypeIndex pool <- liftIO $ MVector.read pools index (pool', memLoc) <- alloc pool requestSize alignment liftIO $ MVector.write pools index pool' pure memLoc ) -- | A raw VkDeviceMemory to be sub-allocated data Block = Block { mem :: VkDeviceMemory , blockSize :: VkDeviceSize , spaceMap :: Map VkDeviceSize Chunk } deriving Show -- The key type to lookup blocks. VkDeviceMemory is a non - dispatchable handle , Vulkan spec says such handles are unique per VkDevice . type BlockId = VkDeviceMemory -- | A free region inside a Block. -- -- Default ordering is by address. data Chunk = Chunk { blockId :: BlockId , chunkOffset :: VkDeviceSize , chunkSize :: VkDeviceSize } deriving (Eq, Ord, Show) chunkEnd :: Chunk -> VkDeviceSize chunkEnd Chunk{..} = chunkOffset + chunkSize chunkStart :: Chunk -> VkDeviceSize chunkStart Chunk{..} = chunkOffset data MemPool = MemPool { dev :: VkDevice , memTypeIndex :: MemTypeIndex , blocks :: Map BlockId Block , sizeMap :: Map VkDeviceSize (Set Chunk) } -- Update with chunk change. New chunk HAS to have the same offset. updatePool :: MemPool -> (Chunk, Maybe Chunk) -> MemPool updatePool pool@MemPool{ blocks, sizeMap } (oldChunk, mayNewChunk) = let Chunk{ blockId, chunkSize, chunkOffset } = oldChunk precond = case mayNewChunk of Just Chunk{ chunkOffset = newOffset } -> newOffset == chunkOffset Nothing -> True blocks' = Map.adjust upd blockId blocks where upd block@Block{ spaceMap } = let spaceMap' = Map.update (const mayNewChunk) chunkOffset spaceMap in block{ spaceMap = spaceMap' } sizeMap' = Map.update del chunkSize sizeMap where del cs = let cs' = Set.delete oldChunk cs in if null cs' then Nothing else Just cs' sizeMap'' = case mayNewChunk of Nothing -> sizeMap' Just newChunk@Chunk{ chunkSize = newChunkSize } -> Map.alter (Just . ins) newChunkSize sizeMap' where ins Nothing = Set.singleton newChunk ins (Just cs) = Set.insert newChunk cs in assert precond $ pool{ blocks = blocks', sizeMap = sizeMap'' } updatePoolFreshBlock :: MemPool -> Block -> Maybe Chunk -> MemPool updatePoolFreshBlock pool@MemPool{ blocks, sizeMap } block mayNewChunk = let Block{ mem = blockId, spaceMap } = block spaceMap' = case mayNewChunk of Nothing -> spaceMap' Just newChunk@Chunk{ chunkOffset } -> Map.insert chunkOffset newChunk spaceMap block' = block{ spaceMap = spaceMap' } blocks' = Map.insert blockId block' blocks sizeMap' = case mayNewChunk of Nothing -> sizeMap Just newChunk@Chunk{ chunkSize = newChunkSize } -> Map.alter (Just . ins) newChunkSize sizeMap where ins Nothing = Set.singleton newChunk ins (Just cs) = Set.insert newChunk cs in pool{ blocks = blocks', sizeMap = sizeMap' } -- TODO maybe reuse/extend updatePool free :: MemPool -> MemoryLoc -> Prog r MemPool free pool@MemPool{..} MemoryLoc{..} = let allocStart = memoryOffset allocEnd = memoryOffset + allocSize block@Block{ spaceMap, blockSize, mem } = blocks Map.! memory leftChunk = snd <$> Map.lookupGT allocStart spaceMap rightChunk = snd <$> Map.lookupLT allocStart spaceMap mergeLeft = leftChunk >>= \chunk -> if chunkEnd chunk == allocStart then pure $ (chunk, chunkStart chunk) else Nothing mergeRight = rightChunk >>= \chunk -> if chunkStart chunk == allocEnd then pure $ (chunk, chunkEnd chunk) else Nothing chunksToReplace = map fst $ catMaybes [mergeLeft, mergeRight] freeStart = fromMaybe allocStart (snd <$> mergeLeft) freeEnd = fromMaybe allocEnd (snd <$> mergeRight) newChunkSize = freeEnd - freeStart blockBecomesEmpty = freeStart == 0 && newChunkSize == blockSize newChunk = Chunk { blockId = memory, chunkOffset = freeStart, chunkSize = newChunkSize } spaceMapDel = foldl' del spaceMap chunksToReplace where del smap chunk = Map.delete (chunkStart chunk) smap spaceMapUpd = Map.insert (chunkEnd newChunk) newChunk spaceMapDel block' = block{ spaceMap = spaceMapUpd } blocksUpd = Map.insert memory block' blocks blocksDel = Map.delete memory blocks sizeMapDel = foldl' del sizeMap chunksToReplace where del smap chunk@Chunk{ chunkSize } = Map.update (del' chunk) chunkSize smap del' chunk cs = let cs' = Set.delete chunk cs in if null cs' then Nothing else Just cs' sizeMapUpd = Map.alter (Just . ins) newChunkSize sizeMapDel where ins Nothing = Set.singleton newChunk ins (Just cs) = Set.insert newChunk cs in if blockBecomesEmpty && length blocks > 1 then do rawFree dev mem pure pool{ blocks = blocksDel, sizeMap = sizeMapDel } else pure $ pool{ blocks = blocksUpd, sizeMap = sizeMapUpd } -- | Try to fit allocation into chunk, as far right as possible. -- -- Returns (if allocation fits in the chunk, needed upper padding in the chunk) fit :: VkDeviceSize -> VkDeviceSize -> VkDeviceSize -> VkDeviceSize -> (Bool, VkDeviceSize) fit chunkOffset chunkSize alignment requestSize = let precond = chunkSize >= requestSize maxOffset = chunkOffset + chunkSize - requestSize padding = maxOffset `mod` alignment in assert precond (maxOffset >= padding, padding) alloc :: MemPool -> VkDeviceSize -- ^ requested size in bytes -> VkDeviceSize -- ^ requested alignment -> Prog r (MemPool, MemoryLoc) alloc pool@MemPool{..} requestSize alignment = let -- Returns Maybe for success if the chunk actually was big enough. Result contains ( given chunk , Chunk with leftover mem from the chunk ) . Leftover mem can be zero , another Maybe for that . tryChunk :: Block -> Chunk -> Maybe ((Chunk, Maybe Chunk), MemoryLoc) tryChunk Block{ mem } chunk@Chunk{..} = let (doesFit, padding) = fit chunkOffset chunkSize alignment requestSize allocSize = requestSize + padding newChunkSize = chunkSize - allocSize chunk' = if newChunkSize > 0 then Just chunk{ chunkSize = newChunkSize } else Nothing memoryOffset = chunkOffset + chunkSize - allocSize loc = MemoryLoc{ memory = mem, memoryOffset, memorySize = requestSize, allocSize } in if doesFit then Just ((chunk, chunk'), loc) else Nothing -- All chunks from existing blocks that are big enough for the request size. -- Not necessarily big enough when respecting alignment. candidateChunks = concatMap toList . map snd . iterateMaybe (flip Map.lookupGT sizeMap . fst) $ Map.lookupGE requestSize sizeMap -- Try to do allocation with the chunks from existing blocks existingTry = headMay $ mapMaybe (\chunk@Chunk{ blockId } -> tryChunk (blocks Map.! blockId) chunk) candidateChunks in case existingTry of Just (chunkUpdate, memoryLoc) -> pure (updatePool pool chunkUpdate, memoryLoc) Nothing -> do let blockSize = max memoryChunkSize requestSize mem <- rawAlloc dev memTypeIndex blockSize let block = Block{ mem, blockSize, spaceMap = Map.empty } ((_, mayNewChunk), memoryLoc) = fromJust $ tryChunk block Chunk{ blockId = mem, chunkOffset = 0, chunkSize = blockSize } pure (updatePoolFreshBlock pool block mayNewChunk, memoryLoc) makeMemPool :: VkDevice -> MemTypeIndex -> MemPool makeMemPool dev memTypeIndex = MemPool{ dev, memTypeIndex, blocks = Map.empty, sizeMap = Map.empty } destroyMemPool :: MemPool -> Prog r () destroyMemPool MemPool{ dev, blocks } = forM_ blocks $ \Block{ mem } -> rawFree dev mem
null
https://raw.githubusercontent.com/cjay/vulkyrie/83edbd0099f9bb02b2b1fe159523245861011018/src/Vulkyrie/Vulkan/Memory.hs
haskell
# LANGUAGE StrictData # | Return an index of a memory type for a device ^ type filter bitfield ^ desired memory properties | Best-fit sub-allocating memory pool. Not thread-safe. across smaller allocations. ^ requested size in bytes ^ requested alignment For real world bufferImageGranularity see . all allocations in its data structures and checks neighboring allocations for their linearity when allocating. Simply bumping the alignment makes No exceptions to this alignment can be made, even if you happen to know that the neighboring allocations are known to be linear/non-linear, because neighbors could be freed and reallocated with different linearity. So either the info about neighbors is always available to check, or the alignment has to be always respected. To avoid the loss, you could sub-allocate from a MemoryLoc and chose to only place non-linear/linear memory resources there. | A raw VkDeviceMemory to be sub-allocated The key type to lookup blocks. | A free region inside a Block. Default ordering is by address. Update with chunk change. New chunk HAS to have the same offset. TODO maybe reuse/extend updatePool | Try to fit allocation into chunk, as far right as possible. Returns (if allocation fits in the chunk, needed upper padding in the chunk) ^ requested size in bytes ^ requested alignment Returns Maybe for success if the chunk actually was big enough. All chunks from existing blocks that are big enough for the request size. Not necessarily big enough when respecting alignment. Try to do allocation with the chunks from existing blocks
# LANGUAGE DuplicateRecordFields # module Vulkyrie.Vulkan.Memory ( findMemoryType , MemTypeIndex(..) , MemoryLoc(..) , allocBindImageMem , allocBindBufferMem , MemoryPool , createMemoryPool , allocMem ) where import Control.Monad import Control.Monad.Primitive import Data.Bits import qualified Data.Map.Strict as Map import Data.Map.Strict (Map) import qualified Data.Set as Set import Data.Set (Set) import qualified Data.Vector.Mutable as MVector import Data.Vector.Mutable (MVector) import Graphics.Vulkan import Graphics.Vulkan.Core_1_0 import Graphics.Vulkan.Marshal.Create import Graphics.Vulkan.Marshal.Create.DataFrame import Numeric.DataFrame ( ixOff ) import UnliftIO.Exception import Vulkyrie.Program import Vulkyrie.Program.Foreign import Vulkyrie.Resource import Data.Maybe import Safe (headMay) import Data.Foldable (toList) import Data.Foldable (foldl') iterateMaybe :: forall a. (a -> Maybe a) -> Maybe a -> [a] iterateMaybe f ma = maybe [] go ma where go a = a : maybe [] go (f a) rawAlloc :: VkDevice -> MemTypeIndex -> VkDeviceSize -> Prog r VkDeviceMemory rawAlloc dev (MemTypeIndex memTypeIndex) size = do let allocInfo = createVk @VkMemoryAllocateInfo $ set @"sType" VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO &* set @"pNext" VK_NULL &* set @"allocationSize" size &* set @"memoryTypeIndex" memTypeIndex withVkPtr allocInfo $ \aiPtr -> allocaPeek $ runVk . vkAllocateMemory dev aiPtr VK_NULL rawFree :: VkDevice -> VkDeviceMemory -> Prog r () rawFree dev mem = liftIO $ vkFreeMemory dev mem VK_NULL newtype MemTypeIndex = MemTypeIndex Word32 findMemoryType :: VkPhysicalDeviceMemoryProperties -> VkMemoryPropertyFlags -> Prog r MemTypeIndex findMemoryType memProps typeFilter properties = do let mtCount = getField @"memoryTypeCount" memProps memTypes = getVec @"memoryTypes" memProps go i | i == mtCount = throwString "Failed to find suitable memory type!" | otherwise = tryType i tryType i = if testBit typeFilter (fromIntegral i) && ( getField @"propertyFlags" (ixOff (fromIntegral i) memTypes) .&. properties ) == properties then return $ MemTypeIndex i else go (i+1) go 0 data MemoryLoc = MemoryLoc { memory :: VkDeviceMemory , memoryOffset :: VkDeviceSize , memorySize :: VkDeviceSize , allocSize :: VkDeviceSize } TODO unify with allocBindBufferMem allocBindImageMem :: MemoryPool -> VkMemoryPropertyFlags -> VkImage -> Resource MemoryLoc allocBindImageMem memPool@MemoryPool{dev, memProps} propFlags image = Resource $ do memRequirements <- allocaPeek $ \reqsPtr -> liftIO $ vkGetImageMemoryRequirements dev image reqsPtr memType <- findMemoryType memProps (getField @"memoryTypeBits" memRequirements) propFlags loc@MemoryLoc{memory, memoryOffset} <- auto $ allocMem memPool memType (getField @"size" memRequirements) (getField @"alignment" memRequirements) runVk $ vkBindImageMemory dev image memory memoryOffset return loc allocBindBufferMem :: MemoryPool -> VkMemoryPropertyFlags -> VkBuffer -> Resource MemoryLoc allocBindBufferMem memPool@MemoryPool{dev, memProps} propFlags buffer = Resource $ do memRequirements <- allocaPeek $ \reqsPtr -> liftIO $ vkGetBufferMemoryRequirements dev buffer reqsPtr memType <- findMemoryType memProps (getField @"memoryTypeBits" memRequirements) propFlags loc@MemoryLoc{memory, memoryOffset} <- auto $ allocMem memPool memType (getField @"size" memRequirements) (getField @"alignment" memRequirements) runVk $ vkBindBufferMemory dev buffer memory memoryOffset return loc TODO determine best size at runtime memoryChunkSize :: VkDeviceSize memoryChunkSize = 128 * 1024 * 1024 Helps with low maxMemoryAllocationCount and time data MemoryPool = MemoryPool { dev :: VkDevice , memProps :: VkPhysicalDeviceMemoryProperties , bufferImageGranularity :: VkDeviceSize , pools :: MVector (PrimState IO) MemPool ^ one vector entry for each memory type index } createMemoryPool :: VkPhysicalDevice -> VkDevice -> Resource MemoryPool createMemoryPool pdev dev = Resource $ do memProps <- allocaPeek $ liftIO . vkGetPhysicalDeviceMemoryProperties pdev let memTypeCount = getField @"memoryTypeCount" memProps devProps <- allocaPeek $ \propsPtr -> liftIO $ vkGetPhysicalDeviceProperties pdev propsPtr let limits = getField @"limits" devProps let bufferImageGranularity = getField @"bufferImageGranularity" limits pools <- liftIO $ MVector.new $ fromIntegral memTypeCount forM_ [0..(memTypeCount - 1)] $ \index -> do let pool = makeMemPool dev (MemTypeIndex index) liftIO $ MVector.write pools (fromIntegral index) pool onDestroy $ forM_ [0..(memTypeCount - 1)] $ \index -> do pool <- liftIO $ MVector.read pools (fromIntegral index) destroyMemPool pool pure MemoryPool{..} allocMem :: MemoryPool -> MemTypeIndex -> MetaResource MemoryLoc allocMem MemoryPool{..} (MemTypeIndex memTypeIndex) requestSize requestAlignment = In order to respect the granularity , Vulkan Memory Allocator keeps track of this unnecessary . On modern hardware with a granularity of 1024 this should lead to only about 512 bytes of loss on average per allocation . Only on some older NVidia hardware it would be 16 KB loss . let alignment = max requestAlignment bufferImageGranularity in metaResource (\loc -> do let index = fromIntegral memTypeIndex pool <- liftIO $ MVector.read pools index pool' <- free pool loc liftIO $ MVector.write pools index pool' ) (do let index = fromIntegral memTypeIndex pool <- liftIO $ MVector.read pools index (pool', memLoc) <- alloc pool requestSize alignment liftIO $ MVector.write pools index pool' pure memLoc ) data Block = Block { mem :: VkDeviceMemory , blockSize :: VkDeviceSize , spaceMap :: Map VkDeviceSize Chunk } deriving Show VkDeviceMemory is a non - dispatchable handle , Vulkan spec says such handles are unique per VkDevice . type BlockId = VkDeviceMemory data Chunk = Chunk { blockId :: BlockId , chunkOffset :: VkDeviceSize , chunkSize :: VkDeviceSize } deriving (Eq, Ord, Show) chunkEnd :: Chunk -> VkDeviceSize chunkEnd Chunk{..} = chunkOffset + chunkSize chunkStart :: Chunk -> VkDeviceSize chunkStart Chunk{..} = chunkOffset data MemPool = MemPool { dev :: VkDevice , memTypeIndex :: MemTypeIndex , blocks :: Map BlockId Block , sizeMap :: Map VkDeviceSize (Set Chunk) } updatePool :: MemPool -> (Chunk, Maybe Chunk) -> MemPool updatePool pool@MemPool{ blocks, sizeMap } (oldChunk, mayNewChunk) = let Chunk{ blockId, chunkSize, chunkOffset } = oldChunk precond = case mayNewChunk of Just Chunk{ chunkOffset = newOffset } -> newOffset == chunkOffset Nothing -> True blocks' = Map.adjust upd blockId blocks where upd block@Block{ spaceMap } = let spaceMap' = Map.update (const mayNewChunk) chunkOffset spaceMap in block{ spaceMap = spaceMap' } sizeMap' = Map.update del chunkSize sizeMap where del cs = let cs' = Set.delete oldChunk cs in if null cs' then Nothing else Just cs' sizeMap'' = case mayNewChunk of Nothing -> sizeMap' Just newChunk@Chunk{ chunkSize = newChunkSize } -> Map.alter (Just . ins) newChunkSize sizeMap' where ins Nothing = Set.singleton newChunk ins (Just cs) = Set.insert newChunk cs in assert precond $ pool{ blocks = blocks', sizeMap = sizeMap'' } updatePoolFreshBlock :: MemPool -> Block -> Maybe Chunk -> MemPool updatePoolFreshBlock pool@MemPool{ blocks, sizeMap } block mayNewChunk = let Block{ mem = blockId, spaceMap } = block spaceMap' = case mayNewChunk of Nothing -> spaceMap' Just newChunk@Chunk{ chunkOffset } -> Map.insert chunkOffset newChunk spaceMap block' = block{ spaceMap = spaceMap' } blocks' = Map.insert blockId block' blocks sizeMap' = case mayNewChunk of Nothing -> sizeMap Just newChunk@Chunk{ chunkSize = newChunkSize } -> Map.alter (Just . ins) newChunkSize sizeMap where ins Nothing = Set.singleton newChunk ins (Just cs) = Set.insert newChunk cs in pool{ blocks = blocks', sizeMap = sizeMap' } free :: MemPool -> MemoryLoc -> Prog r MemPool free pool@MemPool{..} MemoryLoc{..} = let allocStart = memoryOffset allocEnd = memoryOffset + allocSize block@Block{ spaceMap, blockSize, mem } = blocks Map.! memory leftChunk = snd <$> Map.lookupGT allocStart spaceMap rightChunk = snd <$> Map.lookupLT allocStart spaceMap mergeLeft = leftChunk >>= \chunk -> if chunkEnd chunk == allocStart then pure $ (chunk, chunkStart chunk) else Nothing mergeRight = rightChunk >>= \chunk -> if chunkStart chunk == allocEnd then pure $ (chunk, chunkEnd chunk) else Nothing chunksToReplace = map fst $ catMaybes [mergeLeft, mergeRight] freeStart = fromMaybe allocStart (snd <$> mergeLeft) freeEnd = fromMaybe allocEnd (snd <$> mergeRight) newChunkSize = freeEnd - freeStart blockBecomesEmpty = freeStart == 0 && newChunkSize == blockSize newChunk = Chunk { blockId = memory, chunkOffset = freeStart, chunkSize = newChunkSize } spaceMapDel = foldl' del spaceMap chunksToReplace where del smap chunk = Map.delete (chunkStart chunk) smap spaceMapUpd = Map.insert (chunkEnd newChunk) newChunk spaceMapDel block' = block{ spaceMap = spaceMapUpd } blocksUpd = Map.insert memory block' blocks blocksDel = Map.delete memory blocks sizeMapDel = foldl' del sizeMap chunksToReplace where del smap chunk@Chunk{ chunkSize } = Map.update (del' chunk) chunkSize smap del' chunk cs = let cs' = Set.delete chunk cs in if null cs' then Nothing else Just cs' sizeMapUpd = Map.alter (Just . ins) newChunkSize sizeMapDel where ins Nothing = Set.singleton newChunk ins (Just cs) = Set.insert newChunk cs in if blockBecomesEmpty && length blocks > 1 then do rawFree dev mem pure pool{ blocks = blocksDel, sizeMap = sizeMapDel } else pure $ pool{ blocks = blocksUpd, sizeMap = sizeMapUpd } fit :: VkDeviceSize -> VkDeviceSize -> VkDeviceSize -> VkDeviceSize -> (Bool, VkDeviceSize) fit chunkOffset chunkSize alignment requestSize = let precond = chunkSize >= requestSize maxOffset = chunkOffset + chunkSize - requestSize padding = maxOffset `mod` alignment in assert precond (maxOffset >= padding, padding) alloc :: MemPool -> Prog r (MemPool, MemoryLoc) alloc pool@MemPool{..} requestSize alignment = Result contains ( given chunk , Chunk with leftover mem from the chunk ) . Leftover mem can be zero , another Maybe for that . tryChunk :: Block -> Chunk -> Maybe ((Chunk, Maybe Chunk), MemoryLoc) tryChunk Block{ mem } chunk@Chunk{..} = let (doesFit, padding) = fit chunkOffset chunkSize alignment requestSize allocSize = requestSize + padding newChunkSize = chunkSize - allocSize chunk' = if newChunkSize > 0 then Just chunk{ chunkSize = newChunkSize } else Nothing memoryOffset = chunkOffset + chunkSize - allocSize loc = MemoryLoc{ memory = mem, memoryOffset, memorySize = requestSize, allocSize } in if doesFit then Just ((chunk, chunk'), loc) else Nothing candidateChunks = concatMap toList . map snd . iterateMaybe (flip Map.lookupGT sizeMap . fst) $ Map.lookupGE requestSize sizeMap existingTry = headMay $ mapMaybe (\chunk@Chunk{ blockId } -> tryChunk (blocks Map.! blockId) chunk) candidateChunks in case existingTry of Just (chunkUpdate, memoryLoc) -> pure (updatePool pool chunkUpdate, memoryLoc) Nothing -> do let blockSize = max memoryChunkSize requestSize mem <- rawAlloc dev memTypeIndex blockSize let block = Block{ mem, blockSize, spaceMap = Map.empty } ((_, mayNewChunk), memoryLoc) = fromJust $ tryChunk block Chunk{ blockId = mem, chunkOffset = 0, chunkSize = blockSize } pure (updatePoolFreshBlock pool block mayNewChunk, memoryLoc) makeMemPool :: VkDevice -> MemTypeIndex -> MemPool makeMemPool dev memTypeIndex = MemPool{ dev, memTypeIndex, blocks = Map.empty, sizeMap = Map.empty } destroyMemPool :: MemPool -> Prog r () destroyMemPool MemPool{ dev, blocks } = forM_ blocks $ \Block{ mem } -> rawFree dev mem
d9a95c39e4ae7be581fea77c81c737fd31752729d68b1e01d25b831c174f6b20
robert-strandh/SICL
call-instruction.lisp
(cl:in-package #:sicl-mir-to-lir) ;;; We need to store arguments into the appropriate registers and stack slots ( relative to RSP now ) , and then adjust RBP . The code generated is as per the description in section 27.3 " Calling conventions " of the SICL specification , though we have ;;; changed the order of some independent steps to make code ;;; generation easier. The callee function object and arguments have ;;; already been computed by previous instructions, so we are left to ;;; generate code for the rest of the process. ;;; TODO: put these magic numbers into another system. (defconstant +rack-prefix-size+ 2) (defconstant +rack-tag+ 7) (defconstant +standard-object-tag+ 5) (defmethod finish-lir-for-instruction ((instruction cleavir-ir:funcall-instruction)) (destructuring-bind (function &rest arguments) (cleavir-ir:inputs instruction) (let* ((argument-count (length arguments)) (start-of-sequence (make-instance 'cleavir-ir:nop-instruction)) (predecessor start-of-sequence) (function-register x86-64:*r11*) (scratch-register x86-64:*rax*)) (cleavir-ir:insert-instruction-before start-of-sequence instruction) (flet ((emit (instruction) (cleavir-ir:insert-instruction-after instruction predecessor) (setf predecessor instruction))) 1 . Load the rack of the function into a register . (emit (x86-64:load-from-location-instruction function function-register)) (emit (make-instance 'cleavir-ir:memref2-instruction :inputs (list function-register (cleavir-ir:make-immediate-input (- 8 +standard-object-tag+))) :outputs (list function-register))) 2 . Store the ( boxed ) argument count in R9 . (emit (make-instance 'cleavir-ir:assignment-instruction :inputs (list (cleavir-ir:make-immediate-input (ash argument-count 1))) :outputs (list x86-64:*r9*))) 3 . Store the arguments in RDI , RSI , RDX , RCX , and R8 . (loop for argument in arguments for register in x86-64:*argument-registers* do (x86-64:load-from-location-instruction argument register)) (cond ((<= argument-count (length x86-64:*argument-registers*)) 4 . Push the value of RBP on the stack . (emit (make-instance 'sicl-ir:push-instruction :inputs (list x86-64:*rbp*))) 5 . Copy the value of RSP into RBP . (emit (make-instance 'cleavir-ir:assignment-instruction :inputs (list x86-64:*rsp*) :outputs (list x86-64:*rbp*)))) (t 4 . Subtract 8(N - 3 ) from RSP , where N is the number of ;; arguments to pass. (emit (make-instance 'cleavir-ir:unsigned-sub-instruction :inputs (list x86-64:*rsp* (cleavir-ir:make-immediate-input (* 8 (- argument-count 3)))) :outputs (list x86-64:*rsp*))) 5 . Store the remaining arguments relative to RSP . (loop for stack-slot from 0 for argument in (nthcdr (length x86-64:*argument-registers*) arguments) for register = (etypecase argument (cleavir-ir:register-location argument) (cleavir-ir:stack-location (emit (x86-64:load-from-location-instruction argument scratch-register)) scratch-register)) do (emit (make-instance 'cleavir-ir:memset2-instruction :inputs (list x86-64:*rsp* (cleavir-ir:make-immediate-input (* 8 stack-slot)) register)))) 5.25 . Store the value of RBP into [ RSP + 8(N - 4 ) ] . (emit (make-instance 'cleavir-ir:memset2-instruction :inputs (list x86-64:*rbp* x86-64:*rsp* (cleavir-ir:make-immediate-input (* 8 (- argument-count 4)))))) 5.5 Copy the value of RSP + 8(N - 4 ) into RBP . (emit (make-instance 'sicl-ir:load-effective-address-instruction :inputs (list (sicl-ir:effective-address x86-64:*rsp* :displacement (* 8 (- argument-count 4)))) :outputs (list x86-64:*rbp*))))) 6 . Load the static environment of the callee from the ;; callee function object into R10. As per CLOS / funcallable - standard - object - defclass.lisp the environment is in the second slot of a ;; funcallable-standard-object. (emit (make-instance 'cleavir-ir:memref2-instruction :inputs (list function-register (cleavir-ir:make-immediate-input (- (* 8 (+ +rack-prefix-size+ 1)) +rack-tag+))) :outputs (list x86-64:*r10*))) 7 . Load the entry point address of the callee into an available scratch register , typically RAX . (emit (make-instance 'cleavir-ir:memref2-instruction :inputs (list function-register (cleavir-ir:make-immediate-input (- (* 8 (+ +rack-prefix-size+ 0)) +rack-tag+))) :outputs (list x86-64:*rax*))) 8 . Use the CALL instruction with that register as an argument . ;; We will just reuse this CALL instruction. (setf (cleavir-ir:inputs instruction) (list x86-64:*rax*)) 9 . Pop to restore the old stack frame . (cleavir-ir:insert-instruction-after (make-instance 'sicl-ir:pop-instruction :inputs '() :outputs (list x86-64:*rbp*)) instruction)) Remove the NOP instruction . (cleavir-ir:delete-instruction start-of-sequence)))) ;;; However, we don't do anything before a named call. (defmethod finish-lir-for-instruction ((instruction cleavir-ir:named-call-instruction)) nil)
null
https://raw.githubusercontent.com/robert-strandh/SICL/f4d9a0515801f15869692af9d420c9f202fed3fc/Code/Compiler/MIR-to-LIR/call-instruction.lisp
lisp
We need to store arguments into the appropriate registers and changed the order of some independent steps to make code generation easier. The callee function object and arguments have already been computed by previous instructions, so we are left to generate code for the rest of the process. TODO: put these magic numbers into another system. arguments to pass. callee function object into R10. As per funcallable-standard-object. We will just reuse this CALL instruction. However, we don't do anything before a named call.
(cl:in-package #:sicl-mir-to-lir) stack slots ( relative to RSP now ) , and then adjust RBP . The code generated is as per the description in section 27.3 " Calling conventions " of the SICL specification , though we have (defconstant +rack-prefix-size+ 2) (defconstant +rack-tag+ 7) (defconstant +standard-object-tag+ 5) (defmethod finish-lir-for-instruction ((instruction cleavir-ir:funcall-instruction)) (destructuring-bind (function &rest arguments) (cleavir-ir:inputs instruction) (let* ((argument-count (length arguments)) (start-of-sequence (make-instance 'cleavir-ir:nop-instruction)) (predecessor start-of-sequence) (function-register x86-64:*r11*) (scratch-register x86-64:*rax*)) (cleavir-ir:insert-instruction-before start-of-sequence instruction) (flet ((emit (instruction) (cleavir-ir:insert-instruction-after instruction predecessor) (setf predecessor instruction))) 1 . Load the rack of the function into a register . (emit (x86-64:load-from-location-instruction function function-register)) (emit (make-instance 'cleavir-ir:memref2-instruction :inputs (list function-register (cleavir-ir:make-immediate-input (- 8 +standard-object-tag+))) :outputs (list function-register))) 2 . Store the ( boxed ) argument count in R9 . (emit (make-instance 'cleavir-ir:assignment-instruction :inputs (list (cleavir-ir:make-immediate-input (ash argument-count 1))) :outputs (list x86-64:*r9*))) 3 . Store the arguments in RDI , RSI , RDX , RCX , and R8 . (loop for argument in arguments for register in x86-64:*argument-registers* do (x86-64:load-from-location-instruction argument register)) (cond ((<= argument-count (length x86-64:*argument-registers*)) 4 . Push the value of RBP on the stack . (emit (make-instance 'sicl-ir:push-instruction :inputs (list x86-64:*rbp*))) 5 . Copy the value of RSP into RBP . (emit (make-instance 'cleavir-ir:assignment-instruction :inputs (list x86-64:*rsp*) :outputs (list x86-64:*rbp*)))) (t 4 . Subtract 8(N - 3 ) from RSP , where N is the number of (emit (make-instance 'cleavir-ir:unsigned-sub-instruction :inputs (list x86-64:*rsp* (cleavir-ir:make-immediate-input (* 8 (- argument-count 3)))) :outputs (list x86-64:*rsp*))) 5 . Store the remaining arguments relative to RSP . (loop for stack-slot from 0 for argument in (nthcdr (length x86-64:*argument-registers*) arguments) for register = (etypecase argument (cleavir-ir:register-location argument) (cleavir-ir:stack-location (emit (x86-64:load-from-location-instruction argument scratch-register)) scratch-register)) do (emit (make-instance 'cleavir-ir:memset2-instruction :inputs (list x86-64:*rsp* (cleavir-ir:make-immediate-input (* 8 stack-slot)) register)))) 5.25 . Store the value of RBP into [ RSP + 8(N - 4 ) ] . (emit (make-instance 'cleavir-ir:memset2-instruction :inputs (list x86-64:*rbp* x86-64:*rsp* (cleavir-ir:make-immediate-input (* 8 (- argument-count 4)))))) 5.5 Copy the value of RSP + 8(N - 4 ) into RBP . (emit (make-instance 'sicl-ir:load-effective-address-instruction :inputs (list (sicl-ir:effective-address x86-64:*rsp* :displacement (* 8 (- argument-count 4)))) :outputs (list x86-64:*rbp*))))) 6 . Load the static environment of the callee from the CLOS / funcallable - standard - object - defclass.lisp the environment is in the second slot of a (emit (make-instance 'cleavir-ir:memref2-instruction :inputs (list function-register (cleavir-ir:make-immediate-input (- (* 8 (+ +rack-prefix-size+ 1)) +rack-tag+))) :outputs (list x86-64:*r10*))) 7 . Load the entry point address of the callee into an available scratch register , typically RAX . (emit (make-instance 'cleavir-ir:memref2-instruction :inputs (list function-register (cleavir-ir:make-immediate-input (- (* 8 (+ +rack-prefix-size+ 0)) +rack-tag+))) :outputs (list x86-64:*rax*))) 8 . Use the CALL instruction with that register as an argument . (setf (cleavir-ir:inputs instruction) (list x86-64:*rax*)) 9 . Pop to restore the old stack frame . (cleavir-ir:insert-instruction-after (make-instance 'sicl-ir:pop-instruction :inputs '() :outputs (list x86-64:*rbp*)) instruction)) Remove the NOP instruction . (cleavir-ir:delete-instruction start-of-sequence)))) (defmethod finish-lir-for-instruction ((instruction cleavir-ir:named-call-instruction)) nil)
d272fd7eea807bca90c1f7a775842d607f5c6ae3a092aedc937e3672d275668e
davdar/maam
GHCI.hs
module FP.GHCI where
null
https://raw.githubusercontent.com/davdar/maam/2cc3ff3511a7a4daadcd44c60c4b08862c01e183/src/FP/GHCI.hs
haskell
module FP.GHCI where
be535a71e54391d3b4de98a65840646022ee19a841eaafa83232d0e1cf92da99
ds-wizard/engine-backend
MigratorService.hs
module Wizard.Service.Migration.Questionnaire.MigratorService where import Control.Monad.Reader (asks, liftIO) import qualified Data.UUID as U import Shared.Util.Uuid import Wizard.Api.Resource.Migration.Questionnaire.MigratorStateChangeDTO import Wizard.Api.Resource.Migration.Questionnaire.MigratorStateCreateDTO import Wizard.Api.Resource.Migration.Questionnaire.MigratorStateDTO import Wizard.Api.Resource.Questionnaire.QuestionnaireDetailDTO import Wizard.Database.DAO.Common import Wizard.Database.DAO.Migration.Questionnaire.MigratorDAO import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO import Wizard.Model.Context.AppContext import Wizard.Model.Migration.Questionnaire.MigratorState import Wizard.Model.Questionnaire.Questionnaire import Wizard.Model.Questionnaire.QuestionnaireAcl import Wizard.Service.Acl.AclService import Wizard.Service.KnowledgeModel.KnowledgeModelService import Wizard.Service.Migration.Questionnaire.Migrator.Sanitizator import Wizard.Service.Migration.Questionnaire.MigratorAudit import Wizard.Service.Migration.Questionnaire.MigratorMapper import Wizard.Service.Questionnaire.QuestionnaireAcl import Wizard.Service.Questionnaire.QuestionnaireService createQuestionnaireMigration :: String -> MigratorStateCreateDTO -> AppContextM MigratorStateDTO createQuestionnaireMigration oldQtnUuid reqDto = runInTransaction $ do checkPermission _QTN_PERM oldQtn <- findQuestionnaireById oldQtnUuid checkMigrationPermissionToQtn oldQtn.visibility oldQtn.permissions newQtn <- upgradeQuestionnaire reqDto oldQtn insertQuestionnaire newQtn appUuid <- asks currentAppUuid let state = fromCreateDTO oldQtn.uuid newQtn.uuid appUuid insertMigratorState state auditQuestionnaireMigrationCreate reqDto oldQtn newQtn getQuestionnaireMigration (U.toString $ newQtn.uuid) getQuestionnaireMigration :: String -> AppContextM MigratorStateDTO getQuestionnaireMigration qtnUuid = do checkPermission _QTN_PERM state <- findMigratorStateByNewQuestionnaireId qtnUuid oldQtnDto <- getQuestionnaireDetailById (U.toString state.oldQuestionnaireUuid) newQtnDto <- getQuestionnaireDetailById (U.toString state.newQuestionnaireUuid) oldQtn <- findQuestionnaireById (U.toString state.oldQuestionnaireUuid) newQtn <- findQuestionnaireById (U.toString state.newQuestionnaireUuid) checkMigrationPermissionToQtn oldQtn.visibility oldQtn.permissions checkMigrationPermissionToQtn newQtn.visibility newQtn.permissions return $ toDTO oldQtnDto newQtnDto state.resolvedQuestionUuids state.appUuid modifyQuestionnaireMigration :: String -> MigratorStateChangeDTO -> AppContextM MigratorStateDTO modifyQuestionnaireMigration qtnUuid reqDto = runInTransaction $ do checkPermission _QTN_PERM state <- getQuestionnaireMigration qtnUuid let updatedState = fromChangeDTO reqDto state updateMigratorStateByNewQuestionnaireId updatedState auditQuestionnaireMigrationModify state reqDto return $ toDTO state.oldQuestionnaire state.newQuestionnaire updatedState.resolvedQuestionUuids updatedState.appUuid finishQuestionnaireMigration :: String -> AppContextM () finishQuestionnaireMigration qtnUuid = runInTransaction $ do checkPermission _QTN_PERM _ <- getQuestionnaireMigration qtnUuid state <- findMigratorStateByNewQuestionnaireId qtnUuid deleteMigratorStateByNewQuestionnaireId qtnUuid oldQtn <- findQuestionnaireById (U.toString state.oldQuestionnaireUuid) newQtn <- findQuestionnaireById (U.toString state.newQuestionnaireUuid) let updatedQtn = oldQtn { formatUuid = newQtn.formatUuid , documentTemplateId = newQtn.documentTemplateId , selectedQuestionTagUuids = newQtn.selectedQuestionTagUuids , packageId = newQtn.packageId , events = newQtn.events } :: Questionnaire updateQuestionnaireById updatedQtn deleteQuestionnaire (U.toString $ newQtn.uuid) False auditQuestionnaireMigrationFinish oldQtn newQtn return () cancelQuestionnaireMigration :: String -> AppContextM () cancelQuestionnaireMigration qtnUuid = runInTransaction $ do checkPermission _QTN_PERM state <- getQuestionnaireMigration qtnUuid deleteQuestionnaire (U.toString $ state.newQuestionnaire.uuid) True deleteMigratorStateByNewQuestionnaireId qtnUuid auditQuestionnaireMigrationCancel state return () -- -------------------------------- -- PRIVATE -- -------------------------------- upgradeQuestionnaire :: MigratorStateCreateDTO -> Questionnaire -> AppContextM Questionnaire upgradeQuestionnaire reqDto oldQtn = do let newPkgId = reqDto.targetPackageId let newTagUuids = reqDto.targetTagUuids oldKm <- compileKnowledgeModel [] (Just oldQtn.packageId) newTagUuids newKm <- compileKnowledgeModel [] (Just newPkgId) newTagUuids newUuid <- liftIO generateUuid newEvents <- sanitizeQuestionnaireEvents oldKm newKm oldQtn.events newPermissions <- traverse (upgradeQuestionnairePerm newUuid) oldQtn.permissions let upgradedQtn = oldQtn { uuid = newUuid , packageId = newPkgId , events = newEvents , selectedQuestionTagUuids = newTagUuids , documentTemplateId = Nothing , formatUuid = Nothing , permissions = newPermissions } :: Questionnaire return upgradedQtn upgradeQuestionnairePerm :: U.UUID -> QuestionnairePermRecord -> AppContextM QuestionnairePermRecord upgradeQuestionnairePerm newQtnUuid perm = do newUuid <- liftIO generateUuid let upgradedPerm = perm { uuid = newUuid , questionnaireUuid = newQtnUuid } return upgradedPerm
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Service/Migration/Questionnaire/MigratorService.hs
haskell
-------------------------------- PRIVATE --------------------------------
module Wizard.Service.Migration.Questionnaire.MigratorService where import Control.Monad.Reader (asks, liftIO) import qualified Data.UUID as U import Shared.Util.Uuid import Wizard.Api.Resource.Migration.Questionnaire.MigratorStateChangeDTO import Wizard.Api.Resource.Migration.Questionnaire.MigratorStateCreateDTO import Wizard.Api.Resource.Migration.Questionnaire.MigratorStateDTO import Wizard.Api.Resource.Questionnaire.QuestionnaireDetailDTO import Wizard.Database.DAO.Common import Wizard.Database.DAO.Migration.Questionnaire.MigratorDAO import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO import Wizard.Model.Context.AppContext import Wizard.Model.Migration.Questionnaire.MigratorState import Wizard.Model.Questionnaire.Questionnaire import Wizard.Model.Questionnaire.QuestionnaireAcl import Wizard.Service.Acl.AclService import Wizard.Service.KnowledgeModel.KnowledgeModelService import Wizard.Service.Migration.Questionnaire.Migrator.Sanitizator import Wizard.Service.Migration.Questionnaire.MigratorAudit import Wizard.Service.Migration.Questionnaire.MigratorMapper import Wizard.Service.Questionnaire.QuestionnaireAcl import Wizard.Service.Questionnaire.QuestionnaireService createQuestionnaireMigration :: String -> MigratorStateCreateDTO -> AppContextM MigratorStateDTO createQuestionnaireMigration oldQtnUuid reqDto = runInTransaction $ do checkPermission _QTN_PERM oldQtn <- findQuestionnaireById oldQtnUuid checkMigrationPermissionToQtn oldQtn.visibility oldQtn.permissions newQtn <- upgradeQuestionnaire reqDto oldQtn insertQuestionnaire newQtn appUuid <- asks currentAppUuid let state = fromCreateDTO oldQtn.uuid newQtn.uuid appUuid insertMigratorState state auditQuestionnaireMigrationCreate reqDto oldQtn newQtn getQuestionnaireMigration (U.toString $ newQtn.uuid) getQuestionnaireMigration :: String -> AppContextM MigratorStateDTO getQuestionnaireMigration qtnUuid = do checkPermission _QTN_PERM state <- findMigratorStateByNewQuestionnaireId qtnUuid oldQtnDto <- getQuestionnaireDetailById (U.toString state.oldQuestionnaireUuid) newQtnDto <- getQuestionnaireDetailById (U.toString state.newQuestionnaireUuid) oldQtn <- findQuestionnaireById (U.toString state.oldQuestionnaireUuid) newQtn <- findQuestionnaireById (U.toString state.newQuestionnaireUuid) checkMigrationPermissionToQtn oldQtn.visibility oldQtn.permissions checkMigrationPermissionToQtn newQtn.visibility newQtn.permissions return $ toDTO oldQtnDto newQtnDto state.resolvedQuestionUuids state.appUuid modifyQuestionnaireMigration :: String -> MigratorStateChangeDTO -> AppContextM MigratorStateDTO modifyQuestionnaireMigration qtnUuid reqDto = runInTransaction $ do checkPermission _QTN_PERM state <- getQuestionnaireMigration qtnUuid let updatedState = fromChangeDTO reqDto state updateMigratorStateByNewQuestionnaireId updatedState auditQuestionnaireMigrationModify state reqDto return $ toDTO state.oldQuestionnaire state.newQuestionnaire updatedState.resolvedQuestionUuids updatedState.appUuid finishQuestionnaireMigration :: String -> AppContextM () finishQuestionnaireMigration qtnUuid = runInTransaction $ do checkPermission _QTN_PERM _ <- getQuestionnaireMigration qtnUuid state <- findMigratorStateByNewQuestionnaireId qtnUuid deleteMigratorStateByNewQuestionnaireId qtnUuid oldQtn <- findQuestionnaireById (U.toString state.oldQuestionnaireUuid) newQtn <- findQuestionnaireById (U.toString state.newQuestionnaireUuid) let updatedQtn = oldQtn { formatUuid = newQtn.formatUuid , documentTemplateId = newQtn.documentTemplateId , selectedQuestionTagUuids = newQtn.selectedQuestionTagUuids , packageId = newQtn.packageId , events = newQtn.events } :: Questionnaire updateQuestionnaireById updatedQtn deleteQuestionnaire (U.toString $ newQtn.uuid) False auditQuestionnaireMigrationFinish oldQtn newQtn return () cancelQuestionnaireMigration :: String -> AppContextM () cancelQuestionnaireMigration qtnUuid = runInTransaction $ do checkPermission _QTN_PERM state <- getQuestionnaireMigration qtnUuid deleteQuestionnaire (U.toString $ state.newQuestionnaire.uuid) True deleteMigratorStateByNewQuestionnaireId qtnUuid auditQuestionnaireMigrationCancel state return () upgradeQuestionnaire :: MigratorStateCreateDTO -> Questionnaire -> AppContextM Questionnaire upgradeQuestionnaire reqDto oldQtn = do let newPkgId = reqDto.targetPackageId let newTagUuids = reqDto.targetTagUuids oldKm <- compileKnowledgeModel [] (Just oldQtn.packageId) newTagUuids newKm <- compileKnowledgeModel [] (Just newPkgId) newTagUuids newUuid <- liftIO generateUuid newEvents <- sanitizeQuestionnaireEvents oldKm newKm oldQtn.events newPermissions <- traverse (upgradeQuestionnairePerm newUuid) oldQtn.permissions let upgradedQtn = oldQtn { uuid = newUuid , packageId = newPkgId , events = newEvents , selectedQuestionTagUuids = newTagUuids , documentTemplateId = Nothing , formatUuid = Nothing , permissions = newPermissions } :: Questionnaire return upgradedQtn upgradeQuestionnairePerm :: U.UUID -> QuestionnairePermRecord -> AppContextM QuestionnairePermRecord upgradeQuestionnairePerm newQtnUuid perm = do newUuid <- liftIO generateUuid let upgradedPerm = perm { uuid = newUuid , questionnaireUuid = newQtnUuid } return upgradedPerm
39424d96653f3b817f845a5be433740bb1f78fe5f8fd70afe422ea05b55427c1
pirapira/coq2rust
mod_typing.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) Created by , Aug 2002 as part of the implementation of the Coq module system the Coq module system *) (* This module provides the main functions for type-checking module declarations *) open Util open Names open Declarations open Entries open Environ open Modops open Mod_subst type 'alg translation = module_signature * 'alg option * delta_resolver * Univ.constraints let rec mp_from_mexpr = function | MEident mp -> mp | MEapply (expr,_) -> mp_from_mexpr expr | MEwith (expr,_) -> mp_from_mexpr expr let is_modular = function | SFBmodule _ | SFBmodtype _ -> true | SFBconst _ | SFBmind _ -> false (** Split a [structure_body] at some label corresponding to a modular definition or not. *) let split_struc k m struc = let rec split rev_before = function | [] -> raise Not_found | (k',b)::after when Label.equal k k' && (is_modular b) == (m : bool) -> List.rev rev_before,b,after | h::tail -> split (h::rev_before) tail in split [] struc let discr_resolver mtb = match mtb.typ_expr with | NoFunctor _ -> mtb.typ_delta | MoreFunctor _ -> empty_delta_resolver let rec rebuild_mp mp l = match l with | []-> mp | i::r -> rebuild_mp (MPdot(mp,Label.of_id i)) r let (+++) = Univ.Constraint.union let rec check_with_def env struc (idl,c) mp equiv = let lab,idl = match idl with | [] -> assert false | id::idl -> Label.of_id id, idl in try let modular = not (List.is_empty idl) in let before,spec,after = split_struc lab modular struc in let env' = Modops.add_structure mp before equiv env in if List.is_empty idl then Toplevel definition let cb = match spec with | SFBconst cb -> cb | _ -> error_not_a_constant lab in (* In the spirit of subtyping.check_constant, we accept any implementations of parameters and opaques terms, as long as they have the right type *) let ccst = Declareops.constraints_of_constant (opaque_tables env) cb in let env' = Environ.add_constraints ccst env' in let c',cst = match cb.const_body with | Undef _ | OpaqueDef _ -> let j = Typeops.infer env' c in let typ = Typeops.type_of_constant_type env' cb.const_type in let cst = Reduction.infer_conv_leq env' (Environ.universes env') j.uj_type typ in j.uj_val,cst | Def cs -> let cst = Reduction.infer_conv env' (Environ.universes env') c (Mod_subst.force_constr cs) in FIXME MS : what to check here ? subtyping of polymorphic constants ... if cb.const_polymorphic then cst else ccst +++ cst in c, cst in let def = Def (Mod_subst.from_val c') in let cb' = { cb with const_body = def; const_body_code = Cemitcodes.from_val (compile_constant_body env' def) } (* const_universes = Future.from_val cst } *) in before@(lab,SFBconst(cb'))::after, c', cst else (* Definition inside a sub-module *) let mb = match spec with | SFBmodule mb -> mb | _ -> error_not_a_module (Label.to_string lab) in begin match mb.mod_expr with | Abstract -> let struc = Modops.destr_nofunctor mb.mod_type in let struc',c',cst = check_with_def env' struc (idl,c) (MPdot(mp,lab)) mb.mod_delta in let mb' = { mb with mod_type = NoFunctor struc'; mod_type_alg = None } in before@(lab,SFBmodule mb')::after, c', cst | _ -> error_generative_module_expected lab end with | Not_found -> error_no_such_label lab | Reduction.NotConvertible -> error_incorrect_with_constraint lab let rec check_with_mod env struc (idl,mp1) mp equiv = let lab,idl = match idl with | [] -> assert false | id::idl -> Label.of_id id, idl in try let before,spec,after = split_struc lab true struc in let env' = Modops.add_structure mp before equiv env in let old = match spec with | SFBmodule mb -> mb | _ -> error_not_a_module (Label.to_string lab) in if List.is_empty idl then Toplevel module definition let mb_mp1 = lookup_module mp1 env in let mtb_mp1 = module_type_of_module mb_mp1 in let cst = match old.mod_expr with | Abstract -> begin try let mtb_old = module_type_of_module old in Subtyping.check_subtypes env' mtb_mp1 mtb_old +++ old.mod_constraints with Failure _ -> error_incorrect_with_constraint lab end | Algebraic (NoFunctor (MEident(mp'))) -> check_modpath_equiv env' mp1 mp'; old.mod_constraints | _ -> error_generative_module_expected lab in let mp' = MPdot (mp,lab) in let new_mb = strengthen_and_subst_mb mb_mp1 mp' false in let new_mb' = { new_mb with mod_mp = mp'; mod_expr = Algebraic (NoFunctor (MEident mp1)); mod_constraints = cst } in let new_equiv = add_delta_resolver equiv new_mb.mod_delta in (* we propagate the new equality in the rest of the signature with the identity substitution accompagned by the new resolver*) let id_subst = map_mp mp' mp' new_mb.mod_delta in let new_after = subst_structure id_subst after in before@(lab,SFBmodule new_mb')::new_after, new_equiv, cst else (* Module definition of a sub-module *) let mp' = MPdot (mp,lab) in let old = match spec with | SFBmodule msb -> msb | _ -> error_not_a_module (Label.to_string lab) in begin match old.mod_expr with | Abstract -> let struc = destr_nofunctor old.mod_type in let struc',equiv',cst = check_with_mod env' struc (idl,mp1) mp' old.mod_delta in let new_mb = { old with mod_type = NoFunctor struc'; mod_type_alg = None; mod_delta = equiv' } in let new_equiv = add_delta_resolver equiv equiv' in let id_subst = map_mp mp' mp' equiv' in let new_after = subst_structure id_subst after in before@(lab,SFBmodule new_mb)::new_after, new_equiv, cst | Algebraic (NoFunctor (MEident mp0)) -> let mpnew = rebuild_mp mp0 idl in check_modpath_equiv env' mpnew mp; before@(lab,spec)::after, equiv, Univ.Constraint.empty | _ -> error_generative_module_expected lab end with | Not_found -> error_no_such_label lab | Reduction.NotConvertible -> error_incorrect_with_constraint lab let mk_alg_with alg wd = Option.map (fun a -> MEwith (a,wd)) alg let check_with env mp (sign,alg,reso,cst) = function |WithDef(idl,c) -> let struc = destr_nofunctor sign in let struc',c',cst' = check_with_def env struc (idl,c) mp reso in let alg' = mk_alg_with alg (WithDef (idl,c')) in (NoFunctor struc'),alg',reso, cst+++cst' |WithMod(idl,mp1) as wd -> let struc = destr_nofunctor sign in let struc',reso',cst' = check_with_mod env struc (idl,mp1) mp reso in let alg' = mk_alg_with alg wd in (NoFunctor struc'),alg',reso', cst+++cst' let mk_alg_app mpo alg arg = match mpo, alg with | Some _, Some alg -> Some (MEapply (alg,arg)) | _ -> None * Translation of a module struct entry : - We translate to a module when a [ module_path ] is given , otherwise to a module type . - The first output is the expanded signature - The second output is the algebraic expression , kept for the extraction . It is never None when translating to a module , but for module type it could not be contain [ SEBapply ] or [ SEBfunctor ] . - We translate to a module when a [module_path] is given, otherwise to a module type. - The first output is the expanded signature - The second output is the algebraic expression, kept for the extraction. It is never None when translating to a module, but for module type it could not be contain [SEBapply] or [SEBfunctor]. *) let rec translate_mse env mpo inl = function |MEident mp1 -> let sign,reso = match mpo with |Some mp -> let mb = strengthen_and_subst_mb (lookup_module mp1 env) mp false in mb.mod_type, mb.mod_delta |None -> let mtb = lookup_modtype mp1 env in mtb.typ_expr, mtb.typ_delta in sign,Some (MEident mp1),reso,Univ.Constraint.empty |MEapply (fe,mp1) -> translate_apply env inl (translate_mse env mpo inl fe) mp1 (mk_alg_app mpo) |MEwith(me, with_decl) -> assert (mpo == None); (* No 'with' syntax for modules *) let mp = mp_from_mexpr me in check_with env mp (translate_mse env None inl me) with_decl and translate_apply env inl (sign,alg,reso,cst1) mp1 mkalg = let farg_id, farg_b, fbody_b = destr_functor sign in let mtb = module_type_of_module (lookup_module mp1 env) in let cst2 = Subtyping.check_subtypes env mtb farg_b in let mp_delta = discr_resolver mtb in let mp_delta = inline_delta_resolver env inl mp1 farg_id farg_b mp_delta in let subst = map_mbid farg_id mp1 mp_delta in let body = subst_signature subst fbody_b in let alg' = mkalg alg mp1 in let reso' = subst_codom_delta_resolver subst reso in body,alg',reso', cst1 +++ cst2 let mk_alg_funct mpo mbid mtb alg = match mpo, alg with | Some _, Some alg -> Some (MoreFunctor (mbid,mtb,alg)) | _ -> None let rec translate_mse_funct env mpo inl mse = function |[] -> let sign,alg,reso,cst = translate_mse env mpo inl mse in sign, Option.map (fun a -> NoFunctor a) alg, reso, cst |(mbid, ty) :: params -> let mp_id = MPbound mbid in let mtb = translate_modtype env mp_id inl ([],ty) in let env' = add_module_type mp_id mtb env in let sign,alg,reso,cst = translate_mse_funct env' mpo inl mse params in let alg' = mk_alg_funct mpo mbid mtb alg in MoreFunctor (mbid, mtb, sign), alg',reso, cst +++ mtb.typ_constraints and translate_modtype env mp inl (params,mte) = let sign,alg,reso,cst = translate_mse_funct env None inl mte params in let mtb = { typ_mp = mp_from_mexpr mte; typ_expr = sign; typ_expr_alg = None; typ_constraints = cst; typ_delta = reso } in let mtb' = subst_modtype_and_resolver mtb mp in { mtb' with typ_expr_alg = alg } (** [finalize_module] : from an already-translated (or interactive) implementation and a signature entry, produce a final [module_expr] *) let finalize_module env mp (sign,alg,reso,cst) restype = match restype with |None -> let impl = match alg with Some e -> Algebraic e | None -> FullStruct in { mod_mp = mp; mod_expr = impl; mod_type = sign; mod_type_alg = None; mod_constraints = cst; mod_delta = reso; mod_retroknowledge = [] } |Some (params_mte,inl) -> let res_mtb = translate_modtype env mp inl params_mte in let auto_mtb = { typ_mp = mp; typ_expr = sign; typ_expr_alg = None; typ_constraints = Univ.Constraint.empty; typ_delta = reso } in let cst' = Subtyping.check_subtypes env auto_mtb res_mtb in let impl = match alg with Some e -> Algebraic e | None -> Struct sign in { mod_mp = mp; mod_expr = impl; mod_type = res_mtb.typ_expr; mod_type_alg = res_mtb.typ_expr_alg; mod_constraints = cst +++ cst'; mod_delta = res_mtb.typ_delta; mod_retroknowledge = [] } let translate_module env mp inl = function |MType (params,ty) -> let mtb = translate_modtype env mp inl (params,ty) in module_body_of_type mp mtb |MExpr (params,mse,oty) -> let t = translate_mse_funct env (Some mp) inl mse params in let restype = Option.map (fun ty -> ((params,ty),inl)) oty in finalize_module env mp t restype let rec translate_mse_incl env mp inl = function |MEident mp1 -> let mb = strengthen_and_subst_mb (lookup_module mp1 env) mp true in let sign = clean_bounded_mod_expr mb.mod_type in sign,None,mb.mod_delta,Univ.Constraint.empty |MEapply (fe,arg) -> let ftrans = translate_mse_incl env mp inl fe in translate_apply env inl ftrans arg (fun _ _ -> None) |_ -> Modops.error_higher_order_include ()
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/kernel/mod_typing.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** This module provides the main functions for type-checking module declarations * Split a [structure_body] at some label corresponding to a modular definition or not. In the spirit of subtyping.check_constant, we accept any implementations of parameters and opaques terms, as long as they have the right type const_universes = Future.from_val cst } Definition inside a sub-module we propagate the new equality in the rest of the signature with the identity substitution accompagned by the new resolver Module definition of a sub-module No 'with' syntax for modules * [finalize_module] : from an already-translated (or interactive) implementation and a signature entry, produce a final [module_expr]
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Created by , Aug 2002 as part of the implementation of the Coq module system the Coq module system *) open Util open Names open Declarations open Entries open Environ open Modops open Mod_subst type 'alg translation = module_signature * 'alg option * delta_resolver * Univ.constraints let rec mp_from_mexpr = function | MEident mp -> mp | MEapply (expr,_) -> mp_from_mexpr expr | MEwith (expr,_) -> mp_from_mexpr expr let is_modular = function | SFBmodule _ | SFBmodtype _ -> true | SFBconst _ | SFBmind _ -> false let split_struc k m struc = let rec split rev_before = function | [] -> raise Not_found | (k',b)::after when Label.equal k k' && (is_modular b) == (m : bool) -> List.rev rev_before,b,after | h::tail -> split (h::rev_before) tail in split [] struc let discr_resolver mtb = match mtb.typ_expr with | NoFunctor _ -> mtb.typ_delta | MoreFunctor _ -> empty_delta_resolver let rec rebuild_mp mp l = match l with | []-> mp | i::r -> rebuild_mp (MPdot(mp,Label.of_id i)) r let (+++) = Univ.Constraint.union let rec check_with_def env struc (idl,c) mp equiv = let lab,idl = match idl with | [] -> assert false | id::idl -> Label.of_id id, idl in try let modular = not (List.is_empty idl) in let before,spec,after = split_struc lab modular struc in let env' = Modops.add_structure mp before equiv env in if List.is_empty idl then Toplevel definition let cb = match spec with | SFBconst cb -> cb | _ -> error_not_a_constant lab in let ccst = Declareops.constraints_of_constant (opaque_tables env) cb in let env' = Environ.add_constraints ccst env' in let c',cst = match cb.const_body with | Undef _ | OpaqueDef _ -> let j = Typeops.infer env' c in let typ = Typeops.type_of_constant_type env' cb.const_type in let cst = Reduction.infer_conv_leq env' (Environ.universes env') j.uj_type typ in j.uj_val,cst | Def cs -> let cst = Reduction.infer_conv env' (Environ.universes env') c (Mod_subst.force_constr cs) in FIXME MS : what to check here ? subtyping of polymorphic constants ... if cb.const_polymorphic then cst else ccst +++ cst in c, cst in let def = Def (Mod_subst.from_val c') in let cb' = { cb with const_body = def; const_body_code = Cemitcodes.from_val (compile_constant_body env' def) } in before@(lab,SFBconst(cb'))::after, c', cst else let mb = match spec with | SFBmodule mb -> mb | _ -> error_not_a_module (Label.to_string lab) in begin match mb.mod_expr with | Abstract -> let struc = Modops.destr_nofunctor mb.mod_type in let struc',c',cst = check_with_def env' struc (idl,c) (MPdot(mp,lab)) mb.mod_delta in let mb' = { mb with mod_type = NoFunctor struc'; mod_type_alg = None } in before@(lab,SFBmodule mb')::after, c', cst | _ -> error_generative_module_expected lab end with | Not_found -> error_no_such_label lab | Reduction.NotConvertible -> error_incorrect_with_constraint lab let rec check_with_mod env struc (idl,mp1) mp equiv = let lab,idl = match idl with | [] -> assert false | id::idl -> Label.of_id id, idl in try let before,spec,after = split_struc lab true struc in let env' = Modops.add_structure mp before equiv env in let old = match spec with | SFBmodule mb -> mb | _ -> error_not_a_module (Label.to_string lab) in if List.is_empty idl then Toplevel module definition let mb_mp1 = lookup_module mp1 env in let mtb_mp1 = module_type_of_module mb_mp1 in let cst = match old.mod_expr with | Abstract -> begin try let mtb_old = module_type_of_module old in Subtyping.check_subtypes env' mtb_mp1 mtb_old +++ old.mod_constraints with Failure _ -> error_incorrect_with_constraint lab end | Algebraic (NoFunctor (MEident(mp'))) -> check_modpath_equiv env' mp1 mp'; old.mod_constraints | _ -> error_generative_module_expected lab in let mp' = MPdot (mp,lab) in let new_mb = strengthen_and_subst_mb mb_mp1 mp' false in let new_mb' = { new_mb with mod_mp = mp'; mod_expr = Algebraic (NoFunctor (MEident mp1)); mod_constraints = cst } in let new_equiv = add_delta_resolver equiv new_mb.mod_delta in let id_subst = map_mp mp' mp' new_mb.mod_delta in let new_after = subst_structure id_subst after in before@(lab,SFBmodule new_mb')::new_after, new_equiv, cst else let mp' = MPdot (mp,lab) in let old = match spec with | SFBmodule msb -> msb | _ -> error_not_a_module (Label.to_string lab) in begin match old.mod_expr with | Abstract -> let struc = destr_nofunctor old.mod_type in let struc',equiv',cst = check_with_mod env' struc (idl,mp1) mp' old.mod_delta in let new_mb = { old with mod_type = NoFunctor struc'; mod_type_alg = None; mod_delta = equiv' } in let new_equiv = add_delta_resolver equiv equiv' in let id_subst = map_mp mp' mp' equiv' in let new_after = subst_structure id_subst after in before@(lab,SFBmodule new_mb)::new_after, new_equiv, cst | Algebraic (NoFunctor (MEident mp0)) -> let mpnew = rebuild_mp mp0 idl in check_modpath_equiv env' mpnew mp; before@(lab,spec)::after, equiv, Univ.Constraint.empty | _ -> error_generative_module_expected lab end with | Not_found -> error_no_such_label lab | Reduction.NotConvertible -> error_incorrect_with_constraint lab let mk_alg_with alg wd = Option.map (fun a -> MEwith (a,wd)) alg let check_with env mp (sign,alg,reso,cst) = function |WithDef(idl,c) -> let struc = destr_nofunctor sign in let struc',c',cst' = check_with_def env struc (idl,c) mp reso in let alg' = mk_alg_with alg (WithDef (idl,c')) in (NoFunctor struc'),alg',reso, cst+++cst' |WithMod(idl,mp1) as wd -> let struc = destr_nofunctor sign in let struc',reso',cst' = check_with_mod env struc (idl,mp1) mp reso in let alg' = mk_alg_with alg wd in (NoFunctor struc'),alg',reso', cst+++cst' let mk_alg_app mpo alg arg = match mpo, alg with | Some _, Some alg -> Some (MEapply (alg,arg)) | _ -> None * Translation of a module struct entry : - We translate to a module when a [ module_path ] is given , otherwise to a module type . - The first output is the expanded signature - The second output is the algebraic expression , kept for the extraction . It is never None when translating to a module , but for module type it could not be contain [ SEBapply ] or [ SEBfunctor ] . - We translate to a module when a [module_path] is given, otherwise to a module type. - The first output is the expanded signature - The second output is the algebraic expression, kept for the extraction. It is never None when translating to a module, but for module type it could not be contain [SEBapply] or [SEBfunctor]. *) let rec translate_mse env mpo inl = function |MEident mp1 -> let sign,reso = match mpo with |Some mp -> let mb = strengthen_and_subst_mb (lookup_module mp1 env) mp false in mb.mod_type, mb.mod_delta |None -> let mtb = lookup_modtype mp1 env in mtb.typ_expr, mtb.typ_delta in sign,Some (MEident mp1),reso,Univ.Constraint.empty |MEapply (fe,mp1) -> translate_apply env inl (translate_mse env mpo inl fe) mp1 (mk_alg_app mpo) |MEwith(me, with_decl) -> let mp = mp_from_mexpr me in check_with env mp (translate_mse env None inl me) with_decl and translate_apply env inl (sign,alg,reso,cst1) mp1 mkalg = let farg_id, farg_b, fbody_b = destr_functor sign in let mtb = module_type_of_module (lookup_module mp1 env) in let cst2 = Subtyping.check_subtypes env mtb farg_b in let mp_delta = discr_resolver mtb in let mp_delta = inline_delta_resolver env inl mp1 farg_id farg_b mp_delta in let subst = map_mbid farg_id mp1 mp_delta in let body = subst_signature subst fbody_b in let alg' = mkalg alg mp1 in let reso' = subst_codom_delta_resolver subst reso in body,alg',reso', cst1 +++ cst2 let mk_alg_funct mpo mbid mtb alg = match mpo, alg with | Some _, Some alg -> Some (MoreFunctor (mbid,mtb,alg)) | _ -> None let rec translate_mse_funct env mpo inl mse = function |[] -> let sign,alg,reso,cst = translate_mse env mpo inl mse in sign, Option.map (fun a -> NoFunctor a) alg, reso, cst |(mbid, ty) :: params -> let mp_id = MPbound mbid in let mtb = translate_modtype env mp_id inl ([],ty) in let env' = add_module_type mp_id mtb env in let sign,alg,reso,cst = translate_mse_funct env' mpo inl mse params in let alg' = mk_alg_funct mpo mbid mtb alg in MoreFunctor (mbid, mtb, sign), alg',reso, cst +++ mtb.typ_constraints and translate_modtype env mp inl (params,mte) = let sign,alg,reso,cst = translate_mse_funct env None inl mte params in let mtb = { typ_mp = mp_from_mexpr mte; typ_expr = sign; typ_expr_alg = None; typ_constraints = cst; typ_delta = reso } in let mtb' = subst_modtype_and_resolver mtb mp in { mtb' with typ_expr_alg = alg } let finalize_module env mp (sign,alg,reso,cst) restype = match restype with |None -> let impl = match alg with Some e -> Algebraic e | None -> FullStruct in { mod_mp = mp; mod_expr = impl; mod_type = sign; mod_type_alg = None; mod_constraints = cst; mod_delta = reso; mod_retroknowledge = [] } |Some (params_mte,inl) -> let res_mtb = translate_modtype env mp inl params_mte in let auto_mtb = { typ_mp = mp; typ_expr = sign; typ_expr_alg = None; typ_constraints = Univ.Constraint.empty; typ_delta = reso } in let cst' = Subtyping.check_subtypes env auto_mtb res_mtb in let impl = match alg with Some e -> Algebraic e | None -> Struct sign in { mod_mp = mp; mod_expr = impl; mod_type = res_mtb.typ_expr; mod_type_alg = res_mtb.typ_expr_alg; mod_constraints = cst +++ cst'; mod_delta = res_mtb.typ_delta; mod_retroknowledge = [] } let translate_module env mp inl = function |MType (params,ty) -> let mtb = translate_modtype env mp inl (params,ty) in module_body_of_type mp mtb |MExpr (params,mse,oty) -> let t = translate_mse_funct env (Some mp) inl mse params in let restype = Option.map (fun ty -> ((params,ty),inl)) oty in finalize_module env mp t restype let rec translate_mse_incl env mp inl = function |MEident mp1 -> let mb = strengthen_and_subst_mb (lookup_module mp1 env) mp true in let sign = clean_bounded_mod_expr mb.mod_type in sign,None,mb.mod_delta,Univ.Constraint.empty |MEapply (fe,arg) -> let ftrans = translate_mse_incl env mp inl fe in translate_apply env inl ftrans arg (fun _ _ -> None) |_ -> Modops.error_higher_order_include ()
ed90f60aed67fcca51e163f56b604ff629317fdff0ba888768235be4dd6fd770
graninas/Functional-Design-and-Architecture
HardwareTest.hs
module HardwareTest where import Andromeda.Hardware.Device import Andromeda.Hardware.Service import DeviceTest makeDeviceMock _ = blankDevice mockedHandle = newHandle makeDeviceMock blankDevice test = do putStr "With real service: " testDevice defaultHandle putStr "With mocked service: " testDevice mockedHandle how to without passing handle but with ability to exchange service impl ? -- IORef State
null
https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/1736abc16d3e4917fc466010dcc182746af2fd0e/First-Edition/BookSamples/CH03/Services/PureStateless/HardwareTest.hs
haskell
IORef
module HardwareTest where import Andromeda.Hardware.Device import Andromeda.Hardware.Service import DeviceTest makeDeviceMock _ = blankDevice mockedHandle = newHandle makeDeviceMock blankDevice test = do putStr "With real service: " testDevice defaultHandle putStr "With mocked service: " testDevice mockedHandle how to without passing handle but with ability to exchange service impl ? State
705db6c18dd1485e4284a2312274476129968bfedca33881205f36656b586ce8
LambdaScientist/CLaSH-by-example
Dflop_sync_enable.hs
# LANGUAGE DataKinds # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # # LANGUAGE NoImplicitPrelude # module ClocksAndRegisters.Models.Dflop_sync_enable where import CLaSH.Prelude import Control.Lens hiding ((:>)) import Text.PrettyPrint.HughesPJClass import SAFE.TestingTools import SAFE.CommonClash import GHC.Generics (Generic) import Control.DeepSeq data SignalStatus = IsRising | NotRising deriving (Eq, Show) data ActiveStatus = Enabled | Disabled deriving (Eq, Show) data ResetStatus = ResetEnabled | ResetDisabled deriving (Eq, Show) data ClearStatus = ClearEnabled | ClearDisabled deriving (Eq, Show) --inputs data PIn = PIn { _clk :: Bit , _in1 :: Bit , _reset :: ResetStatus , _enable :: ActiveStatus , _clearN :: ClearStatus } deriving (Eq, Show) instance NFData PIn where rnf a = seq a () --Outputs and state data data St = St { _out1 :: Bit } deriving (Eq, Show) makeLenses ''St instance NFData St where rnf a = seq a () getSignalStatus :: (Bounded a, Eq a) => a -> Signal a -> Signal SignalStatus getSignalStatus value sigValue = status <$> isRising value sigValue where status rising = if rising then IsRising else NotRising onTrue :: St -> PIn -> SignalStatus -> St onTrue st PIn{_reset = ResetEnabled} _ = St 0 onTrue st PIn{_enable = Enabled, _clearN = ClearEnabled} IsRising = St 0 onTrue st PIn{_enable = Enabled, _in1 = input1} IsRising = st{ _out1 = input1 } onTrue st _ _ = st topEntity :: Signal PIn -> Signal St topEntity = topEntity' st where st = St 0 topEntity' :: St -> Signal PIn -> Signal St topEntity' st pin = result where result = register st (onTrue <$> result <*> pin <*> rising ) rising = getSignalStatus 0 clk clk = _clk <$> pin - The following code is only for a custom testing framework , and PrettyPrinted output instance SysState St instance Pretty St where pPrint St {..} = text "St" $+$ text "_out1 =" <+> showT _out1 instance PortIn PIn instance Pretty PIn where pPrint PIn {..} = text "PIn:" $+$ text "_clk =" <+> showT _clk $+$ text "_in1 =" <+> showT _in1 $+$ text "_reset =" <+> showT _reset $+$ text "_enable =" <+> showT _enable $+$ text "_clearN =" <+> showT _clearN
null
https://raw.githubusercontent.com/LambdaScientist/CLaSH-by-example/e783cd2f2408e67baf7f36c10398c27036a78ef3/HaskellClashExamples/src/ClocksAndRegisters/Models/Dflop_sync_enable.hs
haskell
inputs Outputs and state data
# LANGUAGE DataKinds # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # # LANGUAGE NoImplicitPrelude # module ClocksAndRegisters.Models.Dflop_sync_enable where import CLaSH.Prelude import Control.Lens hiding ((:>)) import Text.PrettyPrint.HughesPJClass import SAFE.TestingTools import SAFE.CommonClash import GHC.Generics (Generic) import Control.DeepSeq data SignalStatus = IsRising | NotRising deriving (Eq, Show) data ActiveStatus = Enabled | Disabled deriving (Eq, Show) data ResetStatus = ResetEnabled | ResetDisabled deriving (Eq, Show) data ClearStatus = ClearEnabled | ClearDisabled deriving (Eq, Show) data PIn = PIn { _clk :: Bit , _in1 :: Bit , _reset :: ResetStatus , _enable :: ActiveStatus , _clearN :: ClearStatus } deriving (Eq, Show) instance NFData PIn where rnf a = seq a () data St = St { _out1 :: Bit } deriving (Eq, Show) makeLenses ''St instance NFData St where rnf a = seq a () getSignalStatus :: (Bounded a, Eq a) => a -> Signal a -> Signal SignalStatus getSignalStatus value sigValue = status <$> isRising value sigValue where status rising = if rising then IsRising else NotRising onTrue :: St -> PIn -> SignalStatus -> St onTrue st PIn{_reset = ResetEnabled} _ = St 0 onTrue st PIn{_enable = Enabled, _clearN = ClearEnabled} IsRising = St 0 onTrue st PIn{_enable = Enabled, _in1 = input1} IsRising = st{ _out1 = input1 } onTrue st _ _ = st topEntity :: Signal PIn -> Signal St topEntity = topEntity' st where st = St 0 topEntity' :: St -> Signal PIn -> Signal St topEntity' st pin = result where result = register st (onTrue <$> result <*> pin <*> rising ) rising = getSignalStatus 0 clk clk = _clk <$> pin - The following code is only for a custom testing framework , and PrettyPrinted output instance SysState St instance Pretty St where pPrint St {..} = text "St" $+$ text "_out1 =" <+> showT _out1 instance PortIn PIn instance Pretty PIn where pPrint PIn {..} = text "PIn:" $+$ text "_clk =" <+> showT _clk $+$ text "_in1 =" <+> showT _in1 $+$ text "_reset =" <+> showT _reset $+$ text "_enable =" <+> showT _enable $+$ text "_clearN =" <+> showT _clearN
34f0eb5e3417c31b6bcdf97ed9896324ce2752b2fc02cc3fffe2c2d041e24613
aggieben/weblocks
dependencies.lisp
(in-package :weblocks-test) (deftest dependencies-by-symbol-1 (remove nil (weblocks::dependencies-by-symbol 'non-existent-widget-name)) nil) (deftest dependencies-by-symbol-2 (format nil "~A" (mapcar #'dependency-url (remove nil (weblocks::dependencies-by-symbol 'navigation)))) "(/pub/stylesheets/navigation.css)") (deftest make-local-dependency-1 (make-local-dependency :stylesheet "non-existing-file-name") nil) (deftest make-local-dependency-2 (format nil "~A" (dependency-url (make-local-dependency :stylesheet "non-existing-file-name" :do-not-probe t))) "/pub/stylesheets/non-existing-file-name.css") (deftest make-local-dependency-3 (format nil "~A" (dependency-url (make-local-dependency :stylesheet "main"))) "/pub/stylesheets/main.css") (deftest make-local-dependency-4 (format nil "~A" (dependency-url (make-local-dependency :script "weblocks"))) "/pub/scripts/weblocks.js") (deftest make-local-dependency-5 (format nil "~A" (dependency-url (make-local-dependency :script "weblocks" :do-not-probe t))) "/pub/scripts/weblocks.js") (deftest dependencies-equalp-1 (dependencies-equalp (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "")) nil) (deftest dependencies-equalp-2 (dependencies-equalp (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "")) t) (deftest dependencies-equalp-3 (dependencies-equalp (make-instance 'script-dependency :url "") (make-instance 'script-dependency :url "")) nil) (deftest dependencies-equalp-4 (dependencies-equalp (make-instance 'script-dependency :url "") (make-instance 'script-dependency :url "")) t) (deftest dependencies-lessp-1 (dependencies-lessp (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "")) nil) (deftest dependencies-lessp-2 (dependencies-lessp (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "")) nil) (deftest dependencies-lessp-3 (dependencies-lessp (make-instance 'stylesheet-dependency :url "") (make-instance 'script-dependency :url "")) t) (deftest dependencies-lessp-4 (dependencies-lessp (make-instance 'script-dependency :url "") (make-instance 'script-dependency :url "")) nil) (deftest dependencies-lessp-5 (dependencies-lessp nil nil) nil) (deftest per-class-dependencies-1 (per-class-dependencies "a string") nil) (deftest per-class-dependencies-2 (per-class-dependencies (lambda ())) nil) (deftest per-class-dependencies-3 (per-class-dependencies 'some-symbol) nil) (deftest per-class-dependencies-4 (apply #'dependencies-equalp (append (remove nil (per-class-dependencies (make-instance 'navigation))) (list (make-local-dependency :stylesheet "navigation")))) t) (deftest dependencies-1 (dependencies 'some-symbol) nil) (deftest dependencies-2 (dependencies "some-string") nil) (deftest dependencies-3 (dependencies (lambda ())) nil) (deftest dependencies-4 (dependencies (make-instance 'widget :name "abc123")) nil) (deftest dependencies-5 (apply #'dependencies-equalp (append (dependencies "main") (list (make-local-dependency :stylesheet "main")))) t) (deftest dependencies-6 (format nil "~A" (mapcar #'dependency-url (dependencies (make-instance 'navigation)))) "(/pub/stylesheets/navigation.css)") (deftest prune-dependencies-1 (format nil "~A" (mapcar #'dependency-url (weblocks::prune-dependencies (list (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url ""))))) "( )") (deftest prune-dependencies-2 (format nil "~A" (mapcar #'dependency-url (weblocks::prune-dependencies (list (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url ""))))) "( )") (deftest sort-dependencies-by-type-1 (format nil "~A" (mapcar #'dependency-url (weblocks::sort-dependencies-by-type (list (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") )))) "( )") (deftest compact-dependencies-1 (format nil "~A" (mapcar #'dependency-url (compact-dependencies (list (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") )))) "( )") (deftest-html render-dependency-in-page-head-1 (render-dependency-in-page-head (make-instance 'script-dependency :url "")) (:script :src "" :type "text/javascript" "")) (deftest-html render-dependency-in-page-head-2 (render-dependency-in-page-head (make-instance 'stylesheet-dependency :url "")) (:link :rel "stylesheet" :type "text/css" :href ""))
null
https://raw.githubusercontent.com/aggieben/weblocks/8d86be6a4fff8dde0b94181ba60d0dca2cbd9e25/test/dependencies.lisp
lisp
(in-package :weblocks-test) (deftest dependencies-by-symbol-1 (remove nil (weblocks::dependencies-by-symbol 'non-existent-widget-name)) nil) (deftest dependencies-by-symbol-2 (format nil "~A" (mapcar #'dependency-url (remove nil (weblocks::dependencies-by-symbol 'navigation)))) "(/pub/stylesheets/navigation.css)") (deftest make-local-dependency-1 (make-local-dependency :stylesheet "non-existing-file-name") nil) (deftest make-local-dependency-2 (format nil "~A" (dependency-url (make-local-dependency :stylesheet "non-existing-file-name" :do-not-probe t))) "/pub/stylesheets/non-existing-file-name.css") (deftest make-local-dependency-3 (format nil "~A" (dependency-url (make-local-dependency :stylesheet "main"))) "/pub/stylesheets/main.css") (deftest make-local-dependency-4 (format nil "~A" (dependency-url (make-local-dependency :script "weblocks"))) "/pub/scripts/weblocks.js") (deftest make-local-dependency-5 (format nil "~A" (dependency-url (make-local-dependency :script "weblocks" :do-not-probe t))) "/pub/scripts/weblocks.js") (deftest dependencies-equalp-1 (dependencies-equalp (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "")) nil) (deftest dependencies-equalp-2 (dependencies-equalp (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "")) t) (deftest dependencies-equalp-3 (dependencies-equalp (make-instance 'script-dependency :url "") (make-instance 'script-dependency :url "")) nil) (deftest dependencies-equalp-4 (dependencies-equalp (make-instance 'script-dependency :url "") (make-instance 'script-dependency :url "")) t) (deftest dependencies-lessp-1 (dependencies-lessp (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "")) nil) (deftest dependencies-lessp-2 (dependencies-lessp (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "")) nil) (deftest dependencies-lessp-3 (dependencies-lessp (make-instance 'stylesheet-dependency :url "") (make-instance 'script-dependency :url "")) t) (deftest dependencies-lessp-4 (dependencies-lessp (make-instance 'script-dependency :url "") (make-instance 'script-dependency :url "")) nil) (deftest dependencies-lessp-5 (dependencies-lessp nil nil) nil) (deftest per-class-dependencies-1 (per-class-dependencies "a string") nil) (deftest per-class-dependencies-2 (per-class-dependencies (lambda ())) nil) (deftest per-class-dependencies-3 (per-class-dependencies 'some-symbol) nil) (deftest per-class-dependencies-4 (apply #'dependencies-equalp (append (remove nil (per-class-dependencies (make-instance 'navigation))) (list (make-local-dependency :stylesheet "navigation")))) t) (deftest dependencies-1 (dependencies 'some-symbol) nil) (deftest dependencies-2 (dependencies "some-string") nil) (deftest dependencies-3 (dependencies (lambda ())) nil) (deftest dependencies-4 (dependencies (make-instance 'widget :name "abc123")) nil) (deftest dependencies-5 (apply #'dependencies-equalp (append (dependencies "main") (list (make-local-dependency :stylesheet "main")))) t) (deftest dependencies-6 (format nil "~A" (mapcar #'dependency-url (dependencies (make-instance 'navigation)))) "(/pub/stylesheets/navigation.css)") (deftest prune-dependencies-1 (format nil "~A" (mapcar #'dependency-url (weblocks::prune-dependencies (list (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url ""))))) "( )") (deftest prune-dependencies-2 (format nil "~A" (mapcar #'dependency-url (weblocks::prune-dependencies (list (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url ""))))) "( )") (deftest sort-dependencies-by-type-1 (format nil "~A" (mapcar #'dependency-url (weblocks::sort-dependencies-by-type (list (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") )))) "( )") (deftest compact-dependencies-1 (format nil "~A" (mapcar #'dependency-url (compact-dependencies (list (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'script-dependency :url "") (make-instance 'stylesheet-dependency :url "") (make-instance 'stylesheet-dependency :url "") )))) "( )") (deftest-html render-dependency-in-page-head-1 (render-dependency-in-page-head (make-instance 'script-dependency :url "")) (:script :src "" :type "text/javascript" "")) (deftest-html render-dependency-in-page-head-2 (render-dependency-in-page-head (make-instance 'stylesheet-dependency :url "")) (:link :rel "stylesheet" :type "text/css" :href ""))
5421c59bfbd9717db5f09d6dc5cd657c9bb8112721ce30500a8387486de2b4c7
ndmitchell/cmdargs
Process.hs
# LANGUAGE RecordWildCards # module System.Console.CmdArgs.Explicit.Process(process) where import System.Console.CmdArgs.Explicit.Type import Control.Arrow import Data.List import Data.Maybe -- | Process a list of flags (usually obtained from @getArgs@/@expandArgsAt@) with a mode. Returns -- @Left@ and an error message if the command line fails to parse, or @Right@ and -- the associated value. process :: Mode a -> [String] -> Either String a process = processMode processMode :: Mode a -> [String] -> Either String a processMode m args = case find of Ambiguous xs -> Left $ ambiguous "mode" a xs Found x -> processMode x as NotFound | null (fst $ modeArgs m) && isNothing (snd $ modeArgs m) && args /= [] && not (null $ modeModes m) && not ("-" `isPrefixOf` concat args) -> Left $ missing "mode" $ concatMap modeNames $ modeModes m | otherwise -> modeCheck m =<< processFlags m (modeValue m) args where (find,a,as) = case args of [] -> (NotFound,"",[]) x:xs -> (lookupName (map (modeNames &&& id) $ modeModes m) x, x, xs) data S a = S {val :: a -- The value you are accumulating ,args :: [String] -- The arguments you are processing through ,argsCount :: Int -- The number of unnamed arguments you have seen ,errs :: [String] -- The errors you have seen } stop :: Mode a -> S a -> Maybe (Either String a) stop mode S{..} | not $ null errs = Just $ Left $ last errs | null args = Just $ if argsCount >= mn then Right val else Left $ "Expected " ++ (if Just mn == mx then "exactly" else "at least") ++ show mn ++ " unnamed arguments, but got only " ++ show argsCount | otherwise = Nothing where (mn, mx) = argsRange mode err :: S a -> String -> S a err s x = s{errs=x:errs s} upd :: S a -> (a -> Either String a) -> S a upd s f = case f $ val s of Left x -> err s x Right x -> s{val=x} processFlags :: Mode a -> a -> [String] -> Either String a processFlags mode val_ args_ = f $ S val_ args_ 0 [] where f s = fromMaybe (f $ processFlag mode s) $ stop mode s pickFlags long mode = [(filter (\x -> (length x > 1) == long) $ flagNames flag,(flagInfo flag,flag)) | flag <- modeFlags mode] processFlag :: Mode a -> S a -> S a processFlag mode s_@S{args=('-':'-':xs):ys} | xs /= "" = case lookupName (pickFlags True mode) a of Ambiguous poss -> err s $ ambiguous "flag" ("--" ++ a) poss NotFound -> err s $ "Unknown flag: --" ++ a Found (arg,flag) -> case arg of FlagNone | null b -> upd s $ flagValue flag "" | otherwise -> err s $ "Unhandled argument to flag, none expected: --" ++ xs FlagReq | null b && null ys -> err s $ "Flag requires argument: --" ++ xs | null b -> upd s{args=tail ys} $ flagValue flag $ head ys | otherwise -> upd s $ flagValue flag $ tail b _ | null b -> upd s $ flagValue flag $ fromFlagOpt arg | otherwise -> upd s $ flagValue flag $ tail b where s = s_{args=ys} (a,b) = break (== '=') xs processFlag mode s_@S{args=('-':x:xs):ys} | x /= '-' = case lookupName (pickFlags False mode) [x] of Ambiguous poss -> err s $ ambiguous "flag" ['-',x] poss NotFound -> err s $ "Unknown flag: -" ++ [x] Found (arg,flag) -> case arg of FlagNone | "=" `isPrefixOf` xs -> err s $ "Unhandled argument to flag, none expected: -" ++ [x] | otherwise -> upd s_{args=['-':xs|xs/=""] ++ ys} $ flagValue flag "" FlagReq | null xs && null ys -> err s $ "Flag requires argument: -" ++ [x] | null xs -> upd s_{args=tail ys} $ flagValue flag $ head ys | otherwise -> upd s_{args=ys} $ flagValue flag $ if "=" `isPrefixOf` xs then tail xs else xs FlagOpt x | null xs -> upd s_{args=ys} $ flagValue flag x | otherwise -> upd s_{args=ys} $ flagValue flag $ if "=" `isPrefixOf` xs then tail xs else xs FlagOptRare x | "=" `isPrefixOf` xs -> upd s_{args=ys} $ flagValue flag $ tail xs | otherwise -> upd s_{args=['-':xs|xs/=""] ++ ys} $ flagValue flag x where s = s_{args=ys} processFlag mode s_@S{args="--":ys} = f s_{args=ys} where f s | isJust $ stop mode s = s | otherwise = f $ processArg mode s processFlag mode s = processArg mode s processArg mode s_@S{args=x:ys, argsCount=count} = case argsPick mode count of Nothing -> err s $ "Unhandled argument, " ++ str ++ " expected: " ++ x where str = if count == 0 then "none" else "at most " ++ show count Just arg -> case argValue arg x (val s) of Left e -> err s $ "Unhandled argument, " ++ e ++ ": " ++ x Right v -> s{val=v} where s = s_{args=ys, argsCount=count+1} -- find the minimum and maximum allowed number of arguments (Nothing=infinite) argsRange :: Mode a -> (Int, Maybe Int) argsRange Mode{modeArgs=(lst,end)} = (mn,mx) where mn = length $ dropWhile (not . argRequire) $ reverse $ lst ++ maybeToList end mx = if isJust end then Nothing else Just $ length lst argsPick :: Mode a -> Int -> Maybe (Arg a) argsPick Mode{modeArgs=(lst,end)} i = if i < length lst then Just $ lst !! i else end --------------------------------------------------------------------- UTILITIES ambiguous typ got xs = "Ambiguous " ++ typ ++ " '" ++ got ++ "', could be any of: " ++ unwords xs missing typ xs = "Missing " ++ typ ++ ", wanted any of: " ++ unwords xs data LookupName a = NotFound | Ambiguous [Name] | Found a -- different order to lookup so can potentially partially-apply it lookupName :: [([Name],a)] -> Name -> LookupName a lookupName names value = case (match (==), match isPrefixOf) of ([],[]) -> NotFound ([],[x]) -> Found $ snd x ([],xs) -> Ambiguous $ map fst xs ([x],_) -> Found $ snd x (xs,_) -> Ambiguous $ map fst xs where match op = [(head ys,v) | (xs,v) <- names, let ys = filter (op value) xs, ys /= []]
null
https://raw.githubusercontent.com/ndmitchell/cmdargs/107fd11bcc466e7c62b7b2150e05bac20675655a/System/Console/CmdArgs/Explicit/Process.hs
haskell
| Process a list of flags (usually obtained from @getArgs@/@expandArgsAt@) with a mode. Returns @Left@ and an error message if the command line fails to parse, or @Right@ and the associated value. The value you are accumulating The arguments you are processing through The number of unnamed arguments you have seen The errors you have seen find the minimum and maximum allowed number of arguments (Nothing=infinite) ------------------------------------------------------------------- different order to lookup so can potentially partially-apply it
# LANGUAGE RecordWildCards # module System.Console.CmdArgs.Explicit.Process(process) where import System.Console.CmdArgs.Explicit.Type import Control.Arrow import Data.List import Data.Maybe process :: Mode a -> [String] -> Either String a process = processMode processMode :: Mode a -> [String] -> Either String a processMode m args = case find of Ambiguous xs -> Left $ ambiguous "mode" a xs Found x -> processMode x as NotFound | null (fst $ modeArgs m) && isNothing (snd $ modeArgs m) && args /= [] && not (null $ modeModes m) && not ("-" `isPrefixOf` concat args) -> Left $ missing "mode" $ concatMap modeNames $ modeModes m | otherwise -> modeCheck m =<< processFlags m (modeValue m) args where (find,a,as) = case args of [] -> (NotFound,"",[]) x:xs -> (lookupName (map (modeNames &&& id) $ modeModes m) x, x, xs) data S a = S } stop :: Mode a -> S a -> Maybe (Either String a) stop mode S{..} | not $ null errs = Just $ Left $ last errs | null args = Just $ if argsCount >= mn then Right val else Left $ "Expected " ++ (if Just mn == mx then "exactly" else "at least") ++ show mn ++ " unnamed arguments, but got only " ++ show argsCount | otherwise = Nothing where (mn, mx) = argsRange mode err :: S a -> String -> S a err s x = s{errs=x:errs s} upd :: S a -> (a -> Either String a) -> S a upd s f = case f $ val s of Left x -> err s x Right x -> s{val=x} processFlags :: Mode a -> a -> [String] -> Either String a processFlags mode val_ args_ = f $ S val_ args_ 0 [] where f s = fromMaybe (f $ processFlag mode s) $ stop mode s pickFlags long mode = [(filter (\x -> (length x > 1) == long) $ flagNames flag,(flagInfo flag,flag)) | flag <- modeFlags mode] processFlag :: Mode a -> S a -> S a processFlag mode s_@S{args=('-':'-':xs):ys} | xs /= "" = case lookupName (pickFlags True mode) a of Ambiguous poss -> err s $ ambiguous "flag" ("--" ++ a) poss NotFound -> err s $ "Unknown flag: --" ++ a Found (arg,flag) -> case arg of FlagNone | null b -> upd s $ flagValue flag "" | otherwise -> err s $ "Unhandled argument to flag, none expected: --" ++ xs FlagReq | null b && null ys -> err s $ "Flag requires argument: --" ++ xs | null b -> upd s{args=tail ys} $ flagValue flag $ head ys | otherwise -> upd s $ flagValue flag $ tail b _ | null b -> upd s $ flagValue flag $ fromFlagOpt arg | otherwise -> upd s $ flagValue flag $ tail b where s = s_{args=ys} (a,b) = break (== '=') xs processFlag mode s_@S{args=('-':x:xs):ys} | x /= '-' = case lookupName (pickFlags False mode) [x] of Ambiguous poss -> err s $ ambiguous "flag" ['-',x] poss NotFound -> err s $ "Unknown flag: -" ++ [x] Found (arg,flag) -> case arg of FlagNone | "=" `isPrefixOf` xs -> err s $ "Unhandled argument to flag, none expected: -" ++ [x] | otherwise -> upd s_{args=['-':xs|xs/=""] ++ ys} $ flagValue flag "" FlagReq | null xs && null ys -> err s $ "Flag requires argument: -" ++ [x] | null xs -> upd s_{args=tail ys} $ flagValue flag $ head ys | otherwise -> upd s_{args=ys} $ flagValue flag $ if "=" `isPrefixOf` xs then tail xs else xs FlagOpt x | null xs -> upd s_{args=ys} $ flagValue flag x | otherwise -> upd s_{args=ys} $ flagValue flag $ if "=" `isPrefixOf` xs then tail xs else xs FlagOptRare x | "=" `isPrefixOf` xs -> upd s_{args=ys} $ flagValue flag $ tail xs | otherwise -> upd s_{args=['-':xs|xs/=""] ++ ys} $ flagValue flag x where s = s_{args=ys} processFlag mode s_@S{args="--":ys} = f s_{args=ys} where f s | isJust $ stop mode s = s | otherwise = f $ processArg mode s processFlag mode s = processArg mode s processArg mode s_@S{args=x:ys, argsCount=count} = case argsPick mode count of Nothing -> err s $ "Unhandled argument, " ++ str ++ " expected: " ++ x where str = if count == 0 then "none" else "at most " ++ show count Just arg -> case argValue arg x (val s) of Left e -> err s $ "Unhandled argument, " ++ e ++ ": " ++ x Right v -> s{val=v} where s = s_{args=ys, argsCount=count+1} argsRange :: Mode a -> (Int, Maybe Int) argsRange Mode{modeArgs=(lst,end)} = (mn,mx) where mn = length $ dropWhile (not . argRequire) $ reverse $ lst ++ maybeToList end mx = if isJust end then Nothing else Just $ length lst argsPick :: Mode a -> Int -> Maybe (Arg a) argsPick Mode{modeArgs=(lst,end)} i = if i < length lst then Just $ lst !! i else end UTILITIES ambiguous typ got xs = "Ambiguous " ++ typ ++ " '" ++ got ++ "', could be any of: " ++ unwords xs missing typ xs = "Missing " ++ typ ++ ", wanted any of: " ++ unwords xs data LookupName a = NotFound | Ambiguous [Name] | Found a lookupName :: [([Name],a)] -> Name -> LookupName a lookupName names value = case (match (==), match isPrefixOf) of ([],[]) -> NotFound ([],[x]) -> Found $ snd x ([],xs) -> Ambiguous $ map fst xs ([x],_) -> Found $ snd x (xs,_) -> Ambiguous $ map fst xs where match op = [(head ys,v) | (xs,v) <- names, let ys = filter (op value) xs, ys /= []]
85de58ba87c1287878a14a4e182ef4ce5eda6a6fcdcd8624a492f72b93393c2d
realworldocaml/book
interpreter.ml
open Base open Ppxlib open Ast_builder.Default module Filename = Stdlib.Filename module Parsing = Stdlib.Parsing module Type = struct type t = | Var of string | Bool | Int | Char | String | Tuple of t list let rec to_string = function | Var v -> "'" ^ v | Bool -> "bool" | Int -> "int" | Char -> "char" | String -> "string" | Tuple l -> "(" ^ String.concat ~sep:" * " (List.map l ~f:to_string) ^ ")" end module Value = struct type t = | Bool of bool | Int of int | Char of char | String of string | Tuple of t list let ocaml_version = Stdlib.Scanf.sscanf Stdlib.Sys.ocaml_version "%d.%d.%d" (fun major minor patchlevel -> Tuple [Int major; Int minor; Int patchlevel]) ;; let os_type = String Stdlib.Sys.os_type ;; let config_bool name = Bool (Ocaml_common.Config.config_var name |> Option.map ~f:Bool.of_string |> Option.value ~default:false) ;; let flambda_backend = config_bool "flambda_backend";; let flambda2 = config_bool "flambda2";; let rec to_expression loc t = match t with | Bool x -> ebool ~loc x | Int x -> eint ~loc x | Char x -> echar ~loc x | String x -> estring ~loc x | Tuple [] -> eunit ~loc | Tuple [x] -> to_expression loc x | Tuple l -> pexp_tuple ~loc (List.map l ~f:(to_expression loc)) ;; let rec to_pattern loc t = match t with | Bool x -> pbool ~loc x | Int x -> pint ~loc x | Char x -> pchar ~loc x | String x -> pstring ~loc x | Tuple [] -> punit ~loc | Tuple [x] -> to_pattern loc x | Tuple l -> ppat_tuple ~loc (List.map l ~f:(to_pattern loc)) ;; let to_string_pretty v = let e = to_expression Location.none v in Pprintast.string_of_expression e let to_string v = let buf = Buffer.create 128 in let rec aux = function | Bool b -> Buffer.add_string buf (Bool.to_string b) | Int n -> Buffer.add_string buf (Int.to_string n) | Char ch -> Buffer.add_char buf ch | String s -> Buffer.add_string buf s; | Tuple [] -> Buffer.add_string buf "()" | Tuple (x :: l) -> Buffer.add_char buf '('; aux x; List.iter l ~f:(fun x -> Buffer.add_string buf ", "; aux x); Buffer.add_char buf ')' in aux v; Buffer.contents buf ;; let rec type_ : t -> Type.t = function | Bool _ -> Bool | Int _ -> Int | Char _ -> Char | String _ -> String | Tuple l -> Tuple (List.map l ~f:type_) ;; end module Env : sig type t val init : t val empty : t val add : t -> var:string Location.loc -> value:Value.t -> t val undefine : t -> string Location.loc -> t val of_list : (string Location.loc * Value.t) list -> t val eval : t -> string Location.loc -> Value.t val is_defined : ?permissive:bool -> t -> string Location.loc -> bool val seen : t -> string Location.loc -> bool val to_expression : t -> expression end = struct type var_state = | Defined of Value.t | Undefined type entry = { loc : Location.t (** Location at which it was defined/undefined *) ; state : var_state } type t = entry Map.M(String).t let empty = Map.empty (module String) let to_expression t = pexp_apply ~loc:Location.none (evar ~loc:Location.none "env") (List.map (Map.to_alist t) ~f:(fun (var, { loc; state }) -> (Labelled var, match state with | Defined v -> pexp_construct ~loc { txt = Lident "Defined"; loc } (Some (Value.to_expression loc v)) | Undefined -> pexp_construct ~loc { txt = Lident "Undefined"; loc } None))) let seen t (var : _ Loc.t) = Map.mem t var.txt let add t ~(var:_ Loc.t) ~value = Map.set t ~key:var.txt ~data:{ loc = var.loc; state = Defined value } ;; let undefine t (var : _ Loc.t) = Map.set t ~key:var.txt ~data:{ loc = var.loc; state = Undefined } ;; let of_list l = List.fold_left l ~init:empty ~f:(fun acc (var, value) -> add acc ~var ~value) ;; let init = of_list [ { loc = Location.none ; txt = "ocaml_version" }, Value.ocaml_version ; { loc = Location.none ; txt = "os_type" }, Value.os_type ; { loc = Location.none ; txt = "flambda_backend" }, Value.flambda_backend ; { loc = Location.none ; txt = "flambda2" }, Value.flambda2 ] let short_loc_string (loc : Location.t) = Printf.sprintf "%s:%d" loc.loc_start.pos_fname loc.loc_start.pos_lnum ;; let eval (t : t) (var:string Loc.t) = match Map.find t var.txt with | Some { state = Defined v; loc = _ } -> v | Some { state = Undefined; loc } -> Location.raise_errorf ~loc:var.loc "optcomp: %s is undefined (undefined at %s)" var.txt (short_loc_string loc) | None -> Location.raise_errorf ~loc:var.loc "optcomp: unbound value %s" var.txt ;; let is_defined ?(permissive=false) (t : t) (var:string Loc.t) = match Map.find t var.txt with | Some { state = Defined _; _ } -> true | Some { state = Undefined; _ } -> false | None -> if permissive then false else Location.raise_errorf ~loc:var.loc "optcomp: doesn't know about %s.\n\ You need to either define it or undefine it with #undef.\n\ Optcomp doesn't accept variables it doesn't know about to avoid typos." var.txt ;; end (* +-----------------------------------------------------------------+ | Expression evaluation | +-----------------------------------------------------------------+ *) let invalid_type loc expected real = Location.raise_errorf ~loc "optcomp: this expression has type %s but is used with type %s" (Type.to_string real) (Type.to_string expected) ;; let var_of_lid (id : _ Located.t) = match Longident.flatten_exn id.txt with | l -> { id with txt = String.concat ~sep:"." l } | exception _ -> Location.raise_errorf ~loc:id.loc "optcomp: invalid variable name" ;; let cannot_convert loc dst x = Location.raise_errorf ~loc "cannot convert %s to %s" (Value.to_string_pretty x) dst ;; let convert_from_string loc dst f x = try f x with _ -> Location.raise_errorf ~loc "optcomp: cannot convert %S to %s" x dst ;; exception Pattern_match_failure of pattern * Value.t let lid_of_expr e = match e.pexp_desc with | Pexp_ident id | Pexp_construct (id, None) -> id | _ -> Location.raise_errorf ~loc:e.pexp_loc "optcomp: identifier expected" ;; let var_of_expr e = var_of_lid (lid_of_expr e) let not_supported e = Location.raise_errorf ~loc:e.pexp_loc "optcomp: expression not supported" ;; let parse_int loc x = match Int.of_string x with | v -> v | exception _ -> Location.raise_errorf ~loc "optcomp: invalid integer" ;; let rec eval env e : Value.t = let loc = e.pexp_loc in match e.pexp_desc with | Pexp_constant (Pconst_integer (x, None)) -> Int (parse_int loc x) | Pexp_constant (Pconst_char x ) -> Char x | Pexp_constant (Pconst_string (x, _, _)) -> String x | Pexp_construct ({ txt = Lident "true" ; _ }, None) -> Bool true | Pexp_construct ({ txt = Lident "false"; _ }, None) -> Bool false | Pexp_construct ({ txt = Lident "()" ; _ }, None) -> Tuple [] | Pexp_tuple l -> Tuple (List.map l ~f:(eval env)) | Pexp_ident id | Pexp_construct (id, None) -> Env.eval env (var_of_lid id) | Pexp_apply ({ pexp_desc = Pexp_ident { txt = Lident s; _ }; _ }, args) -> begin let args = List.map args ~f:(fun (l, x) -> match l with Nolabel -> x | _ -> not_supported e) in match s, args with | "=" , [x; y] -> eval_cmp env Poly.( = ) x y | "<" , [x; y] -> eval_cmp env Poly.( < ) x y | ">" , [x; y] -> eval_cmp env Poly.( > ) x y | "<=" , [x; y] -> eval_cmp env Poly.( <= ) x y | ">=" , [x; y] -> eval_cmp env Poly.( >= ) x y | "<>" , [x; y] -> eval_cmp env Poly.( <> ) x y | "min", [x; y] -> eval_poly2 env Poly.min x y | "max", [x; y] -> eval_poly2 env Poly.max x y | "+" , [x; y] -> eval_int2 env ( + ) x y | "-" , [x; y] -> eval_int2 env ( - ) x y | "*" , [x; y] -> eval_int2 env ( * ) x y | "/" , [x; y] -> eval_int2 env ( / ) x y | "mod", [x; y] -> eval_int2 env Stdlib.( mod ) x y | "not", [x] -> Bool (not (eval_bool env x)) | "||" , [x; y] -> eval_bool2 env ( || ) x y | "&&" , [x; y] -> eval_bool2 env ( && ) x y | "^" , [x; y] -> eval_string2 env ( ^ ) x y | "fst", [x] -> fst (eval_pair env x) | "snd", [x] -> snd (eval_pair env x) | "to_string", [x] -> String (Value.to_string (eval env x)) | "to_int", [x] -> Int (match eval env x with | String x -> convert_from_string loc "int" Int.of_string x | Int x -> x | Char x -> Char.to_int x | Bool _ | Tuple _ as x -> cannot_convert loc "int" x) | "to_bool", [x] -> Bool (match eval env x with | String x -> convert_from_string loc "bool" Bool.of_string x | Bool x -> x | Int _ | Char _ | Tuple _ as x -> cannot_convert loc "bool" x) | "to_char", [x] -> Char (match eval env x with | String x -> convert_from_string loc "char" (fun s -> assert (String.length s = 1); s.[0]) x | Char x -> x | Int x -> begin match Char.of_int x with | Some x -> x | None -> Location.raise_errorf ~loc "optcomp: cannot convert %d to char" x end | Bool _ | Tuple _ as x -> cannot_convert loc "char" x) | "show", [x] -> let v = eval env x in let ppf = Stdlib.Format.err_formatter in let pprinted = Value.to_string_pretty v in Stdlib.Format.fprintf ppf "%a:@.SHOW %s@." Location.print loc pprinted; v | "defined", [x] -> Bool (Env.is_defined env (var_of_expr x)) | "not_defined", [x] -> Bool (not (Env.is_defined env (var_of_expr x))) | "not_defined_permissive", [x] -> Bool (not ( Env.is_defined ~permissive:true env (var_of_expr x))) | _ -> not_supported e end (* Let-binding *) | Pexp_let (Nonrecursive, vbs, e) -> let env = List.fold_left vbs ~init:env ~f:(fun new_env vb -> let v = eval env vb.pvb_expr in do_bind new_env vb.pvb_pat v) in eval env e (* Pattern matching *) | Pexp_match (e, cases) -> let v = eval env e in let rec loop = function | [] -> Location.raise_errorf ~loc "optcomp: cannot match %s against any of the cases" (Value.to_string v) | case :: rest -> match bind env case.pc_lhs v with | exception Pattern_match_failure _ -> loop rest | env -> let guard_ok = match case.pc_guard with | None -> true | Some e -> eval_bool env e in if guard_ok then eval env case.pc_rhs else loop rest in loop cases | _ -> not_supported e and bind env patt value = let loc = patt.ppat_loc in match patt.ppat_desc, value with | Ppat_any, _ -> env | Ppat_constant (Pconst_integer (x, None)), Int y when parse_int loc x = y -> env | Ppat_constant (Pconst_char x ), Char y when Char.equal x y -> env | Ppat_constant (Pconst_string (x, _, _)), String y when String.equal x y -> env | Ppat_construct ({ txt = Lident "true" ; _ }, None), Bool true -> env | Ppat_construct ({ txt = Lident "false"; _ }, None), Bool false -> env | Ppat_construct ({ txt = Lident "()" ; _ }, None), Tuple [] -> env | Ppat_var var, _ -> Env.add env ~var ~value | Ppat_construct (id, None), _ -> Env.add env ~var:(var_of_lid id) ~value | Ppat_alias (patt, var), _ -> Env.add (bind env patt value) ~var ~value | Ppat_tuple x, Tuple y when List.length x = List.length y -> Stdlib.ListLabels.fold_left2 x y ~init:env ~f:bind | _ -> raise (Pattern_match_failure (patt, value)) and do_bind env patt value = try bind env patt value with Pattern_match_failure (pat, v) -> Location.raise_errorf ~loc:pat.ppat_loc "Cannot match %s with this pattern" (Value.to_string_pretty v) and eval_same env ex ey = let vx = eval env ex and vy = eval env ey in let tx = Value.type_ vx and ty = Value.type_ vy in if Poly.equal tx ty then (vx, vy) else invalid_type ey.pexp_loc tx ty and eval_int env e = match eval env e with | Int x -> x | v -> invalid_type e.pexp_loc Int (Value.type_ v) and eval_bool env e = match eval env e with | Bool x -> x | v -> invalid_type e.pexp_loc Bool (Value.type_ v) and eval_string env e = match eval env e with | String x -> x | v -> invalid_type e.pexp_loc String (Value.type_ v) and eval_pair env e = match eval env e with | Tuple [x; y] -> (x, y) | v -> invalid_type e.pexp_loc (Tuple [Var "a"; Var "b"]) (Value.type_ v) and eval_int2 env f a b = let a = eval_int env a in let b = eval_int env b in Int (f a b) and eval_bool2 env f a b = let a = eval_bool env a in let b = eval_bool env b in Bool (f a b) and eval_string2 env f a b = let a = eval_string env a in let b = eval_string env b in String (f a b) and eval_cmp env f a b = let a, b = eval_same env a b in Bool (f a b) and eval_poly2 env f a b = let a, b = eval_same env a b in f a b (* +-----------------------------------------------------------------+ | Environment serialization | +-----------------------------------------------------------------+ *) module EnvIO = struct let to_expression = Env.to_expression let of_expression expr = Ast_pattern.parse Ast_pattern.(pexp_apply (pexp_ident (lident (string "env"))) __) expr.pexp_loc expr (fun args -> List.fold args ~init:Env.empty ~f:(fun env arg -> match arg with | Labelled var, { pexp_desc = Pexp_construct ({txt=Lident "Defined"; _}, Some e) ; pexp_loc = loc ; _ } -> Env.add env ~var:{ txt = var; loc } ~value:(eval Env.empty e) | Labelled var, { pexp_desc = Pexp_construct ({txt=Lident "Undefined"; _}, None) ; pexp_loc = loc ; _ } -> Env.undefine env { txt = var; loc } | _, e -> Location.raise_errorf ~loc:e.pexp_loc "ppx_optcomp: invalid cookie")) end
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ppx_optcomp/src/interpreter.ml
ocaml
* Location at which it was defined/undefined +-----------------------------------------------------------------+ | Expression evaluation | +-----------------------------------------------------------------+ Let-binding Pattern matching +-----------------------------------------------------------------+ | Environment serialization | +-----------------------------------------------------------------+
open Base open Ppxlib open Ast_builder.Default module Filename = Stdlib.Filename module Parsing = Stdlib.Parsing module Type = struct type t = | Var of string | Bool | Int | Char | String | Tuple of t list let rec to_string = function | Var v -> "'" ^ v | Bool -> "bool" | Int -> "int" | Char -> "char" | String -> "string" | Tuple l -> "(" ^ String.concat ~sep:" * " (List.map l ~f:to_string) ^ ")" end module Value = struct type t = | Bool of bool | Int of int | Char of char | String of string | Tuple of t list let ocaml_version = Stdlib.Scanf.sscanf Stdlib.Sys.ocaml_version "%d.%d.%d" (fun major minor patchlevel -> Tuple [Int major; Int minor; Int patchlevel]) ;; let os_type = String Stdlib.Sys.os_type ;; let config_bool name = Bool (Ocaml_common.Config.config_var name |> Option.map ~f:Bool.of_string |> Option.value ~default:false) ;; let flambda_backend = config_bool "flambda_backend";; let flambda2 = config_bool "flambda2";; let rec to_expression loc t = match t with | Bool x -> ebool ~loc x | Int x -> eint ~loc x | Char x -> echar ~loc x | String x -> estring ~loc x | Tuple [] -> eunit ~loc | Tuple [x] -> to_expression loc x | Tuple l -> pexp_tuple ~loc (List.map l ~f:(to_expression loc)) ;; let rec to_pattern loc t = match t with | Bool x -> pbool ~loc x | Int x -> pint ~loc x | Char x -> pchar ~loc x | String x -> pstring ~loc x | Tuple [] -> punit ~loc | Tuple [x] -> to_pattern loc x | Tuple l -> ppat_tuple ~loc (List.map l ~f:(to_pattern loc)) ;; let to_string_pretty v = let e = to_expression Location.none v in Pprintast.string_of_expression e let to_string v = let buf = Buffer.create 128 in let rec aux = function | Bool b -> Buffer.add_string buf (Bool.to_string b) | Int n -> Buffer.add_string buf (Int.to_string n) | Char ch -> Buffer.add_char buf ch | String s -> Buffer.add_string buf s; | Tuple [] -> Buffer.add_string buf "()" | Tuple (x :: l) -> Buffer.add_char buf '('; aux x; List.iter l ~f:(fun x -> Buffer.add_string buf ", "; aux x); Buffer.add_char buf ')' in aux v; Buffer.contents buf ;; let rec type_ : t -> Type.t = function | Bool _ -> Bool | Int _ -> Int | Char _ -> Char | String _ -> String | Tuple l -> Tuple (List.map l ~f:type_) ;; end module Env : sig type t val init : t val empty : t val add : t -> var:string Location.loc -> value:Value.t -> t val undefine : t -> string Location.loc -> t val of_list : (string Location.loc * Value.t) list -> t val eval : t -> string Location.loc -> Value.t val is_defined : ?permissive:bool -> t -> string Location.loc -> bool val seen : t -> string Location.loc -> bool val to_expression : t -> expression end = struct type var_state = | Defined of Value.t | Undefined type entry = ; state : var_state } type t = entry Map.M(String).t let empty = Map.empty (module String) let to_expression t = pexp_apply ~loc:Location.none (evar ~loc:Location.none "env") (List.map (Map.to_alist t) ~f:(fun (var, { loc; state }) -> (Labelled var, match state with | Defined v -> pexp_construct ~loc { txt = Lident "Defined"; loc } (Some (Value.to_expression loc v)) | Undefined -> pexp_construct ~loc { txt = Lident "Undefined"; loc } None))) let seen t (var : _ Loc.t) = Map.mem t var.txt let add t ~(var:_ Loc.t) ~value = Map.set t ~key:var.txt ~data:{ loc = var.loc; state = Defined value } ;; let undefine t (var : _ Loc.t) = Map.set t ~key:var.txt ~data:{ loc = var.loc; state = Undefined } ;; let of_list l = List.fold_left l ~init:empty ~f:(fun acc (var, value) -> add acc ~var ~value) ;; let init = of_list [ { loc = Location.none ; txt = "ocaml_version" }, Value.ocaml_version ; { loc = Location.none ; txt = "os_type" }, Value.os_type ; { loc = Location.none ; txt = "flambda_backend" }, Value.flambda_backend ; { loc = Location.none ; txt = "flambda2" }, Value.flambda2 ] let short_loc_string (loc : Location.t) = Printf.sprintf "%s:%d" loc.loc_start.pos_fname loc.loc_start.pos_lnum ;; let eval (t : t) (var:string Loc.t) = match Map.find t var.txt with | Some { state = Defined v; loc = _ } -> v | Some { state = Undefined; loc } -> Location.raise_errorf ~loc:var.loc "optcomp: %s is undefined (undefined at %s)" var.txt (short_loc_string loc) | None -> Location.raise_errorf ~loc:var.loc "optcomp: unbound value %s" var.txt ;; let is_defined ?(permissive=false) (t : t) (var:string Loc.t) = match Map.find t var.txt with | Some { state = Defined _; _ } -> true | Some { state = Undefined; _ } -> false | None -> if permissive then false else Location.raise_errorf ~loc:var.loc "optcomp: doesn't know about %s.\n\ You need to either define it or undefine it with #undef.\n\ Optcomp doesn't accept variables it doesn't know about to avoid typos." var.txt ;; end let invalid_type loc expected real = Location.raise_errorf ~loc "optcomp: this expression has type %s but is used with type %s" (Type.to_string real) (Type.to_string expected) ;; let var_of_lid (id : _ Located.t) = match Longident.flatten_exn id.txt with | l -> { id with txt = String.concat ~sep:"." l } | exception _ -> Location.raise_errorf ~loc:id.loc "optcomp: invalid variable name" ;; let cannot_convert loc dst x = Location.raise_errorf ~loc "cannot convert %s to %s" (Value.to_string_pretty x) dst ;; let convert_from_string loc dst f x = try f x with _ -> Location.raise_errorf ~loc "optcomp: cannot convert %S to %s" x dst ;; exception Pattern_match_failure of pattern * Value.t let lid_of_expr e = match e.pexp_desc with | Pexp_ident id | Pexp_construct (id, None) -> id | _ -> Location.raise_errorf ~loc:e.pexp_loc "optcomp: identifier expected" ;; let var_of_expr e = var_of_lid (lid_of_expr e) let not_supported e = Location.raise_errorf ~loc:e.pexp_loc "optcomp: expression not supported" ;; let parse_int loc x = match Int.of_string x with | v -> v | exception _ -> Location.raise_errorf ~loc "optcomp: invalid integer" ;; let rec eval env e : Value.t = let loc = e.pexp_loc in match e.pexp_desc with | Pexp_constant (Pconst_integer (x, None)) -> Int (parse_int loc x) | Pexp_constant (Pconst_char x ) -> Char x | Pexp_constant (Pconst_string (x, _, _)) -> String x | Pexp_construct ({ txt = Lident "true" ; _ }, None) -> Bool true | Pexp_construct ({ txt = Lident "false"; _ }, None) -> Bool false | Pexp_construct ({ txt = Lident "()" ; _ }, None) -> Tuple [] | Pexp_tuple l -> Tuple (List.map l ~f:(eval env)) | Pexp_ident id | Pexp_construct (id, None) -> Env.eval env (var_of_lid id) | Pexp_apply ({ pexp_desc = Pexp_ident { txt = Lident s; _ }; _ }, args) -> begin let args = List.map args ~f:(fun (l, x) -> match l with Nolabel -> x | _ -> not_supported e) in match s, args with | "=" , [x; y] -> eval_cmp env Poly.( = ) x y | "<" , [x; y] -> eval_cmp env Poly.( < ) x y | ">" , [x; y] -> eval_cmp env Poly.( > ) x y | "<=" , [x; y] -> eval_cmp env Poly.( <= ) x y | ">=" , [x; y] -> eval_cmp env Poly.( >= ) x y | "<>" , [x; y] -> eval_cmp env Poly.( <> ) x y | "min", [x; y] -> eval_poly2 env Poly.min x y | "max", [x; y] -> eval_poly2 env Poly.max x y | "+" , [x; y] -> eval_int2 env ( + ) x y | "-" , [x; y] -> eval_int2 env ( - ) x y | "*" , [x; y] -> eval_int2 env ( * ) x y | "/" , [x; y] -> eval_int2 env ( / ) x y | "mod", [x; y] -> eval_int2 env Stdlib.( mod ) x y | "not", [x] -> Bool (not (eval_bool env x)) | "||" , [x; y] -> eval_bool2 env ( || ) x y | "&&" , [x; y] -> eval_bool2 env ( && ) x y | "^" , [x; y] -> eval_string2 env ( ^ ) x y | "fst", [x] -> fst (eval_pair env x) | "snd", [x] -> snd (eval_pair env x) | "to_string", [x] -> String (Value.to_string (eval env x)) | "to_int", [x] -> Int (match eval env x with | String x -> convert_from_string loc "int" Int.of_string x | Int x -> x | Char x -> Char.to_int x | Bool _ | Tuple _ as x -> cannot_convert loc "int" x) | "to_bool", [x] -> Bool (match eval env x with | String x -> convert_from_string loc "bool" Bool.of_string x | Bool x -> x | Int _ | Char _ | Tuple _ as x -> cannot_convert loc "bool" x) | "to_char", [x] -> Char (match eval env x with | String x -> convert_from_string loc "char" (fun s -> assert (String.length s = 1); s.[0]) x | Char x -> x | Int x -> begin match Char.of_int x with | Some x -> x | None -> Location.raise_errorf ~loc "optcomp: cannot convert %d to char" x end | Bool _ | Tuple _ as x -> cannot_convert loc "char" x) | "show", [x] -> let v = eval env x in let ppf = Stdlib.Format.err_formatter in let pprinted = Value.to_string_pretty v in Stdlib.Format.fprintf ppf "%a:@.SHOW %s@." Location.print loc pprinted; v | "defined", [x] -> Bool (Env.is_defined env (var_of_expr x)) | "not_defined", [x] -> Bool (not (Env.is_defined env (var_of_expr x))) | "not_defined_permissive", [x] -> Bool (not ( Env.is_defined ~permissive:true env (var_of_expr x))) | _ -> not_supported e end | Pexp_let (Nonrecursive, vbs, e) -> let env = List.fold_left vbs ~init:env ~f:(fun new_env vb -> let v = eval env vb.pvb_expr in do_bind new_env vb.pvb_pat v) in eval env e | Pexp_match (e, cases) -> let v = eval env e in let rec loop = function | [] -> Location.raise_errorf ~loc "optcomp: cannot match %s against any of the cases" (Value.to_string v) | case :: rest -> match bind env case.pc_lhs v with | exception Pattern_match_failure _ -> loop rest | env -> let guard_ok = match case.pc_guard with | None -> true | Some e -> eval_bool env e in if guard_ok then eval env case.pc_rhs else loop rest in loop cases | _ -> not_supported e and bind env patt value = let loc = patt.ppat_loc in match patt.ppat_desc, value with | Ppat_any, _ -> env | Ppat_constant (Pconst_integer (x, None)), Int y when parse_int loc x = y -> env | Ppat_constant (Pconst_char x ), Char y when Char.equal x y -> env | Ppat_constant (Pconst_string (x, _, _)), String y when String.equal x y -> env | Ppat_construct ({ txt = Lident "true" ; _ }, None), Bool true -> env | Ppat_construct ({ txt = Lident "false"; _ }, None), Bool false -> env | Ppat_construct ({ txt = Lident "()" ; _ }, None), Tuple [] -> env | Ppat_var var, _ -> Env.add env ~var ~value | Ppat_construct (id, None), _ -> Env.add env ~var:(var_of_lid id) ~value | Ppat_alias (patt, var), _ -> Env.add (bind env patt value) ~var ~value | Ppat_tuple x, Tuple y when List.length x = List.length y -> Stdlib.ListLabels.fold_left2 x y ~init:env ~f:bind | _ -> raise (Pattern_match_failure (patt, value)) and do_bind env patt value = try bind env patt value with Pattern_match_failure (pat, v) -> Location.raise_errorf ~loc:pat.ppat_loc "Cannot match %s with this pattern" (Value.to_string_pretty v) and eval_same env ex ey = let vx = eval env ex and vy = eval env ey in let tx = Value.type_ vx and ty = Value.type_ vy in if Poly.equal tx ty then (vx, vy) else invalid_type ey.pexp_loc tx ty and eval_int env e = match eval env e with | Int x -> x | v -> invalid_type e.pexp_loc Int (Value.type_ v) and eval_bool env e = match eval env e with | Bool x -> x | v -> invalid_type e.pexp_loc Bool (Value.type_ v) and eval_string env e = match eval env e with | String x -> x | v -> invalid_type e.pexp_loc String (Value.type_ v) and eval_pair env e = match eval env e with | Tuple [x; y] -> (x, y) | v -> invalid_type e.pexp_loc (Tuple [Var "a"; Var "b"]) (Value.type_ v) and eval_int2 env f a b = let a = eval_int env a in let b = eval_int env b in Int (f a b) and eval_bool2 env f a b = let a = eval_bool env a in let b = eval_bool env b in Bool (f a b) and eval_string2 env f a b = let a = eval_string env a in let b = eval_string env b in String (f a b) and eval_cmp env f a b = let a, b = eval_same env a b in Bool (f a b) and eval_poly2 env f a b = let a, b = eval_same env a b in f a b module EnvIO = struct let to_expression = Env.to_expression let of_expression expr = Ast_pattern.parse Ast_pattern.(pexp_apply (pexp_ident (lident (string "env"))) __) expr.pexp_loc expr (fun args -> List.fold args ~init:Env.empty ~f:(fun env arg -> match arg with | Labelled var, { pexp_desc = Pexp_construct ({txt=Lident "Defined"; _}, Some e) ; pexp_loc = loc ; _ } -> Env.add env ~var:{ txt = var; loc } ~value:(eval Env.empty e) | Labelled var, { pexp_desc = Pexp_construct ({txt=Lident "Undefined"; _}, None) ; pexp_loc = loc ; _ } -> Env.undefine env { txt = var; loc } | _, e -> Location.raise_errorf ~loc:e.pexp_loc "ppx_optcomp: invalid cookie")) end
fa377c9120ece2c5500eee6455b2dd8fbb8b6e71554f50173731f835e2990037
alidloren/interdep
multi_repo.clj
(ns interdep.multi-repo "Unify multiple subrepo deps into one config." (:require [clojure.java.io :as io] [clojure.edn :as edn] [interdep.impl.cli :as cli] [interdep.impl.path :as path])) ;; [Note on dep path handling]: ;; Constraints: * Interdep will throw error when processsing any : local / root deps that are not registered . ;; * All registered local deps must be inside root repo. ;; Reasoning: We can change local paths by just counting how many forward a registered dep is ;; to see how many dirs back a subrepo dep path should be changed to. (def ^:dynamic opts {:registry {} :out-dir path/root-path}) (defn local-dep? "Check if x is a local dep map." [x] (and (map? x) (:local/root x))) (defn- cleanse-root-deps "Remove any custom multi-repo keys from deps config." [deps] (dissoc deps ::registry)) ;; --- Validations (defn- validate-registered-dep-paths! "Ensure registered deps are inside root repo" [registry] (some #(when (re-find #"\.\.\/" %) (throw (cli/err "Registered subrepo path must be inside root repo:" %))) registry) :valid) (defn- validate-subrepo-deps-config! [deps] (when-let [k (some (fn [[k]] (when (not (namespace k)) k)) (:aliases deps))] (throw (cli/err "Only namespaced alias keys are allowed in nested repos:" k))) :valid) --- processing (defn read-root-config "Get root deps cofig loaded by clojure cli." [] (-> "deps.edn" io/file slurp edn/read-string)) (defn read-sub-config "Read a subrepo's deps config." [dir] (-> (str dir "/deps.edn") io/file slurp edn/read-string)) (defn update-key "Update map only if key already exists." [m k f & args] (if (get m k) (apply (partial update m k f) args) m)) (defn map-vals "Update each key-value pair in a map." [m f] (into {} (for [[k v] m] (f k v)))) (defn out-path-back-dirs "Amount dirs back required to reach root from out dir." [] (path/make-back-dirs (path/count-foward-dirs (:out-dir opts)))) (defn- qualify-subdir-path "Make nested path relative to out dir." [subdir local-path] (path/join (out-path-back-dirs) subdir local-path)) (defn qualify-subdir-local-dep "Make :local/root dep relative to out dir." [subdir local-path] (path/join (out-path-back-dirs) (path/append-base-dirs subdir local-path))) (defn- update-subdir-paths "Update list of paths to be relative to output dir." [subdir paths] (mapv #(qualify-subdir-path subdir %) paths)) (defn- update-subdir-deps "Update deps map :local/root paths to be relative to output dir." [subdir deps] (map-vals deps (fn [k v] [k (if-let [path (:local/root v)] (assoc v :local/root (qualify-subdir-local-dep subdir path)) v)]))) (defn- parse-subdeps "Parse subrepo deps config. Updates paths to be relative to output directory." [subdir deps] (validate-subrepo-deps-config! deps) (-> deps (update-key :paths #(update-subdir-paths subdir %)) (update-key :deps #(update-subdir-deps subdir %)) (update-key :aliases (fn [m] (map-vals m (fn [k v] [k (-> v (update-key :extra-paths #(update-subdir-paths subdir %)) (update-key :extra-deps #(update-subdir-deps subdir %)))])))))) (defn- combine-deps "Combines dep aliases, with `d2` taking precedence over `d1`." [d1 d2] (let [{:keys [paths deps aliases]} d2] (cond-> d1 paths (update :paths into paths) deps (update :deps merge deps) aliases (update :aliases merge aliases)))) (defn process-deps "Process root deps and registered subrepo deps. Returns map of: ::main-deps - Unified root and nested deps config. ::nested-deps - Unified nested deps config. ::root-deps - Root deps.edn config that served as basis for processing. ::subrepo-deps - Map of registered subrepos paths to their respective deps configs." ([] (process-deps {})) ([-opts] (cli/with-err-boundary "Error processing Interdep repo dependencies." (let [{::keys [registry] :as root-deps} (read-root-config) root-deps (cleanse-root-deps root-deps)] (binding [opts (-> opts (merge -opts) (assoc :registry registry))] (validate-registered-dep-paths! registry) (let [subrepo-deps (atom {}) nested-deps (reduce (fn [acc subdir] (let [cfg (read-sub-config subdir)] (swap! subrepo-deps assoc subdir cfg) (combine-deps acc (parse-subdeps subdir cfg)))) {} registry)] {::main-deps (combine-deps nested-deps root-deps) ::root-deps root-deps ::nested-deps nested-deps ::subrepo-deps @subrepo-deps}))))))
null
https://raw.githubusercontent.com/alidloren/interdep/ad9bfabb1c72e61854340be791b74e23482a1425/interdep-core/src/interdep/multi_repo.clj
clojure
[Note on dep path handling]: Constraints: * All registered local deps must be inside root repo. Reasoning: to see how many dirs back a subrepo dep path should be changed to. --- Validations
(ns interdep.multi-repo "Unify multiple subrepo deps into one config." (:require [clojure.java.io :as io] [clojure.edn :as edn] [interdep.impl.cli :as cli] [interdep.impl.path :as path])) * Interdep will throw error when processsing any : local / root deps that are not registered . We can change local paths by just counting how many forward a registered dep is (def ^:dynamic opts {:registry {} :out-dir path/root-path}) (defn local-dep? "Check if x is a local dep map." [x] (and (map? x) (:local/root x))) (defn- cleanse-root-deps "Remove any custom multi-repo keys from deps config." [deps] (dissoc deps ::registry)) (defn- validate-registered-dep-paths! "Ensure registered deps are inside root repo" [registry] (some #(when (re-find #"\.\.\/" %) (throw (cli/err "Registered subrepo path must be inside root repo:" %))) registry) :valid) (defn- validate-subrepo-deps-config! [deps] (when-let [k (some (fn [[k]] (when (not (namespace k)) k)) (:aliases deps))] (throw (cli/err "Only namespaced alias keys are allowed in nested repos:" k))) :valid) --- processing (defn read-root-config "Get root deps cofig loaded by clojure cli." [] (-> "deps.edn" io/file slurp edn/read-string)) (defn read-sub-config "Read a subrepo's deps config." [dir] (-> (str dir "/deps.edn") io/file slurp edn/read-string)) (defn update-key "Update map only if key already exists." [m k f & args] (if (get m k) (apply (partial update m k f) args) m)) (defn map-vals "Update each key-value pair in a map." [m f] (into {} (for [[k v] m] (f k v)))) (defn out-path-back-dirs "Amount dirs back required to reach root from out dir." [] (path/make-back-dirs (path/count-foward-dirs (:out-dir opts)))) (defn- qualify-subdir-path "Make nested path relative to out dir." [subdir local-path] (path/join (out-path-back-dirs) subdir local-path)) (defn qualify-subdir-local-dep "Make :local/root dep relative to out dir." [subdir local-path] (path/join (out-path-back-dirs) (path/append-base-dirs subdir local-path))) (defn- update-subdir-paths "Update list of paths to be relative to output dir." [subdir paths] (mapv #(qualify-subdir-path subdir %) paths)) (defn- update-subdir-deps "Update deps map :local/root paths to be relative to output dir." [subdir deps] (map-vals deps (fn [k v] [k (if-let [path (:local/root v)] (assoc v :local/root (qualify-subdir-local-dep subdir path)) v)]))) (defn- parse-subdeps "Parse subrepo deps config. Updates paths to be relative to output directory." [subdir deps] (validate-subrepo-deps-config! deps) (-> deps (update-key :paths #(update-subdir-paths subdir %)) (update-key :deps #(update-subdir-deps subdir %)) (update-key :aliases (fn [m] (map-vals m (fn [k v] [k (-> v (update-key :extra-paths #(update-subdir-paths subdir %)) (update-key :extra-deps #(update-subdir-deps subdir %)))])))))) (defn- combine-deps "Combines dep aliases, with `d2` taking precedence over `d1`." [d1 d2] (let [{:keys [paths deps aliases]} d2] (cond-> d1 paths (update :paths into paths) deps (update :deps merge deps) aliases (update :aliases merge aliases)))) (defn process-deps "Process root deps and registered subrepo deps. Returns map of: ::main-deps - Unified root and nested deps config. ::nested-deps - Unified nested deps config. ::root-deps - Root deps.edn config that served as basis for processing. ::subrepo-deps - Map of registered subrepos paths to their respective deps configs." ([] (process-deps {})) ([-opts] (cli/with-err-boundary "Error processing Interdep repo dependencies." (let [{::keys [registry] :as root-deps} (read-root-config) root-deps (cleanse-root-deps root-deps)] (binding [opts (-> opts (merge -opts) (assoc :registry registry))] (validate-registered-dep-paths! registry) (let [subrepo-deps (atom {}) nested-deps (reduce (fn [acc subdir] (let [cfg (read-sub-config subdir)] (swap! subrepo-deps assoc subdir cfg) (combine-deps acc (parse-subdeps subdir cfg)))) {} registry)] {::main-deps (combine-deps nested-deps root-deps) ::root-deps root-deps ::nested-deps nested-deps ::subrepo-deps @subrepo-deps}))))))
20dfee9cb26cb6f286d9eab740fad2508240ac3a308abd299bef29be3ddd1f9f
vivid-inc/ash-ra-template
args.clj
; Copyright 2020 Vivid Inc. ; 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. (ns vivid.art.cli.args (:require [clojure.java.io :as io] [clojure.spec.alpha :as s] [clojure.string] [clojure.tools.cli] [farolero.core :as farolero] [vivid.art.cli.files :as files] [vivid.art.cli.specs] [vivid.art.cli.validate :as validate]) (:import (java.io File))) (defn- parse-cli-args [args options-spec] (let [{:keys [options arguments errors]} (clojure.tools.cli/parse-opts args options-spec)] (cond (:help options) (farolero/signal :vivid.art.cli/error {:step 'parse-cli-args :exit-status 0 :show-usage true}) errors (farolero/signal :vivid.art.cli/error {:step 'parse-cli-args :message (clojure.string/join \newline errors)}) (= 0 (count arguments)) (farolero/signal :vivid.art.cli/error {:step 'parse-cli-args :show-usage true}) :else [arguments options]))) (defn ->template-path "Takes a base path and a path to a template-file (ostensibly within the base path) and returns a map indicating the providence :src-path and the intended output path of the template file :dest-rel-path relative to the batch's :output-dir." [^File base-path ^File template-file] (let [rel-path-parent (files/relative-path base-path (.getParentFile template-file)) dest-name (files/strip-art-filename-suffix (.getName template-file)) dest-rel-path (apply io/file (concat rel-path-parent [dest-name]))] {:src-path template-file :dest-rel-path dest-rel-path})) (defn paths->template-paths! "Finds all ART templates either at the given paths (as template files) or within their sub-trees (as a directory). This function is impure, as it directly scans the filesystem subtree of each of the paths." [paths] (letfn [(->template-paths [base-path] (let [template-files (files/template-file-seq base-path)] (map #(->template-path base-path %) template-files)))] (mapcat ->template-paths paths))) (defn validate-as-batch "Validates template paths, and resolves and validates everything else, returning a render batch." [templates {:keys [^String output-dir] :as options}] (merge ; Mandatory {:templates (validate/validate-templates templates) :output-dir (validate/validate-output-dir output-dir)} ; Optional (when-let [bindings (when (seq (:bindings options)) (:bindings options))] {:bindings (validate/validate-bindings bindings)}) (when-let [delimiters (:delimiters options)] {:delimiters (validate/validate-delimiters delimiters)}) (when-let [dependencies (:dependencies options)] {:dependencies (validate/validate-dependencies dependencies)}) (when-let [to-phase (:to-phase options)] {:to-phase (validate/validate-to-phase to-phase)}))) (defn direct->batch [templates options] (-> (validate-as-batch templates options) (update :templates paths->template-paths!))) (defn cli-args->batch "Interpret command line arguments, producing a map representing an ART render batch job that can be executed by this CLI lib's (render-batch) fn. All arguments are validated according to the clojure.tools.cli -compliant options specification and resolved. Exceptional cases are signaled." [args options-spec] (let [[arguments options] (parse-cli-args args options-spec)] (-> (validate-as-batch arguments options) (update :templates paths->template-paths!)))) (s/fdef direct->batch :ret :vivid.art.cli/batch) (s/fdef cli-args->batch :ret :vivid.art.cli/batch)
null
https://raw.githubusercontent.com/vivid-inc/ash-ra-template/f64be7efd6f52ccd451cddb851f02511d1665b11/art-cli/src/vivid/art/cli/args.clj
clojure
Copyright 2020 Vivid Inc. 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. Mandatory Optional
distributed under the License is distributed on an " AS IS " BASIS , (ns vivid.art.cli.args (:require [clojure.java.io :as io] [clojure.spec.alpha :as s] [clojure.string] [clojure.tools.cli] [farolero.core :as farolero] [vivid.art.cli.files :as files] [vivid.art.cli.specs] [vivid.art.cli.validate :as validate]) (:import (java.io File))) (defn- parse-cli-args [args options-spec] (let [{:keys [options arguments errors]} (clojure.tools.cli/parse-opts args options-spec)] (cond (:help options) (farolero/signal :vivid.art.cli/error {:step 'parse-cli-args :exit-status 0 :show-usage true}) errors (farolero/signal :vivid.art.cli/error {:step 'parse-cli-args :message (clojure.string/join \newline errors)}) (= 0 (count arguments)) (farolero/signal :vivid.art.cli/error {:step 'parse-cli-args :show-usage true}) :else [arguments options]))) (defn ->template-path "Takes a base path and a path to a template-file (ostensibly within the base path) and returns a map indicating the providence :src-path and the intended output path of the template file :dest-rel-path relative to the batch's :output-dir." [^File base-path ^File template-file] (let [rel-path-parent (files/relative-path base-path (.getParentFile template-file)) dest-name (files/strip-art-filename-suffix (.getName template-file)) dest-rel-path (apply io/file (concat rel-path-parent [dest-name]))] {:src-path template-file :dest-rel-path dest-rel-path})) (defn paths->template-paths! "Finds all ART templates either at the given paths (as template files) or within their sub-trees (as a directory). This function is impure, as it directly scans the filesystem subtree of each of the paths." [paths] (letfn [(->template-paths [base-path] (let [template-files (files/template-file-seq base-path)] (map #(->template-path base-path %) template-files)))] (mapcat ->template-paths paths))) (defn validate-as-batch "Validates template paths, and resolves and validates everything else, returning a render batch." [templates {:keys [^String output-dir] :as options}] (merge {:templates (validate/validate-templates templates) :output-dir (validate/validate-output-dir output-dir)} (when-let [bindings (when (seq (:bindings options)) (:bindings options))] {:bindings (validate/validate-bindings bindings)}) (when-let [delimiters (:delimiters options)] {:delimiters (validate/validate-delimiters delimiters)}) (when-let [dependencies (:dependencies options)] {:dependencies (validate/validate-dependencies dependencies)}) (when-let [to-phase (:to-phase options)] {:to-phase (validate/validate-to-phase to-phase)}))) (defn direct->batch [templates options] (-> (validate-as-batch templates options) (update :templates paths->template-paths!))) (defn cli-args->batch "Interpret command line arguments, producing a map representing an ART render batch job that can be executed by this CLI lib's (render-batch) fn. All arguments are validated according to the clojure.tools.cli -compliant options specification and resolved. Exceptional cases are signaled." [args options-spec] (let [[arguments options] (parse-cli-args args options-spec)] (-> (validate-as-batch arguments options) (update :templates paths->template-paths!)))) (s/fdef direct->batch :ret :vivid.art.cli/batch) (s/fdef cli-args->batch :ret :vivid.art.cli/batch)
62a1548f141033de190fcf998f913ed9e4983e002c7f485389f9e49a9f1a90e9
DSiSc/why3
expr.mli
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) open Wstdlib open Ident open Term open Ity * { 2 Routine symbols } type rsymbol = private { rs_name : ident; rs_cty : cty; rs_logic : rs_logic; rs_field : pvsymbol option; } and rs_logic = | RLnone (* non-pure symbol *) | RLpv of pvsymbol (* local let-function *) | RLls of lsymbol (* top-level let-function or let-predicate *) | RLlemma (* top-level or local let-lemma *) module Mrs : Extmap.S with type key = rsymbol module Srs : Extset.S with module M = Mrs module Hrs : Exthtbl.S with type key = rsymbol module Wrs : Weakhtbl.S with type key = rsymbol val rs_compare : rsymbol -> rsymbol -> int val rs_equal : rsymbol -> rsymbol -> bool val rs_hash : rsymbol -> int type rs_kind = | RKnone (* non-pure symbol *) | RKlocal (* local let-function *) | RKfunc (* top-level let-function *) | RKpred (* top-level let-predicate *) | RKlemma (* top-level or local let-lemma *) val rs_kind : rsymbol -> rs_kind val create_rsymbol : preid -> ?ghost:bool -> ?kind:rs_kind -> cty -> rsymbol * If [ ? kind ] is supplied and is not [ RKnone ] , then [ cty ] must have no effects except for resets which are ignored . If [ ? kind ] is [ RKnone ] or [ RKlemma ] , external mutable reads are allowed , otherwise [ cty.cty_freeze.isb_reg ] must be empty . If [ ? kind ] is [ RKlocal ] , the type variables in [ cty ] are frozen but regions are instantiable . If [ ? kind ] is [ RKpred ] the result type must be [ ity_bool ] . If [ ? kind ] is [ RKlemma ] and the result type is not [ ity_unit ] , an existential premise is generated . must have no effects except for resets which are ignored. If [?kind] is [RKnone] or [RKlemma], external mutable reads are allowed, otherwise [cty.cty_freeze.isb_reg] must be empty. If [?kind] is [RKlocal], the type variables in [cty] are frozen but regions are instantiable. If [?kind] is [RKpred] the result type must be [ity_bool]. If [?kind] is [RKlemma] and the result type is not [ity_unit], an existential premise is generated. *) val create_constructor : constr:int -> preid -> itysymbol -> pvsymbol list -> rsymbol val create_projection : itysymbol -> pvsymbol -> rsymbol val restore_rs : lsymbol -> rsymbol (** raises [Not_found] if the argument is not a [rs_logic] *) val rs_ghost : rsymbol -> bool val ls_of_rs : rsymbol -> lsymbol (** raises [Invalid_argument] is [rs_logic] is not an [RLls] *) val fd_of_rs : rsymbol -> pvsymbol (** raises [Invalid_argument] is [rs_field] is [None] *) * { 2 Program patterns } type pat_ghost = | PGfail (* refutable ghost subpattern before "|" *) | PGlast (* refutable ghost subpattern otherwise *) | PGnone (* every ghost subpattern is irrefutable *) type prog_pattern = private { pp_pat : pattern; (* pure pattern *) pp_ity : ity; (* type of the matched value *) pp_mask : mask; (* mask of the matched value *) pp_fail : pat_ghost; (* refutable ghost subpattern *) } type pre_pattern = | PPwild | PPvar of preid * bool | PPapp of rsymbol * pre_pattern list | PPas of pre_pattern * preid * bool | PPor of pre_pattern * pre_pattern exception ConstructorExpected of rsymbol val create_prog_pattern : pre_pattern -> ity -> mask -> pvsymbol Mstr.t * prog_pattern * { 2 Program expressions } type assertion_kind = Assert | Assume | Check type for_direction = To | DownTo type for_bounds = pvsymbol * for_direction * pvsymbol type invariant = term type variant = term * lsymbol option (** tau * (tau -> tau -> prop) *) type assign = pvsymbol * rsymbol * pvsymbol (* region * field * value *) type expr = private { e_node : expr_node; e_ity : ity; e_mask : mask; e_effect : effect; e_attrs : Sattr.t; e_loc : Loc.position option; } and expr_node = | Evar of pvsymbol | Econst of Number.constant | Eexec of cexp * cty | Eassign of assign list | Elet of let_defn * expr | Eif of expr * expr * expr | Ematch of expr * reg_branch list * exn_branch Mxs.t | Ewhile of expr * invariant list * variant list * expr | Efor of pvsymbol * for_bounds * pvsymbol * invariant list * expr | Eraise of xsymbol * expr | Eexn of xsymbol * expr | Eassert of assertion_kind * term | Eghost of expr | Epure of term | Eabsurd and reg_branch = prog_pattern * expr and exn_branch = pvsymbol list * expr and cexp = private { c_node : cexp_node; c_cty : cty; } and cexp_node = | Capp of rsymbol * pvsymbol list | Cpur of lsymbol * pvsymbol list | Cfun of expr | Cany and let_defn = private | LDvar of pvsymbol * expr | LDsym of rsymbol * cexp | LDrec of rec_defn list and rec_defn = private { rec_sym : rsymbol; (* exported symbol *) rec_rsym : rsymbol; (* internal symbol *) rec_fun : cexp; (* necessary a Cfun *) rec_varl : variant list; } * { 2 Expressions } val e_attr_set : ?loc:Loc.position -> Sattr.t -> expr -> expr val e_attr_push : ?loc:Loc.position -> Sattr.t -> expr -> expr val e_attr_add : attribute -> expr -> expr val e_attr_copy : expr -> expr -> expr * { 2 Definitions } val let_var : preid -> ?ghost:bool -> expr -> let_defn * pvsymbol val let_sym : preid -> ?ghost:bool -> ?kind:rs_kind -> cexp -> let_defn * rsymbol val let_rec : (rsymbol * cexp * variant list * rs_kind) list -> let_defn * rec_defn list val ls_decr_of_rec_defn : rec_defn -> lsymbol option (* returns the dummy predicate symbol used in the precondition of the rec_rsym rsymbol to store the instantiated variant list *) * { 2 Callable expressions } val c_app : rsymbol -> pvsymbol list -> ity list -> ity -> cexp val c_pur : lsymbol -> pvsymbol list -> ity list -> ity -> cexp val c_fun : ?mask:mask -> pvsymbol list -> pre list -> post list -> post list Mxs.t -> pvsymbol Mpv.t -> expr -> cexp val c_any : cty -> cexp * { 2 Expression constructors } val e_var : pvsymbol -> expr val e_const : Number.constant -> ity -> expr val e_nat_const : int -> expr val e_exec : cexp -> expr val e_app : rsymbol -> expr list -> ity list -> ity -> expr val e_pur : lsymbol -> expr list -> ity list -> ity -> expr val e_let : let_defn -> expr -> expr exception FieldExpected of rsymbol val e_assign : (expr * rsymbol * expr) list -> expr val e_if : expr -> expr -> expr -> expr val e_and : expr -> expr -> expr val e_or : expr -> expr -> expr val e_not : expr -> expr val e_true : expr val e_false : expr val is_e_true : expr -> bool val is_e_false : expr -> bool exception ExceptionLeak of xsymbol val e_exn : xsymbol -> expr -> expr val e_raise : xsymbol -> expr -> ity -> expr val e_match : expr -> reg_branch list -> exn_branch Mxs.t -> expr val e_while : expr -> invariant list -> variant list -> expr -> expr val e_for : pvsymbol -> expr -> for_direction -> expr -> pvsymbol -> invariant list -> expr -> expr val e_assert : assertion_kind -> term -> expr val e_ghostify : bool -> expr -> expr val e_pure : term -> expr val e_absurd : ity -> expr * { 2 Expression manipulation tools } val e_fold : ('a -> expr -> 'a) -> 'a -> expr -> 'a (** [e_fold] does not descend into Cfun *) val e_locate_effect : (effect -> bool) -> expr -> Loc.position option (** [e_locate_effect pr e] looks for a minimal sub-expression of [e] whose effect satisfies [pr] and returns its location *) val proxy_attr : attribute val e_rs_subst : rsymbol Mrs.t -> expr -> expr val c_rs_subst : rsymbol Mrs.t -> cexp -> cexp val term_of_post : prop:bool -> vsymbol -> term -> (term * term) option val term_of_expr : prop:bool -> expr -> term option val post_of_expr : term -> expr -> term option val e_ghost : expr -> bool val c_ghost : cexp -> bool * { 2 Built - in symbols } val rs_true : rsymbol val rs_false : rsymbol val rs_tuple : int -> rsymbol val e_tuple : expr list -> expr val rs_void : rsymbol val fs_void : lsymbol val e_void : expr val t_void : term val is_e_void : expr -> bool val is_rs_tuple : rsymbol -> bool val rs_func_app : rsymbol val ld_func_app : let_defn val e_func_app : expr -> expr -> expr val e_func_app_l : expr -> expr list -> expr * { 2 Pretty - printing } val forget_rs : rsymbol -> unit (* flush id_unique for a program symbol *) val print_rs : Format.formatter -> rsymbol -> unit (* program symbol *) val print_expr : Format.formatter -> expr -> unit (* expression *) val print_let_defn : Format.formatter -> let_defn -> unit
null
https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/mlw/expr.mli
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ****************************************************************** non-pure symbol local let-function top-level let-function or let-predicate top-level or local let-lemma non-pure symbol local let-function top-level let-function top-level let-predicate top-level or local let-lemma * raises [Not_found] if the argument is not a [rs_logic] * raises [Invalid_argument] is [rs_logic] is not an [RLls] * raises [Invalid_argument] is [rs_field] is [None] refutable ghost subpattern before "|" refutable ghost subpattern otherwise every ghost subpattern is irrefutable pure pattern type of the matched value mask of the matched value refutable ghost subpattern * tau * (tau -> tau -> prop) region * field * value exported symbol internal symbol necessary a Cfun returns the dummy predicate symbol used in the precondition of the rec_rsym rsymbol to store the instantiated variant list * [e_fold] does not descend into Cfun * [e_locate_effect pr e] looks for a minimal sub-expression of [e] whose effect satisfies [pr] and returns its location flush id_unique for a program symbol program symbol expression
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University General Public License version 2.1 , with the special exception open Wstdlib open Ident open Term open Ity * { 2 Routine symbols } type rsymbol = private { rs_name : ident; rs_cty : cty; rs_logic : rs_logic; rs_field : pvsymbol option; } and rs_logic = module Mrs : Extmap.S with type key = rsymbol module Srs : Extset.S with module M = Mrs module Hrs : Exthtbl.S with type key = rsymbol module Wrs : Weakhtbl.S with type key = rsymbol val rs_compare : rsymbol -> rsymbol -> int val rs_equal : rsymbol -> rsymbol -> bool val rs_hash : rsymbol -> int type rs_kind = val rs_kind : rsymbol -> rs_kind val create_rsymbol : preid -> ?ghost:bool -> ?kind:rs_kind -> cty -> rsymbol * If [ ? kind ] is supplied and is not [ RKnone ] , then [ cty ] must have no effects except for resets which are ignored . If [ ? kind ] is [ RKnone ] or [ RKlemma ] , external mutable reads are allowed , otherwise [ cty.cty_freeze.isb_reg ] must be empty . If [ ? kind ] is [ RKlocal ] , the type variables in [ cty ] are frozen but regions are instantiable . If [ ? kind ] is [ RKpred ] the result type must be [ ity_bool ] . If [ ? kind ] is [ RKlemma ] and the result type is not [ ity_unit ] , an existential premise is generated . must have no effects except for resets which are ignored. If [?kind] is [RKnone] or [RKlemma], external mutable reads are allowed, otherwise [cty.cty_freeze.isb_reg] must be empty. If [?kind] is [RKlocal], the type variables in [cty] are frozen but regions are instantiable. If [?kind] is [RKpred] the result type must be [ity_bool]. If [?kind] is [RKlemma] and the result type is not [ity_unit], an existential premise is generated. *) val create_constructor : constr:int -> preid -> itysymbol -> pvsymbol list -> rsymbol val create_projection : itysymbol -> pvsymbol -> rsymbol val restore_rs : lsymbol -> rsymbol val rs_ghost : rsymbol -> bool val ls_of_rs : rsymbol -> lsymbol val fd_of_rs : rsymbol -> pvsymbol * { 2 Program patterns } type pat_ghost = type prog_pattern = private { } type pre_pattern = | PPwild | PPvar of preid * bool | PPapp of rsymbol * pre_pattern list | PPas of pre_pattern * preid * bool | PPor of pre_pattern * pre_pattern exception ConstructorExpected of rsymbol val create_prog_pattern : pre_pattern -> ity -> mask -> pvsymbol Mstr.t * prog_pattern * { 2 Program expressions } type assertion_kind = Assert | Assume | Check type for_direction = To | DownTo type for_bounds = pvsymbol * for_direction * pvsymbol type invariant = term type expr = private { e_node : expr_node; e_ity : ity; e_mask : mask; e_effect : effect; e_attrs : Sattr.t; e_loc : Loc.position option; } and expr_node = | Evar of pvsymbol | Econst of Number.constant | Eexec of cexp * cty | Eassign of assign list | Elet of let_defn * expr | Eif of expr * expr * expr | Ematch of expr * reg_branch list * exn_branch Mxs.t | Ewhile of expr * invariant list * variant list * expr | Efor of pvsymbol * for_bounds * pvsymbol * invariant list * expr | Eraise of xsymbol * expr | Eexn of xsymbol * expr | Eassert of assertion_kind * term | Eghost of expr | Epure of term | Eabsurd and reg_branch = prog_pattern * expr and exn_branch = pvsymbol list * expr and cexp = private { c_node : cexp_node; c_cty : cty; } and cexp_node = | Capp of rsymbol * pvsymbol list | Cpur of lsymbol * pvsymbol list | Cfun of expr | Cany and let_defn = private | LDvar of pvsymbol * expr | LDsym of rsymbol * cexp | LDrec of rec_defn list and rec_defn = private { rec_varl : variant list; } * { 2 Expressions } val e_attr_set : ?loc:Loc.position -> Sattr.t -> expr -> expr val e_attr_push : ?loc:Loc.position -> Sattr.t -> expr -> expr val e_attr_add : attribute -> expr -> expr val e_attr_copy : expr -> expr -> expr * { 2 Definitions } val let_var : preid -> ?ghost:bool -> expr -> let_defn * pvsymbol val let_sym : preid -> ?ghost:bool -> ?kind:rs_kind -> cexp -> let_defn * rsymbol val let_rec : (rsymbol * cexp * variant list * rs_kind) list -> let_defn * rec_defn list val ls_decr_of_rec_defn : rec_defn -> lsymbol option * { 2 Callable expressions } val c_app : rsymbol -> pvsymbol list -> ity list -> ity -> cexp val c_pur : lsymbol -> pvsymbol list -> ity list -> ity -> cexp val c_fun : ?mask:mask -> pvsymbol list -> pre list -> post list -> post list Mxs.t -> pvsymbol Mpv.t -> expr -> cexp val c_any : cty -> cexp * { 2 Expression constructors } val e_var : pvsymbol -> expr val e_const : Number.constant -> ity -> expr val e_nat_const : int -> expr val e_exec : cexp -> expr val e_app : rsymbol -> expr list -> ity list -> ity -> expr val e_pur : lsymbol -> expr list -> ity list -> ity -> expr val e_let : let_defn -> expr -> expr exception FieldExpected of rsymbol val e_assign : (expr * rsymbol * expr) list -> expr val e_if : expr -> expr -> expr -> expr val e_and : expr -> expr -> expr val e_or : expr -> expr -> expr val e_not : expr -> expr val e_true : expr val e_false : expr val is_e_true : expr -> bool val is_e_false : expr -> bool exception ExceptionLeak of xsymbol val e_exn : xsymbol -> expr -> expr val e_raise : xsymbol -> expr -> ity -> expr val e_match : expr -> reg_branch list -> exn_branch Mxs.t -> expr val e_while : expr -> invariant list -> variant list -> expr -> expr val e_for : pvsymbol -> expr -> for_direction -> expr -> pvsymbol -> invariant list -> expr -> expr val e_assert : assertion_kind -> term -> expr val e_ghostify : bool -> expr -> expr val e_pure : term -> expr val e_absurd : ity -> expr * { 2 Expression manipulation tools } val e_fold : ('a -> expr -> 'a) -> 'a -> expr -> 'a val e_locate_effect : (effect -> bool) -> expr -> Loc.position option val proxy_attr : attribute val e_rs_subst : rsymbol Mrs.t -> expr -> expr val c_rs_subst : rsymbol Mrs.t -> cexp -> cexp val term_of_post : prop:bool -> vsymbol -> term -> (term * term) option val term_of_expr : prop:bool -> expr -> term option val post_of_expr : term -> expr -> term option val e_ghost : expr -> bool val c_ghost : cexp -> bool * { 2 Built - in symbols } val rs_true : rsymbol val rs_false : rsymbol val rs_tuple : int -> rsymbol val e_tuple : expr list -> expr val rs_void : rsymbol val fs_void : lsymbol val e_void : expr val t_void : term val is_e_void : expr -> bool val is_rs_tuple : rsymbol -> bool val rs_func_app : rsymbol val ld_func_app : let_defn val e_func_app : expr -> expr -> expr val e_func_app_l : expr -> expr list -> expr * { 2 Pretty - printing } val print_let_defn : Format.formatter -> let_defn -> unit
f0d392373d36c068e866fe0b899304879be83f9303a7cb696fded80962e23bf2
DomainDrivenArchitecture/dda-serverspec-crate
http_test.clj
Licensed to the Apache Software Foundation ( ASF ) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file 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. (ns dda.pallet.dda-serverspec-crate.infra.fact.http-test (:require [clojure.test :refer :all] [data-test :refer :all] [clojure.tools.logging :as logging] [dda.pallet.dda-serverspec-crate.infra.fact.http :as sut])) ; ------------------------ test data ------------------------ (def reference-date (java.time.LocalDate/parse "10.02.2018" (java.time.format.DateTimeFormatter/ofPattern "dd.MM.yyyy"))) (def date-2018-04-15 (java.time.LocalDate/parse "15.04.2018" (java.time.format.DateTimeFormatter/ofPattern "dd.MM.yyyy"))) (def date-2020-02-06-12-00 (java.time.LocalDate/parse "06.02.2020 12:00:00" (java.time.format.DateTimeFormatter/ofPattern "dd.MM.yyyy hh:mm:ss"))) (def date-offset (try (.between (java.time.temporal.ChronoUnit/DAYS) reference-date (java.time.LocalDate/now)) (catch java.time.DateTimeException ex (logging/warn "Exception encountered : " ex)))) (def fact-756 {:_some_url {:expiration-days (- 756 date-offset)}}) (def fact-bahn-and-google {:https___bahn.de {:expiration-days (- 756 date-offset)} :https___google.com {:expiration-days (- 66 date-offset)}}) (def fact-64 {:https___domaindrivenarchitecture.org {:expiration-days (- 64 date-offset)}}) (def fact-194 {:https___domaindrivenarchitecture.org {:expiration-days (- 194 date-offset)}}) ; ------------------------ tests ------------------------------ (deftest test-parse-date (testing "test parsing http output" (is (= date-2018-04-15 (sut/parse-date-16-04 "Sun, 15 Apr 2018 12:01:04 GMT"))) (is (= date-2018-04-15 (sut/parse-date-18-04 "Apr 15 12:01:04 2018 GMT"))) (is (= date-2020-02-06-12-00 (sut/parse-date-18-04 "Feb 6 12:00:00 2020 GMT"))))) (defdatatest should-parse-756 [input _] (is (= fact-756 (sut/parse-http-response input)))) (defdatatest should-parse-bahn-and-google [input _] (is (= fact-bahn-and-google (sut/parse-http-script-responses (str (:google input) sut/output-separator (:bahn input) sut/output-separator))))) (defdatatest should-parse-invalid [input expected] (is (= expected (sut/parse-http-script-responses input)))) (defdatatest should-parse-64 [input _] (is (= fact-64 (sut/parse-http-script-responses input)))) (defdatatest should-parse-194 [input _] (is (= fact-194 (sut/parse-http-script-responses input))))
null
https://raw.githubusercontent.com/DomainDrivenArchitecture/dda-serverspec-crate/0a2fd8cdd54a9efc3aad9e141098c2bf01d40861/test/src/dda/pallet/dda_serverspec_crate/infra/fact/http_test.clj
clojure
or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file "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 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. ------------------------ test data ------------------------ ------------------------ tests ------------------------------
Licensed to the Apache Software Foundation ( ASF ) under one to you under the Apache License , Version 2.0 ( the distributed under the License is distributed on an " AS IS " BASIS , (ns dda.pallet.dda-serverspec-crate.infra.fact.http-test (:require [clojure.test :refer :all] [data-test :refer :all] [clojure.tools.logging :as logging] [dda.pallet.dda-serverspec-crate.infra.fact.http :as sut])) (def reference-date (java.time.LocalDate/parse "10.02.2018" (java.time.format.DateTimeFormatter/ofPattern "dd.MM.yyyy"))) (def date-2018-04-15 (java.time.LocalDate/parse "15.04.2018" (java.time.format.DateTimeFormatter/ofPattern "dd.MM.yyyy"))) (def date-2020-02-06-12-00 (java.time.LocalDate/parse "06.02.2020 12:00:00" (java.time.format.DateTimeFormatter/ofPattern "dd.MM.yyyy hh:mm:ss"))) (def date-offset (try (.between (java.time.temporal.ChronoUnit/DAYS) reference-date (java.time.LocalDate/now)) (catch java.time.DateTimeException ex (logging/warn "Exception encountered : " ex)))) (def fact-756 {:_some_url {:expiration-days (- 756 date-offset)}}) (def fact-bahn-and-google {:https___bahn.de {:expiration-days (- 756 date-offset)} :https___google.com {:expiration-days (- 66 date-offset)}}) (def fact-64 {:https___domaindrivenarchitecture.org {:expiration-days (- 64 date-offset)}}) (def fact-194 {:https___domaindrivenarchitecture.org {:expiration-days (- 194 date-offset)}}) (deftest test-parse-date (testing "test parsing http output" (is (= date-2018-04-15 (sut/parse-date-16-04 "Sun, 15 Apr 2018 12:01:04 GMT"))) (is (= date-2018-04-15 (sut/parse-date-18-04 "Apr 15 12:01:04 2018 GMT"))) (is (= date-2020-02-06-12-00 (sut/parse-date-18-04 "Feb 6 12:00:00 2020 GMT"))))) (defdatatest should-parse-756 [input _] (is (= fact-756 (sut/parse-http-response input)))) (defdatatest should-parse-bahn-and-google [input _] (is (= fact-bahn-and-google (sut/parse-http-script-responses (str (:google input) sut/output-separator (:bahn input) sut/output-separator))))) (defdatatest should-parse-invalid [input expected] (is (= expected (sut/parse-http-script-responses input)))) (defdatatest should-parse-64 [input _] (is (= fact-64 (sut/parse-http-script-responses input)))) (defdatatest should-parse-194 [input _] (is (= fact-194 (sut/parse-http-script-responses input))))
656a43ebd7c4bec5e222f0f5874919ffaffdd69c8a352af24e49cf5920d7c033
mirage/wodan
test.mli
* Copyright ( c ) 2013 - 2017 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2017 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) (* left empty on purpose *)
null
https://raw.githubusercontent.com/mirage/wodan/fa37883ed73a1e9d7a05781453caf926134edcf3/tests/wodan-irmin/test.mli
ocaml
left empty on purpose
* Copyright ( c ) 2013 - 2017 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013-2017 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
87115e7fccb6f18a72e4cc9979a765fd8c553af9d6107c205def78f2e5ba5e0c
stumpwm/stumpwm-contrib
swm-gaps.lisp
;;;; swm-gaps.lisp (in-package #:swm-gaps) (export '(*inner-gaps-size* *outer-gaps-size* *head-gaps-size* *gaps-on* toggle-gaps toggle-gaps-on toggle-gaps-off)) (defvar *inner-gaps-size* 5) (defvar *outer-gaps-size* 10) (defvar *head-gaps-size* 0) (defvar *gaps-on* nil) (defun apply-gaps-p (win) "Tell if gaps should be applied to this window" (and *gaps-on* (not (stumpwm::window-transient-p win)) (not (window-fullscreen win)))) (defun window-edging-p (win direction) "Tell if the window is touching the head in the given direction." (let* ((frame (stumpwm::window-frame win)) (head (stumpwm::frame-head (stumpwm:window-group win) frame)) (offset (nth-value 2 (stumpwm::get-edge frame direction)))) (ecase direction (:top (= offset (stumpwm::head-y head))) (:bottom (= offset (+ (stumpwm::head-y head) (stumpwm::head-height head)))) (:left (= offset (stumpwm::head-x head))) (:right (= offset (+ (stumpwm::head-x head) (stumpwm::head-width head))))))) (defun gaps-offsets (win) "Return gap offset values for the window. X and Y values are added. WIDTH and HEIGHT are subtracted." (let ((x *inner-gaps-size*) (y *inner-gaps-size*) (width (* 2 *inner-gaps-size*)) (height (* 2 *inner-gaps-size*))) (if (window-edging-p win :top) (setf y (+ y *outer-gaps-size*) height (+ height *outer-gaps-size*))) (if (window-edging-p win :bottom) (setf height (+ height *outer-gaps-size*))) (if (window-edging-p win :left) (setf x (+ x *outer-gaps-size*) width (+ width *outer-gaps-size*))) (if (window-edging-p win :right) (setf width (+ width *outer-gaps-size*))) (values x y width height))) (defun stumpwm::maximize-window (win) "Redefined gaps aware maximize function." (multiple-value-bind (x y wx wy width height border stick) (stumpwm::geometry-hints win) (let ((ox 0) (oy 0) (ow 0) (oh 0) (frame (stumpwm::window-frame win))) (if (apply-gaps-p win) (multiple-value-setq (ox oy ow oh) (gaps-offsets win))) ;; Only do width or height subtraction if result will be positive, otherwise stumpwm will crash . Also , only modify window dimensions ;; if needed (i.e. window at least fills frame minus gap). (when (and (< ow width) (>= width (- (frame-width frame) ow))) (setf width (- width ow))) (when (and (< oh height) (>= height (- (frame-height frame) oh))) (setf height (- height oh))) (setf x (+ x ox) y (+ y oy)) ;; This is the only place a window's geometry should change (set-window-geometry win :x wx :y wy :width width :height height :border-width 0) (xlib:with-state ((window-parent win)) ;; FIXME: updating the border doesn't need to be run everytime ;; the window is maximized, but only when the border style or ;; window type changes. The overhead is probably minimal, ;; though. (setf (xlib:drawable-x (window-parent win)) x (xlib:drawable-y (window-parent win)) y (xlib:drawable-border-width (window-parent win)) border) ;; the parent window should stick to the size of the window ;; unless it isn't being maximized to fill the frame. (if (or stick (find *window-border-style* '(:tight :none))) (setf (xlib:drawable-width (window-parent win)) (window-width win) (xlib:drawable-height (window-parent win)) (window-height win)) (let ((frame (stumpwm::window-frame win))) (setf (xlib:drawable-width (window-parent win)) (- (frame-width frame) (* 2 (xlib:drawable-border-width (window-parent win))) ow) (xlib:drawable-height (window-parent win)) (- (stumpwm::frame-display-height (window-group win) frame) (* 2 (xlib:drawable-border-width (window-parent win))) oh)))) ;; update the "extents" (xlib:change-property (window-xwin win) :_NET_FRAME_EXTENTS (list wx (- (xlib:drawable-width (window-parent win)) width wx) wy (- (xlib:drawable-height (window-parent win)) height wy)) :cardinal 32)) (update-configuration win)))) (defun reset-all-windows () "Reset the size for all tiled windows" (mapcar #'stumpwm::maximize-window (stumpwm::only-tile-windows (stumpwm:screen-windows (current-screen))))) ;; Redefined neighbour for working with head gaps (defun stumpwm::neighbour (direction frame frameset) "Returns the best neighbour of FRAME in FRAMESET on the DIRECTION edge. Valid directions are :UP, :DOWN, :LEFT, :RIGHT. eg: (NEIGHBOUR :UP F FS) finds the frame in FS that is the 'best' neighbour above F." (let ((src-edge (ecase direction (:up :top) (:down :bottom) (:left :left) (:right :right))) (opposite (ecase direction (:up :bottom) (:down :top) (:left :right) (:right :left))) (best-frame nil) (best-overlap 0) (nearest-edge-diff nil)) (multiple-value-bind (src-s src-e src-offset) (stumpwm::get-edge frame src-edge) ;; Get the edge distance closest in the required direction (dolist (f frameset) (multiple-value-bind (s e offset) (stumpwm::get-edge f opposite) (let ((offset-diff (abs (- src-offset offset)))) (if nearest-edge-diff (if (< offset-diff nearest-edge-diff) (setf nearest-edge-diff offset-diff)) (setf nearest-edge-diff offset-diff))))) (dolist (f frameset) (multiple-value-bind (s e offset) (stumpwm::get-edge f opposite) (let ((overlap (- (min src-e e) (max src-s s)))) Two edges are neighbours if they have the same offset ( after ;; accounting for gaps) and their starts and ends overlap. We want ;; to find the neighbour that overlaps the most. (when (and (= (abs (- src-offset offset)) nearest-edge-diff) (> overlap best-overlap)) (setf best-frame f) (setf best-overlap overlap)))))) best-frame)) (defun add-head-gaps () "Add extra gap to the head boundary" (mapcar (lambda (head) (let* ((height (stumpwm::head-height head)) (width (stumpwm::head-width head)) (x (stumpwm::head-x head)) (y (stumpwm::head-y head)) (gap *head-gaps-size*) (new-height (- height (* 2 gap))) (new-width (- width (* 2 gap)))) (stumpwm::resize-head (stumpwm::head-number head) (+ x gap) (+ y gap) new-width new-height))) (screen-heads (current-screen)))) (defcommand toggle-gaps () () "Toggle gaps" (if (null *gaps-on*) (toggle-gaps-on) (toggle-gaps-off))) (defcommand toggle-gaps-on () () "Turn gaps on" (setf *gaps-on* t) (progn (add-head-gaps) (reset-all-windows))) (defcommand toggle-gaps-off () () "Turn gaps off" (setf *gaps-on* nil) (stumpwm:refresh-heads))
null
https://raw.githubusercontent.com/stumpwm/stumpwm-contrib/a7dc1c663d04e6c73a4772c8a6ad56a34381096a/util/swm-gaps/swm-gaps.lisp
lisp
swm-gaps.lisp Only do width or height subtraction if result will be positive, if needed (i.e. window at least fills frame minus gap). This is the only place a window's geometry should change FIXME: updating the border doesn't need to be run everytime the window is maximized, but only when the border style or window type changes. The overhead is probably minimal, though. the parent window should stick to the size of the window unless it isn't being maximized to fill the frame. update the "extents" Redefined neighbour for working with head gaps Get the edge distance closest in the required direction accounting for gaps) and their starts and ends overlap. We want to find the neighbour that overlaps the most.
(in-package #:swm-gaps) (export '(*inner-gaps-size* *outer-gaps-size* *head-gaps-size* *gaps-on* toggle-gaps toggle-gaps-on toggle-gaps-off)) (defvar *inner-gaps-size* 5) (defvar *outer-gaps-size* 10) (defvar *head-gaps-size* 0) (defvar *gaps-on* nil) (defun apply-gaps-p (win) "Tell if gaps should be applied to this window" (and *gaps-on* (not (stumpwm::window-transient-p win)) (not (window-fullscreen win)))) (defun window-edging-p (win direction) "Tell if the window is touching the head in the given direction." (let* ((frame (stumpwm::window-frame win)) (head (stumpwm::frame-head (stumpwm:window-group win) frame)) (offset (nth-value 2 (stumpwm::get-edge frame direction)))) (ecase direction (:top (= offset (stumpwm::head-y head))) (:bottom (= offset (+ (stumpwm::head-y head) (stumpwm::head-height head)))) (:left (= offset (stumpwm::head-x head))) (:right (= offset (+ (stumpwm::head-x head) (stumpwm::head-width head))))))) (defun gaps-offsets (win) "Return gap offset values for the window. X and Y values are added. WIDTH and HEIGHT are subtracted." (let ((x *inner-gaps-size*) (y *inner-gaps-size*) (width (* 2 *inner-gaps-size*)) (height (* 2 *inner-gaps-size*))) (if (window-edging-p win :top) (setf y (+ y *outer-gaps-size*) height (+ height *outer-gaps-size*))) (if (window-edging-p win :bottom) (setf height (+ height *outer-gaps-size*))) (if (window-edging-p win :left) (setf x (+ x *outer-gaps-size*) width (+ width *outer-gaps-size*))) (if (window-edging-p win :right) (setf width (+ width *outer-gaps-size*))) (values x y width height))) (defun stumpwm::maximize-window (win) "Redefined gaps aware maximize function." (multiple-value-bind (x y wx wy width height border stick) (stumpwm::geometry-hints win) (let ((ox 0) (oy 0) (ow 0) (oh 0) (frame (stumpwm::window-frame win))) (if (apply-gaps-p win) (multiple-value-setq (ox oy ow oh) (gaps-offsets win))) otherwise stumpwm will crash . Also , only modify window dimensions (when (and (< ow width) (>= width (- (frame-width frame) ow))) (setf width (- width ow))) (when (and (< oh height) (>= height (- (frame-height frame) oh))) (setf height (- height oh))) (setf x (+ x ox) y (+ y oy)) (set-window-geometry win :x wx :y wy :width width :height height :border-width 0) (xlib:with-state ((window-parent win)) (setf (xlib:drawable-x (window-parent win)) x (xlib:drawable-y (window-parent win)) y (xlib:drawable-border-width (window-parent win)) border) (if (or stick (find *window-border-style* '(:tight :none))) (setf (xlib:drawable-width (window-parent win)) (window-width win) (xlib:drawable-height (window-parent win)) (window-height win)) (let ((frame (stumpwm::window-frame win))) (setf (xlib:drawable-width (window-parent win)) (- (frame-width frame) (* 2 (xlib:drawable-border-width (window-parent win))) ow) (xlib:drawable-height (window-parent win)) (- (stumpwm::frame-display-height (window-group win) frame) (* 2 (xlib:drawable-border-width (window-parent win))) oh)))) (xlib:change-property (window-xwin win) :_NET_FRAME_EXTENTS (list wx (- (xlib:drawable-width (window-parent win)) width wx) wy (- (xlib:drawable-height (window-parent win)) height wy)) :cardinal 32)) (update-configuration win)))) (defun reset-all-windows () "Reset the size for all tiled windows" (mapcar #'stumpwm::maximize-window (stumpwm::only-tile-windows (stumpwm:screen-windows (current-screen))))) (defun stumpwm::neighbour (direction frame frameset) "Returns the best neighbour of FRAME in FRAMESET on the DIRECTION edge. Valid directions are :UP, :DOWN, :LEFT, :RIGHT. eg: (NEIGHBOUR :UP F FS) finds the frame in FS that is the 'best' neighbour above F." (let ((src-edge (ecase direction (:up :top) (:down :bottom) (:left :left) (:right :right))) (opposite (ecase direction (:up :bottom) (:down :top) (:left :right) (:right :left))) (best-frame nil) (best-overlap 0) (nearest-edge-diff nil)) (multiple-value-bind (src-s src-e src-offset) (stumpwm::get-edge frame src-edge) (dolist (f frameset) (multiple-value-bind (s e offset) (stumpwm::get-edge f opposite) (let ((offset-diff (abs (- src-offset offset)))) (if nearest-edge-diff (if (< offset-diff nearest-edge-diff) (setf nearest-edge-diff offset-diff)) (setf nearest-edge-diff offset-diff))))) (dolist (f frameset) (multiple-value-bind (s e offset) (stumpwm::get-edge f opposite) (let ((overlap (- (min src-e e) (max src-s s)))) Two edges are neighbours if they have the same offset ( after (when (and (= (abs (- src-offset offset)) nearest-edge-diff) (> overlap best-overlap)) (setf best-frame f) (setf best-overlap overlap)))))) best-frame)) (defun add-head-gaps () "Add extra gap to the head boundary" (mapcar (lambda (head) (let* ((height (stumpwm::head-height head)) (width (stumpwm::head-width head)) (x (stumpwm::head-x head)) (y (stumpwm::head-y head)) (gap *head-gaps-size*) (new-height (- height (* 2 gap))) (new-width (- width (* 2 gap)))) (stumpwm::resize-head (stumpwm::head-number head) (+ x gap) (+ y gap) new-width new-height))) (screen-heads (current-screen)))) (defcommand toggle-gaps () () "Toggle gaps" (if (null *gaps-on*) (toggle-gaps-on) (toggle-gaps-off))) (defcommand toggle-gaps-on () () "Turn gaps on" (setf *gaps-on* t) (progn (add-head-gaps) (reset-all-windows))) (defcommand toggle-gaps-off () () "Turn gaps off" (setf *gaps-on* nil) (stumpwm:refresh-heads))
ea3b7eb947b6e853770510a0b929f18e9157d86dda1b2853bedfdc7ccaf40c68
biocaml/phylogenetics
alignment.ml
open Core type t = { descriptions : string array ; sequences : string array ; } let sequence t i = t.sequences.(i) let description t i = t.descriptions.(i) let nrows a = Array.length a.sequences let ncols a = String.length a.sequences.(0) type error = [ | `Empty_alignment | `Unequal_sequence_lengths ] [@@deriving show] type parsing_error = [ | `Fasta_parser_error of string | error ] [@@deriving show] let check_non_empty_list = function | [] -> Error (`Empty_alignment) | items -> Ok items let of_tuples items = let descriptions, sequences = Array.unzip items in let n = String.length sequences.(0) in if (Array.for_all sequences ~f:(fun s -> String.length s = n)) then Ok { descriptions ; sequences ; } else Error `Unequal_sequence_lengths let of_assoc_list l = match check_non_empty_list l with | Ok items -> Array.of_list items |> of_tuples | Error e -> Error e let map t ~f = Array.map2_exn t.descriptions t.sequences ~f:(fun description sequence -> f ~description ~sequence) |> of_tuples let array_mapi t ~f = Array.mapi t.descriptions ~f:(fun i description -> f i ~description ~sequence:t.sequences.(i)) let fold t ~init ~f = Array.fold2_exn t.descriptions t.sequences ~init ~f:(fun acc description sequence -> f acc ~description ~sequence) module Fasta = struct let of_fasta_items (items:Biotk.Fasta.item list) = List.map items ~f:(fun x -> x.description, x.sequence) |> of_assoc_list let from_file fn = let open Biotk.Let_syntax.Result in let* _, items = Biotk.Fasta.from_file fn |> Result.map_error ~f:(fun msg -> `Fasta_parser_error msg) in of_fasta_items items let from_file_exn fn = match from_file fn with | Ok al -> al | Error e -> failwith (show_parsing_error e) let to_channel ({sequences ; descriptions}) oc = Array.iter2_exn descriptions sequences ~f:(fun desc seq -> Out_channel.output_lines oc [ sprintf ">%s" desc ; seq; ]) let to_file al fn = Out_channel.with_file fn ~f:(to_channel al) end let find_sequence t id = Array.findi t.descriptions ~f:(fun _ x -> String.equal x id) |> Option.map ~f:(fun (i, _) -> t.sequences.(i)) let indel_free_columns ali = Array.init (nrows ali) ~f:(fun j -> Array.for_all ali.sequences ~f:(fun s -> Char.(s.[j] <> '-')) ) let residues al ~column:j = if j < 0 || j > ncols al then raise (Invalid_argument "Alignment.residues") ; Array.fold al.sequences ~init:Char.Set.empty ~f:(fun acc s -> Char.Set.add acc s.[j]) let number_of_residues_per_column_stats al = let x = Array.init (ncols al) ~f:(fun column -> residues al ~column |> Char.Set.length ) in Binning.counts (Caml.Array.to_seq x) |> Caml.List.of_seq let composition al = let module C = Binning.Counter in let acc = C.create () in let n = float (nrows al * ncols al) in Array.iter al.sequences ~f:(fun s -> String.iter s ~f:(fun c -> C.tick acc c) ) ; Caml.Seq.map (fun (c, k) -> (c, float k /. n)) (Binning.seq acc) |> Caml.List.of_seq let constant_site al j = let m = nrows al in let rec find_state i = if i < m then match al.sequences.(i).[j] with | '-' -> find_state (i + 1) | c -> find_other_state c (i + 1) else true and find_other_state c i = if i < m then match al.sequences.(i).[j] with | '-' -> find_other_state c (i + 1) | c' when Char.equal c c' -> find_other_state c (i + 1) | _ -> false else true in find_state 0 open Core module Make(S : Seq.S) = struct type base = S.base type sequence = S.t type index = string type t = (index, sequence) Hashtbl.t module Sequence = S let get_base tab ~seq ~pos = S.get (Hashtbl.find_exn tab seq) pos let of_assoc_list l = let align = String.Table.create ~size:(List.length l) () in List.iter ~f:(fun (i,s) -> Hashtbl.add_exn ~key:i ~data:s align) l ; align let of_string_list l = let align = String.Table.create ~size:(List.length l) () in arbitrarily indexes sequences by string Ti where i is an integer ; this mimics the format used by bppseqgen this mimics the format used by bppseqgen *) List.iteri ~f:(fun i s -> Hashtbl.add_exn ~key:(Printf.sprintf "T%d" i) ~data:(S.of_string_exn s) align) l ; align let of_fasta filename = placeholder size TODO let _, items = Biotk.Fasta.from_file_exn filename in List.iter items ~f:(fun item -> let data = S.of_string_exn item.Biotk.Fasta.sequence in Hashtbl.add_exn ~key:item.Biotk.Fasta.description ~data:data align ) ; align let length x = (* this is the length of the sequences, not the nb of sequences! *) if Hashtbl.is_empty x then invalid_arg "empty alignment" else Hashtbl.fold x ~init:0 ~f:(fun ~key:_ ~data acc -> let l = S.length data in if l=0 then invalid_arg "alignment with empty sequence" else if acc<>0 && acc<>l then invalid_arg "sequence length mismatch" else l (* returns only if all lengths were equal *) ) let nb_seq x = Hashtbl.length x let pp fmt x = Hashtbl.to_alist x |> List.map ~f:(fun (i,s) -> Printf.sprintf "%s: %s" i (S.to_string s)) |> String.concat ~sep:"\n" |> Format.fprintf fmt "%s" let to_file x filename = Hashtbl.to_alist x |> List.map ~f:(fun (i,s) -> Printf.sprintf ">%s\n%s" i (S.to_string s)) |> Out_channel.write_lines filename let equal (x : t) y = Hashtbl.equal Poly.equal x y end
null
https://raw.githubusercontent.com/biocaml/phylogenetics/3697dcf2f94485fea680718bdec7d59edf962ad3/lib/alignment.ml
ocaml
this is the length of the sequences, not the nb of sequences! returns only if all lengths were equal
open Core type t = { descriptions : string array ; sequences : string array ; } let sequence t i = t.sequences.(i) let description t i = t.descriptions.(i) let nrows a = Array.length a.sequences let ncols a = String.length a.sequences.(0) type error = [ | `Empty_alignment | `Unequal_sequence_lengths ] [@@deriving show] type parsing_error = [ | `Fasta_parser_error of string | error ] [@@deriving show] let check_non_empty_list = function | [] -> Error (`Empty_alignment) | items -> Ok items let of_tuples items = let descriptions, sequences = Array.unzip items in let n = String.length sequences.(0) in if (Array.for_all sequences ~f:(fun s -> String.length s = n)) then Ok { descriptions ; sequences ; } else Error `Unequal_sequence_lengths let of_assoc_list l = match check_non_empty_list l with | Ok items -> Array.of_list items |> of_tuples | Error e -> Error e let map t ~f = Array.map2_exn t.descriptions t.sequences ~f:(fun description sequence -> f ~description ~sequence) |> of_tuples let array_mapi t ~f = Array.mapi t.descriptions ~f:(fun i description -> f i ~description ~sequence:t.sequences.(i)) let fold t ~init ~f = Array.fold2_exn t.descriptions t.sequences ~init ~f:(fun acc description sequence -> f acc ~description ~sequence) module Fasta = struct let of_fasta_items (items:Biotk.Fasta.item list) = List.map items ~f:(fun x -> x.description, x.sequence) |> of_assoc_list let from_file fn = let open Biotk.Let_syntax.Result in let* _, items = Biotk.Fasta.from_file fn |> Result.map_error ~f:(fun msg -> `Fasta_parser_error msg) in of_fasta_items items let from_file_exn fn = match from_file fn with | Ok al -> al | Error e -> failwith (show_parsing_error e) let to_channel ({sequences ; descriptions}) oc = Array.iter2_exn descriptions sequences ~f:(fun desc seq -> Out_channel.output_lines oc [ sprintf ">%s" desc ; seq; ]) let to_file al fn = Out_channel.with_file fn ~f:(to_channel al) end let find_sequence t id = Array.findi t.descriptions ~f:(fun _ x -> String.equal x id) |> Option.map ~f:(fun (i, _) -> t.sequences.(i)) let indel_free_columns ali = Array.init (nrows ali) ~f:(fun j -> Array.for_all ali.sequences ~f:(fun s -> Char.(s.[j] <> '-')) ) let residues al ~column:j = if j < 0 || j > ncols al then raise (Invalid_argument "Alignment.residues") ; Array.fold al.sequences ~init:Char.Set.empty ~f:(fun acc s -> Char.Set.add acc s.[j]) let number_of_residues_per_column_stats al = let x = Array.init (ncols al) ~f:(fun column -> residues al ~column |> Char.Set.length ) in Binning.counts (Caml.Array.to_seq x) |> Caml.List.of_seq let composition al = let module C = Binning.Counter in let acc = C.create () in let n = float (nrows al * ncols al) in Array.iter al.sequences ~f:(fun s -> String.iter s ~f:(fun c -> C.tick acc c) ) ; Caml.Seq.map (fun (c, k) -> (c, float k /. n)) (Binning.seq acc) |> Caml.List.of_seq let constant_site al j = let m = nrows al in let rec find_state i = if i < m then match al.sequences.(i).[j] with | '-' -> find_state (i + 1) | c -> find_other_state c (i + 1) else true and find_other_state c i = if i < m then match al.sequences.(i).[j] with | '-' -> find_other_state c (i + 1) | c' when Char.equal c c' -> find_other_state c (i + 1) | _ -> false else true in find_state 0 open Core module Make(S : Seq.S) = struct type base = S.base type sequence = S.t type index = string type t = (index, sequence) Hashtbl.t module Sequence = S let get_base tab ~seq ~pos = S.get (Hashtbl.find_exn tab seq) pos let of_assoc_list l = let align = String.Table.create ~size:(List.length l) () in List.iter ~f:(fun (i,s) -> Hashtbl.add_exn ~key:i ~data:s align) l ; align let of_string_list l = let align = String.Table.create ~size:(List.length l) () in arbitrarily indexes sequences by string Ti where i is an integer ; this mimics the format used by bppseqgen this mimics the format used by bppseqgen *) List.iteri ~f:(fun i s -> Hashtbl.add_exn ~key:(Printf.sprintf "T%d" i) ~data:(S.of_string_exn s) align) l ; align let of_fasta filename = placeholder size TODO let _, items = Biotk.Fasta.from_file_exn filename in List.iter items ~f:(fun item -> let data = S.of_string_exn item.Biotk.Fasta.sequence in Hashtbl.add_exn ~key:item.Biotk.Fasta.description ~data:data align ) ; align if Hashtbl.is_empty x then invalid_arg "empty alignment" else Hashtbl.fold x ~init:0 ~f:(fun ~key:_ ~data acc -> let l = S.length data in if l=0 then invalid_arg "alignment with empty sequence" else if acc<>0 && acc<>l then invalid_arg "sequence length mismatch" ) let nb_seq x = Hashtbl.length x let pp fmt x = Hashtbl.to_alist x |> List.map ~f:(fun (i,s) -> Printf.sprintf "%s: %s" i (S.to_string s)) |> String.concat ~sep:"\n" |> Format.fprintf fmt "%s" let to_file x filename = Hashtbl.to_alist x |> List.map ~f:(fun (i,s) -> Printf.sprintf ">%s\n%s" i (S.to_string s)) |> Out_channel.write_lines filename let equal (x : t) y = Hashtbl.equal Poly.equal x y end
04a2a5f5b110a37dc31ed5ef15c62c575de92dc91925af58e26afe5c8327e848
renatoalencar/milho-ocaml
milho_core.ml
exception Invalid_argument of string let sum args = let sum a b = match a, b with | Value.Number (an, ad), Value.Number (bn, bd) -> Value.Number ((an * bd) + (bn *ad), ad * bd) | _ -> Value.Nil in List.fold_left sum (Number (0, 1)) args let sub args = let negative x = match x with | Value.Number (a, b) -> Value.Number (-a, b) | _ -> Value.Nil in let sub a b = match a with | Value.Nil -> b | Value.Number _ -> sum [a; (negative b)] | _ -> Value.Nil in List.fold_left sub Value.Nil args let mul args = let mul a b = match a, b with | Value.Number (an, ad), Value.Number (bn, bd) -> Value.Number (an * bn, ad * bd) | _ -> Value.Nil in List.fold_left mul (Number (1, 1)) args let div args = let inverse x = match x with | Value.Number (a, b) -> Value.Number (b, a) | _ -> Value.Nil in let div a b = match a with | Value.Nil -> b | Value.Number _ -> mul [a; (inverse b)] | _ -> Value.Nil in List.fold_left div Value.Nil args let abs args = match args with | Value.Number (n, d) :: [] -> Value.Number (Stdlib.abs n, Stdlib.abs d) | _ -> raise (Invalid_argument "Milho_core.abs") let cmp args = match args with | a :: b :: _ -> let a = abs [a] in let b = abs [b] in sub [a; b] | _ -> Value.Nil let less_than args = match cmp args with | Value.Number (n, _) -> Value.of_boolean (n < 0) | _ -> raise (Invalid_argument "Milho_core.less_than") let greater_than args = match cmp args with | Value.Number (n, _) -> Value.of_boolean (n > 0) | _ -> raise (Invalid_argument "Milho_core.less_than") let equal args = match args with | a :: b :: _ -> ( match a, b with | Value.Symbol a, Value.Symbol b -> Value.of_boolean (a == b) | Value.String a, Value.String b -> Value.of_boolean (a == b) | Value.True, Value.True -> Value.True | Value.False, Value.False -> Value.True | Value.Nil, Value.Nil -> Value.True | Value.Number _, Value.Number _ -> Value.of_boolean (Value.to_number a = Value.to_number b) | _ -> Value.False ) | _ -> raise (Invalid_argument "Milho_core.equal") let str args = args |> List.map Value.to_string |> String.concat " " let println args = args |> str |> print_endline; Value.Nil let rec cons args = match args with | [] -> Value.List [] | value :: [] -> Value.List [value] | value :: lst :: [] -> ( match lst with | Value.List lst -> Value.List (value :: lst) | v -> Value.List [value; v] ) | value :: rest -> cons [value; (cons rest)] let car args = match args with | Value.List (value :: _) :: [] -> value | _ -> raise (Invalid_argument "Milho_core.car") let cdr args = match args with | Value.List (_ :: tl ) :: [] -> Value.List tl | _ -> raise (Invalid_argument "Milho_core.cdr") let length args = match args with | Value.List lst :: [] -> Value.Number (List.length lst, 1) | _ -> raise (Invalid_argument "Milho_core.length")
null
https://raw.githubusercontent.com/renatoalencar/milho-ocaml/9e0f75e3d531f927851604631dca453ee814949b/milho_core.ml
ocaml
exception Invalid_argument of string let sum args = let sum a b = match a, b with | Value.Number (an, ad), Value.Number (bn, bd) -> Value.Number ((an * bd) + (bn *ad), ad * bd) | _ -> Value.Nil in List.fold_left sum (Number (0, 1)) args let sub args = let negative x = match x with | Value.Number (a, b) -> Value.Number (-a, b) | _ -> Value.Nil in let sub a b = match a with | Value.Nil -> b | Value.Number _ -> sum [a; (negative b)] | _ -> Value.Nil in List.fold_left sub Value.Nil args let mul args = let mul a b = match a, b with | Value.Number (an, ad), Value.Number (bn, bd) -> Value.Number (an * bn, ad * bd) | _ -> Value.Nil in List.fold_left mul (Number (1, 1)) args let div args = let inverse x = match x with | Value.Number (a, b) -> Value.Number (b, a) | _ -> Value.Nil in let div a b = match a with | Value.Nil -> b | Value.Number _ -> mul [a; (inverse b)] | _ -> Value.Nil in List.fold_left div Value.Nil args let abs args = match args with | Value.Number (n, d) :: [] -> Value.Number (Stdlib.abs n, Stdlib.abs d) | _ -> raise (Invalid_argument "Milho_core.abs") let cmp args = match args with | a :: b :: _ -> let a = abs [a] in let b = abs [b] in sub [a; b] | _ -> Value.Nil let less_than args = match cmp args with | Value.Number (n, _) -> Value.of_boolean (n < 0) | _ -> raise (Invalid_argument "Milho_core.less_than") let greater_than args = match cmp args with | Value.Number (n, _) -> Value.of_boolean (n > 0) | _ -> raise (Invalid_argument "Milho_core.less_than") let equal args = match args with | a :: b :: _ -> ( match a, b with | Value.Symbol a, Value.Symbol b -> Value.of_boolean (a == b) | Value.String a, Value.String b -> Value.of_boolean (a == b) | Value.True, Value.True -> Value.True | Value.False, Value.False -> Value.True | Value.Nil, Value.Nil -> Value.True | Value.Number _, Value.Number _ -> Value.of_boolean (Value.to_number a = Value.to_number b) | _ -> Value.False ) | _ -> raise (Invalid_argument "Milho_core.equal") let str args = args |> List.map Value.to_string |> String.concat " " let println args = args |> str |> print_endline; Value.Nil let rec cons args = match args with | [] -> Value.List [] | value :: [] -> Value.List [value] | value :: lst :: [] -> ( match lst with | Value.List lst -> Value.List (value :: lst) | v -> Value.List [value; v] ) | value :: rest -> cons [value; (cons rest)] let car args = match args with | Value.List (value :: _) :: [] -> value | _ -> raise (Invalid_argument "Milho_core.car") let cdr args = match args with | Value.List (_ :: tl ) :: [] -> Value.List tl | _ -> raise (Invalid_argument "Milho_core.cdr") let length args = match args with | Value.List lst :: [] -> Value.Number (List.length lst, 1) | _ -> raise (Invalid_argument "Milho_core.length")
ec39ec3b75327b064c43c5dea88c0b2b83691c8faa8bd034d6e62d66509f52e2
mbutterick/typesetting
test0.rkt
#lang racket/base (require pitfall/pdftest) (define-runtime-path pdf "test0rkt.pdf") (make-doc pdf #f) (define-runtime-path pdfc "test0crkt.pdf") (make-doc pdfc #t)
null
https://raw.githubusercontent.com/mbutterick/typesetting/6f7a8bbc422a64d3a54cbbbd78801a01410f5c92/pitfall/ptest/test0.rkt
racket
#lang racket/base (require pitfall/pdftest) (define-runtime-path pdf "test0rkt.pdf") (make-doc pdf #f) (define-runtime-path pdfc "test0crkt.pdf") (make-doc pdfc #t)
017c7eb0621ea55ea54049b7f1ef1381dbfa7f71403902b639e10db40c878059
charlieg/Sparser
initialize1.lisp
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- copyright ( c ) 1997 - 2005 -- all rights reserved extensions copyright ( c ) 2009 BBNT Solutions LLC . All Rights Reserved $ Id:$ ;;; ;;; File: "initialize" ;;; Module: "objects;model:lattice-points:" version : 1.0 August 2009 initiated 11/29/97 . Moved code in from other files 7/7/98 . 9/3/99 renamed Construct - self - lattice - point to avoid brain - dead conflict with the constructor of the structure . 9/7 extended that routine to set the ;; upward pointer of the new node so that you can successfully climb ;; through it. 3/20/00 Added to Index-node-to-top-point so that it would ;; properly set the down pointers of the top-lp, thereby fixing bug that ;; find wasn't working. 0.1 ( 6/21 ) Reworked the constructors to use the resource mechanism . ( 2/8/05 ) Added category - of - self - lattice - point . ( 2/9 ) fixed bug in ;; Index-node-to-top-point when the entry exists but the new lp node is n't in it and there 's just one lp in the entry at this point . ( 2/17 ) fixed ;; problem with Find-self-node returning a list instead of the self-lp. 1.0 ( 7/22/09 ) Fan out from simplifying the indexing structure and putting more on the psi . Working on it through 8/6 . (in-package :sparser) ;;;------------- ;;; entry point ;;;------------- ;; Called from decode-category-parameter-list. Returned value becomes ;; the value of the category's lattice-position field. (defun initialize-top-lattice-point (category &key specializes) (let ((lp (get-lp 'top-lattice-point :category category :super-category specializes)) (vars (cat-slots category))) (setf (lp-variables-bound lp) nil) (setf (lp-variables-free lp) vars) (setf (lp-down-pointers lp) nil) (setf (lp-subtypes lp) nil) (setf (lp-top-psi lp) nil) (setf (lp-top-lp lp) lp) lp )) ;;;----------------------------------------------------- ;;; The lattice point that soaks up the category per-se ;;;----------------------------------------------------- (defun find-self-node (category) ;;/// Since "self" nodes aren't being used (they would have soaked ;; up the category per-se, which doesn't seem useful right now. ;; Maybe later when we use rnodes), this should be renamed (cat-lattice-position category)) (defun construct-self-lattice-point (category top-lp) (break "construct-self-lattice-point") (let ((node (get-lp 'self-lattice-point))) (setf (lp-variables-bound node) (list category)) (setf (lp-variables-free node) (remove category (lp-variables-free top-lp))) (setf (lp-upward-pointers node) (list top-lp)) (setf (lp-down-pointers node) nil) (index-node-to-top-point category node top-lp) (tr :make-self-lp top-lp) node)) (defun category-of-self-lattice-point (lp) (dolist (var (lp-variables-bound lp)) (when (typep var 'referential-category) (return-from category-of-self-lattice-point var))) (break "Cannot locate the categor of the self-lattice-point~%~a" lp)) ;;;----------------------- ;;; middle lattice-points ;;;----------------------- ;; Given a lattice-point, construct the node below it that ;; binds this particular variable (defun new-lattice-point (starting-lattice-point variable) (let ((node (get-lp 'lattice-point)) (top (lp-top-lp starting-lattice-point))) (setf (lp-variables-bound node) (cons variable (lp-variables-bound starting-lattice-point))) (setf (lp-variables-free node) (remove variable (lp-variables-free starting-lattice-point))) (setf (lp-down-pointers node) nil) ( setf ( lp - upward - pointers node ) ( list starting - lattice - point ) ) ;; (index-node-to-top-point variable node top-lp) (index-lp-to-top-lp node top) (setf (lp-top-lp node) top) (tr :created-lp-to-extend-lp-via-var node starting-lattice-point variable) node )) ;;;---------- ;;; indexing ;;;---------- (defun cross-index-node-to-top-point (node top-lp) (break "Probably shouldn't call cross-index-node-to-top-point") (dolist (var (lp-variables-bound node)) (index-node-to-top-point var node top-lp))) (defun index-lp-to-top-lp (lp top-lp) ;; goes with find-lattice-point-with-variables1, which will have ;; returned nil before this is called. (let* ((number-of-variables-bound (length (lp-variables-bound lp))) (entry (when (lp-subnodes top-lp) (assq number-of-variables-bound (lp-subnodes top-lp))))) (cond (entry (rplacd entry (cons lp (cdr entry)))) (t (push `(,number-of-variables-bound ,lp) (lp-subnodes top-lp)))))) ;; Not using this. But it's suggestive of what can be done on the ;; psi themselves (intermediary of using LP is too intricate to get the interning and ' find ' operations correct -- 8/09 . (defun index-node-to-top-point (variable node top-lp) (break "Shouldn't be calling index-node-to-top-point") 1 . put a value in the index - by - variable field (let ((field (lp-index-by-variable top-lp))) (if (null field) (setf (lp-index-by-variable top-lp) `( (,variable ,node) )) (let ((variable-entry (assoc variable field))) (if (null variable-entry) (setf (lp-index-by-variable top-lp) (cons `(,variable ,node) field)) (rplacd variable-entry (cons node (cdr variable-entry))))))) 2 . Set the down link (let ((down-links (lp-down-pointers top-lp))) (if (null down-links) ;; no downlinks before (setf (lp-down-pointers top-lp) `( (,variable . ,node) )) (let ((entry (assq variable down-links))) ;; no downlink for this variable (if (null entry) (push `(,variable . ,node) (lp-down-pointers top-lp)) ;; no downlink from this variable to this sub-lattice-point (if (and (consp (cdr entry)) (null (memq node (cdr entry)))) (rplacd (cdr entry) (cons node (cdr entry))) (rplacd entry (list node (cdr entry))))))))) ;;;------------------------ ;;; clearing out a lattice ;;;------------------------ (defun clear-lattice (category) (let ((top-lp (cat-lattice-position category))) (reclaim-lattice (find-lp-daughter category top-lp)) (setf (lp-index-by-variable top-lp) nil))) (defun reclaim-lattice (top-lp) (when top-lp (dolist (lp (lp-down-pointers top-lp)) (reclaim-lattice lp)) (reclaim-lattice-point top-lp))) (defun reclaim-lattice-point (lp) ;; Stub for when resources are used. (declare (ignore lp)))
null
https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/objects/model/lattice-points/initialize1.lisp
lisp
-*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- File: "initialize" Module: "objects;model:lattice-points:" upward pointer of the new node so that you can successfully climb through it. 3/20/00 Added to Index-node-to-top-point so that it would properly set the down pointers of the top-lp, thereby fixing bug that find wasn't working. Index-node-to-top-point when the entry exists but the new lp node problem with Find-self-node returning a list instead of the self-lp. ------------- entry point ------------- Called from decode-category-parameter-list. Returned value becomes the value of the category's lattice-position field. ----------------------------------------------------- The lattice point that soaks up the category per-se ----------------------------------------------------- /// Since "self" nodes aren't being used (they would have soaked up the category per-se, which doesn't seem useful right now. Maybe later when we use rnodes), this should be renamed ----------------------- middle lattice-points ----------------------- Given a lattice-point, construct the node below it that binds this particular variable (index-node-to-top-point variable node top-lp) ---------- indexing ---------- goes with find-lattice-point-with-variables1, which will have returned nil before this is called. Not using this. But it's suggestive of what can be done on the psi themselves (intermediary of using LP is too intricate to get no downlinks before no downlink for this variable no downlink from this variable to this sub-lattice-point ------------------------ clearing out a lattice ------------------------ Stub for when resources are used.
copyright ( c ) 1997 - 2005 -- all rights reserved extensions copyright ( c ) 2009 BBNT Solutions LLC . All Rights Reserved $ Id:$ version : 1.0 August 2009 initiated 11/29/97 . Moved code in from other files 7/7/98 . 9/3/99 renamed Construct - self - lattice - point to avoid brain - dead conflict with the constructor of the structure . 9/7 extended that routine to set the 0.1 ( 6/21 ) Reworked the constructors to use the resource mechanism . ( 2/8/05 ) Added category - of - self - lattice - point . ( 2/9 ) fixed bug in is n't in it and there 's just one lp in the entry at this point . ( 2/17 ) fixed 1.0 ( 7/22/09 ) Fan out from simplifying the indexing structure and putting more on the psi . Working on it through 8/6 . (in-package :sparser) (defun initialize-top-lattice-point (category &key specializes) (let ((lp (get-lp 'top-lattice-point :category category :super-category specializes)) (vars (cat-slots category))) (setf (lp-variables-bound lp) nil) (setf (lp-variables-free lp) vars) (setf (lp-down-pointers lp) nil) (setf (lp-subtypes lp) nil) (setf (lp-top-psi lp) nil) (setf (lp-top-lp lp) lp) lp )) (defun find-self-node (category) (cat-lattice-position category)) (defun construct-self-lattice-point (category top-lp) (break "construct-self-lattice-point") (let ((node (get-lp 'self-lattice-point))) (setf (lp-variables-bound node) (list category)) (setf (lp-variables-free node) (remove category (lp-variables-free top-lp))) (setf (lp-upward-pointers node) (list top-lp)) (setf (lp-down-pointers node) nil) (index-node-to-top-point category node top-lp) (tr :make-self-lp top-lp) node)) (defun category-of-self-lattice-point (lp) (dolist (var (lp-variables-bound lp)) (when (typep var 'referential-category) (return-from category-of-self-lattice-point var))) (break "Cannot locate the categor of the self-lattice-point~%~a" lp)) (defun new-lattice-point (starting-lattice-point variable) (let ((node (get-lp 'lattice-point)) (top (lp-top-lp starting-lattice-point))) (setf (lp-variables-bound node) (cons variable (lp-variables-bound starting-lattice-point))) (setf (lp-variables-free node) (remove variable (lp-variables-free starting-lattice-point))) (setf (lp-down-pointers node) nil) ( setf ( lp - upward - pointers node ) ( list starting - lattice - point ) ) (index-lp-to-top-lp node top) (setf (lp-top-lp node) top) (tr :created-lp-to-extend-lp-via-var node starting-lattice-point variable) node )) (defun cross-index-node-to-top-point (node top-lp) (break "Probably shouldn't call cross-index-node-to-top-point") (dolist (var (lp-variables-bound node)) (index-node-to-top-point var node top-lp))) (defun index-lp-to-top-lp (lp top-lp) (let* ((number-of-variables-bound (length (lp-variables-bound lp))) (entry (when (lp-subnodes top-lp) (assq number-of-variables-bound (lp-subnodes top-lp))))) (cond (entry (rplacd entry (cons lp (cdr entry)))) (t (push `(,number-of-variables-bound ,lp) (lp-subnodes top-lp)))))) the interning and ' find ' operations correct -- 8/09 . (defun index-node-to-top-point (variable node top-lp) (break "Shouldn't be calling index-node-to-top-point") 1 . put a value in the index - by - variable field (let ((field (lp-index-by-variable top-lp))) (if (null field) (setf (lp-index-by-variable top-lp) `( (,variable ,node) )) (let ((variable-entry (assoc variable field))) (if (null variable-entry) (setf (lp-index-by-variable top-lp) (cons `(,variable ,node) field)) (rplacd variable-entry (cons node (cdr variable-entry))))))) 2 . Set the down link (let ((down-links (lp-down-pointers top-lp))) (if (null down-links) (setf (lp-down-pointers top-lp) `( (,variable . ,node) )) (let ((entry (assq variable down-links))) (if (null entry) (push `(,variable . ,node) (lp-down-pointers top-lp)) (if (and (consp (cdr entry)) (null (memq node (cdr entry)))) (rplacd (cdr entry) (cons node (cdr entry))) (rplacd entry (list node (cdr entry))))))))) (defun clear-lattice (category) (let ((top-lp (cat-lattice-position category))) (reclaim-lattice (find-lp-daughter category top-lp)) (setf (lp-index-by-variable top-lp) nil))) (defun reclaim-lattice (top-lp) (when top-lp (dolist (lp (lp-down-pointers top-lp)) (reclaim-lattice lp)) (reclaim-lattice-point top-lp))) (defun reclaim-lattice-point (lp) (declare (ignore lp)))
44783702394a0b080dc554b319a8b5cacdf64125a5925cea2a6751bcfa2785b0
basho/riak_shell
debug_EXT.erl
%% ------------------------------------------------------------------- %% %% debug extension for riak_shell %% Copyright ( c ) 2007 - 2016 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. %% %% ------------------------------------------------------------------- -module(debug_EXT). %% NOTE this is the only extention that is not loaded when you run the load commmand %% PLEASE DO NOT add additional functions to this module -export([ help/1, load/2, observer/2 ]). -ignore_xref([ help/1, load/2, observer/2 ]). -include("riak_shell.hrl"). help(observer) -> "Typing `observer;` starts the Erlang observer application."; help(load) -> "This is for developing extensions only.~n~n" "Typing `load;` reloads all the EXT modules after they have been~n" "compiled. This only works after a module has been compiled and~n" "loaded the first time.~n~n" "The first time you create a module you will need to stop and~n" "restart the shell.~n~n" "If you invoke this command via the history command it will crash~n" "the shell.". observer(Cmd, #state{} = State) -> observer:start(), {Cmd#command{response = "Observer started", log_this_cmd = false}, State}. load(Cmd, #state{} = State) -> NewState = riak_shell:register_extensions(State), {Cmd#command{response = "Modules reloaded.", log_this_cmd = false}, NewState}.
null
https://raw.githubusercontent.com/basho/riak_shell/afc4b7c04925f8accaa5b32ee0253d8c0ddc5000/src/debug_EXT.erl
erlang
------------------------------------------------------------------- debug extension for riak_shell 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. ------------------------------------------------------------------- NOTE this is the only extention that is not loaded when you run the load commmand PLEASE DO NOT add additional functions to this module
Copyright ( c ) 2007 - 2016 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 -module(debug_EXT). -export([ help/1, load/2, observer/2 ]). -ignore_xref([ help/1, load/2, observer/2 ]). -include("riak_shell.hrl"). help(observer) -> "Typing `observer;` starts the Erlang observer application."; help(load) -> "This is for developing extensions only.~n~n" "Typing `load;` reloads all the EXT modules after they have been~n" "compiled. This only works after a module has been compiled and~n" "loaded the first time.~n~n" "The first time you create a module you will need to stop and~n" "restart the shell.~n~n" "If you invoke this command via the history command it will crash~n" "the shell.". observer(Cmd, #state{} = State) -> observer:start(), {Cmd#command{response = "Observer started", log_this_cmd = false}, State}. load(Cmd, #state{} = State) -> NewState = riak_shell:register_extensions(State), {Cmd#command{response = "Modules reloaded.", log_this_cmd = false}, NewState}.
45c5e46a2f0edc139a2efcbb9e3b0348184b4beeabda4da6477a4bf6737fafab
SKA-ScienceDataProcessor/RC
Activity.hs
module Profiling.CUDA.Activity ( cuptiEnable, cuptiDisable, cuptiFlush , CUptiMemLoc(..) , cuptiGetMemsetTime, cuptiGetMemcpyTime , cuptiGetKernelTime, cuptiGetOverheadTime , cuptiGetMemsetBytes, cuptiGetMemcpyBytes , cuptiGetMemcpyTimeTo, cuptiGetMemcpyBytesTo ) where import Control.Monad (when) import Data.Word import Foreign.C.Types import Foreign.C.String import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import GHC.IO.Exception ( IOException(..), IOErrorType(..) ) foreign import ccall unsafe "cupti_enable" c_cupti_enable :: IO CInt foreign import ccall unsafe "cupti_disable" c_cupti_disable :: IO () foreign import ccall unsafe "cupti_getMemsetTime" c_cupti_getMemsetTime :: IO Word64 foreign import ccall unsafe "cupti_getMemcpyTime" c_cupti_getMemcpyTime :: CInt -> CInt -> IO Word64 foreign import ccall unsafe "cupti_getKernelTime" c_cupti_getKernelTime :: IO Word64 foreign import ccall unsafe "cupti_getOverheadTime" c_cupti_getOverheadTime :: IO Word64 --foreign import ccall unsafe "cupti_getDroppedRecords" c_cupti_getDroppedRecords : : IO CInt foreign import ccall unsafe "cupti_getMemsetBytes" c_cupti_getMemsetBytes :: IO Word64 foreign import ccall unsafe "cupti_getMemcpyBytes" c_cupti_getMemcpyBytes :: CInt -> CInt -> IO Word64 foreign import ccall unsafe "cuptiActivityFlushAll" c_cuptiActivityFlushAll :: Word32 -> IO CInt foreign import ccall unsafe "cuptiGetResultString" c_cuptiGetResultString :: CInt -> Ptr CString -> IO () -- | Enables CUDA activity monitoring, starting the counters. cuptiEnable :: IO () cuptiEnable = do res <- c_cupti_enable when (res /= 0) $ do alloca $ \pstr -> do c_cuptiGetResultString res pstr resStr <- peekCString =<< peek pstr ioError IOError { ioe_handle = Nothing , ioe_type = IllegalOperation , ioe_location = "cuptiActivityEnable" , ioe_description = resStr , ioe_errno = Nothing , ioe_filename = Nothing } -- | Disables CUDA activity monitoring cuptiDisable :: IO () cuptiDisable = c_cupti_disable -- | Flushes CUDA performance counters cuptiFlush :: IO () cuptiFlush = do res <- c_cuptiActivityFlushAll 0 when (res /= 0) $ do alloca $ \pstr -> do c_cuptiGetResultString res pstr resStr <- peekCString =<< peek pstr ioError IOError { ioe_handle = Nothing , ioe_type = IllegalOperation , ioe_location = "cuptiActivityFlushAll" , ioe_description = resStr , ioe_errno = Nothing , ioe_filename = Nothing } -- | Queries times. The return values are the sum of times spend on -- certain actions. Note that with parallel execution, this might -- advance faster than the clock. cuptiGetMemsetTime, cuptiGetKernelTime, cuptiGetOverheadTime, cuptiGetMemsetBytes :: IO Integer cuptiGetMemsetTime = fmap fromIntegral c_cupti_getMemsetTime cuptiGetKernelTime = fmap fromIntegral c_cupti_getKernelTime cuptiGetOverheadTime = fmap fromIntegral c_cupti_getOverheadTime cuptiGetMemsetBytes = fmap fromIntegral c_cupti_getMemsetBytes -- | A memory location for memory transfers data CUptiMemLoc = CUptiHost | CUptiDevice | CUptiArray deriving (Eq, Enum) allLocs :: [CUptiMemLoc] allLocs = [(CUptiHost)..(CUptiArray)] cuptiGetMemcpyTime :: CUptiMemLoc -> CUptiMemLoc -> IO Integer cuptiGetMemcpyTime from to = fmap fromIntegral $ c_cupti_getMemcpyTime (fromIntegral (fromEnum from)) (fromIntegral (fromEnum to)) cuptiGetMemcpyBytes :: CUptiMemLoc -> CUptiMemLoc -> IO Integer cuptiGetMemcpyBytes from to = fmap fromIntegral $ c_cupti_getMemcpyBytes (fromIntegral (fromEnum from)) (fromIntegral (fromEnum to)) cuptiGetMemcpyTimeTo :: CUptiMemLoc -> IO Integer cuptiGetMemcpyTimeTo to = sum `fmap` mapM (flip cuptiGetMemcpyTime to) allLocs cuptiGetMemcpyBytesTo :: CUptiMemLoc -> IO Integer cuptiGetMemcpyBytesTo to = sum `fmap` mapM (flip cuptiGetMemcpyBytes to) allLocs
null
https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS6/dna/cupti/Profiling/CUDA/Activity.hs
haskell
foreign import ccall unsafe "cupti_getDroppedRecords" | Enables CUDA activity monitoring, starting the counters. | Disables CUDA activity monitoring | Flushes CUDA performance counters | Queries times. The return values are the sum of times spend on certain actions. Note that with parallel execution, this might advance faster than the clock. | A memory location for memory transfers
module Profiling.CUDA.Activity ( cuptiEnable, cuptiDisable, cuptiFlush , CUptiMemLoc(..) , cuptiGetMemsetTime, cuptiGetMemcpyTime , cuptiGetKernelTime, cuptiGetOverheadTime , cuptiGetMemsetBytes, cuptiGetMemcpyBytes , cuptiGetMemcpyTimeTo, cuptiGetMemcpyBytesTo ) where import Control.Monad (when) import Data.Word import Foreign.C.Types import Foreign.C.String import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import GHC.IO.Exception ( IOException(..), IOErrorType(..) ) foreign import ccall unsafe "cupti_enable" c_cupti_enable :: IO CInt foreign import ccall unsafe "cupti_disable" c_cupti_disable :: IO () foreign import ccall unsafe "cupti_getMemsetTime" c_cupti_getMemsetTime :: IO Word64 foreign import ccall unsafe "cupti_getMemcpyTime" c_cupti_getMemcpyTime :: CInt -> CInt -> IO Word64 foreign import ccall unsafe "cupti_getKernelTime" c_cupti_getKernelTime :: IO Word64 foreign import ccall unsafe "cupti_getOverheadTime" c_cupti_getOverheadTime :: IO Word64 c_cupti_getDroppedRecords : : IO CInt foreign import ccall unsafe "cupti_getMemsetBytes" c_cupti_getMemsetBytes :: IO Word64 foreign import ccall unsafe "cupti_getMemcpyBytes" c_cupti_getMemcpyBytes :: CInt -> CInt -> IO Word64 foreign import ccall unsafe "cuptiActivityFlushAll" c_cuptiActivityFlushAll :: Word32 -> IO CInt foreign import ccall unsafe "cuptiGetResultString" c_cuptiGetResultString :: CInt -> Ptr CString -> IO () cuptiEnable :: IO () cuptiEnable = do res <- c_cupti_enable when (res /= 0) $ do alloca $ \pstr -> do c_cuptiGetResultString res pstr resStr <- peekCString =<< peek pstr ioError IOError { ioe_handle = Nothing , ioe_type = IllegalOperation , ioe_location = "cuptiActivityEnable" , ioe_description = resStr , ioe_errno = Nothing , ioe_filename = Nothing } cuptiDisable :: IO () cuptiDisable = c_cupti_disable cuptiFlush :: IO () cuptiFlush = do res <- c_cuptiActivityFlushAll 0 when (res /= 0) $ do alloca $ \pstr -> do c_cuptiGetResultString res pstr resStr <- peekCString =<< peek pstr ioError IOError { ioe_handle = Nothing , ioe_type = IllegalOperation , ioe_location = "cuptiActivityFlushAll" , ioe_description = resStr , ioe_errno = Nothing , ioe_filename = Nothing } cuptiGetMemsetTime, cuptiGetKernelTime, cuptiGetOverheadTime, cuptiGetMemsetBytes :: IO Integer cuptiGetMemsetTime = fmap fromIntegral c_cupti_getMemsetTime cuptiGetKernelTime = fmap fromIntegral c_cupti_getKernelTime cuptiGetOverheadTime = fmap fromIntegral c_cupti_getOverheadTime cuptiGetMemsetBytes = fmap fromIntegral c_cupti_getMemsetBytes data CUptiMemLoc = CUptiHost | CUptiDevice | CUptiArray deriving (Eq, Enum) allLocs :: [CUptiMemLoc] allLocs = [(CUptiHost)..(CUptiArray)] cuptiGetMemcpyTime :: CUptiMemLoc -> CUptiMemLoc -> IO Integer cuptiGetMemcpyTime from to = fmap fromIntegral $ c_cupti_getMemcpyTime (fromIntegral (fromEnum from)) (fromIntegral (fromEnum to)) cuptiGetMemcpyBytes :: CUptiMemLoc -> CUptiMemLoc -> IO Integer cuptiGetMemcpyBytes from to = fmap fromIntegral $ c_cupti_getMemcpyBytes (fromIntegral (fromEnum from)) (fromIntegral (fromEnum to)) cuptiGetMemcpyTimeTo :: CUptiMemLoc -> IO Integer cuptiGetMemcpyTimeTo to = sum `fmap` mapM (flip cuptiGetMemcpyTime to) allLocs cuptiGetMemcpyBytesTo :: CUptiMemLoc -> IO Integer cuptiGetMemcpyBytesTo to = sum `fmap` mapM (flip cuptiGetMemcpyBytes to) allLocs
18dc497997bab9f73118186b59f9a66bcdc07984618c2a858e6245e9b5d23320
shriphani/pegasus
project.clj
(defproject pegasus "0.7.1" :description "A scaleable production-ready crawler in clojure" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[clj-http "3.9.1"] [clj-named-leveldb "0.1.0"] [clj-robots "0.6.0"] [clj-time "0.14.4"] [com.taoensso/timbre "4.10.0"] [enlive "1.1.6"] [factual/clj-leveldb "0.1.1"] [fort-knox "0.4.0"] [com.github.kyleburton/clj-xpath "1.4.11"] [factual/durable-queue "0.1.5"] [me.raynes/fs "1.4.6"] [org.bovinegenius/exploding-fish "0.3.6"] [org.clojure/clojure "1.9.0"] [org.clojure/core.async "0.4.474"] [org.clojure/tools.namespace "0.2.11"] [prismatic/schema "1.1.9"] [slingshot "0.12.2"]] :plugins [[lein-ancient "0.6.8"]])
null
https://raw.githubusercontent.com/shriphani/pegasus/0ffbce77e596ae0af8d5ae9ffb85a8f1fa66914b/project.clj
clojure
(defproject pegasus "0.7.1" :description "A scaleable production-ready crawler in clojure" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[clj-http "3.9.1"] [clj-named-leveldb "0.1.0"] [clj-robots "0.6.0"] [clj-time "0.14.4"] [com.taoensso/timbre "4.10.0"] [enlive "1.1.6"] [factual/clj-leveldb "0.1.1"] [fort-knox "0.4.0"] [com.github.kyleburton/clj-xpath "1.4.11"] [factual/durable-queue "0.1.5"] [me.raynes/fs "1.4.6"] [org.bovinegenius/exploding-fish "0.3.6"] [org.clojure/clojure "1.9.0"] [org.clojure/core.async "0.4.474"] [org.clojure/tools.namespace "0.2.11"] [prismatic/schema "1.1.9"] [slingshot "0.12.2"]] :plugins [[lein-ancient "0.6.8"]])
f1aafa42355d80cc005c5030799ba1510c9b8c19bd70ff126fcc69e46ab6facf
nuprl/gradual-typing-performance
footnote.rkt
#lang scheme/base (require scribble/core scribble/decode scribble/html-properties scribble/latex-properties racket/promise setup/main-collects "private/counter.rkt") (provide note define-footnote) (define footnote-style-extras (let ([abs (lambda (s) (path->main-collects-relative (collection-file-path s "scriblib")))]) (list (make-css-addition (abs "footnote.css")) (make-tex-addition (abs "footnote.tex"))))) (define note-box-style (make-style "NoteBox" footnote-style-extras)) (define note-content-style (make-style "NoteContent" footnote-style-extras)) (define (note . text) (make-element note-box-style (make-element note-content-style (decode-content text)))) (define footnote-style (make-style "Footnote" footnote-style-extras)) (define footnote-ref-style (make-style "FootnoteRef" footnote-style-extras)) (define footnote-content-style (make-style "FootnoteContent" footnote-style-extras)) (define footnote-target-style (make-style "FootnoteTarget" footnote-style-extras)) (define footnote-block-style (make-style "FootnoteBlock" footnote-style-extras)) (define footnote-block-content-style (make-style "FootnoteBlockContent" footnote-style-extras)) (define-syntax-rule (define-footnote footnote footnote-part) (begin (define footnotes (new-counter "footnote")) (define id (gensym)) (define (footnote . text) (do-footnote footnotes id text)) (define (footnote-part . text) (do-footnote-part footnotes id)))) (define (do-footnote footnotes id text) (let ([tag (generated-tag)] [content (decode-content text)]) (make-traverse-element (lambda (get set) (set id (cons (cons (make-element footnote-target-style (make-element 'superscript (counter-target footnotes tag #f))) content) (get id null))) (make-element footnote-style (list (make-element footnote-ref-style (make-element 'superscript (counter-ref footnotes tag #f))) (make-element footnote-content-style content))))))) (define (do-footnote-part footnotes id) (make-part #f (list `(part ,(generated-tag))) #f (make-style #f '(hidden toc-hidden)) null (list (make-traverse-block (lambda (get set) (make-compound-paragraph footnote-block-style (map (lambda (content) (make-paragraph footnote-block-content-style content)) (reverse (get id null))))))) null))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/scribble-lib/scriblib/footnote.rkt
racket
#lang scheme/base (require scribble/core scribble/decode scribble/html-properties scribble/latex-properties racket/promise setup/main-collects "private/counter.rkt") (provide note define-footnote) (define footnote-style-extras (let ([abs (lambda (s) (path->main-collects-relative (collection-file-path s "scriblib")))]) (list (make-css-addition (abs "footnote.css")) (make-tex-addition (abs "footnote.tex"))))) (define note-box-style (make-style "NoteBox" footnote-style-extras)) (define note-content-style (make-style "NoteContent" footnote-style-extras)) (define (note . text) (make-element note-box-style (make-element note-content-style (decode-content text)))) (define footnote-style (make-style "Footnote" footnote-style-extras)) (define footnote-ref-style (make-style "FootnoteRef" footnote-style-extras)) (define footnote-content-style (make-style "FootnoteContent" footnote-style-extras)) (define footnote-target-style (make-style "FootnoteTarget" footnote-style-extras)) (define footnote-block-style (make-style "FootnoteBlock" footnote-style-extras)) (define footnote-block-content-style (make-style "FootnoteBlockContent" footnote-style-extras)) (define-syntax-rule (define-footnote footnote footnote-part) (begin (define footnotes (new-counter "footnote")) (define id (gensym)) (define (footnote . text) (do-footnote footnotes id text)) (define (footnote-part . text) (do-footnote-part footnotes id)))) (define (do-footnote footnotes id text) (let ([tag (generated-tag)] [content (decode-content text)]) (make-traverse-element (lambda (get set) (set id (cons (cons (make-element footnote-target-style (make-element 'superscript (counter-target footnotes tag #f))) content) (get id null))) (make-element footnote-style (list (make-element footnote-ref-style (make-element 'superscript (counter-ref footnotes tag #f))) (make-element footnote-content-style content))))))) (define (do-footnote-part footnotes id) (make-part #f (list `(part ,(generated-tag))) #f (make-style #f '(hidden toc-hidden)) null (list (make-traverse-block (lambda (get set) (make-compound-paragraph footnote-block-style (map (lambda (content) (make-paragraph footnote-block-content-style content)) (reverse (get id null))))))) null))
4a968d22471edd314835a8cc2ab695cf3d60e527e2b4e944c1625ba2f3adfcbc
clojurecup2014/parade-route
def.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.test-clojure.def (:use clojure.test clojure.test-helper clojure.test-clojure.protocols)) (deftest defn-error-messages (testing "multiarity syntax invalid parameter declaration" (is (fails-with-cause? IllegalArgumentException #"Parameter declaration arg1 should be a vector" (eval-in-temp-ns (defn foo (arg1 arg2)))))) (testing "multiarity syntax invalid signature" (is (fails-with-cause? IllegalArgumentException #"Invalid signature \[a b\] should be a list" (eval-in-temp-ns (defn foo ([a] 1) [a b]))))) (testing "assume single arity syntax" (is (fails-with-cause? IllegalArgumentException #"Parameter declaration a should be a vector" (eval-in-temp-ns (defn foo a))))) (testing "bad name" (is (fails-with-cause? IllegalArgumentException #"First argument to defn must be a symbol" (eval-in-temp-ns (defn "bad docstring" testname [arg1 arg2]))))) (testing "missing parameter/signature" (is (fails-with-cause? IllegalArgumentException #"Parameter declaration missing" (eval-in-temp-ns (defn testname))))) (testing "allow trailing map" (is (eval-in-temp-ns (defn a "asdf" ([a] 1) {:a :b})))) (testing "don't allow interleaved map" (is (fails-with-cause? IllegalArgumentException #"Invalid signature \{:a :b\} should be a list" (eval-in-temp-ns (defn a "asdf" ([a] 1) {:a :b} ([] 1))))))) (deftest non-dynamic-warnings (testing "no warning for **" (is (empty? (with-err-print-writer (eval-in-temp-ns (defn ** ([a b] (Math/pow (double a) (double b))))))))) (testing "warning for *hello*" (is (not (empty? (with-err-print-writer (eval-in-temp-ns (def *hello* "hi")))))))) (deftest dynamic-redefinition ;; too many contextual things for this kind of caching to work... (testing "classes are never cached, even if their bodies are the same" (is (= :b (eval '(do (defmacro my-macro [] :a) (defn do-macro [] (my-macro)) (defmacro my-macro [] :b) (defn do-macro [] (my-macro)) (do-macro))))))) (deftest nested-dynamic-declaration (testing "vars :dynamic meta data is applied immediately to vars declared anywhere" (is (= 10 (eval '(do (list (declare ^:dynamic p) (defn q [] @p)) (binding [p (atom 10)] (q))))))))
null
https://raw.githubusercontent.com/clojurecup2014/parade-route/adb2e1ea202228e3da07902849dee08f0bb8d81c/Assets/Clojure/Internal/Plugins/clojure/test_clojure/def.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. too many contextual things for this kind of caching to work...
Copyright ( c ) . All rights reserved . (ns clojure.test-clojure.def (:use clojure.test clojure.test-helper clojure.test-clojure.protocols)) (deftest defn-error-messages (testing "multiarity syntax invalid parameter declaration" (is (fails-with-cause? IllegalArgumentException #"Parameter declaration arg1 should be a vector" (eval-in-temp-ns (defn foo (arg1 arg2)))))) (testing "multiarity syntax invalid signature" (is (fails-with-cause? IllegalArgumentException #"Invalid signature \[a b\] should be a list" (eval-in-temp-ns (defn foo ([a] 1) [a b]))))) (testing "assume single arity syntax" (is (fails-with-cause? IllegalArgumentException #"Parameter declaration a should be a vector" (eval-in-temp-ns (defn foo a))))) (testing "bad name" (is (fails-with-cause? IllegalArgumentException #"First argument to defn must be a symbol" (eval-in-temp-ns (defn "bad docstring" testname [arg1 arg2]))))) (testing "missing parameter/signature" (is (fails-with-cause? IllegalArgumentException #"Parameter declaration missing" (eval-in-temp-ns (defn testname))))) (testing "allow trailing map" (is (eval-in-temp-ns (defn a "asdf" ([a] 1) {:a :b})))) (testing "don't allow interleaved map" (is (fails-with-cause? IllegalArgumentException #"Invalid signature \{:a :b\} should be a list" (eval-in-temp-ns (defn a "asdf" ([a] 1) {:a :b} ([] 1))))))) (deftest non-dynamic-warnings (testing "no warning for **" (is (empty? (with-err-print-writer (eval-in-temp-ns (defn ** ([a b] (Math/pow (double a) (double b))))))))) (testing "warning for *hello*" (is (not (empty? (with-err-print-writer (eval-in-temp-ns (def *hello* "hi")))))))) (deftest dynamic-redefinition (testing "classes are never cached, even if their bodies are the same" (is (= :b (eval '(do (defmacro my-macro [] :a) (defn do-macro [] (my-macro)) (defmacro my-macro [] :b) (defn do-macro [] (my-macro)) (do-macro))))))) (deftest nested-dynamic-declaration (testing "vars :dynamic meta data is applied immediately to vars declared anywhere" (is (= 10 (eval '(do (list (declare ^:dynamic p) (defn q [] @p)) (binding [p (atom 10)] (q))))))))
7b3550d9eb4a43cebcb6b0a45c7f28ca0899c674cad9d046883747683425834a
andersfugmann/aws-s3
s3.ml
(** Async aware S3 commands. For API documentation @see <../../../aws-s3/Aws_s3/S3/Make/index.html>({!module:Aws_s3.S3.Make}) *) include Aws_s3.S3.Make(Io)
null
https://raw.githubusercontent.com/andersfugmann/aws-s3/84af629119e313ba46cf3eab9dd7b914e6bae5e9/aws-s3-async/s3.ml
ocaml
* Async aware S3 commands. For API documentation @see <../../../aws-s3/Aws_s3/S3/Make/index.html>({!module:Aws_s3.S3.Make})
include Aws_s3.S3.Make(Io)
a1fd84d2d156ce633f3252962ce53ec3ab321f48e053e17927106a246a6293a9
mwand/5010-examples
07-1-number-list-with-stress-tests.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-intermediate-lambda-reader.ss" "lang")((modname 07-1-number-list-with-stress-tests) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require rackunit) (require "extras.rkt") ;; comment out all versions of number-list except the one you want, ;; then say (run-stress-tests 0) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; DATA DEFINITIONS A NumberedX is a ( list ) A NumberedListOfX is a ListOfNumberedX ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The contract and purpose statement: ;; number-list : ListOfX -> NumberedListOfX ;; RETURNS: a list like the original, but with the ;; elements numbered consecutively, starting from 1 ;; EXAMPLE: ( number - list ( list 66 88 77 ) ) = ( list ( list 1 66 ) ( list 2 88 ) ( list 3 77 ) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Solution 1: write a more general function that can number a list ;; starting from any number. ;; number-list-from : ListOfX Number -> NumberedListOfX RETURNS : a list with same elements as lst , but numbered starting at n. EXAMPLE : ( number - list - from ( list 88 77 ) 2 ) = ( list ( list 2 88 ) ( list 3 77 ) ) ;; STRATEGY: Use the template for ListOfX on lst (define (number-list-from lst n) (cond [(empty? lst) empty] [else (cons (list n (first lst)) (number-list-from (rest lst) (+ n 1)))])) (check-equal? (number-list-from (list 88 77) 2) (list (list 2 88) (list 3 77))) ;; now we can specialize number-list-from to get number-list: ;; STRATEGY: Call a more general function (define (number-list1 lst) (number-list-from lst 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Solution 2: Version with invariant ;; same code, different purpose statement ;; number-list-from : ListOfX Number -> NumberedListOfX GIVEN a sublist slst WHERE slst is the n - th sublist of some list lst0 RETURNS : a copy of slst numbered according to its position in lst0 . ;; STRATEGY: Use the template for ListOfX on lst (define (number-sublist slst n) (cond [(empty? slst) empty] [else (cons (list n (first slst)) (number-sublist (rest slst) (+ n 1)))])) (define (number-list2 lst) (number-sublist lst 1)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Solution 3: pure structural decomposition ;; STRATEGY: Use template for ListOfX on lst (define (number-list3 lst) (cond [(empty? lst) empty] [else (number-list-combiner (first lst) (number-list3 (rest lst)))])) ;; number-list-combiner : X NumberedListOfX -> NumberedListOfX GIVEN : an X x1 and a NumberedListOfX ( ( 1 x2 ) ( 2 x3 ) ... ) RETURNS : the list ( ( 1 x1 ) ( 2 x2 ) ( 3 x3 ) ... ) ;; STRATEGY: HOFC (define (number-list-combiner first-val numbered-list) (cons (list 1 first-val) (map NumberedX - > NumberedX ;; GIVEN: a list containing a number and a value ;; RETURNS: a list like the given one, but with the number ;; increased by one. (lambda (elt) (list (+ 1 (first elt)) (second elt))) numbered-list))) (begin-for-test (check-equal? (number-list-combiner 11 (list (list 1 33) (list 2 13) (list 3 42))) (list (list 1 11) (list 2 33) (list 3 13) (list 4 42)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; these next tests illustrate functions that build Checks, and also ;; tests that test properties of the answer rather than the whole answer A Check is a ( check - equal ? ErrorMessage ) ;; ListOfX -> Check Given a list lst , check to see that the first elements of ( number - list lst ) are ( 1 ... ( length lst ) ) (define (make-test1 lst) (check-equal? (map first (number-list lst)) (build-list (length lst) add1) (format "first elements of (number-list ~s) should be 1 through ~s" lst (add1 (length lst))))) (define (number-list lst) (number-list1 lst)) ;; ListOfX -> Check Given a list lst , check to see that the second elements of ( number - list lst ) are the same as lst (define (make-test2 lst) (check-equal? (map second (number-list lst)) lst)) (begin-for-test (check-equal? (number-list empty) empty "(number-list empty) should be empty") (check-equal? (number-list '(a b c)) '((1 a) (2 b) (3 c)) "(number-list '(a b c)) should be ((1 a) (2 b) (3 c))") (make-test1 '(11 22 33 44)) (make-test2 '(11 22 33 44)) (make-test1 empty) (make-test2 empty)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; stress tests (require racket) ;; included for getting time out of stress tests. Don't let me catch ;; you requiring racket. ( X - > Any ) ( X - > Any ) X - > ( list ) (define (compare-times fn1 fn2 val) (let-values (((v1 t1 y1 z) (time-apply fn1 (list val))) ((v2 t2 y2 zz) (time-apply fn2 (list val)))) (list y1 y2))) ;; builds a list of size n (define (list-of-size n) (build-list n (lambda (i) 666))) (define (stress-test sizes) (map (lambda (n) (cons n (compare-times number-list2 number-list (list-of-size n)))) sizes)) (define (run-stress-tests) (stress-test '(1000 2000 4000 8000))) ;; do this twice-- once with the invariant and once with pure template: ;; with the invariant: ;; > (run-stress-tests) ( list ( list 1000 0 1 ) ( list 2000 0 0 ) ( list 4000 2 1 ) ( list 8000 42 2 ) ) ;; solution #3: pure template, no invariant: ;> (run-stress-tests) ( list ( list 1000 0 125 ) ( list 2000 15 484 ) ( list 4000 0 1950 ) ( list 8000 16 7924 ) )
null
https://raw.githubusercontent.com/mwand/5010-examples/ac24491ec2e533d048e11087ccc30ff1c087c218/07-1-number-list-with-stress-tests.rkt
racket
about the language level of this file in a form that our tools can easily process. comment out all versions of number-list except the one you want, then say (run-stress-tests 0) DATA DEFINITIONS The contract and purpose statement: number-list : ListOfX -> NumberedListOfX RETURNS: a list like the original, but with the elements numbered consecutively, starting EXAMPLE: Solution 1: write a more general function that can number a list starting from any number. number-list-from : ListOfX Number -> NumberedListOfX STRATEGY: Use the template for ListOfX on lst now we can specialize number-list-from to get number-list: STRATEGY: Call a more general function Solution 2: Version with invariant same code, different purpose statement number-list-from : ListOfX Number -> NumberedListOfX STRATEGY: Use the template for ListOfX on lst Solution 3: pure structural decomposition STRATEGY: Use template for ListOfX on lst number-list-combiner : X NumberedListOfX -> NumberedListOfX STRATEGY: HOFC GIVEN: a list containing a number and a value RETURNS: a list like the given one, but with the number increased by one. these next tests illustrate functions that build Checks, and also tests that test properties of the answer rather than the whole answer ListOfX -> Check ListOfX -> Check stress tests included for getting time out of stress tests. Don't let me catch you requiring racket. builds a list of size n do this twice-- once with the invariant and once with pure template: with the invariant: > (run-stress-tests) solution #3: pure template, no invariant: > (run-stress-tests)
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname 07-1-number-list-with-stress-tests) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require rackunit) (require "extras.rkt") A NumberedX is a ( list ) A NumberedListOfX is a ListOfNumberedX from 1 ( number - list ( list 66 88 77 ) ) = ( list ( list 1 66 ) ( list 2 88 ) ( list 3 77 ) ) RETURNS : a list with same elements as lst , but numbered starting at n. EXAMPLE : ( number - list - from ( list 88 77 ) 2 ) = ( list ( list 2 88 ) ( list 3 77 ) ) (define (number-list-from lst n) (cond [(empty? lst) empty] [else (cons (list n (first lst)) (number-list-from (rest lst) (+ n 1)))])) (check-equal? (number-list-from (list 88 77) 2) (list (list 2 88) (list 3 77))) (define (number-list1 lst) (number-list-from lst 1)) GIVEN a sublist slst WHERE slst is the n - th sublist of some list lst0 RETURNS : a copy of slst numbered according to its position in lst0 . (define (number-sublist slst n) (cond [(empty? slst) empty] [else (cons (list n (first slst)) (number-sublist (rest slst) (+ n 1)))])) (define (number-list2 lst) (number-sublist lst 1)) (define (number-list3 lst) (cond [(empty? lst) empty] [else (number-list-combiner (first lst) (number-list3 (rest lst)))])) GIVEN : an X x1 and a NumberedListOfX ( ( 1 x2 ) ( 2 x3 ) ... ) RETURNS : the list ( ( 1 x1 ) ( 2 x2 ) ( 3 x3 ) ... ) (define (number-list-combiner first-val numbered-list) (cons (list 1 first-val) (map NumberedX - > NumberedX (lambda (elt) (list (+ 1 (first elt)) (second elt))) numbered-list))) (begin-for-test (check-equal? (number-list-combiner 11 (list (list 1 33) (list 2 13) (list 3 42))) (list (list 1 11) (list 2 33) (list 3 13) (list 4 42)))) A Check is a ( check - equal ? ErrorMessage ) Given a list lst , check to see that the first elements of ( number - list lst ) are ( 1 ... ( length lst ) ) (define (make-test1 lst) (check-equal? (map first (number-list lst)) (build-list (length lst) add1) (format "first elements of (number-list ~s) should be 1 through ~s" lst (add1 (length lst))))) (define (number-list lst) (number-list1 lst)) Given a list lst , check to see that the second elements of ( number - list lst ) are the same as lst (define (make-test2 lst) (check-equal? (map second (number-list lst)) lst)) (begin-for-test (check-equal? (number-list empty) empty "(number-list empty) should be empty") (check-equal? (number-list '(a b c)) '((1 a) (2 b) (3 c)) "(number-list '(a b c)) should be ((1 a) (2 b) (3 c))") (make-test1 '(11 22 33 44)) (make-test2 '(11 22 33 44)) (make-test1 empty) (make-test2 empty)) (require racket) ( X - > Any ) ( X - > Any ) X - > ( list ) (define (compare-times fn1 fn2 val) (let-values (((v1 t1 y1 z) (time-apply fn1 (list val))) ((v2 t2 y2 zz) (time-apply fn2 (list val)))) (list y1 y2))) (define (list-of-size n) (build-list n (lambda (i) 666))) (define (stress-test sizes) (map (lambda (n) (cons n (compare-times number-list2 number-list (list-of-size n)))) sizes)) (define (run-stress-tests) (stress-test '(1000 2000 4000 8000))) ( list ( list 1000 0 1 ) ( list 2000 0 0 ) ( list 4000 2 1 ) ( list 8000 42 2 ) ) ( list ( list 1000 0 125 ) ( list 2000 15 484 ) ( list 4000 0 1950 ) ( list 8000 16 7924 ) )
0ae0f6cbf81e8b356662d6f60f14eacc78a6bc73146fba619f5f2738cdef2109
CoNarrative/precept
listeners_test.cljc
(ns precept.listeners-test (:require [clojure.test :refer [use-fixtures is deftest testing run-tests]] [clara.rules.accumulators :as acc] [clara.rules :refer [query fire-rules] :as cr] [precept.listeners :as l] [precept.state :as state] [precept.query :as q] [precept.util :refer [guid ->Tuple] :as util] [precept.rules :refer [rule session]]) (:import [precept.util Tuple])) (defn reset-globals [f] (reset! state/fact-index {}) (util/make-ancestors-fn) (f) (reset! state/fact-index {}) (util/make-ancestors-fn)) (use-fixtures :once reset-globals) (use-fixtures :each reset-globals) (defn trace [& args] (comment (apply prn args))) (rule insert-logical-for-every-a [?f <- [?e :attr/a]] => (trace "Found " ?f "Inserting logical fact" [?e :attr/logical-insert ?f]) (util/insert! [?e :attr/logical-insert ?f])) (rule retract-a-fact-that-caused-a-logical-insertion [[_ :attr/logical-insert ?f]] => (trace "Found " ?f " Retracting its condition for existing") (cr/retract! ?f)) (rule accumulate-count [?facts <- (acc/all) :from [:all]] => (trace "All facts" ?facts) (do nil)) (def background-facts (repeatedly 5 #(vector (guid) :junk 42))) (deftest trace-parsing-fns (let [fact-t (inc @state/fact-id) traced-session (-> @(session trace-parsing-session) (l/replace-listener) (util/insert (into [[1 :attr/a "state-0"] [1 :attr/b "state-0"]] background-facts)) (util/retract (->Tuple 1 :attr/a "state-0" fact-t) #_[1 :attr/a "state-0"]) (fire-rules)) traces (l/fact-traces traced-session) keyed-by-type (l/trace-by-type (first traces)) additions (l/insertions keyed-by-type) removals (l/retractions keyed-by-type) split-ops (l/split-ops (first traces)) vectorized-trace (l/vectorize-trace (first traces)) vec-ops (l/vec-ops traced-session)] (testing "fact-traces should return seq of trace vectors" (is (and vector? (not (> 1 (count traces)))) "More than one item in trace vector. May have more than one tracer on session?") (is (every? vector? traces)) (is (every? (comp map? first) traces)) (is (every? (comp #(contains? % :facts) first) traces)) (is (every? (comp #(contains? % :type) first) traces))) (testing ":facts in fact-traces should be Tuples" (is (every? (comp #(every? (partial instance? Tuple) %) :facts first) traces) "Expected every item in :facts to be a Tuple")) (testing "trace-by-type should return trace keyed by clara op" (let [clara-fact-ops #{:add-facts :add-facts-logical :retract-facts :retract-facts-logical}] (is (every? clara-fact-ops (keys keyed-by-type))))) (testing "insertions should return add operations only" (is (every? #{:add-facts :add-facts-logical} (keys additions)))) (testing "removals should return retract operations only" (is (every? #{:retract-facts :retract-facts-logical} (keys removals)))) (testing "vectorize-trace should return trace with each Tuple in :facts as vector" (is (every? map? vectorized-trace)) (is (every? #(contains? % :facts) vectorized-trace)) (is (every? #(contains? % :type) vectorized-trace)) (is (every? (comp #(every? vector? %) :facts) vectorized-trace))) (testing "vec-ops should return m of :added, :removed as vec of vecs" (is (= '(:added :removed) (keys vec-ops))) (is (= (:removed vec-ops) []) "Fact was added then removed. Net removals should be []")) (testing "ops-0 :added" (is (= (set (:added vec-ops)) (set (conj background-facts [1 :attr/b "state-0"]))))))) (deftest listeners-state-transitions (let [test-session @(session the-session 'precept.listeners-test 'precept.query) state-0-inserts (into [(->Tuple 123 :attr/a "state-0" 0) (->Tuple 123 :attr/b "state-0" 1)] (mapv util/vec->record background-facts)) state-0-retracts [] state-0 (-> test-session (l/replace-listener) (util/insert state-0-inserts) (fire-rules)) ops-0 (l/vec-ops state-0) ent-0 (q/entityv state-0 123) state-1-inserts [123 :attr/b "state-1"] state-1-retracts (->Tuple 123 :attr/b "state-0" 1) state-1 (-> state-0 (l/replace-listener) (util/retract state-1-retracts) (util/insert state-1-inserts) (fire-rules)) ops-1 (l/vec-ops state-1) ent-1 (q/entityv state-1 123) state-2-inserts [123 :attr/b "state-2"] state-2-retracts [] state-2 (-> state-1 (l/replace-listener) (util/insert state-2-inserts) (fire-rules)) ops-2 (l/vec-ops state-2) ent-2 (q/entityv state-2 123)] (testing "session-0: net additions" (is (= (set (conj background-facts [123 :attr/b "state-0"])) (set (:added ops-0))))) (testing "session-0: net removals" (is (= (:removed (l/vec-ops state-0)) []))) (testing "session-1: net additions" (is (= (:added (l/vec-ops state-1)) (vector state-1-inserts)))) (testing "session-1: net removals" (is (= (:removed (l/vec-ops state-1)) (vector (util/record->vec state-1-retracts))))) (testing "session-2: net additions" (is (= (:added (l/vec-ops state-2)) [[123 :attr/b "state-2"]]) (into #{} (:added ops-2)))) (testing "session-2 net removals" (is (= (:removed (l/vec-ops state-2)) [[123 :attr/b "state-1"]]))))) ;; affected by one - to - one enforcement (run-tests)
null
https://raw.githubusercontent.com/CoNarrative/precept/6078286cae641b924a2bffca4ecba19dcc304dde/test/cljc/precept/listeners_test.cljc
clojure
affected by
(ns precept.listeners-test (:require [clojure.test :refer [use-fixtures is deftest testing run-tests]] [clara.rules.accumulators :as acc] [clara.rules :refer [query fire-rules] :as cr] [precept.listeners :as l] [precept.state :as state] [precept.query :as q] [precept.util :refer [guid ->Tuple] :as util] [precept.rules :refer [rule session]]) (:import [precept.util Tuple])) (defn reset-globals [f] (reset! state/fact-index {}) (util/make-ancestors-fn) (f) (reset! state/fact-index {}) (util/make-ancestors-fn)) (use-fixtures :once reset-globals) (use-fixtures :each reset-globals) (defn trace [& args] (comment (apply prn args))) (rule insert-logical-for-every-a [?f <- [?e :attr/a]] => (trace "Found " ?f "Inserting logical fact" [?e :attr/logical-insert ?f]) (util/insert! [?e :attr/logical-insert ?f])) (rule retract-a-fact-that-caused-a-logical-insertion [[_ :attr/logical-insert ?f]] => (trace "Found " ?f " Retracting its condition for existing") (cr/retract! ?f)) (rule accumulate-count [?facts <- (acc/all) :from [:all]] => (trace "All facts" ?facts) (do nil)) (def background-facts (repeatedly 5 #(vector (guid) :junk 42))) (deftest trace-parsing-fns (let [fact-t (inc @state/fact-id) traced-session (-> @(session trace-parsing-session) (l/replace-listener) (util/insert (into [[1 :attr/a "state-0"] [1 :attr/b "state-0"]] background-facts)) (util/retract (->Tuple 1 :attr/a "state-0" fact-t) #_[1 :attr/a "state-0"]) (fire-rules)) traces (l/fact-traces traced-session) keyed-by-type (l/trace-by-type (first traces)) additions (l/insertions keyed-by-type) removals (l/retractions keyed-by-type) split-ops (l/split-ops (first traces)) vectorized-trace (l/vectorize-trace (first traces)) vec-ops (l/vec-ops traced-session)] (testing "fact-traces should return seq of trace vectors" (is (and vector? (not (> 1 (count traces)))) "More than one item in trace vector. May have more than one tracer on session?") (is (every? vector? traces)) (is (every? (comp map? first) traces)) (is (every? (comp #(contains? % :facts) first) traces)) (is (every? (comp #(contains? % :type) first) traces))) (testing ":facts in fact-traces should be Tuples" (is (every? (comp #(every? (partial instance? Tuple) %) :facts first) traces) "Expected every item in :facts to be a Tuple")) (testing "trace-by-type should return trace keyed by clara op" (let [clara-fact-ops #{:add-facts :add-facts-logical :retract-facts :retract-facts-logical}] (is (every? clara-fact-ops (keys keyed-by-type))))) (testing "insertions should return add operations only" (is (every? #{:add-facts :add-facts-logical} (keys additions)))) (testing "removals should return retract operations only" (is (every? #{:retract-facts :retract-facts-logical} (keys removals)))) (testing "vectorize-trace should return trace with each Tuple in :facts as vector" (is (every? map? vectorized-trace)) (is (every? #(contains? % :facts) vectorized-trace)) (is (every? #(contains? % :type) vectorized-trace)) (is (every? (comp #(every? vector? %) :facts) vectorized-trace))) (testing "vec-ops should return m of :added, :removed as vec of vecs" (is (= '(:added :removed) (keys vec-ops))) (is (= (:removed vec-ops) []) "Fact was added then removed. Net removals should be []")) (testing "ops-0 :added" (is (= (set (:added vec-ops)) (set (conj background-facts [1 :attr/b "state-0"]))))))) (deftest listeners-state-transitions (let [test-session @(session the-session 'precept.listeners-test 'precept.query) state-0-inserts (into [(->Tuple 123 :attr/a "state-0" 0) (->Tuple 123 :attr/b "state-0" 1)] (mapv util/vec->record background-facts)) state-0-retracts [] state-0 (-> test-session (l/replace-listener) (util/insert state-0-inserts) (fire-rules)) ops-0 (l/vec-ops state-0) ent-0 (q/entityv state-0 123) state-1-inserts [123 :attr/b "state-1"] state-1-retracts (->Tuple 123 :attr/b "state-0" 1) state-1 (-> state-0 (l/replace-listener) (util/retract state-1-retracts) (util/insert state-1-inserts) (fire-rules)) ops-1 (l/vec-ops state-1) ent-1 (q/entityv state-1 123) state-2-inserts [123 :attr/b "state-2"] state-2-retracts [] state-2 (-> state-1 (l/replace-listener) (util/insert state-2-inserts) (fire-rules)) ops-2 (l/vec-ops state-2) ent-2 (q/entityv state-2 123)] (testing "session-0: net additions" (is (= (set (conj background-facts [123 :attr/b "state-0"])) (set (:added ops-0))))) (testing "session-0: net removals" (is (= (:removed (l/vec-ops state-0)) []))) (testing "session-1: net additions" (is (= (:added (l/vec-ops state-1)) (vector state-1-inserts)))) (testing "session-1: net removals" (is (= (:removed (l/vec-ops state-1)) (vector (util/record->vec state-1-retracts))))) (testing "session-2: net additions" (is (= (:added (l/vec-ops state-2)) [[123 :attr/b "state-2"]]) (into #{} (:added ops-2)))) (testing "session-2 net removals" one - to - one enforcement (run-tests)
bd042684a870717d7ffda8b1cf164cdcaf8082c9cd3cea16539a0bae90d289f0
cse-bristol/110-thermos-ui
core.clj
This file is part of THERMOS , copyright © Centre for Sustainable Energy , 2017 - 2021 Licensed under the Reciprocal Public License v1.5 . See LICENSE for licensing details . (ns thermos-backend.routes.core)
null
https://raw.githubusercontent.com/cse-bristol/110-thermos-ui/e13b96329f3c95e5a10bae431e8ae9bccdb475f4/src/thermos_backend/routes/core.clj
clojure
This file is part of THERMOS , copyright © Centre for Sustainable Energy , 2017 - 2021 Licensed under the Reciprocal Public License v1.5 . See LICENSE for licensing details . (ns thermos-backend.routes.core)
ea563c240bece73e8c1e4b60e8deb0dbb884a6f252631e90b7436ce0f74e1219
links-lang/links
lens_errors.ml
open Lens open Lens.Utility let unpack r ~die ~fmt = match r with | Result.Ok t -> t | Result.Error e -> Format.asprintf "%a" fmt e |> die let format_lens_sort_error f e = let open Sort.Lens_sort_error in match e with | UnboundColumns c -> Format.fprintf f "The columns { %a } are not bound." Alias.Set.pp_pretty c let unpack_lens_sort_result ~die res = unpack ~die ~fmt:format_lens_sort_error res let unpack_type_lens_result ~die res = unpack_lens_sort_result ~die res let format_fun_dep_tree_form_error f e = let open Fun_dep.Tree.Tree_form_error in match e with | ContainsCycle cycle -> Format.fprintf f "The functional dependencies contain a cycle:\n %a" (Format.pp_print_list ~pp_sep:(Format.pp_constant " -> ") Alias.Set.pp_pretty) cycle | NotDisjoint cols -> Format.fprintf f "The columns { %a } were found in two non-disjoint nodes." Alias.Set.pp_pretty cols let format_select_sort_error f e = let open Sort.Select_sort_error in match e with | UnboundColumns c -> Format.fprintf f "The columns { %a } in the predicate are not bound by the lens." Alias.Set.pp_pretty c | PredicateDoesntIgnoreOutputs { columns; fds } -> Format.fprintf f "The lens has restrictions on the columns { %a }, which are defined as \ outputs of the functional dependencies { %a }." Alias.Set.pp_pretty columns Fun_dep.Set.pp_pretty fds | TreeFormError { error } -> Format.fprintf f "The functional dependencies were not in tree form. %a" format_fun_dep_tree_form_error error let format_drop_sort_error f e = let open Sort.Drop_sort_error in match e with | UnboundColumns c -> Format.fprintf f "The columns { %a } are not bound by the lens." Alias.Set.pp_pretty c | DropNotDefinedByKey -> Format.fprintf f "The functional dependencies do not specify that the drop columns are \ defined by the key columns." | DefaultDropMismatch -> Format.fprintf f "The number of default values does not match the number of drop \ columns." | DropTypeError { column; default_type; column_type } -> Format.fprintf f "The type of column '%s' is %a, but the default value is of type %a." column Phrase.Type.pp column_type Phrase.Type.pp default_type | DefiningFDNotFound c -> Format.fprintf f "A functional dependency defining the columns { %a } could not be \ found." Alias.Set.pp_pretty c | DefaultDoesntMatchPredicate -> Format.fprintf f "The default value specified does not satisfy the lens predicate." | NotIndependent c -> Format.fprintf f "The columns { %a} are not independent in the predicate." Alias.Set.pp_pretty c let unpack_type_drop_lens_result ~die res = unpack ~die ~fmt:format_drop_sort_error res let format_phrase_typesugar_error f { Lens.Phrase.Typesugar.msg; data = _ } = Format.fprintf f "%s" msg let format_type_select_error f e = let open Type.Select_lens_error in match e with | SortError e -> format_select_sort_error f e | PredicateTypeError e -> Format.fprintf f "%a" format_phrase_typesugar_error e | PredicateNotBoolean ty -> Format.fprintf f "Lens select predicate is of type %a, but should be a boolean \ expression." Phrase.Type.pp_pretty ty let unpack_type_select_lens_result ~die res = unpack ~die ~fmt:format_type_select_error res let unpack_phrase_typesugar_result ~die res = unpack ~die ~fmt:format_phrase_typesugar_error res let unpack_sort_select_result ~die res = unpack ~die ~fmt:format_select_sort_error res let format_sort_join_error f e = let open Sort.Join_sort_error in match e with | UnboundColumn c -> Format.fprintf f "The columns { %a } are not bound." Alias.Set.pp_pretty c | AlreadyBound c -> Format.fprintf f "The columns { %a } are already bound." Alias.Set.pp_pretty c | TreeFormError { error } -> Format.fprintf f "The functional dependencies were not in tree form. %a" format_fun_dep_tree_form_error error let unpack_sort_join_result ~die res = unpack ~die ~fmt:format_sort_join_error res let format_type_join_error f e = let open Type.Join_lens_error in let pp_lens f l = match l with | Left -> Format.fprintf f "left" | Right -> Format.fprintf f "right" in match e with | SortError e -> format_sort_join_error f e | PredicateNotBoolean (l, t) -> Format.fprintf f "The delete %a predicate is of type %a, but should be a boolean \ expression." pp_lens l Phrase.Type.pp_pretty t | PredicateTypeError (l, e) -> Format.fprintf f "The delete %a predicate failed to type check: %a" pp_lens l format_phrase_typesugar_error e let unpack_type_join_lens_result ~die res = unpack ~die ~fmt:format_type_join_error res let format_eval_error f e = let open Eval.Error in match e with | InvalidData -> Format.fprintf f "Not all records in data satisfy the condition in the lens sort." | InvalidDataType -> Format.fprintf f "Data is not a set of records." | ViolatesFunDepConstraint fd -> Format.fprintf f "Data violates the functional dependency %a." Fun_dep.pp_pretty fd let unpack_eval_error ~die res = unpack ~die ~fmt:format_eval_error res let format_lens_unchecked_error f e = let open Type.Unchecked_lens_error in match e with | UncheckedLens -> Format.fprintf f "This lens has some checks which can only be performed at runtime. To \ ignore this use `lenscheck`." let unpack_lens_checked_result ~die res = unpack ~die ~fmt:format_lens_unchecked_error res
null
https://raw.githubusercontent.com/links-lang/links/2923893c80677b67cacc6747a25b5bcd65c4c2b6/core/lens_errors.ml
ocaml
open Lens open Lens.Utility let unpack r ~die ~fmt = match r with | Result.Ok t -> t | Result.Error e -> Format.asprintf "%a" fmt e |> die let format_lens_sort_error f e = let open Sort.Lens_sort_error in match e with | UnboundColumns c -> Format.fprintf f "The columns { %a } are not bound." Alias.Set.pp_pretty c let unpack_lens_sort_result ~die res = unpack ~die ~fmt:format_lens_sort_error res let unpack_type_lens_result ~die res = unpack_lens_sort_result ~die res let format_fun_dep_tree_form_error f e = let open Fun_dep.Tree.Tree_form_error in match e with | ContainsCycle cycle -> Format.fprintf f "The functional dependencies contain a cycle:\n %a" (Format.pp_print_list ~pp_sep:(Format.pp_constant " -> ") Alias.Set.pp_pretty) cycle | NotDisjoint cols -> Format.fprintf f "The columns { %a } were found in two non-disjoint nodes." Alias.Set.pp_pretty cols let format_select_sort_error f e = let open Sort.Select_sort_error in match e with | UnboundColumns c -> Format.fprintf f "The columns { %a } in the predicate are not bound by the lens." Alias.Set.pp_pretty c | PredicateDoesntIgnoreOutputs { columns; fds } -> Format.fprintf f "The lens has restrictions on the columns { %a }, which are defined as \ outputs of the functional dependencies { %a }." Alias.Set.pp_pretty columns Fun_dep.Set.pp_pretty fds | TreeFormError { error } -> Format.fprintf f "The functional dependencies were not in tree form. %a" format_fun_dep_tree_form_error error let format_drop_sort_error f e = let open Sort.Drop_sort_error in match e with | UnboundColumns c -> Format.fprintf f "The columns { %a } are not bound by the lens." Alias.Set.pp_pretty c | DropNotDefinedByKey -> Format.fprintf f "The functional dependencies do not specify that the drop columns are \ defined by the key columns." | DefaultDropMismatch -> Format.fprintf f "The number of default values does not match the number of drop \ columns." | DropTypeError { column; default_type; column_type } -> Format.fprintf f "The type of column '%s' is %a, but the default value is of type %a." column Phrase.Type.pp column_type Phrase.Type.pp default_type | DefiningFDNotFound c -> Format.fprintf f "A functional dependency defining the columns { %a } could not be \ found." Alias.Set.pp_pretty c | DefaultDoesntMatchPredicate -> Format.fprintf f "The default value specified does not satisfy the lens predicate." | NotIndependent c -> Format.fprintf f "The columns { %a} are not independent in the predicate." Alias.Set.pp_pretty c let unpack_type_drop_lens_result ~die res = unpack ~die ~fmt:format_drop_sort_error res let format_phrase_typesugar_error f { Lens.Phrase.Typesugar.msg; data = _ } = Format.fprintf f "%s" msg let format_type_select_error f e = let open Type.Select_lens_error in match e with | SortError e -> format_select_sort_error f e | PredicateTypeError e -> Format.fprintf f "%a" format_phrase_typesugar_error e | PredicateNotBoolean ty -> Format.fprintf f "Lens select predicate is of type %a, but should be a boolean \ expression." Phrase.Type.pp_pretty ty let unpack_type_select_lens_result ~die res = unpack ~die ~fmt:format_type_select_error res let unpack_phrase_typesugar_result ~die res = unpack ~die ~fmt:format_phrase_typesugar_error res let unpack_sort_select_result ~die res = unpack ~die ~fmt:format_select_sort_error res let format_sort_join_error f e = let open Sort.Join_sort_error in match e with | UnboundColumn c -> Format.fprintf f "The columns { %a } are not bound." Alias.Set.pp_pretty c | AlreadyBound c -> Format.fprintf f "The columns { %a } are already bound." Alias.Set.pp_pretty c | TreeFormError { error } -> Format.fprintf f "The functional dependencies were not in tree form. %a" format_fun_dep_tree_form_error error let unpack_sort_join_result ~die res = unpack ~die ~fmt:format_sort_join_error res let format_type_join_error f e = let open Type.Join_lens_error in let pp_lens f l = match l with | Left -> Format.fprintf f "left" | Right -> Format.fprintf f "right" in match e with | SortError e -> format_sort_join_error f e | PredicateNotBoolean (l, t) -> Format.fprintf f "The delete %a predicate is of type %a, but should be a boolean \ expression." pp_lens l Phrase.Type.pp_pretty t | PredicateTypeError (l, e) -> Format.fprintf f "The delete %a predicate failed to type check: %a" pp_lens l format_phrase_typesugar_error e let unpack_type_join_lens_result ~die res = unpack ~die ~fmt:format_type_join_error res let format_eval_error f e = let open Eval.Error in match e with | InvalidData -> Format.fprintf f "Not all records in data satisfy the condition in the lens sort." | InvalidDataType -> Format.fprintf f "Data is not a set of records." | ViolatesFunDepConstraint fd -> Format.fprintf f "Data violates the functional dependency %a." Fun_dep.pp_pretty fd let unpack_eval_error ~die res = unpack ~die ~fmt:format_eval_error res let format_lens_unchecked_error f e = let open Type.Unchecked_lens_error in match e with | UncheckedLens -> Format.fprintf f "This lens has some checks which can only be performed at runtime. To \ ignore this use `lenscheck`." let unpack_lens_checked_result ~die res = unpack ~die ~fmt:format_lens_unchecked_error res
cb811ff586239ff939cd9cd6b1364d712adf39ca7888a063f6b8d9f135e58b36
csg-tokyo/typelevelLR
Spec.hs
import Test.Hspec import Syntax import SyntaxParser import qualified SampleSyntaxes import qualified UtilitySpec import qualified IntegratedTest import Control.Monad (forM_) import Data.Either (isRight) ------------------------------------------------------------------------------- main :: IO () main = hspec $ do describe "sample syntaxes" $ do it "should parse sample syntaxes" $ do forM_ SampleSyntaxes.sampleSyntaxSources $ \source -> do parse parseSyntax "" source `shouldSatisfy` isRight it "show and parseSyntax are isomorphic" $ do forM_ SampleSyntaxes.sampleSyntaxes $ \syntax -> do case parse parseSyntax "" (show syntax) of Left err -> expectationFailure (show err) Right syntax' -> show syntax' `shouldBe` show syntax UtilitySpec.spec describe "integrated test" $ do IntegratedTest.integratedSpec -------------------------------------------------------------------------------
null
https://raw.githubusercontent.com/csg-tokyo/typelevelLR/ca5853890fac7fb819a026f0fd15d8b43f7c8470/test/Spec.hs
haskell
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
import Test.Hspec import Syntax import SyntaxParser import qualified SampleSyntaxes import qualified UtilitySpec import qualified IntegratedTest import Control.Monad (forM_) import Data.Either (isRight) main :: IO () main = hspec $ do describe "sample syntaxes" $ do it "should parse sample syntaxes" $ do forM_ SampleSyntaxes.sampleSyntaxSources $ \source -> do parse parseSyntax "" source `shouldSatisfy` isRight it "show and parseSyntax are isomorphic" $ do forM_ SampleSyntaxes.sampleSyntaxes $ \syntax -> do case parse parseSyntax "" (show syntax) of Left err -> expectationFailure (show err) Right syntax' -> show syntax' `shouldBe` show syntax UtilitySpec.spec describe "integrated test" $ do IntegratedTest.integratedSpec
a8f1daf19b24e81cdc047d70439a13aceb83f514fd3cfc303be2283d6b802fbe
Clozure/ccl
display.lisp
;;; ;;; Copyright 2013 Clozure Associates ;;; 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. (in-package :hemlock) ;; Functions used by the IDE display code. (defmacro with-display-context ((view &optional pane) &body body) (let ((viewvar (gensym "VIEW"))) `(let* ((,viewvar ,view) (hi::*current-view* ,viewvar) (hi::*current-buffer* (ecase ,pane ((:text) (hi::hemlock-view-buffer ,viewvar)) ((:echo) (hi::hemlock-echo-area-buffer ,viewvar)) ((nil) (hi::hemlock-view-current-buffer ,viewvar))))) (hi::with-default-view-for-buffer (,viewvar) ,@body)))) ;; User variable. Maps symbol categories (see compute-symbol-category) to color specs (defvar *lisp-code-colors* '((:string :blue) (:comment :brown) (:double-comment :orange) (:triple-comment :red) (:system-symbol (0 .5 0 1)) (:definition (1 0 1 1)) (:keyword :purple) (:unmatched-paren :red) (:matched-paren (:background (0.3 0.875 0.8125 1))))) ;; Cache for actual color objects. (ccl:defloadvar *lisp-code-colors-cache* nil) ;; (cached-lisp-code-colors) (defun cached-lisp-code-colors () (let ((specs (car *lisp-code-colors-cache*)) (alist (cdr *lisp-code-colors-cache*)) (user-alist *lisp-code-colors*)) (flet ((get-spec (cell) (let ((spec (cdr cell))) (if (and (consp spec) (null (cdr spec))) (car spec) spec)))) (declare (inline get-spec)) (unless (and (eql (length user-alist) (length alist)) (loop for spec in specs for cell in alist for user-cell in user-alist always (and (eq (car cell) (car user-cell)) (eq spec (get-spec user-cell))))) (setq specs (mapcar #'get-spec user-alist)) (setq alist (mapcar #'(lambda (user-cell spec) (cons (car user-cell) (if (and (consp spec) (keywordp (car spec)) (null (cddr spec))) (cons (car spec) (hemlock-ext:lookup-color (cadr spec))) (cons :foreground (hemlock-ext:lookup-color spec))))) user-alist specs)) (setq *lisp-code-colors-cache* (cons specs alist))) alist))) (defun hemlock:compute-paren-highlighting () "Compute the positions of the characters to be shown as matching parens" (let* ((point (current-point)) (color-alist (cached-lisp-code-colors)) (color (cdr (assq :matched-paren color-alist)))) (when color (cond ((test-char (next-character point) :lisp-syntax :open-paren) (pre-command-parse-check point) (when (valid-spot point t) (with-mark ((temp point)) (when (list-offset temp 1) (list (cons (mark-absolute-position point) color) (cons (1- (mark-absolute-position temp)) color)))))) ((test-char (previous-character point) :lisp-syntax :close-paren) (pre-command-parse-check point) (when (valid-spot point nil) (with-mark ((temp point)) (when (list-offset temp -1) (list (cons (mark-absolute-position temp) color) (cons (1- (mark-absolute-position point)) color)))))))))) Return nil to use the default Cocoa selection , which will be word for double - click , line for triple . (defun hemlock:selection-for-click (mark paragraph-mode-p) Handle lisp mode specially , otherwise just go with default Cocoa behavior (when (lisp-mode? mark) (unless paragraph-mode-p (let ((region (word-region-at-mark mark))) (when region (return-from selection-for-click region)))) (pre-command-parse-check mark) (form-region-at-mark mark))) (defun hemlock:move-point-for-click (buffer index) (let* ((point (buffer-point buffer)) (mark (and (%buffer-region-active-p buffer) (buffer-mark buffer)))) (setf (hi::buffer-region-active buffer) nil) (unless (eql (mark-absolute-position point) index) ;; if point is already at target, leave mark alone (if (and mark (eql (mark-absolute-position mark) index)) (move-mark mark point) (push-new-buffer-mark point)) (move-to-absolute-position point index)))) (defun shortest-package-name (package) (let* ((name (package-name package)) (len (length name))) (dolist (nick (package-nicknames package) name) (let* ((nicklen (length nick))) (if (< nicklen len) (setq name nick len nicklen)))))) (defun hemlock:update-current-package (&optional pkg (buffer (current-buffer))) (when (lisp-mode? buffer) (unless pkg (setq pkg (or (package-at-mark (current-point)) (variable-value 'default-package :buffer buffer)))) (when pkg (let* ((name (if (packagep pkg) (package-name pkg) (string pkg))) (curname (variable-value 'current-package :buffer buffer))) (when (setq pkg (find-package name)) (setq name (shortest-package-name pkg))) (if (or (null curname) (not (string= curname name))) (setf (variable-value 'current-package :buffer buffer) name)))))) ;; advance to next symbol, ignoring form boundaries, strings, etc. (defun %scan-to-symbol (mark) (loop while (%scan-to-form mark t) do (unless (test-char (next-character mark) :lisp-syntax (or :string-quote :open-paren :close-paren)) (return mark)) do (mark-after mark))) ;; Advance to next atom, ignoring open parens (but not close parens, unlike above). (defun %scan-down-to-atom (mark) (loop while (%scan-to-form mark t) do (unless (test-char (next-character mark) :lisp-syntax :open-paren) (return mark)) do (mark-after mark))) #+debug (defun buffer-short-name () (let* ((full-name (buffer-name (current-buffer))) (pos (position #\space full-name))) (if pos (subseq full-name 0 pos) full-name))) ;; When get a cache miss, means we'll fill in parsing and line-origin caches for the whole buffer, so might ;; as well get a little extra coloring pre-computed in as well, for smoother scrolling... (defparameter $coloring-cache-extra 1000) (defstruct coloring-cache (tick nil) (start 0) (end 0) (colors nil) (data nil)) (defun make-sym-vec () (make-array 0 :displaced-to "" :adjustable t)) (defun displace-to-region (sym-vec start-mark end-mark) (let* ((sym-line (mark-line start-mark)) (line-str (line-string sym-line)) (start-pos (mark-charpos start-mark)) (end-pos (if (eq sym-line (mark-line end-mark)) (mark-charpos end-mark) (progn (setq line-str (region-to-string (region start-mark end-mark))) (setq start-pos 0) (length line-str))))) (ccl::%displace-array sym-vec nil (- end-pos start-pos) line-str start-pos T))) #+debug (defmethod print-object ((cache coloring-cache) stream) (print-unreadable-object (stream cache :identity nil :type t) (format stream "~s:~s @~s" (coloring-cache-start cache) (coloring-cache-end cache) (coloring-cache-tick cache)))) (defun hemlock:compute-syntax-coloring (start-pos length) (let* ((buffer (current-buffer)) (end-pos (+ start-pos length)) (tick (buffer-signature buffer)) (colors (cached-lisp-code-colors)) (cache (or (getf (buffer-plist buffer) 'coloring-cache) (setf (getf (buffer-plist buffer) 'coloring-cache) (make-coloring-cache))))) (unless (and (eql (coloring-cache-tick cache) tick) (<= (coloring-cache-start cache) start-pos) (<= end-pos (coloring-cache-end cache)) (eq colors (coloring-cache-colors cache))) (setq start-pos (max 0 (- start-pos $coloring-cache-extra))) (setq end-pos (+ end-pos $coloring-cache-extra)) (let ((res (compute-syntax-coloring-in-region buffer start-pos end-pos))) (setf (coloring-cache-start cache) start-pos (coloring-cache-end cache) end-pos (coloring-cache-colors cache) colors (coloring-cache-data cache) res (coloring-cache-tick cache) tick))) (coloring-cache-data cache))) (defun case-insensitive-string-to-symbol (string pkg) (when (null pkg) (setq pkg *package*)) (let* ((str (coerce string 'simple-string))) (ignore-errors (case (readtable-case *readtable*) (:upcase (find-symbol (nstring-upcase str) pkg)) (:downcase (find-symbol (nstring-downcase str) pkg)) (:preserve (find-symbol str pkg)) (t (find-symbol (nstring-upcase str) pkg) ; not the right way to handle :invert. Do we care? ))))) ;; Try to exclude use of symbol in data. (defun mark-at-invocation-p (start-mark) (and (test-char (previous-character start-mark) :lisp-syntax :open-paren) (prog2 (mark-before start-mark) (not (test-char (previous-character start-mark) :lisp-syntax (or :prefix :open-paren))) (mark-after start-mark)))) (defun compute-symbol-category (start-mark sym) (when (ccl::non-nil-symbol-p sym) (cond ((and (or (macro-function sym) (ccl::special-form-p sym)) (mark-at-invocation-p start-mark)) :system-symbol) ((keywordp sym) :keyword) (t nil)))) (defvar *defining-symbols* '(defun defgeneric defmethod defmacro define-compiler-macro define-modify-macro define-symbol-macro define-setf-expander defsetf defvar defparameter defconstant define-method-combination defclass defstruct deftype define-condition defpackage ccl:advise ccl:def-load-pointers ccl:define-definition-type ccl:defloadvar ccl:defglobal ccl:defstaticvar ccl:define-declaration ccl:defstatic ccl:defcallback ccl:define-setf-method ccl:define-character-encoding ccl:defglobal hemlock-interface:defcommand hemlock-interface:define-file-option hemlock-interface:define-file-type-hook hemlock-interface:define-keysym-code gui::def-cocoa-default objc:define-objc-class-method objc:define-objc-method objc:defmethod)) If true , the next atom following this sym will be automatically categorized as : definition , without going through compute - symbol - category . (defun defining-symbol-p (start-mark sym) (and (mark-at-invocation-p start-mark) (or (member sym *defining-symbols*) ;; recognize these even if indented or embedded. (and (eql (mark-charpos start-mark) 1) ;; but accept any toplevel "(def". (or (let ((str (string sym))) (and (> (length str) 3) (string-equal "def" str :end2 3))) color top - level setq 's , just for fun (eq sym 'setq)))))) (defun compute-string/comment-coloring-in-region (region-start region-end) (when (lisp-mode? region-start) (let* ((lisp-code-colors (cached-lisp-code-colors)) (start-line (mark-line region-start)) (end-line (line-next (mark-line region-end))) (start-charpos (mark-charpos region-start))) (assert (not (eq start-line end-line))) (loop for line = start-line then (line-next line) until (eq line end-line) for info = (getf (line-plist line) 'lisp-info) when info nconc (loop with origin = (hi::line-origin line) for last-end = 0 then end-offset for (start-offset . end-offset) in (lisp-info-ranges-to-ignore info) for syntax = (if (eql start-offset 0) (lisp-info-begins-quoted info) (if (< last-end start-offset) (character-attribute :lisp-syntax (line-character line (1- start-offset))) :comment)) do (when (member syntax '(:symbol-quote :string-quote)) (when (< 0 start-offset) (decf start-offset)) (when (< end-offset (line-length line)) (incf end-offset))) unless (and (eq line start-line) (<= end-offset start-charpos)) nconc (let* ((type (case syntax ((:char-quote :symbol-quote) nil) (:string-quote :string) (t (loop for i from start-offset as nsemi upfrom 0 until (or (eql nsemi 3) (eql i end-offset) (not (test-char (line-character line i) :lisp-syntax :comment))) finally (return (case nsemi (2 :double-comment) (3 :triple-comment) (t :comment))))))) (color (and type (cdr (assq type lisp-code-colors))))) (when color (list (list* (+ origin start-offset) (- end-offset start-offset) color))))))))) (defun coloring-region (start-mark end-mark color) (when color (let* ((start (mark-absolute-position start-mark)) (end (mark-absolute-position end-mark)) (len (- end start))) (when (> len 0) (list* start len color))))) (defun compute-symbol-coloring-in-region (region-start region-end) (when (lisp-mode? region-start) (let* ((sym-vec (make-sym-vec)) (pkg nil) (lisp-colors (cached-lisp-code-colors)) (defn-color (cdr (assq :definition lisp-colors)))) (with-mark ((start-mark region-start) (end-mark region-start)) (let ((pkgname (package-at-mark region-end end-mark))) (when pkgname (when (mark< region-start end-mark) Argh , more than one package in region . KLUDGE ! ! (return-from compute-symbol-coloring-in-region (nconc (compute-symbol-coloring-in-region region-start (mark-before end-mark)) (compute-symbol-coloring-in-region (mark-after end-mark) region-end)))) (setq pkg (find-package pkgname)))) (loop while (and (%scan-to-symbol start-mark) (mark< start-mark region-end)) for sym = (progn (move-mark end-mark start-mark) (unless (forward-form end-mark) (move-mark end-mark region-end)) (case-insensitive-string-to-symbol (displace-to-region sym-vec start-mark end-mark) pkg)) for type = (compute-symbol-category start-mark sym) for reg = (when type (let ((color (cdr (assq type lisp-colors)))) (when color (coloring-region start-mark end-mark color)))) when reg collect reg ;; if we're at start of a defining form, color the thing being defined. when (and defn-color (defining-symbol-p start-mark sym) (form-offset (move-mark start-mark end-mark) 1) (%scan-down-to-atom end-mark) (mark< end-mark region-end)) collect (progn (move-mark start-mark end-mark) (unless (and (forward-form end-mark) (mark<= end-mark region-end)) (move-mark end-mark region-end)) (unless (mark< start-mark end-mark) (warn "definition got start ~s end ~s region-end ~s" start-mark end-mark region-end) (move-mark end-mark start-mark)) (coloring-region start-mark end-mark defn-color)) do (rotatef start-mark end-mark)))))) (defun compute-unmatched-parens-coloring-in-region (start-mark end-mark) ; not checking for lisp mode here because this is still useful even in text mode (macrolet ((scan-loop (forwardp open-key buffer-start-mark start-line end-line close-key) `(loop with paren-count = 0 with limit-line = (neighbor-line ,end-line ,forwardp) with in-region-p = nil for line = (mark-line (,buffer-start-mark (mark-buffer m))) then (neighbor-line line ,forwardp) until (eq line limit-line) for info = (or (getf (line-plist line) 'lisp-info) (return nil)) as parens-on-line = ,(if forwardp '(lisp-info-net-close-parens info) '(lisp-info-net-open-parens info)) do (when (eq line ,start-line) (setq in-region-p t)) do (decf paren-count parens-on-line) do (when (< paren-count 0) (when in-region-p ,(if forwardp '(line-start m line) '(line-end m line)) (loop with net-count = (+ paren-count parens-on-line) doing (unless (scan-direction-valid m ,forwardp :lisp-syntax (or :close-paren :open-paren :newline)) (error "couldn't find ~s mismatches" (- paren-count))) (ecase (character-attribute :lisp-syntax (direction-char m ,forwardp)) (,open-key (incf net-count)) (,close-key (when (< (decf net-count) 0) (push (cons ,(if forwardp '(mark-absolute-position m) '(1- (mark-absolute-position m))) coloring-data) result) (when (eql (incf paren-count) 0) (return)) (setq net-count 0)))) (neighbor-mark m ,forwardp))) (setq paren-count 0)) do (incf paren-count ,(if forwardp '(lisp-info-net-open-parens info) '(lisp-info-net-close-parens info)))))) (with-mark ((m start-mark)) (let* ((end-line (mark-line end-mark)) (start-line (mark-line start-mark)) (color (or (cdr (assq :unmatched-paren (cached-lisp-code-colors))) (return-from compute-unmatched-parens-coloring-in-region nil))) (coloring-data (cons 1 color)) (result nil)) (scan-loop t :open-paren buffer-start-mark start-line end-line :close-paren) ; Compute unmatched close parens, top down. (scan-loop nil :close-paren buffer-end-mark end-line start-line :open-paren) ; Compute umatched open parens, bottom up. result)))) (defun compute-syntax-coloring-in-region (buffer start-pos end-pos) (let* ((some-mark (buffer-point buffer))) (with-mark ((start-mark some-mark) (end-mark some-mark)) (unless (move-to-absolute-position start-mark start-pos) (buffer-end start-mark)) (unless (move-to-absolute-position end-mark end-pos) (buffer-end end-mark)) (assert (mark<= start-mark end-mark)) (when (mark< start-mark end-mark) (pre-command-parse-check start-mark) (sort (nconc (compute-string/comment-coloring-in-region start-mark end-mark) (compute-symbol-coloring-in-region start-mark end-mark) (compute-unmatched-parens-coloring-in-region start-mark end-mark)) #'< :key #'car)))))
null
https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/cocoa-ide/hemlock/src/display.lisp
lisp
Copyright 2013 Clozure Associates 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. Functions used by the IDE display code. User variable. Maps symbol categories (see compute-symbol-category) to color specs Cache for actual color objects. (cached-lisp-code-colors) if point is already at target, leave mark alone advance to next symbol, ignoring form boundaries, strings, etc. Advance to next atom, ignoring open parens (but not close parens, unlike above). When get a cache miss, means we'll fill in parsing and line-origin caches for the whole buffer, so might as well get a little extra coloring pre-computed in as well, for smoother scrolling... not the right way to handle :invert. Do we care? Try to exclude use of symbol in data. recognize these even if indented or embedded. but accept any toplevel "(def". if we're at start of a defining form, color the thing being defined. not checking for lisp mode here because this is still useful even in text mode Compute unmatched close parens, top down. Compute umatched open parens, bottom up.
distributed under the License is distributed on an " AS IS " BASIS , (in-package :hemlock) (defmacro with-display-context ((view &optional pane) &body body) (let ((viewvar (gensym "VIEW"))) `(let* ((,viewvar ,view) (hi::*current-view* ,viewvar) (hi::*current-buffer* (ecase ,pane ((:text) (hi::hemlock-view-buffer ,viewvar)) ((:echo) (hi::hemlock-echo-area-buffer ,viewvar)) ((nil) (hi::hemlock-view-current-buffer ,viewvar))))) (hi::with-default-view-for-buffer (,viewvar) ,@body)))) (defvar *lisp-code-colors* '((:string :blue) (:comment :brown) (:double-comment :orange) (:triple-comment :red) (:system-symbol (0 .5 0 1)) (:definition (1 0 1 1)) (:keyword :purple) (:unmatched-paren :red) (:matched-paren (:background (0.3 0.875 0.8125 1))))) (ccl:defloadvar *lisp-code-colors-cache* nil) (defun cached-lisp-code-colors () (let ((specs (car *lisp-code-colors-cache*)) (alist (cdr *lisp-code-colors-cache*)) (user-alist *lisp-code-colors*)) (flet ((get-spec (cell) (let ((spec (cdr cell))) (if (and (consp spec) (null (cdr spec))) (car spec) spec)))) (declare (inline get-spec)) (unless (and (eql (length user-alist) (length alist)) (loop for spec in specs for cell in alist for user-cell in user-alist always (and (eq (car cell) (car user-cell)) (eq spec (get-spec user-cell))))) (setq specs (mapcar #'get-spec user-alist)) (setq alist (mapcar #'(lambda (user-cell spec) (cons (car user-cell) (if (and (consp spec) (keywordp (car spec)) (null (cddr spec))) (cons (car spec) (hemlock-ext:lookup-color (cadr spec))) (cons :foreground (hemlock-ext:lookup-color spec))))) user-alist specs)) (setq *lisp-code-colors-cache* (cons specs alist))) alist))) (defun hemlock:compute-paren-highlighting () "Compute the positions of the characters to be shown as matching parens" (let* ((point (current-point)) (color-alist (cached-lisp-code-colors)) (color (cdr (assq :matched-paren color-alist)))) (when color (cond ((test-char (next-character point) :lisp-syntax :open-paren) (pre-command-parse-check point) (when (valid-spot point t) (with-mark ((temp point)) (when (list-offset temp 1) (list (cons (mark-absolute-position point) color) (cons (1- (mark-absolute-position temp)) color)))))) ((test-char (previous-character point) :lisp-syntax :close-paren) (pre-command-parse-check point) (when (valid-spot point nil) (with-mark ((temp point)) (when (list-offset temp -1) (list (cons (mark-absolute-position temp) color) (cons (1- (mark-absolute-position point)) color)))))))))) Return nil to use the default Cocoa selection , which will be word for double - click , line for triple . (defun hemlock:selection-for-click (mark paragraph-mode-p) Handle lisp mode specially , otherwise just go with default Cocoa behavior (when (lisp-mode? mark) (unless paragraph-mode-p (let ((region (word-region-at-mark mark))) (when region (return-from selection-for-click region)))) (pre-command-parse-check mark) (form-region-at-mark mark))) (defun hemlock:move-point-for-click (buffer index) (let* ((point (buffer-point buffer)) (mark (and (%buffer-region-active-p buffer) (buffer-mark buffer)))) (setf (hi::buffer-region-active buffer) nil) (if (and mark (eql (mark-absolute-position mark) index)) (move-mark mark point) (push-new-buffer-mark point)) (move-to-absolute-position point index)))) (defun shortest-package-name (package) (let* ((name (package-name package)) (len (length name))) (dolist (nick (package-nicknames package) name) (let* ((nicklen (length nick))) (if (< nicklen len) (setq name nick len nicklen)))))) (defun hemlock:update-current-package (&optional pkg (buffer (current-buffer))) (when (lisp-mode? buffer) (unless pkg (setq pkg (or (package-at-mark (current-point)) (variable-value 'default-package :buffer buffer)))) (when pkg (let* ((name (if (packagep pkg) (package-name pkg) (string pkg))) (curname (variable-value 'current-package :buffer buffer))) (when (setq pkg (find-package name)) (setq name (shortest-package-name pkg))) (if (or (null curname) (not (string= curname name))) (setf (variable-value 'current-package :buffer buffer) name)))))) (defun %scan-to-symbol (mark) (loop while (%scan-to-form mark t) do (unless (test-char (next-character mark) :lisp-syntax (or :string-quote :open-paren :close-paren)) (return mark)) do (mark-after mark))) (defun %scan-down-to-atom (mark) (loop while (%scan-to-form mark t) do (unless (test-char (next-character mark) :lisp-syntax :open-paren) (return mark)) do (mark-after mark))) #+debug (defun buffer-short-name () (let* ((full-name (buffer-name (current-buffer))) (pos (position #\space full-name))) (if pos (subseq full-name 0 pos) full-name))) (defparameter $coloring-cache-extra 1000) (defstruct coloring-cache (tick nil) (start 0) (end 0) (colors nil) (data nil)) (defun make-sym-vec () (make-array 0 :displaced-to "" :adjustable t)) (defun displace-to-region (sym-vec start-mark end-mark) (let* ((sym-line (mark-line start-mark)) (line-str (line-string sym-line)) (start-pos (mark-charpos start-mark)) (end-pos (if (eq sym-line (mark-line end-mark)) (mark-charpos end-mark) (progn (setq line-str (region-to-string (region start-mark end-mark))) (setq start-pos 0) (length line-str))))) (ccl::%displace-array sym-vec nil (- end-pos start-pos) line-str start-pos T))) #+debug (defmethod print-object ((cache coloring-cache) stream) (print-unreadable-object (stream cache :identity nil :type t) (format stream "~s:~s @~s" (coloring-cache-start cache) (coloring-cache-end cache) (coloring-cache-tick cache)))) (defun hemlock:compute-syntax-coloring (start-pos length) (let* ((buffer (current-buffer)) (end-pos (+ start-pos length)) (tick (buffer-signature buffer)) (colors (cached-lisp-code-colors)) (cache (or (getf (buffer-plist buffer) 'coloring-cache) (setf (getf (buffer-plist buffer) 'coloring-cache) (make-coloring-cache))))) (unless (and (eql (coloring-cache-tick cache) tick) (<= (coloring-cache-start cache) start-pos) (<= end-pos (coloring-cache-end cache)) (eq colors (coloring-cache-colors cache))) (setq start-pos (max 0 (- start-pos $coloring-cache-extra))) (setq end-pos (+ end-pos $coloring-cache-extra)) (let ((res (compute-syntax-coloring-in-region buffer start-pos end-pos))) (setf (coloring-cache-start cache) start-pos (coloring-cache-end cache) end-pos (coloring-cache-colors cache) colors (coloring-cache-data cache) res (coloring-cache-tick cache) tick))) (coloring-cache-data cache))) (defun case-insensitive-string-to-symbol (string pkg) (when (null pkg) (setq pkg *package*)) (let* ((str (coerce string 'simple-string))) (ignore-errors (case (readtable-case *readtable*) (:upcase (find-symbol (nstring-upcase str) pkg)) (:downcase (find-symbol (nstring-downcase str) pkg)) (:preserve (find-symbol str pkg)) (t (find-symbol (nstring-upcase str) pkg) ))))) (defun mark-at-invocation-p (start-mark) (and (test-char (previous-character start-mark) :lisp-syntax :open-paren) (prog2 (mark-before start-mark) (not (test-char (previous-character start-mark) :lisp-syntax (or :prefix :open-paren))) (mark-after start-mark)))) (defun compute-symbol-category (start-mark sym) (when (ccl::non-nil-symbol-p sym) (cond ((and (or (macro-function sym) (ccl::special-form-p sym)) (mark-at-invocation-p start-mark)) :system-symbol) ((keywordp sym) :keyword) (t nil)))) (defvar *defining-symbols* '(defun defgeneric defmethod defmacro define-compiler-macro define-modify-macro define-symbol-macro define-setf-expander defsetf defvar defparameter defconstant define-method-combination defclass defstruct deftype define-condition defpackage ccl:advise ccl:def-load-pointers ccl:define-definition-type ccl:defloadvar ccl:defglobal ccl:defstaticvar ccl:define-declaration ccl:defstatic ccl:defcallback ccl:define-setf-method ccl:define-character-encoding ccl:defglobal hemlock-interface:defcommand hemlock-interface:define-file-option hemlock-interface:define-file-type-hook hemlock-interface:define-keysym-code gui::def-cocoa-default objc:define-objc-class-method objc:define-objc-method objc:defmethod)) If true , the next atom following this sym will be automatically categorized as : definition , without going through compute - symbol - category . (defun defining-symbol-p (start-mark sym) (and (mark-at-invocation-p start-mark) (or (let ((str (string sym))) (and (> (length str) 3) (string-equal "def" str :end2 3))) color top - level setq 's , just for fun (eq sym 'setq)))))) (defun compute-string/comment-coloring-in-region (region-start region-end) (when (lisp-mode? region-start) (let* ((lisp-code-colors (cached-lisp-code-colors)) (start-line (mark-line region-start)) (end-line (line-next (mark-line region-end))) (start-charpos (mark-charpos region-start))) (assert (not (eq start-line end-line))) (loop for line = start-line then (line-next line) until (eq line end-line) for info = (getf (line-plist line) 'lisp-info) when info nconc (loop with origin = (hi::line-origin line) for last-end = 0 then end-offset for (start-offset . end-offset) in (lisp-info-ranges-to-ignore info) for syntax = (if (eql start-offset 0) (lisp-info-begins-quoted info) (if (< last-end start-offset) (character-attribute :lisp-syntax (line-character line (1- start-offset))) :comment)) do (when (member syntax '(:symbol-quote :string-quote)) (when (< 0 start-offset) (decf start-offset)) (when (< end-offset (line-length line)) (incf end-offset))) unless (and (eq line start-line) (<= end-offset start-charpos)) nconc (let* ((type (case syntax ((:char-quote :symbol-quote) nil) (:string-quote :string) (t (loop for i from start-offset as nsemi upfrom 0 until (or (eql nsemi 3) (eql i end-offset) (not (test-char (line-character line i) :lisp-syntax :comment))) finally (return (case nsemi (2 :double-comment) (3 :triple-comment) (t :comment))))))) (color (and type (cdr (assq type lisp-code-colors))))) (when color (list (list* (+ origin start-offset) (- end-offset start-offset) color))))))))) (defun coloring-region (start-mark end-mark color) (when color (let* ((start (mark-absolute-position start-mark)) (end (mark-absolute-position end-mark)) (len (- end start))) (when (> len 0) (list* start len color))))) (defun compute-symbol-coloring-in-region (region-start region-end) (when (lisp-mode? region-start) (let* ((sym-vec (make-sym-vec)) (pkg nil) (lisp-colors (cached-lisp-code-colors)) (defn-color (cdr (assq :definition lisp-colors)))) (with-mark ((start-mark region-start) (end-mark region-start)) (let ((pkgname (package-at-mark region-end end-mark))) (when pkgname (when (mark< region-start end-mark) Argh , more than one package in region . KLUDGE ! ! (return-from compute-symbol-coloring-in-region (nconc (compute-symbol-coloring-in-region region-start (mark-before end-mark)) (compute-symbol-coloring-in-region (mark-after end-mark) region-end)))) (setq pkg (find-package pkgname)))) (loop while (and (%scan-to-symbol start-mark) (mark< start-mark region-end)) for sym = (progn (move-mark end-mark start-mark) (unless (forward-form end-mark) (move-mark end-mark region-end)) (case-insensitive-string-to-symbol (displace-to-region sym-vec start-mark end-mark) pkg)) for type = (compute-symbol-category start-mark sym) for reg = (when type (let ((color (cdr (assq type lisp-colors)))) (when color (coloring-region start-mark end-mark color)))) when reg collect reg when (and defn-color (defining-symbol-p start-mark sym) (form-offset (move-mark start-mark end-mark) 1) (%scan-down-to-atom end-mark) (mark< end-mark region-end)) collect (progn (move-mark start-mark end-mark) (unless (and (forward-form end-mark) (mark<= end-mark region-end)) (move-mark end-mark region-end)) (unless (mark< start-mark end-mark) (warn "definition got start ~s end ~s region-end ~s" start-mark end-mark region-end) (move-mark end-mark start-mark)) (coloring-region start-mark end-mark defn-color)) do (rotatef start-mark end-mark)))))) (defun compute-unmatched-parens-coloring-in-region (start-mark end-mark) (macrolet ((scan-loop (forwardp open-key buffer-start-mark start-line end-line close-key) `(loop with paren-count = 0 with limit-line = (neighbor-line ,end-line ,forwardp) with in-region-p = nil for line = (mark-line (,buffer-start-mark (mark-buffer m))) then (neighbor-line line ,forwardp) until (eq line limit-line) for info = (or (getf (line-plist line) 'lisp-info) (return nil)) as parens-on-line = ,(if forwardp '(lisp-info-net-close-parens info) '(lisp-info-net-open-parens info)) do (when (eq line ,start-line) (setq in-region-p t)) do (decf paren-count parens-on-line) do (when (< paren-count 0) (when in-region-p ,(if forwardp '(line-start m line) '(line-end m line)) (loop with net-count = (+ paren-count parens-on-line) doing (unless (scan-direction-valid m ,forwardp :lisp-syntax (or :close-paren :open-paren :newline)) (error "couldn't find ~s mismatches" (- paren-count))) (ecase (character-attribute :lisp-syntax (direction-char m ,forwardp)) (,open-key (incf net-count)) (,close-key (when (< (decf net-count) 0) (push (cons ,(if forwardp '(mark-absolute-position m) '(1- (mark-absolute-position m))) coloring-data) result) (when (eql (incf paren-count) 0) (return)) (setq net-count 0)))) (neighbor-mark m ,forwardp))) (setq paren-count 0)) do (incf paren-count ,(if forwardp '(lisp-info-net-open-parens info) '(lisp-info-net-close-parens info)))))) (with-mark ((m start-mark)) (let* ((end-line (mark-line end-mark)) (start-line (mark-line start-mark)) (color (or (cdr (assq :unmatched-paren (cached-lisp-code-colors))) (return-from compute-unmatched-parens-coloring-in-region nil))) (coloring-data (cons 1 color)) (result nil)) result)))) (defun compute-syntax-coloring-in-region (buffer start-pos end-pos) (let* ((some-mark (buffer-point buffer))) (with-mark ((start-mark some-mark) (end-mark some-mark)) (unless (move-to-absolute-position start-mark start-pos) (buffer-end start-mark)) (unless (move-to-absolute-position end-mark end-pos) (buffer-end end-mark)) (assert (mark<= start-mark end-mark)) (when (mark< start-mark end-mark) (pre-command-parse-check start-mark) (sort (nconc (compute-string/comment-coloring-in-region start-mark end-mark) (compute-symbol-coloring-in-region start-mark end-mark) (compute-unmatched-parens-coloring-in-region start-mark end-mark)) #'< :key #'car)))))
0474a6544a6e388836b482cbb6dda649a81dd610a12a8298bb9d2e391486380f
TGOlson/blockchain
BlockchainConfig.hs
module Data.Blockchain.Types.BlockchainConfig ( BlockchainConfig(..) , defaultConfig , targetReward , targetDifficulty ) where import Control.Monad (when) import qualified Data.Aeson as Aeson import qualified Data.Time.Clock as Time import qualified Data.Word as Word import qualified GHC.Generics as Generic import Data.Blockchain.Types.Block import Data.Blockchain.Types.Difficulty import Data.Blockchain.Types.Hex data BlockchainConfig = BlockchainConfig { initialDifficulty :: Difficulty -- Maximum hash - difficulties will be calculated using this value , difficulty1Target :: Hex256 , targetSecondsPerBlock :: Word.Word , difficultyRecalculationHeight :: Word.Word , initialMiningReward :: Word.Word -- Defines num blocks when reward is halved -- `0` means reward never changes , miningRewardHalvingHeight :: Word.Word } deriving (Generic.Generic, Eq, Show) instance Aeson.FromJSON BlockchainConfig instance Aeson.ToJSON BlockchainConfig -- | A reasonable default config to use for testing. Mines blocks quickly and changes difficulty and rewards frequently. Note : reward will go to zero after 1100 blocks , which will take about 180 minutes of mining . -- -- @ defaultConfig : : BlockchainConfig defaultConfig = BlockchainConfig { initialDifficulty = Difficulty 1 , = hex256LeadingZeros 4 , targetSecondsPerBlock = 10 , = 50 , initialMiningReward = 1024 , miningRewardHalvingHeight = 100 -- } -- @ -- defaultConfig :: BlockchainConfig defaultConfig = BlockchainConfig { initialDifficulty = Difficulty 1 , difficulty1Target = hex256LeadingZeros 4 , targetSecondsPerBlock = 10 , difficultyRecalculationHeight = 50 , initialMiningReward = 1024 , miningRewardHalvingHeight = 100 } -- | Calculates the target reward for a blockchain. Uses the longest chain. targetReward :: BlockchainConfig -> Word.Word -> Word.Word targetReward config height = either id id $ do let initialReward = initialMiningReward config halveHeight = miningRewardHalvingHeight config when (halveHeight == 0) $ Left initialReward let numHalves = height `div` halveHeight 2 ^ 64 is greater than maxBound : : Word And any word halved 64 times will be zero when (numHalves >= 64) $ Left 0 return $ initialReward `div` (2 ^ numHalves) -- TODO: array of blocks hold no assurances of expected invariants -- for example block1 could be created more recently than blockN should create a ` SingleChain ` wrapper -- TODO: take in entire blockchain -- | Calculates the target difficulty for a blockchain. Uses the longest chain. targetDifficulty :: BlockchainConfig -> [Block] -> Difficulty targetDifficulty config [] = initialDifficulty config targetDifficulty config _ | difficultyRecalculationHeight config == 0 = initialDifficulty config targetDifficulty config _ | difficultyRecalculationHeight config == 1 = initialDifficulty config targetDifficulty config _ | targetSecondsPerBlock config == 0 = initialDifficulty config targetDifficulty config blocks | length blocks = = 1 = initialDifficulty config -- super messy ... targetDifficulty config blocks = case length blocks `mod` fromIntegral recalcHeight of -- Note: this includes the genesis block, is that correct? 0 -> let recentBlocks = take (fromIntegral recalcHeight) (reverse blocks) -- TODO: (drop (length blocks - recalcHeight)) lastBlock = head recentBlocks firstBlock = last recentBlocks -- TODO: get rid of `abs`, move invariant into types diffTime = abs $ Time.diffUTCTime (blockTime lastBlock) (blockTime firstBlock) avgSolveTime = realToFrac diffTime / fromIntegral recalcHeight solveRate = fromIntegral (targetSecondsPerBlock config) / avgSolveTime lastDifficulty = difficulty (blockHeader lastBlock) nextDifficulty = Difficulty $ round $ solveRate * toRational lastDifficulty in nextDifficulty _ -> difficulty $ blockHeader $ last blocks where recalcHeight = difficultyRecalculationHeight config blockTime = time . blockHeader
null
https://raw.githubusercontent.com/TGOlson/blockchain/da53ad888589b5a2f3fd2c53c33a399fefb48ab1/lib/Data/Blockchain/Types/BlockchainConfig.hs
haskell
Maximum hash - difficulties will be calculated using this value Defines num blocks when reward is halved -- `0` means reward never changes | A reasonable default config to use for testing. Mines blocks quickly and changes difficulty and rewards frequently. @ } @ | Calculates the target reward for a blockchain. Uses the longest chain. TODO: array of blocks hold no assurances of expected invariants for example block1 could be created more recently than blockN TODO: take in entire blockchain | Calculates the target difficulty for a blockchain. Uses the longest chain. super messy ... Note: this includes the genesis block, is that correct? TODO: (drop (length blocks - recalcHeight)) TODO: get rid of `abs`, move invariant into types
module Data.Blockchain.Types.BlockchainConfig ( BlockchainConfig(..) , defaultConfig , targetReward , targetDifficulty ) where import Control.Monad (when) import qualified Data.Aeson as Aeson import qualified Data.Time.Clock as Time import qualified Data.Word as Word import qualified GHC.Generics as Generic import Data.Blockchain.Types.Block import Data.Blockchain.Types.Difficulty import Data.Blockchain.Types.Hex data BlockchainConfig = BlockchainConfig { initialDifficulty :: Difficulty , difficulty1Target :: Hex256 , targetSecondsPerBlock :: Word.Word , difficultyRecalculationHeight :: Word.Word , initialMiningReward :: Word.Word , miningRewardHalvingHeight :: Word.Word } deriving (Generic.Generic, Eq, Show) instance Aeson.FromJSON BlockchainConfig instance Aeson.ToJSON BlockchainConfig Note : reward will go to zero after 1100 blocks , which will take about 180 minutes of mining . defaultConfig : : BlockchainConfig defaultConfig = BlockchainConfig { initialDifficulty = Difficulty 1 , = hex256LeadingZeros 4 , targetSecondsPerBlock = 10 , = 50 , initialMiningReward = 1024 , miningRewardHalvingHeight = 100 defaultConfig :: BlockchainConfig defaultConfig = BlockchainConfig { initialDifficulty = Difficulty 1 , difficulty1Target = hex256LeadingZeros 4 , targetSecondsPerBlock = 10 , difficultyRecalculationHeight = 50 , initialMiningReward = 1024 , miningRewardHalvingHeight = 100 } targetReward :: BlockchainConfig -> Word.Word -> Word.Word targetReward config height = either id id $ do let initialReward = initialMiningReward config halveHeight = miningRewardHalvingHeight config when (halveHeight == 0) $ Left initialReward let numHalves = height `div` halveHeight 2 ^ 64 is greater than maxBound : : Word And any word halved 64 times will be zero when (numHalves >= 64) $ Left 0 return $ initialReward `div` (2 ^ numHalves) should create a ` SingleChain ` wrapper targetDifficulty :: BlockchainConfig -> [Block] -> Difficulty targetDifficulty config [] = initialDifficulty config targetDifficulty config _ | difficultyRecalculationHeight config == 0 = initialDifficulty config targetDifficulty config _ | difficultyRecalculationHeight config == 1 = initialDifficulty config targetDifficulty config _ | targetSecondsPerBlock config == 0 = initialDifficulty config targetDifficulty config blocks = case length blocks `mod` fromIntegral recalcHeight of 0 -> lastBlock = head recentBlocks firstBlock = last recentBlocks diffTime = abs $ Time.diffUTCTime (blockTime lastBlock) (blockTime firstBlock) avgSolveTime = realToFrac diffTime / fromIntegral recalcHeight solveRate = fromIntegral (targetSecondsPerBlock config) / avgSolveTime lastDifficulty = difficulty (blockHeader lastBlock) nextDifficulty = Difficulty $ round $ solveRate * toRational lastDifficulty in nextDifficulty _ -> difficulty $ blockHeader $ last blocks where recalcHeight = difficultyRecalculationHeight config blockTime = time . blockHeader
bbe5ac123860a3b4c5957f99aea74debb1b3a5938b2bf62bbef4157ceaa277a4
nuprl/gradual-typing-performance
eval.rkt
#lang racket/base (require "manual.rkt" "struct.rkt" "scheme.rkt" "decode.rkt" (only-in "core.rkt" content?) racket/list file/convertible ;; attached into new namespace via anchor racket/serialize ;; attached into new namespace via anchor racket/pretty ;; attached into new namespace via anchor scribble/private/serialize ;; attached into new namespace via anchor racket/sandbox racket/promise racket/port racket/gui/dynamic (for-syntax racket/base syntax/srcloc unstable/struct) racket/stxparam racket/splicing racket/string scribble/text/wrap) (provide interaction interaction0 interaction/no-prompt interaction-eval interaction-eval-show racketblock+eval (rename-out [racketblock+eval schemeblock+eval]) racketblock0+eval racketmod+eval (rename-out [racketmod+eval schememod+eval]) def+int defs+int examples examples* defexamples defexamples* as-examples make-base-eval make-base-eval-factory make-eval-factory close-eval scribble-exn->string scribble-eval-handler with-eval-preserve-source-locations) (define scribble-eval-handler (make-parameter (lambda (ev c? x) (ev x)))) (define image-counter 0) (define maxlen 60) (define-namespace-anchor anchor) (define (literal-string style s) (let ([m (regexp-match #rx"^(.*)( +|^ )(.*)$" s)]) (if m (make-element #f (list (literal-string style (cadr m)) (hspace (string-length (caddr m))) (literal-string style (cadddr m)))) (make-element style (list s))))) (define list.flow.list (compose1 list make-flow list)) (define (format-output str style) (if (string=? "" str) '() (list (list.flow.list (let ([s (regexp-split #rx"\n" (regexp-replace #rx"\n$" str ""))]) (if (= 1 (length s)) (make-paragraph (list (literal-string style (car s)))) (make-table #f (map (lambda (s) (list.flow.list (make-paragraph (list (literal-string style s))))) s)))))))) (define (format-output-stream in style) (define (add-string string-accum line-accum) (if string-accum (cons (list->string (reverse string-accum)) (or line-accum null)) line-accum)) (define (add-line line-accum flow-accum) (if line-accum (cons (make-paragraph (map (lambda (s) (if (string? s) (literal-string style s) s)) (reverse line-accum))) flow-accum) flow-accum)) (let loop ([string-accum #f] [line-accum #f] [flow-accum null]) (let ([v (read-char-or-special in)]) (cond [(eof-object? v) (let* ([line-accum (add-string string-accum line-accum)] [flow-accum (add-line line-accum flow-accum)]) (list (list.flow.list (if (= 1 (length flow-accum)) (car flow-accum) (make-table #f (map list.flow.list (reverse flow-accum)))))))] [(equal? #\newline v) (loop #f #f (add-line (add-string string-accum line-accum) flow-accum))] [(char? v) (loop (cons v (or string-accum null)) line-accum flow-accum)] [else (loop #f (cons v (or (add-string string-accum line-accum) null)) flow-accum)])))) (define (string->wrapped-lines str) (apply append (for/list ([line-str (regexp-split #rx"\n" str)]) (wrap-line line-str maxlen (λ (word fits) (if ((string-length word) . > . maxlen) (values (substring word 0 fits) (substring word fits) #f) (values #f word #f))))))) (struct formatted-result (content)) (define (interleave inset? title expr-paras val-list+outputs) (let ([lines (let loop ([expr-paras expr-paras] [val-list+outputs val-list+outputs] [first? #t]) (if (null? expr-paras) null (append (list (list (let ([p (car expr-paras)]) (if (flow? p) p (make-flow (list p)))))) (format-output (cadar val-list+outputs) output-color) (format-output (caddar val-list+outputs) error-color) (cond [(string? (caar val-list+outputs)) ;; Error result case: (map (lambda (s) (define p (format-output s error-color)) (if (null? p) (list null) (car p))) (string->wrapped-lines (caar val-list+outputs)))] [(box? (caar val-list+outputs)) ;; Output written to a port (format-output-stream (unbox (caar val-list+outputs)) result-color)] [else ;; Normal result case: (let ([val-list (caar val-list+outputs)]) (if (equal? val-list (list (void))) null (map (lambda (v) (list.flow.list (make-paragraph (list (if (formatted-result? v) (formatted-result-content v) (elem #:style result-color (to-element/no-color v #:expr? (print-as-expression)))))))) val-list)))]) (loop (cdr expr-paras) (cdr val-list+outputs) #f))))]) (if inset? (let ([p (code-inset (make-table block-color lines))]) (if title (make-table block-color (list (list.flow.list title) (list.flow.list p))) p)) (make-table block-color (if title (cons (list.flow.list title) lines) lines))))) ;; extracts from a datum or syntax object --- while keeping the ;; syntax-objectness of the original intact, instead of always ;; generating a syntax object or always generating a datum (define (extract s . ops) (let loop ([s s] [ops ops]) (cond [(null? ops) s] [(syntax? s) (loop (syntax-e s) ops)] [else (loop ((car ops) s) (cdr ops))]))) (struct nothing-to-eval ()) (struct eval-results (contents out err)) (define (make-eval-results contents out err) (unless (and (list? contents) (andmap content? contents)) (raise-argument-error 'eval:results "(listof content?)" contents)) (unless (string? out) (raise-argument-error 'eval:results "string?" out)) (unless (string? err) (raise-argument-error 'eval:results "string?" err)) (eval-results contents out err)) (define (make-eval-result content out err) (unless (content? content) (raise-argument-error 'eval:result "content?" content)) (unless (string? out) (raise-argument-error 'eval:result "string?" out)) (unless (string? err) (raise-argument-error 'eval:result "string?" err)) (eval-results (list content) out err)) (define (extract-to-evaluate s) (let loop ([s s] [expect #f]) (syntax-case s (code:line code:comment eval:alts eval:check) [(code:line v (code:comment . rest)) (loop (extract s cdr car) expect)] [(code:comment . rest) (values (nothing-to-eval) expect)] [(eval:alts p e) (loop (extract s cdr cdr car) expect)] [(eval:check e expect) (loop (extract s cdr car) (list (syntax->datum (datum->syntax #f (extract s cdr cdr car)))))] [else (values s expect)]))) (define (do-eval ev who) (define (get-outputs) (define (get getter what) (define s (getter ev)) (if (string? s) s (error who "missing ~a, possibly from a sandbox without a `sandbox-~a' configured to 'string" what (string-join (string-split what) "-")))) (list (get get-output "output") (get get-error-output "error output"))) (define (render-value v) (let-values ([(eval-print eval-print-as-expr?) (call-in-sandbox-context ev (lambda () (values (current-print) (print-as-expression))))]) (cond [(and (eq? eval-print (current-print)) eval-print-as-expr?) ;; default printer => get result as S-expression (make-reader-graph (copy-value v (make-hasheq)))] [else ;; other printer => go through a pipe ;; If it happens to be the pretty printer, tell it to retain ;; convertible objects (via write-special) (box (call-in-sandbox-context ev (lambda () (define-values [in out] (make-pipe-with-specials)) (parameterize ((current-output-port out) (pretty-print-size-hook (lambda (obj _mode _out) (and (convertible? obj) 1))) (pretty-print-print-hook (lambda (obj _mode out) (write-special (if (serializable? obj) (make-serialized-convertible (serialize obj)) obj) out)))) (map (current-print) v)) (close-output-port out) in)))]))) (define (do-ev s) (with-handlers ([(lambda (x) (not (exn:break? x))) (lambda (e) (cons ((scribble-exn->string) e) (get-outputs)))]) (cons (render-value (do-plain-eval ev s #t)) (get-outputs)))) (define (do-ev/expect s expect) (define r (do-ev s)) (when expect (let ([expect (do-plain-eval ev (car expect) #t)]) (unless (equal? (car r) expect) (raise-syntax-error 'eval "example result check failed" s)))) r) (lambda (str) (if (eval-results? str) (list (map formatted-result (eval-results-contents str)) (eval-results-out str) (eval-results-err str)) (let-values ([(s expect) (extract-to-evaluate str)]) (if (nothing-to-eval? s) (list (list (void)) "" "") (do-ev/expect s expect)))))) (define scribble-exn->string (make-parameter (λ (e) (if (exn? e) (exn-message e) (format "uncaught exception: ~s" e))))) ;; Since we evaluate everything in an interaction before we typeset, ;; copy each value to avoid side-effects. (define (copy-value v ht) (define (install v v2) (hash-set! ht v v2) v2) (let loop ([v v]) (cond [(and v (hash-ref ht v #f)) => (lambda (v) v)] [(syntax? v) (make-literal-syntax v)] [(string? v) (install v (string-copy v))] [(bytes? v) (install v (bytes-copy v))] [(pair? v) (let ([ph (make-placeholder #f)]) (hash-set! ht v ph) (placeholder-set! ph (cons (loop (car v)) (loop (cdr v)))) ph)] [(mpair? v) (let ([p (mcons #f #f)]) (hash-set! ht v p) (set-mcar! p (loop (mcar v))) (set-mcdr! p (loop (mcdr v))) p)] [(vector? v) (let ([v2 (make-vector (vector-length v))]) (hash-set! ht v v2) (for ([i (in-range (vector-length v2))]) (vector-set! v2 i (loop (vector-ref v i)))) v2)] [(box? v) (let ([v2 (box #f)]) (hash-set! ht v v2) (set-box! v2 (loop (unbox v))) v2)] [(hash? v) (let ([ph (make-placeholder #f)]) (hash-set! ht v ph) (let ([a (hash-map v (lambda (k v) (cons (loop k) (loop v))))]) (placeholder-set! ph (cond [(hash-eq? v) (make-hasheq-placeholder a)] [(hash-eqv? v) (make-hasheqv-placeholder a)] [else (make-hash-placeholder a)]))) ph)] [else v]))) (define (strip-comments stx) (cond [(syntax? stx) (datum->syntax stx (strip-comments (syntax-e stx)) stx stx stx)] [(pair? stx) (define a (car stx)) (define (comment? a) (and (pair? a) (or (eq? (car a) 'code:comment) (and (identifier? (car a)) (eq? (syntax-e (car a)) 'code:comment))))) (if (or (comment? a) (and (syntax? a) (comment? (syntax-e a)))) (strip-comments (cdr stx)) (cons (strip-comments a) (strip-comments (cdr stx))))] [(eq? stx 'code:blank) (void)] [else stx])) (define (make-base-eval #:lang [lang '(begin)] #:pretty-print? [pretty-print? #t] . ips) (call-with-trusted-sandbox-configuration (lambda () (parameterize ([sandbox-output 'string] [sandbox-error-output 'string] [sandbox-propagate-breaks #f] [sandbox-namespace-specs (append (sandbox-namespace-specs) (if pretty-print? '(racket/pretty) '()) '(file/convertible racket/serialize scribble/private/serialize))]) (let ([e (apply make-evaluator lang ips)]) (when pretty-print? (call-in-sandbox-context e (lambda () (current-print (dynamic-require 'racket/pretty 'pretty-print-handler))))) e))))) (define (make-base-eval-factory mod-paths #:lang [lang '(begin)] #:pretty-print? [pretty-print? #t] . ips) (parameterize ([sandbox-namespace-specs (cons (λ () (let ([ns ;; This namespace-creation choice needs to be consistent ;; with the sandbox (i.e., with `make-base-eval') (if gui? ((gui-dynamic-require 'make-gui-empty-namespace)) (make-base-empty-namespace))]) (parameterize ([current-namespace ns]) (for ([mod-path (in-list mod-paths)]) (dynamic-require mod-path #f)) (when pretty-print? (dynamic-require 'racket/pretty #f))) ns)) (append mod-paths (if pretty-print? '(racket/pretty) '())))]) (lambda () (let ([ev (apply make-base-eval #:lang lang #:pretty-print? #f ips)]) (when pretty-print? (call-in-sandbox-context ev (lambda () (current-print (dynamic-require 'racket/pretty 'pretty-print-handler))))) ev)))) (define (make-eval-factory mod-paths #:lang [lang '(begin)] #:pretty-print? [pretty-print? #t] . ips) (let ([base-factory (apply make-base-eval-factory mod-paths #:lang lang #:pretty-print? pretty-print? ips)]) (lambda () (let ([ev (base-factory)]) (call-in-sandbox-context ev (lambda () (for ([mod-path (in-list mod-paths)]) (namespace-require mod-path)))) ev)))) (define (close-eval e) (kill-evaluator e) "") (define (do-plain-eval ev s catching-exns?) (parameterize ([sandbox-propagate-breaks #f]) (call-with-values (lambda () ((scribble-eval-handler) ev catching-exns? (let ([s (strip-comments s)]) (cond [(syntax? s) (syntax-case s (module) [(module . _rest) (syntax->datum s)] [_else s])] ;; a sandbox treats strings and byte strings as code ;; streams, so protect them as syntax objects: [(string? s) (datum->syntax #f s)] [(bytes? s) (datum->syntax #f s)] [else s])))) list))) (define-syntax-parameter quote-expr-preserve-source? #f) (define-syntax (with-eval-preserve-source-locations stx) (syntax-case stx () [(with-eval-preserve-source-locations e ...) (syntax/loc stx (splicing-syntax-parameterize ([quote-expr-preserve-source? #t]) e ...))])) ;; Quote an expression to be evaluated or wrap as escaped: (define-syntax quote-expr (syntax-rules (eval:alts eval:result eval:results) [(_ (eval:alts e1 e2)) (quote-expr e2)] [(_ (eval:result e)) (make-eval-result (list e) "" "")] [(_ (eval:result e out)) (make-eval-result (list e) out "")] [(_ (eval:result e out err)) (make-eval-result (list e) out err)] [(_ (eval:results es)) (make-eval-results es "" "")] [(_ (eval:results es out)) (make-eval-results es out "")] [(_ (eval:results es out err)) (make-eval-results es out err)] [(_ e) (base-quote-expr e)])) (define orig-stx (read-syntax 'orig (open-input-string "()"))) (define-syntax (base-quote-expr stx) (syntax-case stx () [(_ e) (cond [(syntax-parameter-value #'quote-expr-preserve-source?) ;; Preserve source; produce an expression resulting in a ;; syntax object with no lexical context (like strip-context) ;; but with (quotable) source locations. ;; Also preserve syntax-original?, since that seems important ;; to some syntax-based code (eg redex term->pict). (define (get-source-location e) (let* ([src (build-source-location-list e)] [old-source (source-location-source src)] [new-source (cond [(path? old-source) ;; not quotable/writable ;;(path->string old-source) ;; don't leak build paths 'eval] [(or (string? old-source) (symbol? old-source)) ;; Okay? Or should this be replaced also? old-source] [else #f])]) (update-source-location src #:source new-source))) (let loop ([e #'e]) (cond [(syntax? e) (let ([src (get-source-location e)] [original? (syntax-original? (syntax-local-introduce e))]) #`(syntax-property (datum->syntax #f #,(loop (syntax-e e)) (quote #,src) #,(if original? #'orig-stx #'#f)) 'paren-shape (quote #,(syntax-property e 'paren-shape))))] [(pair? e) #`(cons #,(loop (car e)) #,(loop (cdr e)))] [(vector? e) #`(list->vector #,(loop (vector->list e)))] [(box? e) #`(box #,(loop (unbox e)))] [(prefab-struct-key e) => (lambda (key) #`(apply make-prefab-struct (quote #,key) #,(loop (struct->list e))))] [else #`(quote #,e)]))] [else ;; Using quote means that sandbox evaluation works on ;; sexprs; to get it to work on syntaxes, use ;; (strip-context (quote-syntax e))) ;; while importing ;; (require syntax/strip-context) #'(quote e)])])) (define (do-interaction-eval ev e) (let-values ([(e expect) (extract-to-evaluate e)]) (unless (nothing-to-eval? e) (parameterize ([current-command-line-arguments #()]) (do-plain-eval (or ev (make-base-eval)) e #f))) "")) (define-syntax interaction-eval (syntax-rules () [(_ #:eval ev e) (do-interaction-eval ev (quote-expr e))] [(_ e) (do-interaction-eval #f (quote-expr e))])) (define (show-val v) (elem #:style result-color (to-element/no-color v #:expr? (print-as-expression)))) (define (do-interaction-eval-show ev e) (parameterize ([current-command-line-arguments #()]) (show-val (car (do-plain-eval (or ev (make-base-eval)) e #f))))) (define-syntax interaction-eval-show (syntax-rules () [(_ #:eval ev e) (do-interaction-eval-show ev (quote-expr e))] [(_ e) (do-interaction-eval-show #f (quote-expr e))])) (define-syntax racketinput* (syntax-rules (eval:alts code:comment) [(_ #:escape id (code:comment . rest)) (racketblock0 #:escape id (code:comment . rest))] [(_ #:escape id (eval:alts a b)) (racketinput* #:escape id a)] [(_ #:escape id e) (racketinput0 #:escape id e)])) (define-syntax racketblock* (syntax-rules (eval:alts code:comment) [(_ #:escape id (code:comment . rest)) (racketblock0 #:escape id (code:comment . rest))] [(_ #:escape id (eval:alts a b)) (racketblock #:escape id a)] [(_ #:escape id e) (racketblock0 #:escape id e)])) (define-code racketblock0+line (to-paragraph/prefix "" "" (list " "))) (define-syntax (racketdefinput* stx) (syntax-case stx (define define-values define-struct) [(_ #:escape id (define . rest)) (syntax-case stx () [(_ #:escape _ e) #'(racketblock0+line #:escape id e)])] [(_ #:escape id (define-values . rest)) (syntax-case stx () [(_ #:escape _ e) #'(racketblock0+line #:escape id e)])] [(_ #:escape id (define-struct . rest)) (syntax-case stx () [(_ #:escape _ e) #'(racketblock0+line #:escape id e)])] [(_ #:escape id (code:line (define . rest) . rest2)) (syntax-case stx () [(_ #:escape _ e) #'(racketblock0+line #:escape id e)])] [(_ #:escape id e) #'(racketinput* #:escape id e)])) (define (do-titled-interaction who inset? ev t shows evals) (interleave inset? t shows (map (do-eval ev who) evals))) (define-syntax titled-interaction (syntax-rules () [(_ who inset? t racketinput* #:eval ev #:escape unsyntax-id e ...) (do-titled-interaction 'who inset? ev t (list (racketinput* #:escape unsyntax-id e) ...) (list (quote-expr e) ...))] [(_ who inset? t racketinput* #:eval ev e ...) (titled-interaction who inset? t racketinput* #:eval ev #:escape unsyntax e ...)] [(_ who inset? t racketinput* #:escape unsyntax-id e ...) (titled-interaction who inset? t racketinput* #:eval (make-base-eval) #:escape unsyntax-id e ...)] [(_ who inset? t racketinput* e ...) (titled-interaction who inset? t racketinput* #:eval (make-base-eval) e ...)])) (define-syntax (-interaction stx) (syntax-case stx () [(_ who e ...) (syntax/loc stx (titled-interaction who #f #f racketinput* e ...))])) (define-syntax (interaction stx) (syntax-case stx () [(H e ...) (syntax/loc stx (code-inset (-interaction H e ...)))])) (define-syntax (interaction/no-prompt stx) (syntax-case stx () [(H e ...) (syntax/loc stx (code-inset (titled-interaction who #f #f racketblock* e ...)))])) (define-syntax (interaction0 stx) (syntax-case stx () [(H e ...) (syntax/loc stx (-interaction H e ...))])) (define-syntax racketblockX+eval (syntax-rules () [(_ racketblock #:eval ev #:escape unsyntax-id e ...) (let ([eva ev]) (#%expression (begin (interaction-eval #:eval eva e) ... (racketblock #:escape unsyntax-id e ...))))] [(_ racketblock #:eval ev e ...) (racketblockX+eval racketblock #:eval ev #:escape unsyntax e ...)] [(_ racketblock #:escape unsyntax-id e ...) (racketblockX+eval racketblock #:eval (make-base-eval) #:escape unsyntax-id e ...)] [(_ racketblock e ...) (racketblockX+eval racketblock #:eval (make-base-eval) #:escape unsyntax e ...)])) (define-syntax racketblock+eval (syntax-rules () [(_ e ...) (racketblockX+eval racketblock e ...)])) (define-syntax racketblock0+eval (syntax-rules () [(_ e ...) (racketblockX+eval racketblock0 e ...)])) (define-syntax racketmod+eval (syntax-rules () [(_ #:eval ev #:escape unsyntax-id name e ...) (let ([eva ev]) (#%expression (begin (interaction-eval #:eval eva e) ... (racketmod #:escape unsyntax-id name e ...))))] [(_ #:eval ev name e ...) (racketmod+eval #:eval ev #:escape unsyntax name e ...)] [(_ #:escape unsyntax-id name e ...) (racketmod+eval #:eval (make-base-eval) #:escape unsyntax-id name e ...)] [(_ name e ...) (racketmod+eval #:eval (make-base-eval) #:escape unsyntax name e ...)])) (define-syntax (defs+int stx) (syntax-case stx () [(H #:eval ev #:escape unsyntax-id [def ...] e ...) (syntax/loc stx (let ([eva ev]) (column (list (racketblock0+eval #:eval eva #:escape unsyntax-id def ...) blank-line (-interaction H #:eval eva #:escape unsyntax-id e ...)))))] [(H #:eval ev [def ...] e ...) (syntax/loc stx (defs+int #:eval ev #:escape unsyntax [def ...] e ...))] [(_ #:escape unsyntax-id [def ...] e ...) (syntax/loc stx (defs+int #:eval (make-base-eval) #:escape unsyntax-id [def ...] e ...))] [(_ [def ...] e ...) (syntax/loc stx (defs+int #:eval (make-base-eval) [def ...] e ...))])) (define-syntax def+int (syntax-rules () [(H #:eval ev #:escape unsyntax-id def e ...) (defs+int #:eval ev #:escape unsyntax-id [def] e ...)] [(H #:eval ev def e ...) (defs+int #:eval ev [def] e ...)] [(H #:escape unsyntax-id def e ...) (defs+int #:escape unsyntax-id [def] e ...)] [(H def e ...) (defs+int [def] e ...)])) (define example-title (make-paragraph (list "Example:"))) (define examples-title (make-paragraph (list "Examples:"))) (define-syntax pick-example-title (syntax-rules () [(_ e) example-title] [(_ #:eval ev e) example-title] [(_ #:escape id e) example-title] [(_ #:eval ev #:escape id e) example-title] [(_ . _) examples-title])) (define-syntax (examples stx) (syntax-case stx () [(H e ...) (syntax/loc stx (titled-interaction H #t (pick-example-title e ...) racketinput* e ...))])) (define-syntax (examples* stx) (syntax-case stx () [(H example-title e ...) (syntax/loc stx (titled-interaction H #t example-title racketinput* e ...))])) (define-syntax (defexamples stx) (syntax-case stx () [(H e ...) (syntax/loc stx (titled-interaction H #t (pick-example-title e ...) racketdefinput* e ...))])) (define-syntax (defexamples* stx) (syntax-case stx () [(H example-title e ...) (syntax/loc stx (titled-interaction H #t example-title racketdefinput* e ...))])) (define blank-line (make-paragraph (list 'nbsp))) (define (column l) (code-inset (make-table #f (map list.flow.list l)))) (define (do-splice l) (cond [(null? l) null] [(splice? (car l)) `(,@(splice-run (car l)) ,@(do-splice (cdr l)))] [else (cons (car l) (do-splice (cdr l)))])) (define as-examples (case-lambda [(t) (as-examples examples-title t)] [(example-title t) (make-table #f (list (list.flow.list example-title) (list (make-flow (do-splice (list t))))))]))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/scribble-lib/scribble/eval.rkt
racket
attached into new namespace via anchor attached into new namespace via anchor attached into new namespace via anchor attached into new namespace via anchor Error result case: Output written to a port Normal result case: extracts from a datum or syntax object --- while keeping the syntax-objectness of the original intact, instead of always generating a syntax object or always generating a datum default printer => get result as S-expression other printer => go through a pipe If it happens to be the pretty printer, tell it to retain convertible objects (via write-special) Since we evaluate everything in an interaction before we typeset, copy each value to avoid side-effects. This namespace-creation choice needs to be consistent with the sandbox (i.e., with `make-base-eval') a sandbox treats strings and byte strings as code streams, so protect them as syntax objects: Quote an expression to be evaluated or wrap as escaped: Preserve source; produce an expression resulting in a syntax object with no lexical context (like strip-context) but with (quotable) source locations. Also preserve syntax-original?, since that seems important to some syntax-based code (eg redex term->pict). not quotable/writable (path->string old-source) ;; don't leak build paths Okay? Or should this be replaced also? Using quote means that sandbox evaluation works on sexprs; to get it to work on syntaxes, use (strip-context (quote-syntax e))) while importing (require syntax/strip-context)
#lang racket/base (require "manual.rkt" "struct.rkt" "scheme.rkt" "decode.rkt" (only-in "core.rkt" content?) racket/list racket/sandbox racket/promise racket/port racket/gui/dynamic (for-syntax racket/base syntax/srcloc unstable/struct) racket/stxparam racket/splicing racket/string scribble/text/wrap) (provide interaction interaction0 interaction/no-prompt interaction-eval interaction-eval-show racketblock+eval (rename-out [racketblock+eval schemeblock+eval]) racketblock0+eval racketmod+eval (rename-out [racketmod+eval schememod+eval]) def+int defs+int examples examples* defexamples defexamples* as-examples make-base-eval make-base-eval-factory make-eval-factory close-eval scribble-exn->string scribble-eval-handler with-eval-preserve-source-locations) (define scribble-eval-handler (make-parameter (lambda (ev c? x) (ev x)))) (define image-counter 0) (define maxlen 60) (define-namespace-anchor anchor) (define (literal-string style s) (let ([m (regexp-match #rx"^(.*)( +|^ )(.*)$" s)]) (if m (make-element #f (list (literal-string style (cadr m)) (hspace (string-length (caddr m))) (literal-string style (cadddr m)))) (make-element style (list s))))) (define list.flow.list (compose1 list make-flow list)) (define (format-output str style) (if (string=? "" str) '() (list (list.flow.list (let ([s (regexp-split #rx"\n" (regexp-replace #rx"\n$" str ""))]) (if (= 1 (length s)) (make-paragraph (list (literal-string style (car s)))) (make-table #f (map (lambda (s) (list.flow.list (make-paragraph (list (literal-string style s))))) s)))))))) (define (format-output-stream in style) (define (add-string string-accum line-accum) (if string-accum (cons (list->string (reverse string-accum)) (or line-accum null)) line-accum)) (define (add-line line-accum flow-accum) (if line-accum (cons (make-paragraph (map (lambda (s) (if (string? s) (literal-string style s) s)) (reverse line-accum))) flow-accum) flow-accum)) (let loop ([string-accum #f] [line-accum #f] [flow-accum null]) (let ([v (read-char-or-special in)]) (cond [(eof-object? v) (let* ([line-accum (add-string string-accum line-accum)] [flow-accum (add-line line-accum flow-accum)]) (list (list.flow.list (if (= 1 (length flow-accum)) (car flow-accum) (make-table #f (map list.flow.list (reverse flow-accum)))))))] [(equal? #\newline v) (loop #f #f (add-line (add-string string-accum line-accum) flow-accum))] [(char? v) (loop (cons v (or string-accum null)) line-accum flow-accum)] [else (loop #f (cons v (or (add-string string-accum line-accum) null)) flow-accum)])))) (define (string->wrapped-lines str) (apply append (for/list ([line-str (regexp-split #rx"\n" str)]) (wrap-line line-str maxlen (λ (word fits) (if ((string-length word) . > . maxlen) (values (substring word 0 fits) (substring word fits) #f) (values #f word #f))))))) (struct formatted-result (content)) (define (interleave inset? title expr-paras val-list+outputs) (let ([lines (let loop ([expr-paras expr-paras] [val-list+outputs val-list+outputs] [first? #t]) (if (null? expr-paras) null (append (list (list (let ([p (car expr-paras)]) (if (flow? p) p (make-flow (list p)))))) (format-output (cadar val-list+outputs) output-color) (format-output (caddar val-list+outputs) error-color) (cond [(string? (caar val-list+outputs)) (map (lambda (s) (define p (format-output s error-color)) (if (null? p) (list null) (car p))) (string->wrapped-lines (caar val-list+outputs)))] [(box? (caar val-list+outputs)) (format-output-stream (unbox (caar val-list+outputs)) result-color)] [else (let ([val-list (caar val-list+outputs)]) (if (equal? val-list (list (void))) null (map (lambda (v) (list.flow.list (make-paragraph (list (if (formatted-result? v) (formatted-result-content v) (elem #:style result-color (to-element/no-color v #:expr? (print-as-expression)))))))) val-list)))]) (loop (cdr expr-paras) (cdr val-list+outputs) #f))))]) (if inset? (let ([p (code-inset (make-table block-color lines))]) (if title (make-table block-color (list (list.flow.list title) (list.flow.list p))) p)) (make-table block-color (if title (cons (list.flow.list title) lines) lines))))) (define (extract s . ops) (let loop ([s s] [ops ops]) (cond [(null? ops) s] [(syntax? s) (loop (syntax-e s) ops)] [else (loop ((car ops) s) (cdr ops))]))) (struct nothing-to-eval ()) (struct eval-results (contents out err)) (define (make-eval-results contents out err) (unless (and (list? contents) (andmap content? contents)) (raise-argument-error 'eval:results "(listof content?)" contents)) (unless (string? out) (raise-argument-error 'eval:results "string?" out)) (unless (string? err) (raise-argument-error 'eval:results "string?" err)) (eval-results contents out err)) (define (make-eval-result content out err) (unless (content? content) (raise-argument-error 'eval:result "content?" content)) (unless (string? out) (raise-argument-error 'eval:result "string?" out)) (unless (string? err) (raise-argument-error 'eval:result "string?" err)) (eval-results (list content) out err)) (define (extract-to-evaluate s) (let loop ([s s] [expect #f]) (syntax-case s (code:line code:comment eval:alts eval:check) [(code:line v (code:comment . rest)) (loop (extract s cdr car) expect)] [(code:comment . rest) (values (nothing-to-eval) expect)] [(eval:alts p e) (loop (extract s cdr cdr car) expect)] [(eval:check e expect) (loop (extract s cdr car) (list (syntax->datum (datum->syntax #f (extract s cdr cdr car)))))] [else (values s expect)]))) (define (do-eval ev who) (define (get-outputs) (define (get getter what) (define s (getter ev)) (if (string? s) s (error who "missing ~a, possibly from a sandbox without a `sandbox-~a' configured to 'string" what (string-join (string-split what) "-")))) (list (get get-output "output") (get get-error-output "error output"))) (define (render-value v) (let-values ([(eval-print eval-print-as-expr?) (call-in-sandbox-context ev (lambda () (values (current-print) (print-as-expression))))]) (cond [(and (eq? eval-print (current-print)) eval-print-as-expr?) (make-reader-graph (copy-value v (make-hasheq)))] [else (box (call-in-sandbox-context ev (lambda () (define-values [in out] (make-pipe-with-specials)) (parameterize ((current-output-port out) (pretty-print-size-hook (lambda (obj _mode _out) (and (convertible? obj) 1))) (pretty-print-print-hook (lambda (obj _mode out) (write-special (if (serializable? obj) (make-serialized-convertible (serialize obj)) obj) out)))) (map (current-print) v)) (close-output-port out) in)))]))) (define (do-ev s) (with-handlers ([(lambda (x) (not (exn:break? x))) (lambda (e) (cons ((scribble-exn->string) e) (get-outputs)))]) (cons (render-value (do-plain-eval ev s #t)) (get-outputs)))) (define (do-ev/expect s expect) (define r (do-ev s)) (when expect (let ([expect (do-plain-eval ev (car expect) #t)]) (unless (equal? (car r) expect) (raise-syntax-error 'eval "example result check failed" s)))) r) (lambda (str) (if (eval-results? str) (list (map formatted-result (eval-results-contents str)) (eval-results-out str) (eval-results-err str)) (let-values ([(s expect) (extract-to-evaluate str)]) (if (nothing-to-eval? s) (list (list (void)) "" "") (do-ev/expect s expect)))))) (define scribble-exn->string (make-parameter (λ (e) (if (exn? e) (exn-message e) (format "uncaught exception: ~s" e))))) (define (copy-value v ht) (define (install v v2) (hash-set! ht v v2) v2) (let loop ([v v]) (cond [(and v (hash-ref ht v #f)) => (lambda (v) v)] [(syntax? v) (make-literal-syntax v)] [(string? v) (install v (string-copy v))] [(bytes? v) (install v (bytes-copy v))] [(pair? v) (let ([ph (make-placeholder #f)]) (hash-set! ht v ph) (placeholder-set! ph (cons (loop (car v)) (loop (cdr v)))) ph)] [(mpair? v) (let ([p (mcons #f #f)]) (hash-set! ht v p) (set-mcar! p (loop (mcar v))) (set-mcdr! p (loop (mcdr v))) p)] [(vector? v) (let ([v2 (make-vector (vector-length v))]) (hash-set! ht v v2) (for ([i (in-range (vector-length v2))]) (vector-set! v2 i (loop (vector-ref v i)))) v2)] [(box? v) (let ([v2 (box #f)]) (hash-set! ht v v2) (set-box! v2 (loop (unbox v))) v2)] [(hash? v) (let ([ph (make-placeholder #f)]) (hash-set! ht v ph) (let ([a (hash-map v (lambda (k v) (cons (loop k) (loop v))))]) (placeholder-set! ph (cond [(hash-eq? v) (make-hasheq-placeholder a)] [(hash-eqv? v) (make-hasheqv-placeholder a)] [else (make-hash-placeholder a)]))) ph)] [else v]))) (define (strip-comments stx) (cond [(syntax? stx) (datum->syntax stx (strip-comments (syntax-e stx)) stx stx stx)] [(pair? stx) (define a (car stx)) (define (comment? a) (and (pair? a) (or (eq? (car a) 'code:comment) (and (identifier? (car a)) (eq? (syntax-e (car a)) 'code:comment))))) (if (or (comment? a) (and (syntax? a) (comment? (syntax-e a)))) (strip-comments (cdr stx)) (cons (strip-comments a) (strip-comments (cdr stx))))] [(eq? stx 'code:blank) (void)] [else stx])) (define (make-base-eval #:lang [lang '(begin)] #:pretty-print? [pretty-print? #t] . ips) (call-with-trusted-sandbox-configuration (lambda () (parameterize ([sandbox-output 'string] [sandbox-error-output 'string] [sandbox-propagate-breaks #f] [sandbox-namespace-specs (append (sandbox-namespace-specs) (if pretty-print? '(racket/pretty) '()) '(file/convertible racket/serialize scribble/private/serialize))]) (let ([e (apply make-evaluator lang ips)]) (when pretty-print? (call-in-sandbox-context e (lambda () (current-print (dynamic-require 'racket/pretty 'pretty-print-handler))))) e))))) (define (make-base-eval-factory mod-paths #:lang [lang '(begin)] #:pretty-print? [pretty-print? #t] . ips) (parameterize ([sandbox-namespace-specs (cons (λ () (let ([ns (if gui? ((gui-dynamic-require 'make-gui-empty-namespace)) (make-base-empty-namespace))]) (parameterize ([current-namespace ns]) (for ([mod-path (in-list mod-paths)]) (dynamic-require mod-path #f)) (when pretty-print? (dynamic-require 'racket/pretty #f))) ns)) (append mod-paths (if pretty-print? '(racket/pretty) '())))]) (lambda () (let ([ev (apply make-base-eval #:lang lang #:pretty-print? #f ips)]) (when pretty-print? (call-in-sandbox-context ev (lambda () (current-print (dynamic-require 'racket/pretty 'pretty-print-handler))))) ev)))) (define (make-eval-factory mod-paths #:lang [lang '(begin)] #:pretty-print? [pretty-print? #t] . ips) (let ([base-factory (apply make-base-eval-factory mod-paths #:lang lang #:pretty-print? pretty-print? ips)]) (lambda () (let ([ev (base-factory)]) (call-in-sandbox-context ev (lambda () (for ([mod-path (in-list mod-paths)]) (namespace-require mod-path)))) ev)))) (define (close-eval e) (kill-evaluator e) "") (define (do-plain-eval ev s catching-exns?) (parameterize ([sandbox-propagate-breaks #f]) (call-with-values (lambda () ((scribble-eval-handler) ev catching-exns? (let ([s (strip-comments s)]) (cond [(syntax? s) (syntax-case s (module) [(module . _rest) (syntax->datum s)] [_else s])] [(string? s) (datum->syntax #f s)] [(bytes? s) (datum->syntax #f s)] [else s])))) list))) (define-syntax-parameter quote-expr-preserve-source? #f) (define-syntax (with-eval-preserve-source-locations stx) (syntax-case stx () [(with-eval-preserve-source-locations e ...) (syntax/loc stx (splicing-syntax-parameterize ([quote-expr-preserve-source? #t]) e ...))])) (define-syntax quote-expr (syntax-rules (eval:alts eval:result eval:results) [(_ (eval:alts e1 e2)) (quote-expr e2)] [(_ (eval:result e)) (make-eval-result (list e) "" "")] [(_ (eval:result e out)) (make-eval-result (list e) out "")] [(_ (eval:result e out err)) (make-eval-result (list e) out err)] [(_ (eval:results es)) (make-eval-results es "" "")] [(_ (eval:results es out)) (make-eval-results es out "")] [(_ (eval:results es out err)) (make-eval-results es out err)] [(_ e) (base-quote-expr e)])) (define orig-stx (read-syntax 'orig (open-input-string "()"))) (define-syntax (base-quote-expr stx) (syntax-case stx () [(_ e) (cond [(syntax-parameter-value #'quote-expr-preserve-source?) (define (get-source-location e) (let* ([src (build-source-location-list e)] [old-source (source-location-source src)] [new-source 'eval] [(or (string? old-source) (symbol? old-source)) old-source] [else #f])]) (update-source-location src #:source new-source))) (let loop ([e #'e]) (cond [(syntax? e) (let ([src (get-source-location e)] [original? (syntax-original? (syntax-local-introduce e))]) #`(syntax-property (datum->syntax #f #,(loop (syntax-e e)) (quote #,src) #,(if original? #'orig-stx #'#f)) 'paren-shape (quote #,(syntax-property e 'paren-shape))))] [(pair? e) #`(cons #,(loop (car e)) #,(loop (cdr e)))] [(vector? e) #`(list->vector #,(loop (vector->list e)))] [(box? e) #`(box #,(loop (unbox e)))] [(prefab-struct-key e) => (lambda (key) #`(apply make-prefab-struct (quote #,key) #,(loop (struct->list e))))] [else #`(quote #,e)]))] [else #'(quote e)])])) (define (do-interaction-eval ev e) (let-values ([(e expect) (extract-to-evaluate e)]) (unless (nothing-to-eval? e) (parameterize ([current-command-line-arguments #()]) (do-plain-eval (or ev (make-base-eval)) e #f))) "")) (define-syntax interaction-eval (syntax-rules () [(_ #:eval ev e) (do-interaction-eval ev (quote-expr e))] [(_ e) (do-interaction-eval #f (quote-expr e))])) (define (show-val v) (elem #:style result-color (to-element/no-color v #:expr? (print-as-expression)))) (define (do-interaction-eval-show ev e) (parameterize ([current-command-line-arguments #()]) (show-val (car (do-plain-eval (or ev (make-base-eval)) e #f))))) (define-syntax interaction-eval-show (syntax-rules () [(_ #:eval ev e) (do-interaction-eval-show ev (quote-expr e))] [(_ e) (do-interaction-eval-show #f (quote-expr e))])) (define-syntax racketinput* (syntax-rules (eval:alts code:comment) [(_ #:escape id (code:comment . rest)) (racketblock0 #:escape id (code:comment . rest))] [(_ #:escape id (eval:alts a b)) (racketinput* #:escape id a)] [(_ #:escape id e) (racketinput0 #:escape id e)])) (define-syntax racketblock* (syntax-rules (eval:alts code:comment) [(_ #:escape id (code:comment . rest)) (racketblock0 #:escape id (code:comment . rest))] [(_ #:escape id (eval:alts a b)) (racketblock #:escape id a)] [(_ #:escape id e) (racketblock0 #:escape id e)])) (define-code racketblock0+line (to-paragraph/prefix "" "" (list " "))) (define-syntax (racketdefinput* stx) (syntax-case stx (define define-values define-struct) [(_ #:escape id (define . rest)) (syntax-case stx () [(_ #:escape _ e) #'(racketblock0+line #:escape id e)])] [(_ #:escape id (define-values . rest)) (syntax-case stx () [(_ #:escape _ e) #'(racketblock0+line #:escape id e)])] [(_ #:escape id (define-struct . rest)) (syntax-case stx () [(_ #:escape _ e) #'(racketblock0+line #:escape id e)])] [(_ #:escape id (code:line (define . rest) . rest2)) (syntax-case stx () [(_ #:escape _ e) #'(racketblock0+line #:escape id e)])] [(_ #:escape id e) #'(racketinput* #:escape id e)])) (define (do-titled-interaction who inset? ev t shows evals) (interleave inset? t shows (map (do-eval ev who) evals))) (define-syntax titled-interaction (syntax-rules () [(_ who inset? t racketinput* #:eval ev #:escape unsyntax-id e ...) (do-titled-interaction 'who inset? ev t (list (racketinput* #:escape unsyntax-id e) ...) (list (quote-expr e) ...))] [(_ who inset? t racketinput* #:eval ev e ...) (titled-interaction who inset? t racketinput* #:eval ev #:escape unsyntax e ...)] [(_ who inset? t racketinput* #:escape unsyntax-id e ...) (titled-interaction who inset? t racketinput* #:eval (make-base-eval) #:escape unsyntax-id e ...)] [(_ who inset? t racketinput* e ...) (titled-interaction who inset? t racketinput* #:eval (make-base-eval) e ...)])) (define-syntax (-interaction stx) (syntax-case stx () [(_ who e ...) (syntax/loc stx (titled-interaction who #f #f racketinput* e ...))])) (define-syntax (interaction stx) (syntax-case stx () [(H e ...) (syntax/loc stx (code-inset (-interaction H e ...)))])) (define-syntax (interaction/no-prompt stx) (syntax-case stx () [(H e ...) (syntax/loc stx (code-inset (titled-interaction who #f #f racketblock* e ...)))])) (define-syntax (interaction0 stx) (syntax-case stx () [(H e ...) (syntax/loc stx (-interaction H e ...))])) (define-syntax racketblockX+eval (syntax-rules () [(_ racketblock #:eval ev #:escape unsyntax-id e ...) (let ([eva ev]) (#%expression (begin (interaction-eval #:eval eva e) ... (racketblock #:escape unsyntax-id e ...))))] [(_ racketblock #:eval ev e ...) (racketblockX+eval racketblock #:eval ev #:escape unsyntax e ...)] [(_ racketblock #:escape unsyntax-id e ...) (racketblockX+eval racketblock #:eval (make-base-eval) #:escape unsyntax-id e ...)] [(_ racketblock e ...) (racketblockX+eval racketblock #:eval (make-base-eval) #:escape unsyntax e ...)])) (define-syntax racketblock+eval (syntax-rules () [(_ e ...) (racketblockX+eval racketblock e ...)])) (define-syntax racketblock0+eval (syntax-rules () [(_ e ...) (racketblockX+eval racketblock0 e ...)])) (define-syntax racketmod+eval (syntax-rules () [(_ #:eval ev #:escape unsyntax-id name e ...) (let ([eva ev]) (#%expression (begin (interaction-eval #:eval eva e) ... (racketmod #:escape unsyntax-id name e ...))))] [(_ #:eval ev name e ...) (racketmod+eval #:eval ev #:escape unsyntax name e ...)] [(_ #:escape unsyntax-id name e ...) (racketmod+eval #:eval (make-base-eval) #:escape unsyntax-id name e ...)] [(_ name e ...) (racketmod+eval #:eval (make-base-eval) #:escape unsyntax name e ...)])) (define-syntax (defs+int stx) (syntax-case stx () [(H #:eval ev #:escape unsyntax-id [def ...] e ...) (syntax/loc stx (let ([eva ev]) (column (list (racketblock0+eval #:eval eva #:escape unsyntax-id def ...) blank-line (-interaction H #:eval eva #:escape unsyntax-id e ...)))))] [(H #:eval ev [def ...] e ...) (syntax/loc stx (defs+int #:eval ev #:escape unsyntax [def ...] e ...))] [(_ #:escape unsyntax-id [def ...] e ...) (syntax/loc stx (defs+int #:eval (make-base-eval) #:escape unsyntax-id [def ...] e ...))] [(_ [def ...] e ...) (syntax/loc stx (defs+int #:eval (make-base-eval) [def ...] e ...))])) (define-syntax def+int (syntax-rules () [(H #:eval ev #:escape unsyntax-id def e ...) (defs+int #:eval ev #:escape unsyntax-id [def] e ...)] [(H #:eval ev def e ...) (defs+int #:eval ev [def] e ...)] [(H #:escape unsyntax-id def e ...) (defs+int #:escape unsyntax-id [def] e ...)] [(H def e ...) (defs+int [def] e ...)])) (define example-title (make-paragraph (list "Example:"))) (define examples-title (make-paragraph (list "Examples:"))) (define-syntax pick-example-title (syntax-rules () [(_ e) example-title] [(_ #:eval ev e) example-title] [(_ #:escape id e) example-title] [(_ #:eval ev #:escape id e) example-title] [(_ . _) examples-title])) (define-syntax (examples stx) (syntax-case stx () [(H e ...) (syntax/loc stx (titled-interaction H #t (pick-example-title e ...) racketinput* e ...))])) (define-syntax (examples* stx) (syntax-case stx () [(H example-title e ...) (syntax/loc stx (titled-interaction H #t example-title racketinput* e ...))])) (define-syntax (defexamples stx) (syntax-case stx () [(H e ...) (syntax/loc stx (titled-interaction H #t (pick-example-title e ...) racketdefinput* e ...))])) (define-syntax (defexamples* stx) (syntax-case stx () [(H example-title e ...) (syntax/loc stx (titled-interaction H #t example-title racketdefinput* e ...))])) (define blank-line (make-paragraph (list 'nbsp))) (define (column l) (code-inset (make-table #f (map list.flow.list l)))) (define (do-splice l) (cond [(null? l) null] [(splice? (car l)) `(,@(splice-run (car l)) ,@(do-splice (cdr l)))] [else (cons (car l) (do-splice (cdr l)))])) (define as-examples (case-lambda [(t) (as-examples examples-title t)] [(example-title t) (make-table #f (list (list.flow.list example-title) (list (make-flow (do-splice (list t))))))]))
e997411d2ffa2e53bc1f89ce0040c96406645f6b98fb650ee82ef7e3fb668448
emotiq/emotiq
test-vecrepr.lisp
(in-package :core-crypto-test) (define-test conversions (let* ((n (field-random *ed-r*)) (n1 (bev n)) (n2 (lev n)) (n3 (hex n)) (n4 (base58 n)) (n5 (base64 n))) (assert-true (and (int= n n1) (int= n n2) (int= n n3) (int= n n4) (int= n n5) (vec= (bev-vec n1) (reverse (lev-vec n2))) )))) #| (lisp-unit:run-tests :all :crypto/test) |#
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/Crypto/test/test-vecrepr.lisp
lisp
(lisp-unit:run-tests :all :crypto/test)
(in-package :core-crypto-test) (define-test conversions (let* ((n (field-random *ed-r*)) (n1 (bev n)) (n2 (lev n)) (n3 (hex n)) (n4 (base58 n)) (n5 (base64 n))) (assert-true (and (int= n n1) (int= n n2) (int= n n3) (int= n n4) (int= n n5) (vec= (bev-vec n1) (reverse (lev-vec n2))) ))))
8257028d1ff653b3ef2eccbeacda3a9955f842f86eebdc948aba9492dc26dde1
Ericson2314/lighthouse
runghc.hs
# OPTIONS -cpp -fffi # #if __GLASGOW_HASKELL__ < 603 #include "config.h" #else #include "ghcconfig.h" #endif ----------------------------------------------------------------------------- -- ( c ) The University of Glasgow , 2004 -- -- runghc program, for invoking from a #! line in a script. For example: -- script.lhs : -- #! /usr/bin/runghc -- > main = putStrLn "hello!" -- runghc accepts one flag : -- -- -f <path> specify the path -- -- ----------------------------------------------------------------------------- module Main (main) where import System.Environment import System.IO import Data.List import System.Exit import Data.Char #ifdef USING_COMPAT import Compat.RawSystem ( rawSystem ) import Compat.Directory ( findExecutable ) #else import System.Cmd ( rawSystem ) import System.Directory ( findExecutable ) #endif main :: IO () main = do args <- getArgs case getGhcLoc args of (Just ghc, args') -> doIt ghc args' (Nothing, args') -> do mb_ghc <- findExecutable "ghc" case mb_ghc of Nothing -> dieProg ("cannot find ghc") Just ghc -> doIt ghc args' getGhcLoc :: [String] -> (Maybe FilePath, [String]) getGhcLoc ("-f" : ghc : args) = (Just ghc, args) getGhcLoc (('-' : 'f' : ghc) : args) = (Just ghc, args) If you need the first GHC flag to be a -f flag then you can pass -- -- first getGhcLoc ("--" : args) = (Nothing, args) getGhcLoc args = (Nothing, args) doIt :: String -> [String] -> IO () doIt ghc args = do let (ghc_args, rest) = getGhcArgs args case rest of [] -> dieProg usage filename : prog_args -> do let expr = "System.Environment.withProgName " ++ show filename ++ " (System.Environment.withArgs " ++ show prog_args ++ " (GHC.TopHandler.runIOFastExit" ++ " (Main.main Prelude.>> Prelude.return ())))" res <- rawSystem ghc (["-ignore-dot-ghci"] ++ ghc_args ++ [ "-e", expr, filename]) runIOFastExit : makes exceptions raised by Main.main -- behave in the same way as for a compiled program. -- The "fast exit" part just calls exit() directly -- instead of doing an orderly runtime shutdown, -- otherwise the main GHCi thread will complain about -- being interrupted. -- -- Why (main >> return ()) rather than just main? Because -- otherwise GHCi by default tries to evaluate the result of the IO in order to show it ( see # 1200 ) . exitWith res getGhcArgs :: [String] -> ([String], [String]) getGhcArgs args = case break pastArgs args of (xs, "--":ys) -> (xs, ys) (xs, ys) -> (xs, ys) pastArgs :: String -> Bool You can use -- to mark the end of the flags , in you need to use -- a file called -foo.hs for some reason. You almost certainly shouldn't, -- though. pastArgs "--" = True pastArgs ('-':_) = False pastArgs _ = True dieProg :: String -> IO a dieProg msg = do p <- getProgName hPutStrLn stderr (p ++ ": " ++ msg) exitWith (ExitFailure 1) usage :: String usage = "syntax: runghc [-f GHC-PATH | --] [GHC-ARGS] [--] FILE ARG..."
null
https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/utils/runghc/runghc.hs
haskell
--------------------------------------------------------------------------- runghc program, for invoking from a #! line in a script. For example: #! /usr/bin/runghc > main = putStrLn "hello!" -f <path> specify the path ----------------------------------------------------------------------------- first behave in the same way as for a compiled program. The "fast exit" part just calls exit() directly instead of doing an orderly runtime shutdown, otherwise the main GHCi thread will complain about being interrupted. Why (main >> return ()) rather than just main? Because otherwise GHCi by default tries to evaluate the result to mark the end of the flags , in you need to use a file called -foo.hs for some reason. You almost certainly shouldn't, though.
# OPTIONS -cpp -fffi # #if __GLASGOW_HASKELL__ < 603 #include "config.h" #else #include "ghcconfig.h" #endif ( c ) The University of Glasgow , 2004 script.lhs : runghc accepts one flag : module Main (main) where import System.Environment import System.IO import Data.List import System.Exit import Data.Char #ifdef USING_COMPAT import Compat.RawSystem ( rawSystem ) import Compat.Directory ( findExecutable ) #else import System.Cmd ( rawSystem ) import System.Directory ( findExecutable ) #endif main :: IO () main = do args <- getArgs case getGhcLoc args of (Just ghc, args') -> doIt ghc args' (Nothing, args') -> do mb_ghc <- findExecutable "ghc" case mb_ghc of Nothing -> dieProg ("cannot find ghc") Just ghc -> doIt ghc args' getGhcLoc :: [String] -> (Maybe FilePath, [String]) getGhcLoc ("-f" : ghc : args) = (Just ghc, args) getGhcLoc (('-' : 'f' : ghc) : args) = (Just ghc, args) getGhcLoc ("--" : args) = (Nothing, args) getGhcLoc args = (Nothing, args) doIt :: String -> [String] -> IO () doIt ghc args = do let (ghc_args, rest) = getGhcArgs args case rest of [] -> dieProg usage filename : prog_args -> do let expr = "System.Environment.withProgName " ++ show filename ++ " (System.Environment.withArgs " ++ show prog_args ++ " (GHC.TopHandler.runIOFastExit" ++ " (Main.main Prelude.>> Prelude.return ())))" res <- rawSystem ghc (["-ignore-dot-ghci"] ++ ghc_args ++ [ "-e", expr, filename]) runIOFastExit : makes exceptions raised by Main.main of the IO in order to show it ( see # 1200 ) . exitWith res getGhcArgs :: [String] -> ([String], [String]) getGhcArgs args = case break pastArgs args of (xs, "--":ys) -> (xs, ys) (xs, ys) -> (xs, ys) pastArgs :: String -> Bool pastArgs "--" = True pastArgs ('-':_) = False pastArgs _ = True dieProg :: String -> IO a dieProg msg = do p <- getProgName hPutStrLn stderr (p ++ ": " ++ msg) exitWith (ExitFailure 1) usage :: String usage = "syntax: runghc [-f GHC-PATH | --] [GHC-ARGS] [--] FILE ARG..."
26f14c1c47c5fa068e5b6c1b75012e2f2c60e910f5972dfa5ab44768d284975d
juliannagele/ebso
uninterpreted_instruction.mli
Copyright 2020 and 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 . 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. *) val init : Enc_consts.t -> Evm_stack.t -> Z3.Expr.expr val enc : Enc_consts.t -> Evm_stack.t -> Z3.Expr.expr -> Instruction.t -> Z3.Expr.expr
null
https://raw.githubusercontent.com/juliannagele/ebso/8e516036fcb98074b6be14fc81ae020f76977712/lib/uninterpreted_instruction.mli
ocaml
Copyright 2020 and 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 . 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. *) val init : Enc_consts.t -> Evm_stack.t -> Z3.Expr.expr val enc : Enc_consts.t -> Evm_stack.t -> Z3.Expr.expr -> Instruction.t -> Z3.Expr.expr
00fda069095d01159b9c240676325af45906fc0af9d87d77714565c1da808651
ghcjs/ghcjs-base
ArrayBuffer.hs
module JavaScript.TypedArray.ArrayBuffer ( ArrayBuffer , MutableArrayBuffer , freeze, unsafeFreeze , thaw, unsafeThaw , byteLength ) where import JavaScript.TypedArray.ArrayBuffer.Internal import GHC.Exts import GHC.Types create :: Int -> IO MutableArrayBuffer create n = fmap SomeArrayBuffer (IO (js_create n)) # INLINE create # {- | Create an immutable 'ArrayBuffer' by copying a 'MutableArrayBuffer' -} freeze :: MutableArrayBuffer -> IO ArrayBuffer freeze (SomeArrayBuffer b) = fmap SomeArrayBuffer (IO (js_slice1 0 b)) # INLINE freeze # {- | Create an immutable 'ArrayBuffer' from a 'MutableArrayBuffer' without copying. The result shares the buffer with the argument, not modify the data in the 'MutableArrayBuffer' after freezing -} unsafeFreeze :: MutableArrayBuffer -> IO ArrayBuffer unsafeFreeze (SomeArrayBuffer b) = pure (SomeArrayBuffer b) # INLINE unsafeFreeze # {- | Create a 'MutableArrayBuffer' by copying an immutable 'ArrayBuffer' -} thaw :: ArrayBuffer -> IO MutableArrayBuffer thaw (SomeArrayBuffer b) = fmap SomeArrayBuffer (IO (js_slice1 0 b)) # INLINE thaw # unsafeThaw :: ArrayBuffer -> IO MutableArrayBuffer unsafeThaw (SomeArrayBuffer b) = pure (SomeArrayBuffer b) # INLINE unsafeThaw # slice :: Int -> Maybe Int -> SomeArrayBuffer any -> SomeArrayBuffer any slice begin (Just end) b = js_slice_imm begin end b slice begin _ b = js_slice1_imm begin b # INLINE slice # byteLength :: SomeArrayBuffer any -> Int byteLength b = js_byteLength b # INLINE byteLength #
null
https://raw.githubusercontent.com/ghcjs/ghcjs-base/18f31dec5d9eae1ef35ff8bbf163394942efd227/JavaScript/TypedArray/ArrayBuffer.hs
haskell
| Create an immutable 'ArrayBuffer' by copying a 'MutableArrayBuffer' | Create an immutable 'ArrayBuffer' from a 'MutableArrayBuffer' without copying. The result shares the buffer with the argument, not modify the data in the 'MutableArrayBuffer' after freezing | Create a 'MutableArrayBuffer' by copying an immutable 'ArrayBuffer'
module JavaScript.TypedArray.ArrayBuffer ( ArrayBuffer , MutableArrayBuffer , freeze, unsafeFreeze , thaw, unsafeThaw , byteLength ) where import JavaScript.TypedArray.ArrayBuffer.Internal import GHC.Exts import GHC.Types create :: Int -> IO MutableArrayBuffer create n = fmap SomeArrayBuffer (IO (js_create n)) # INLINE create # freeze :: MutableArrayBuffer -> IO ArrayBuffer freeze (SomeArrayBuffer b) = fmap SomeArrayBuffer (IO (js_slice1 0 b)) # INLINE freeze # unsafeFreeze :: MutableArrayBuffer -> IO ArrayBuffer unsafeFreeze (SomeArrayBuffer b) = pure (SomeArrayBuffer b) # INLINE unsafeFreeze # thaw :: ArrayBuffer -> IO MutableArrayBuffer thaw (SomeArrayBuffer b) = fmap SomeArrayBuffer (IO (js_slice1 0 b)) # INLINE thaw # unsafeThaw :: ArrayBuffer -> IO MutableArrayBuffer unsafeThaw (SomeArrayBuffer b) = pure (SomeArrayBuffer b) # INLINE unsafeThaw # slice :: Int -> Maybe Int -> SomeArrayBuffer any -> SomeArrayBuffer any slice begin (Just end) b = js_slice_imm begin end b slice begin _ b = js_slice1_imm begin b # INLINE slice # byteLength :: SomeArrayBuffer any -> Int byteLength b = js_byteLength b # INLINE byteLength #
dbbe82378c79ecda3d9e77c7673f7b73eccecd70e643a8d7bac78ff37eb92390
finnishtransportagency/harja
laskutusyhteenveto.cljs
(ns harja.views.urakka.laskutusyhteenveto "Urakan Laskutusyhteenveto-välilehti" (:require [reagent.core :refer [atom] :as r] [cljs.core.async :refer [<! >! chan]] [harja.ui.yleiset :refer [ajax-loader linkki livi-pudotusvalikko]] [harja.ui.komponentti :as komp] [harja.ui.ikonit :as ikonit] [harja.tiedot.raportit :as raportit] [harja.tiedot.urakka :as u] [harja.tiedot.navigaatio :as nav] [harja.ui.upotettu-raportti :as upotettu-raportti] [harja.views.urakka.valinnat :as valinnat] [harja.ui.lomake :refer [lomake]] [harja.loki :refer [log logt tarkkaile!]] [harja.ui.protokollat :refer [Haku hae]] [harja.domain.skeema :refer [+tyotyypit+]] [harja.ui.raportti :refer [muodosta-html]] [harja.asiakas.kommunikaatio :as k] [harja.transit :as t] [harja.ui.yleiset :as yleiset]) (:require-macros [cljs.core.async.macros :refer [go]] [reagent.ratom :refer [reaction run!]] [harja.atom :refer [reaction<!]])) (defonce laskutusyhteenveto-nakyvissa? (atom false)) (defonce laskutusyhteenvedon-parametrit (reaction (let [ur @nav/valittu-urakka [alkupvm loppupvm] @u/valittu-hoitokauden-kuukausi nakymassa? @laskutusyhteenveto-nakyvissa? urakkatyyppi (:tyyppi ur) raportin-nimi (if (= :teiden-hoito urakkatyyppi) :laskutusyhteenveto-mhu :laskutusyhteenveto)] (when (and ur alkupvm loppupvm nakymassa?) (raportit/urakkaraportin-parametrit (:id ur) raportin-nimi {:alkupvm alkupvm :loppupvm loppupvm :urakkatyyppi urakkatyyppi}))))) (defonce laskutusyhteenvedon-tiedot (reaction<! [p @laskutusyhteenvedon-parametrit] {:nil-kun-haku-kaynnissa? true} (when p (raportit/suorita-raportti p)))) (defn laskutusyhteenveto [] (komp/luo (komp/lippu laskutusyhteenveto-nakyvissa?) (fn [] (let [ur @nav/valittu-urakka valittu-aikavali @u/valittu-hoitokauden-kuukausi raportin-nimi (if (= :teiden-hoito (:urakkatyyppi ur)) :laskutusyhteenveto-mhu :laskutusyhteenveto)] [:span.laskutusyhteenveto [:div.flex-row.alkuun [valinnat/urakan-hoitokausi ur] [valinnat/hoitokauden-kuukausi] (when-let [p @laskutusyhteenvedon-parametrit] [upotettu-raportti/raportin-vientimuodot p])] (if-let [tiedot @laskutusyhteenvedon-tiedot] [muodosta-html (assoc-in tiedot [1 :tunniste] raportin-nimi)] [yleiset/ajax-loader "Raporttia suoritetaan..."])]))))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/81a676bf90e43128ebb836f1f5424b47f27a0b76/src/cljs/harja/views/urakka/laskutusyhteenveto.cljs
clojure
(ns harja.views.urakka.laskutusyhteenveto "Urakan Laskutusyhteenveto-välilehti" (:require [reagent.core :refer [atom] :as r] [cljs.core.async :refer [<! >! chan]] [harja.ui.yleiset :refer [ajax-loader linkki livi-pudotusvalikko]] [harja.ui.komponentti :as komp] [harja.ui.ikonit :as ikonit] [harja.tiedot.raportit :as raportit] [harja.tiedot.urakka :as u] [harja.tiedot.navigaatio :as nav] [harja.ui.upotettu-raportti :as upotettu-raportti] [harja.views.urakka.valinnat :as valinnat] [harja.ui.lomake :refer [lomake]] [harja.loki :refer [log logt tarkkaile!]] [harja.ui.protokollat :refer [Haku hae]] [harja.domain.skeema :refer [+tyotyypit+]] [harja.ui.raportti :refer [muodosta-html]] [harja.asiakas.kommunikaatio :as k] [harja.transit :as t] [harja.ui.yleiset :as yleiset]) (:require-macros [cljs.core.async.macros :refer [go]] [reagent.ratom :refer [reaction run!]] [harja.atom :refer [reaction<!]])) (defonce laskutusyhteenveto-nakyvissa? (atom false)) (defonce laskutusyhteenvedon-parametrit (reaction (let [ur @nav/valittu-urakka [alkupvm loppupvm] @u/valittu-hoitokauden-kuukausi nakymassa? @laskutusyhteenveto-nakyvissa? urakkatyyppi (:tyyppi ur) raportin-nimi (if (= :teiden-hoito urakkatyyppi) :laskutusyhteenveto-mhu :laskutusyhteenveto)] (when (and ur alkupvm loppupvm nakymassa?) (raportit/urakkaraportin-parametrit (:id ur) raportin-nimi {:alkupvm alkupvm :loppupvm loppupvm :urakkatyyppi urakkatyyppi}))))) (defonce laskutusyhteenvedon-tiedot (reaction<! [p @laskutusyhteenvedon-parametrit] {:nil-kun-haku-kaynnissa? true} (when p (raportit/suorita-raportti p)))) (defn laskutusyhteenveto [] (komp/luo (komp/lippu laskutusyhteenveto-nakyvissa?) (fn [] (let [ur @nav/valittu-urakka valittu-aikavali @u/valittu-hoitokauden-kuukausi raportin-nimi (if (= :teiden-hoito (:urakkatyyppi ur)) :laskutusyhteenveto-mhu :laskutusyhteenveto)] [:span.laskutusyhteenveto [:div.flex-row.alkuun [valinnat/urakan-hoitokausi ur] [valinnat/hoitokauden-kuukausi] (when-let [p @laskutusyhteenvedon-parametrit] [upotettu-raportti/raportin-vientimuodot p])] (if-let [tiedot @laskutusyhteenvedon-tiedot] [muodosta-html (assoc-in tiedot [1 :tunniste] raportin-nimi)] [yleiset/ajax-loader "Raporttia suoritetaan..."])]))))
210ea198ffe1bd84b1e5f4c51afb6e46fb85bf3f4ea107715df46db3547bb8a1
c4-project/c4f
lvalue.ml
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) open Import module type S = sig type t = Fir.Lvalue.t [@@deriving sexp_of, quickcheck] end module On_env (E : Fir.Env_types.S) : S = Fir.Lvalue.Quickcheck_generic (Fir.Env.Random_var (E)) module Values_on_env (E : Fir.Env_types.S) : sig type t = Fir.Lvalue.t [@@deriving sexp_of, quickcheck] end = struct include On_env (E) (* to override as needed *) module Gen = Fir.Env.Random_var_with_type (E) let quickcheck_generator : t Q.Generator.t = Q.Generator.map Gen.quickcheck_generator ~f:Fir.Lvalue.on_value_of_typed_id end module Int_values (E : Fir.Env_types.S) : S = Values_on_env (struct let env = Fir.Env.variables_of_basic_type E.env ~basic:(Fir.Type.Basic.int ()) end) module Bool_values (E : Fir.Env_types.S) : S = Values_on_env (struct let env = Fir.Env.variables_of_basic_type E.env ~basic:(Fir.Type.Basic.bool ()) end)
null
https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/fir_gen/src/lvalue.ml
ocaml
to override as needed
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) open Import module type S = sig type t = Fir.Lvalue.t [@@deriving sexp_of, quickcheck] end module On_env (E : Fir.Env_types.S) : S = Fir.Lvalue.Quickcheck_generic (Fir.Env.Random_var (E)) module Values_on_env (E : Fir.Env_types.S) : sig type t = Fir.Lvalue.t [@@deriving sexp_of, quickcheck] end = struct module Gen = Fir.Env.Random_var_with_type (E) let quickcheck_generator : t Q.Generator.t = Q.Generator.map Gen.quickcheck_generator ~f:Fir.Lvalue.on_value_of_typed_id end module Int_values (E : Fir.Env_types.S) : S = Values_on_env (struct let env = Fir.Env.variables_of_basic_type E.env ~basic:(Fir.Type.Basic.int ()) end) module Bool_values (E : Fir.Env_types.S) : S = Values_on_env (struct let env = Fir.Env.variables_of_basic_type E.env ~basic:(Fir.Type.Basic.bool ()) end)
efc067103f92bc0180dd0573c6ed522486f21a8c31000fd489ec915c77b8a048
cj1128/sicp-review
2.51.scm
; writing a procedure that is analogous to the beside (define (below painter1 painter2) (let ((split-point (make-vect 0.0 0.5))) (let ((painter-top (transform-painter painter2 split-point (make-vect 1.0 0.5) (make-vect 0.0 1.0))) (painter-bottom painter1 (make-vect 0.0 0.0) (make-vect 1.0 0.0) split-point)) (lambda (frame) (painter-top frame) (painter-bottom frame))))) ; using beside and rotate to implement below (define (below painter1 painter2) (rotate90 (beside (rotate270 painter1) (rotate270 painter2))))
null
https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-2/2.2/2.51.scm
scheme
writing a procedure that is analogous to the beside using beside and rotate to implement below
(define (below painter1 painter2) (let ((split-point (make-vect 0.0 0.5))) (let ((painter-top (transform-painter painter2 split-point (make-vect 1.0 0.5) (make-vect 0.0 1.0))) (painter-bottom painter1 (make-vect 0.0 0.0) (make-vect 1.0 0.0) split-point)) (lambda (frame) (painter-top frame) (painter-bottom frame))))) (define (below painter1 painter2) (rotate90 (beside (rotate270 painter1) (rotate270 painter2))))
3001c1631a6290c6d7c60be0fde1a25a5e88e4c3407b6c5270f92682ff96e0fe
TerrorJack/ghc-alter
Show.hs
# LANGUAGE Trustworthy # # LANGUAGE CPP , NoImplicitPrelude , BangPatterns , StandaloneDeriving , MagicHash , UnboxedTuples # MagicHash, UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} #include "MachDeps.h" #if SIZEOF_HSWORD == 4 #define DIGITS 9 #define BASE 1000000000 #elif SIZEOF_HSWORD == 8 #define DIGITS 18 #define BASE 1000000000000000000 #else #error Please define DIGITS and BASE -- DIGITS should be the largest integer such that 10^DIGITS < 2^(SIZEOF_HSWORD * 8 - 1 ) BASE should be 10^DIGITS . Note that ^ is not available yet . #endif ----------------------------------------------------------------------------- -- | -- Module : GHC.Show Copyright : ( c ) The University of Glasgow , 1992 - 2002 -- License : see libraries/base/LICENSE -- -- Maintainer : -- Stability : internal Portability : non - portable ( GHC Extensions ) -- -- The 'Show' class, and related operations. -- ----------------------------------------------------------------------------- module GHC.Show ( Show(..), ShowS, Instances for Show : ( ) , [ ] , , Ordering , Int , -- Show support code shows, showChar, showString, showMultiLineString, showParen, showList__, showCommaSpace, showSpace, showLitChar, showLitString, protectEsc, intToDigit, showSignedInt, appPrec, appPrec1, -- Character operations asciiTab, ) where import GHC.Base import GHC.List ((!!), foldr1, break) import GHC.Num import GHC.Stack.Types -- | The @shows@ functions return a function that prepends the -- output 'String' to an existing 'String'. This allows constant-time -- concatenation of results using function composition. type ShowS = String -> String | Conversion of values to readable ' 's . -- -- Derived instances of 'Show' have the following properties, which -- are compatible with derived instances of 'Text.Read.Read': -- * The result of ' show ' is a syntactically correct -- expression containing only constants, given the fixity -- declarations in force at the point where the type is declared. -- It contains only the constructor names defined in the data type, -- parentheses, and spaces. When labelled constructor fields are -- used, braces, commas, field names, and equal signs are also used. -- -- * If the constructor is defined to be an infix operator, then -- 'showsPrec' will produce infix applications of the constructor. -- -- * the representation will be enclosed in parentheses if the -- precedence of the top-level constructor in @x@ is less than @d@ ( associativity is ignored ) . Thus , if @d@ is @0@ then the result -- is never surrounded in parentheses; if @d@ is @11@ it is always -- surrounded in parentheses, unless it is an atomic expression. -- -- * If the constructor is defined using record syntax, then 'show' -- will produce the record-syntax form, with the fields given in the -- same order as the original declaration. -- -- For example, given the declarations -- > infixr 5 : ^ : > data Tree a = Leaf a | Tree a : ^ : Tree a -- -- the derived instance of 'Show' is equivalent to -- -- > instance (Show a) => Show (Tree a) where -- > > showsPrec d ( Leaf m ) ( d > app_prec ) $ -- > showString "Leaf " . showsPrec (app_prec+1) m > where app_prec = 10 -- > > showsPrec d ( u : ^ : v ) ( d > up_prec ) $ > showsPrec ( up_prec+1 ) u . -- > showString " :^: " . > showsPrec ( ) v > where up_prec = 5 -- -- Note that right-associativity of @:^:@ is ignored. For example, -- * @'show ' ( Leaf 1 : ^ : Leaf 2 : ^ : Leaf 3)@ produces the string -- @\"Leaf 1 :^: (Leaf 2 :^: Leaf 3)\"@. class Show a where # MINIMAL showsPrec | show # -- | Convert a value to a readable 'String'. -- -- 'showsPrec' should satisfy the law -- -- > showsPrec d x r ++ s == showsPrec d x (r ++ s) -- -- Derived instances of 'Text.Read.Read' and 'Show' satisfy the following: -- -- * @(x,\"\")@ is an element of @('Text . Read.readsPrec ' d ( ' showsPrec ' d x \"\"))@. -- That is , ' Text . Read.readsPrec ' parses the string produced by -- 'showsPrec', and delivers the value that 'showsPrec' started with. showsPrec :: Int -- ^ the operator precedence of the enclosing context ( a number from @0@ to @11@ ) . Function application has precedence -> a -- ^ the value to be converted to a 'String' -> ShowS -- | A specialised variant of 'showsPrec', using precedence context zero , and returning an ordinary ' String ' . show :: a -> String -- | The method 'showList' is provided to allow the programmer to -- give a specialised way of showing lists of values. -- For example, this is used by the predefined 'Show' instance of the ' ' type , where values of type ' String ' should be shown -- in double quotes, rather than between square brackets. showList :: [a] -> ShowS showsPrec _ x s = show x ++ s show x = shows x "" showList ls s = showList__ shows ls s showList__ :: (a -> ShowS) -> [a] -> ShowS showList__ _ [] s = "[]" ++ s showList__ showx (x:xs) s = '[' : showx x (showl xs) where showl [] = ']' : s showl (y:ys) = ',' : showx y (showl ys) appPrec, appPrec1 :: Int -- Use unboxed stuff because we don't have overloaded numerics yet appPrec = I# 10# -- Precedence of application: one more than the maximum operator precedence of 9 appPrec1 = I# 11# -- appPrec + 1 -------------------------------------------------------------- -- Simple Instances -------------------------------------------------------------- deriving instance Show () | @since 2.01 instance Show a => Show [a] where {-# SPECIALISE instance Show [String] #-} {-# SPECIALISE instance Show [Char] #-} {-# SPECIALISE instance Show [Int] #-} showsPrec _ = showList deriving instance Show Bool deriving instance Show Ordering | @since 2.01 instance Show Char where showsPrec _ '\'' = showString "'\\''" showsPrec _ c = showChar '\'' . showLitChar c . showChar '\'' showList cs = showChar '"' . showLitString cs . showChar '"' | @since 2.01 instance Show Int where showsPrec = showSignedInt | @since 2.01 instance Show Word where showsPrec _ (W# w) = showWord w showWord :: Word# -> ShowS showWord w# cs | isTrue# (w# `ltWord#` 10##) = C# (chr# (ord# '0'# +# word2Int# w#)) : cs | otherwise = case chr# (ord# '0'# +# word2Int# (w# `remWord#` 10##)) of c# -> showWord (w# `quotWord#` 10##) (C# c# : cs) deriving instance Show a => Show (Maybe a) | @since 2.01 instance Show TyCon where showsPrec p (TyCon _ _ _ tc_name _ _) = showsPrec p tc_name | @since 4.9.0.0 instance Show TrName where showsPrec _ (TrNameS s) = showString (unpackCString# s) showsPrec _ (TrNameD s) = showString s | @since 4.9.0.0 instance Show Module where showsPrec _ (Module p m) = shows p . (':' :) . shows m | @since 4.9.0.0 instance Show CallStack where showsPrec _ = shows . getCallStack deriving instance Show SrcLoc -------------------------------------------------------------- Show instances for the first few tuple -------------------------------------------------------------- -- The explicit 's' parameters are important Otherwise GHC thinks that " shows x " might take a lot of work to compute and generates defns like -- showsPrec _ (x,y) = let sx = shows x; sy = shows y in \s - > showChar ' ( ' ( sx ( showChar ' , ' ( sy ( ' ) ' s ) ) ) ) | @since 2.01 instance (Show a, Show b) => Show (a,b) where showsPrec _ (a,b) s = show_tuple [shows a, shows b] s | @since 2.01 instance (Show a, Show b, Show c) => Show (a, b, c) where showsPrec _ (a,b,c) s = show_tuple [shows a, shows b, shows c] s | @since 2.01 instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d) where showsPrec _ (a,b,c,d) s = show_tuple [shows a, shows b, shows c, shows d] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e) where showsPrec _ (a,b,c,d,e) s = show_tuple [shows a, shows b, shows c, shows d, shows e] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a,b,c,d,e,f) where showsPrec _ (a,b,c,d,e,f) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g) => Show (a,b,c,d,e,f,g) where showsPrec _ (a,b,c,d,e,f,g) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h) => Show (a,b,c,d,e,f,g,h) where showsPrec _ (a,b,c,d,e,f,g,h) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i) => Show (a,b,c,d,e,f,g,h,i) where showsPrec _ (a,b,c,d,e,f,g,h,i) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j) => Show (a,b,c,d,e,f,g,h,i,j) where showsPrec _ (a,b,c,d,e,f,g,h,i,j) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k) => Show (a,b,c,d,e,f,g,h,i,j,k) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l) => Show (a,b,c,d,e,f,g,h,i,j,k,l) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k, shows l] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m) => Show (a,b,c,d,e,f,g,h,i,j,k,l,m) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k, shows l, shows m] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n) => Show (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m,n) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k, shows l, shows m, shows n] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n, Show o) => Show (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k, shows l, shows m, shows n, shows o] s show_tuple :: [ShowS] -> ShowS show_tuple ss = showChar '(' . foldr1 (\s r -> s . showChar ',' . r) ss . showChar ')' -------------------------------------------------------------- -- Support code for Show -------------------------------------------------------------- | equivalent to ' showsPrec ' with a precedence of 0 . shows :: (Show a) => a -> ShowS shows = showsPrec 0 | utility function converting a ' ' to a show function that -- simply prepends the character unchanged. showChar :: Char -> ShowS showChar = (:) -- | utility function converting a 'String' to a show function that -- simply prepends the string unchanged. showString :: String -> ShowS showString = (++) -- | utility function that surrounds the inner show function with -- parentheses when the 'Bool' parameter is 'True'. showParen :: Bool -> ShowS -> ShowS showParen b p = if b then showChar '(' . p . showChar ')' else p showSpace :: ShowS showSpace = {-showChar ' '-} \ xs -> ' ' : xs showCommaSpace :: ShowS showCommaSpace = showString ", " -- Code specific for characters -- | Convert a character to a string using only printable characters, using Haskell source - language escape conventions . For example : -- > showLitChar ' \n ' s = " \\n " + + s -- showLitChar :: Char -> ShowS showLitChar c s | c > '\DEL' = showChar '\\' (protectEsc isDec (shows (ord c)) s) showLitChar '\DEL' s = showString "\\DEL" s showLitChar '\\' s = showString "\\\\" s showLitChar c s | c >= ' ' = showChar c s showLitChar '\a' s = showString "\\a" s showLitChar '\b' s = showString "\\b" s showLitChar '\f' s = showString "\\f" s showLitChar '\n' s = showString "\\n" s showLitChar '\r' s = showString "\\r" s showLitChar '\t' s = showString "\\t" s showLitChar '\v' s = showString "\\v" s showLitChar '\SO' s = protectEsc (== 'H') (showString "\\SO") s showLitChar c s = showString ('\\' : asciiTab!!ord c) s -- I've done manual eta-expansion here, because otherwise it's impossible to stop ( asciiTab!!ord ) getting floated out as an MFE showLitString :: String -> ShowS -- | Same as 'showLitChar', but for strings It converts the string to a string using escape conventions -- for non-printable characters. Does not add double-quotes around the -- whole thing; the caller should do that. -- The main difference from showLitChar (apart from the fact that the -- argument is a string not a list) is that we must escape double-quotes showLitString [] s = s showLitString ('"' : cs) s = showString "\\\"" (showLitString cs s) showLitString (c : cs) s = showLitChar c (showLitString cs s) Making 's ' an explicit parameter makes it clear to GHC that showLitString has arity 2 , which avoids it allocating an extra lambda -- The sticking point is the recursive call to (showLitString cs), which it ca n't figure out would be ok with arity 2 . showMultiLineString :: String -> [String] | Like ' showLitString ' ( expand escape characters using -- escape conventions), but -- * break the string into multiple lines -- * wrap the entire thing in double quotes -- Example: @showMultiLineString "hello\ngoodbye\nblah"@ returns @["\"hello\\n\\ " , " \\goodbye\n\\ " , " \\blah\""]@ showMultiLineString str = go '\"' str where go ch s = case break (== '\n') s of (l, _:s'@(_:_)) -> (ch : showLitString l "\\n\\") : go '\\' s' (l, "\n") -> [ch : showLitString l "\\n\""] (l, _) -> [ch : showLitString l "\""] isDec :: Char -> Bool isDec c = c >= '0' && c <= '9' protectEsc :: (Char -> Bool) -> ShowS -> ShowS protectEsc p f = f . cont where cont s@(c:_) | p c = "\\&" ++ s cont s = s asciiTab :: [String] asciiTab = -- Using an array drags in the array module. listArray ('\NUL', ' ') ["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US", "SP"] Code specific for Ints . -- | Convert an 'Int' in the range @0@..@15@ to the corresponding single digit ' ' . This function fails on other inputs , and generates -- lower-case hexadecimal digits. intToDigit :: Int -> Char intToDigit (I# i) | isTrue# (i >=# 0#) && isTrue# (i <=# 9#) = unsafeChr (ord '0' + I# i) | isTrue# (i >=# 10#) && isTrue# (i <=# 15#) = unsafeChr (ord 'a' + I# i - 10) | otherwise = errorWithoutStackTrace ("Char.intToDigit: not a digit " ++ show (I# i)) showSignedInt :: Int -> Int -> ShowS showSignedInt (I# p) (I# n) r | isTrue# (n <# 0#) && isTrue# (p ># 6#) = '(' : itos n (')' : r) | otherwise = itos n r itos :: Int# -> String -> String itos n# cs | isTrue# (n# <# 0#) = let !(I# minInt#) = minInt in if isTrue# (n# ==# minInt#) -- negateInt# minInt overflows, so we can't do that: then '-' : (case n# `quotRemInt#` 10# of (# q, r #) -> itos' (negateInt# q) (itos' (negateInt# r) cs)) else '-' : itos' (negateInt# n#) cs | otherwise = itos' n# cs where itos' :: Int# -> String -> String itos' x# cs' | isTrue# (x# <# 10#) = C# (chr# (ord# '0'# +# x#)) : cs' | otherwise = case x# `quotRemInt#` 10# of (# q, r #) -> case chr# (ord# '0'# +# r) of c# -> itos' q (C# c# : cs') -------------------------------------------------------------- The Integer instances for Show -------------------------------------------------------------- | @since 2.01 instance Show Integer where showsPrec p n r | p > 6 && n < 0 = '(' : integerToString n (')' : r) Minor point : testing p first gives better code in the not - uncommon case where the p argument -- is a constant | otherwise = integerToString n r showList = showList__ (showsPrec 0) -- Divide an conquer implementation of string conversion integerToString :: Integer -> String -> String integerToString n0 cs0 | n0 < 0 = '-' : integerToString' (- n0) cs0 | otherwise = integerToString' n0 cs0 where integerToString' :: Integer -> String -> String integerToString' n cs | n < BASE = jhead (fromInteger n) cs | otherwise = jprinth (jsplitf (BASE*BASE) n) cs Split n into digits in base p. We first split n into digits in base p*p and then split each of these digits into two . Note that the first ' digit ' modulo p*p may have a leading zero -- in base p that we need to drop - this is what jsplith takes care of. -- jsplitb the handles the remaining digits. jsplitf :: Integer -> Integer -> [Integer] jsplitf p n | p > n = [n] | otherwise = jsplith p (jsplitf (p*p) n) jsplith :: Integer -> [Integer] -> [Integer] jsplith p (n:ns) = case n `quotRemInteger` p of (# q, r #) -> if q > 0 then q : r : jsplitb p ns else r : jsplitb p ns jsplith _ [] = errorWithoutStackTrace "jsplith: []" jsplitb :: Integer -> [Integer] -> [Integer] jsplitb _ [] = [] jsplitb p (n:ns) = case n `quotRemInteger` p of (# q, r #) -> q : r : jsplitb p ns -- Convert a number that has been split into digits in base BASE^2 -- this includes a last splitting step and then conversion of digits -- that all fit into a machine word. jprinth :: [Integer] -> String -> String jprinth (n:ns) cs = case n `quotRemInteger` BASE of (# q', r' #) -> let q = fromInteger q' r = fromInteger r' in if q > 0 then jhead q $ jblock r $ jprintb ns cs else jhead r $ jprintb ns cs jprinth [] _ = errorWithoutStackTrace "jprinth []" jprintb :: [Integer] -> String -> String jprintb [] cs = cs jprintb (n:ns) cs = case n `quotRemInteger` BASE of (# q', r' #) -> let q = fromInteger q' r = fromInteger r' in jblock q $ jblock r $ jprintb ns cs Convert an integer that fits into a machine word . Again , we have two functions , one that drops leading zeros ( ) and one that does n't -- (jblock) jhead :: Int -> String -> String jhead n cs | n < 10 = case unsafeChr (ord '0' + n) of c@(C# _) -> c : cs | otherwise = case unsafeChr (ord '0' + r) of c@(C# _) -> jhead q (c : cs) where (q, r) = n `quotRemInt` 10 jblock = jblock' {- ' -} DIGITS jblock' :: Int -> Int -> String -> String jblock' d n cs | d == 1 = case unsafeChr (ord '0' + n) of c@(C# _) -> c : cs | otherwise = case unsafeChr (ord '0' + r) of c@(C# _) -> jblock' (d - 1) q (c : cs) where (q, r) = n `quotRemInt` 10
null
https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/GHC/Show.hs
haskell
# OPTIONS_HADDOCK hide # DIGITS should be the largest integer such that --------------------------------------------------------------------------- | Module : GHC.Show License : see libraries/base/LICENSE Maintainer : Stability : internal The 'Show' class, and related operations. --------------------------------------------------------------------------- Show support code Character operations | The @shows@ functions return a function that prepends the output 'String' to an existing 'String'. This allows constant-time concatenation of results using function composition. Derived instances of 'Show' have the following properties, which are compatible with derived instances of 'Text.Read.Read': expression containing only constants, given the fixity declarations in force at the point where the type is declared. It contains only the constructor names defined in the data type, parentheses, and spaces. When labelled constructor fields are used, braces, commas, field names, and equal signs are also used. * If the constructor is defined to be an infix operator, then 'showsPrec' will produce infix applications of the constructor. * the representation will be enclosed in parentheses if the precedence of the top-level constructor in @x@ is less than @d@ is never surrounded in parentheses; if @d@ is @11@ it is always surrounded in parentheses, unless it is an atomic expression. * If the constructor is defined using record syntax, then 'show' will produce the record-syntax form, with the fields given in the same order as the original declaration. For example, given the declarations the derived instance of 'Show' is equivalent to > instance (Show a) => Show (Tree a) where > > showString "Leaf " . showsPrec (app_prec+1) m > > showString " :^: " . Note that right-associativity of @:^:@ is ignored. For example, @\"Leaf 1 :^: (Leaf 2 :^: Leaf 3)\"@. | Convert a value to a readable 'String'. 'showsPrec' should satisfy the law > showsPrec d x r ++ s == showsPrec d x (r ++ s) Derived instances of 'Text.Read.Read' and 'Show' satisfy the following: * @(x,\"\")@ is an element of 'showsPrec', and delivers the value that 'showsPrec' started with. ^ the operator precedence of the enclosing ^ the value to be converted to a 'String' | A specialised variant of 'showsPrec', using precedence context | The method 'showList' is provided to allow the programmer to give a specialised way of showing lists of values. For example, this is used by the predefined 'Show' instance of in double quotes, rather than between square brackets. Use unboxed stuff because we don't have overloaded numerics yet Precedence of application: appPrec + 1 ------------------------------------------------------------ Simple Instances ------------------------------------------------------------ # SPECIALISE instance Show [String] # # SPECIALISE instance Show [Char] # # SPECIALISE instance Show [Int] # ------------------------------------------------------------ ------------------------------------------------------------ The explicit 's' parameters are important showsPrec _ (x,y) = let sx = shows x; sy = shows y in ------------------------------------------------------------ Support code for Show ------------------------------------------------------------ simply prepends the character unchanged. | utility function converting a 'String' to a show function that simply prepends the string unchanged. | utility function that surrounds the inner show function with parentheses when the 'Bool' parameter is 'True'. showChar ' ' Code specific for characters | Convert a character to a string using only printable characters, I've done manual eta-expansion here, because otherwise it's | Same as 'showLitChar', but for strings for non-printable characters. Does not add double-quotes around the whole thing; the caller should do that. The main difference from showLitChar (apart from the fact that the argument is a string not a list) is that we must escape double-quotes The sticking point is the recursive call to (showLitString cs), which escape conventions), but * break the string into multiple lines * wrap the entire thing in double quotes Example: @showMultiLineString "hello\ngoodbye\nblah"@ Using an array drags in the array module. listArray ('\NUL', ' ') | Convert an 'Int' in the range @0@..@15@ to the corresponding single lower-case hexadecimal digits. negateInt# minInt overflows, so we can't do that: ------------------------------------------------------------ ------------------------------------------------------------ is a constant Divide an conquer implementation of string conversion in base p that we need to drop - this is what jsplith takes care of. jsplitb the handles the remaining digits. Convert a number that has been split into digits in base BASE^2 this includes a last splitting step and then conversion of digits that all fit into a machine word. (jblock) '
# LANGUAGE Trustworthy # # LANGUAGE CPP , NoImplicitPrelude , BangPatterns , StandaloneDeriving , MagicHash , UnboxedTuples # MagicHash, UnboxedTuples #-} #include "MachDeps.h" #if SIZEOF_HSWORD == 4 #define DIGITS 9 #define BASE 1000000000 #elif SIZEOF_HSWORD == 8 #define DIGITS 18 #define BASE 1000000000000000000 #else #error Please define DIGITS and BASE 10^DIGITS < 2^(SIZEOF_HSWORD * 8 - 1 ) BASE should be 10^DIGITS . Note that ^ is not available yet . #endif Copyright : ( c ) The University of Glasgow , 1992 - 2002 Portability : non - portable ( GHC Extensions ) module GHC.Show ( Show(..), ShowS, Instances for Show : ( ) , [ ] , , Ordering , Int , shows, showChar, showString, showMultiLineString, showParen, showList__, showCommaSpace, showSpace, showLitChar, showLitString, protectEsc, intToDigit, showSignedInt, appPrec, appPrec1, asciiTab, ) where import GHC.Base import GHC.List ((!!), foldr1, break) import GHC.Num import GHC.Stack.Types type ShowS = String -> String | Conversion of values to readable ' 's . * The result of ' show ' is a syntactically correct ( associativity is ignored ) . Thus , if @d@ is @0@ then the result > infixr 5 : ^ : > data Tree a = Leaf a | Tree a : ^ : Tree a > showsPrec d ( Leaf m ) ( d > app_prec ) $ > where app_prec = 10 > showsPrec d ( u : ^ : v ) ( d > up_prec ) $ > showsPrec ( up_prec+1 ) u . > showsPrec ( ) v > where up_prec = 5 * @'show ' ( Leaf 1 : ^ : Leaf 2 : ^ : Leaf 3)@ produces the string class Show a where # MINIMAL showsPrec | show # @('Text . Read.readsPrec ' d ( ' showsPrec ' d x \"\"))@. That is , ' Text . Read.readsPrec ' parses the string produced by context ( a number from @0@ to @11@ ) . Function application has precedence -> ShowS zero , and returning an ordinary ' String ' . show :: a -> String the ' ' type , where values of type ' String ' should be shown showList :: [a] -> ShowS showsPrec _ x s = show x ++ s show x = shows x "" showList ls s = showList__ shows ls s showList__ :: (a -> ShowS) -> [a] -> ShowS showList__ _ [] s = "[]" ++ s showList__ showx (x:xs) s = '[' : showx x (showl xs) where showl [] = ']' : s showl (y:ys) = ',' : showx y (showl ys) appPrec, appPrec1 :: Int one more than the maximum operator precedence of 9 deriving instance Show () | @since 2.01 instance Show a => Show [a] where showsPrec _ = showList deriving instance Show Bool deriving instance Show Ordering | @since 2.01 instance Show Char where showsPrec _ '\'' = showString "'\\''" showsPrec _ c = showChar '\'' . showLitChar c . showChar '\'' showList cs = showChar '"' . showLitString cs . showChar '"' | @since 2.01 instance Show Int where showsPrec = showSignedInt | @since 2.01 instance Show Word where showsPrec _ (W# w) = showWord w showWord :: Word# -> ShowS showWord w# cs | isTrue# (w# `ltWord#` 10##) = C# (chr# (ord# '0'# +# word2Int# w#)) : cs | otherwise = case chr# (ord# '0'# +# word2Int# (w# `remWord#` 10##)) of c# -> showWord (w# `quotWord#` 10##) (C# c# : cs) deriving instance Show a => Show (Maybe a) | @since 2.01 instance Show TyCon where showsPrec p (TyCon _ _ _ tc_name _ _) = showsPrec p tc_name | @since 4.9.0.0 instance Show TrName where showsPrec _ (TrNameS s) = showString (unpackCString# s) showsPrec _ (TrNameD s) = showString s | @since 4.9.0.0 instance Show Module where showsPrec _ (Module p m) = shows p . (':' :) . shows m | @since 4.9.0.0 instance Show CallStack where showsPrec _ = shows . getCallStack deriving instance Show SrcLoc Show instances for the first few tuple Otherwise GHC thinks that " shows x " might take a lot of work to compute and generates defns like \s - > showChar ' ( ' ( sx ( showChar ' , ' ( sy ( ' ) ' s ) ) ) ) | @since 2.01 instance (Show a, Show b) => Show (a,b) where showsPrec _ (a,b) s = show_tuple [shows a, shows b] s | @since 2.01 instance (Show a, Show b, Show c) => Show (a, b, c) where showsPrec _ (a,b,c) s = show_tuple [shows a, shows b, shows c] s | @since 2.01 instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d) where showsPrec _ (a,b,c,d) s = show_tuple [shows a, shows b, shows c, shows d] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e) where showsPrec _ (a,b,c,d,e) s = show_tuple [shows a, shows b, shows c, shows d, shows e] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a,b,c,d,e,f) where showsPrec _ (a,b,c,d,e,f) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g) => Show (a,b,c,d,e,f,g) where showsPrec _ (a,b,c,d,e,f,g) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h) => Show (a,b,c,d,e,f,g,h) where showsPrec _ (a,b,c,d,e,f,g,h) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i) => Show (a,b,c,d,e,f,g,h,i) where showsPrec _ (a,b,c,d,e,f,g,h,i) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j) => Show (a,b,c,d,e,f,g,h,i,j) where showsPrec _ (a,b,c,d,e,f,g,h,i,j) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k) => Show (a,b,c,d,e,f,g,h,i,j,k) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l) => Show (a,b,c,d,e,f,g,h,i,j,k,l) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k, shows l] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m) => Show (a,b,c,d,e,f,g,h,i,j,k,l,m) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k, shows l, shows m] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n) => Show (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m,n) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k, shows l, shows m, shows n] s | @since 2.01 instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n, Show o) => Show (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h, shows i, shows j, shows k, shows l, shows m, shows n, shows o] s show_tuple :: [ShowS] -> ShowS show_tuple ss = showChar '(' . foldr1 (\s r -> s . showChar ',' . r) ss . showChar ')' | equivalent to ' showsPrec ' with a precedence of 0 . shows :: (Show a) => a -> ShowS shows = showsPrec 0 | utility function converting a ' ' to a show function that showChar :: Char -> ShowS showChar = (:) showString :: String -> ShowS showString = (++) showParen :: Bool -> ShowS -> ShowS showParen b p = if b then showChar '(' . p . showChar ')' else p showSpace :: ShowS showCommaSpace :: ShowS showCommaSpace = showString ", " using Haskell source - language escape conventions . For example : > showLitChar ' \n ' s = " \\n " + + s showLitChar :: Char -> ShowS showLitChar c s | c > '\DEL' = showChar '\\' (protectEsc isDec (shows (ord c)) s) showLitChar '\DEL' s = showString "\\DEL" s showLitChar '\\' s = showString "\\\\" s showLitChar c s | c >= ' ' = showChar c s showLitChar '\a' s = showString "\\a" s showLitChar '\b' s = showString "\\b" s showLitChar '\f' s = showString "\\f" s showLitChar '\n' s = showString "\\n" s showLitChar '\r' s = showString "\\r" s showLitChar '\t' s = showString "\\t" s showLitChar '\v' s = showString "\\v" s showLitChar '\SO' s = protectEsc (== 'H') (showString "\\SO") s showLitChar c s = showString ('\\' : asciiTab!!ord c) s impossible to stop ( asciiTab!!ord ) getting floated out as an MFE showLitString :: String -> ShowS It converts the string to a string using escape conventions showLitString [] s = s showLitString ('"' : cs) s = showString "\\\"" (showLitString cs s) showLitString (c : cs) s = showLitChar c (showLitString cs s) Making 's ' an explicit parameter makes it clear to GHC that showLitString has arity 2 , which avoids it allocating an extra lambda it ca n't figure out would be ok with arity 2 . showMultiLineString :: String -> [String] | Like ' showLitString ' ( expand escape characters using returns @["\"hello\\n\\ " , " \\goodbye\n\\ " , " \\blah\""]@ showMultiLineString str = go '\"' str where go ch s = case break (== '\n') s of (l, _:s'@(_:_)) -> (ch : showLitString l "\\n\\") : go '\\' s' (l, "\n") -> [ch : showLitString l "\\n\""] (l, _) -> [ch : showLitString l "\""] isDec :: Char -> Bool isDec c = c >= '0' && c <= '9' protectEsc :: (Char -> Bool) -> ShowS -> ShowS protectEsc p f = f . cont where cont s@(c:_) | p c = "\\&" ++ s cont s = s asciiTab :: [String] ["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US", "SP"] Code specific for Ints . digit ' ' . This function fails on other inputs , and generates intToDigit :: Int -> Char intToDigit (I# i) | isTrue# (i >=# 0#) && isTrue# (i <=# 9#) = unsafeChr (ord '0' + I# i) | isTrue# (i >=# 10#) && isTrue# (i <=# 15#) = unsafeChr (ord 'a' + I# i - 10) | otherwise = errorWithoutStackTrace ("Char.intToDigit: not a digit " ++ show (I# i)) showSignedInt :: Int -> Int -> ShowS showSignedInt (I# p) (I# n) r | isTrue# (n <# 0#) && isTrue# (p ># 6#) = '(' : itos n (')' : r) | otherwise = itos n r itos :: Int# -> String -> String itos n# cs | isTrue# (n# <# 0#) = let !(I# minInt#) = minInt in if isTrue# (n# ==# minInt#) then '-' : (case n# `quotRemInt#` 10# of (# q, r #) -> itos' (negateInt# q) (itos' (negateInt# r) cs)) else '-' : itos' (negateInt# n#) cs | otherwise = itos' n# cs where itos' :: Int# -> String -> String itos' x# cs' | isTrue# (x# <# 10#) = C# (chr# (ord# '0'# +# x#)) : cs' | otherwise = case x# `quotRemInt#` 10# of (# q, r #) -> case chr# (ord# '0'# +# r) of c# -> itos' q (C# c# : cs') The Integer instances for Show | @since 2.01 instance Show Integer where showsPrec p n r | p > 6 && n < 0 = '(' : integerToString n (')' : r) Minor point : testing p first gives better code in the not - uncommon case where the p argument | otherwise = integerToString n r showList = showList__ (showsPrec 0) integerToString :: Integer -> String -> String integerToString n0 cs0 | n0 < 0 = '-' : integerToString' (- n0) cs0 | otherwise = integerToString' n0 cs0 where integerToString' :: Integer -> String -> String integerToString' n cs | n < BASE = jhead (fromInteger n) cs | otherwise = jprinth (jsplitf (BASE*BASE) n) cs Split n into digits in base p. We first split n into digits in base p*p and then split each of these digits into two . Note that the first ' digit ' modulo p*p may have a leading zero jsplitf :: Integer -> Integer -> [Integer] jsplitf p n | p > n = [n] | otherwise = jsplith p (jsplitf (p*p) n) jsplith :: Integer -> [Integer] -> [Integer] jsplith p (n:ns) = case n `quotRemInteger` p of (# q, r #) -> if q > 0 then q : r : jsplitb p ns else r : jsplitb p ns jsplith _ [] = errorWithoutStackTrace "jsplith: []" jsplitb :: Integer -> [Integer] -> [Integer] jsplitb _ [] = [] jsplitb p (n:ns) = case n `quotRemInteger` p of (# q, r #) -> q : r : jsplitb p ns jprinth :: [Integer] -> String -> String jprinth (n:ns) cs = case n `quotRemInteger` BASE of (# q', r' #) -> let q = fromInteger q' r = fromInteger r' in if q > 0 then jhead q $ jblock r $ jprintb ns cs else jhead r $ jprintb ns cs jprinth [] _ = errorWithoutStackTrace "jprinth []" jprintb :: [Integer] -> String -> String jprintb [] cs = cs jprintb (n:ns) cs = case n `quotRemInteger` BASE of (# q', r' #) -> let q = fromInteger q' r = fromInteger r' in jblock q $ jblock r $ jprintb ns cs Convert an integer that fits into a machine word . Again , we have two functions , one that drops leading zeros ( ) and one that does n't jhead :: Int -> String -> String jhead n cs | n < 10 = case unsafeChr (ord '0' + n) of c@(C# _) -> c : cs | otherwise = case unsafeChr (ord '0' + r) of c@(C# _) -> jhead q (c : cs) where (q, r) = n `quotRemInt` 10 jblock' :: Int -> Int -> String -> String jblock' d n cs | d == 1 = case unsafeChr (ord '0' + n) of c@(C# _) -> c : cs | otherwise = case unsafeChr (ord '0' + r) of c@(C# _) -> jblock' (d - 1) q (c : cs) where (q, r) = n `quotRemInt` 10
7a259e3ea5ac0b0fb77c0b11795d12492468ade2e51729a50eae0e976cc323d5
HaskellEmbedded/data-stm32
UART.hs
# LANGUAGE DataKinds # # LANGUAGE TypeFamilies # # LANGUAGE FlexibleContexts # {-# LANGUAGE Rank2Types #-} # LANGUAGE ExistentialQuantification # # LANGUAGE TypeOperators # module {{ modns }} ( UART(..) , UARTPins(..) , UARTVersion(..) , mkUARTVersion module Ivory . BSP.STM32.Peripheral . UART1.Peripheral ) where import Ivory.Language import Ivory.BSP.STM32.Interrupt import Ivory.BSP.STM32.ClockConfig import Ivory.BSP.STM32.Peripheral.GPIO (GPIOPin, GPIO_AF) import Ivory.BSP.STM32.Peripheral.UART.Pins (UARTPins(..)) {{#versions}} import qualified Ivory.BSP.STM32.Peripheral.UARTv{{ version }}.Peripheral as P{{ version }} {{/versions}} data UARTVersion = {{#versions}} {{ prefix }} V{{ version }} {{/versions}} data UART = {{#versions}} {{ prefix }} WrappedV{{ version }} P{{ version }}.UART {{/versions}} mkUARTVersion :: (STM32Interrupt i) => UARTVersion -> Integer -> (forall eff . Ivory eff ()) -> (forall eff . Ivory eff ()) -> i -> PClk -> (GPIOPin -> GPIO_AF) -> String -> UART {{#versions}} mkUARTVersion V{{ version }} i e1 e2 j c af s = WrappedV{{ version }} $ P{{ version }}.mkUART i e1 e2 j c af s {{/versions}}
null
https://raw.githubusercontent.com/HaskellEmbedded/data-stm32/204aff53eaae422d30516039719a6ec7522a6ab7/templates/STM32/Peripheral/UART.hs
haskell
# LANGUAGE Rank2Types #
# LANGUAGE DataKinds # # LANGUAGE TypeFamilies # # LANGUAGE FlexibleContexts # # LANGUAGE ExistentialQuantification # # LANGUAGE TypeOperators # module {{ modns }} ( UART(..) , UARTPins(..) , UARTVersion(..) , mkUARTVersion module Ivory . BSP.STM32.Peripheral . UART1.Peripheral ) where import Ivory.Language import Ivory.BSP.STM32.Interrupt import Ivory.BSP.STM32.ClockConfig import Ivory.BSP.STM32.Peripheral.GPIO (GPIOPin, GPIO_AF) import Ivory.BSP.STM32.Peripheral.UART.Pins (UARTPins(..)) {{#versions}} import qualified Ivory.BSP.STM32.Peripheral.UARTv{{ version }}.Peripheral as P{{ version }} {{/versions}} data UARTVersion = {{#versions}} {{ prefix }} V{{ version }} {{/versions}} data UART = {{#versions}} {{ prefix }} WrappedV{{ version }} P{{ version }}.UART {{/versions}} mkUARTVersion :: (STM32Interrupt i) => UARTVersion -> Integer -> (forall eff . Ivory eff ()) -> (forall eff . Ivory eff ()) -> i -> PClk -> (GPIOPin -> GPIO_AF) -> String -> UART {{#versions}} mkUARTVersion V{{ version }} i e1 e2 j c af s = WrappedV{{ version }} $ P{{ version }}.mkUART i e1 e2 j c af s {{/versions}}
616b0123b6277ce4d887dece0b7b8ebc2af255a65aad0aa3eea566b40b5984c3
bobzhang/fan
ref.mli
(** @params r v body treat [r]'s state as [v] in [body], the value will be restored when exit *) val protect : 'a ref -> 'a -> (unit -> 'b) -> 'b (** see [protect]*) val protect2 : 'a ref * 'a -> 'b ref * 'b -> (unit -> 'c) -> 'c val protects : 'a ref list -> 'a list -> (unit -> 'b) -> 'b (** A weak form of [protect]. Restore the value when exit *) val save : 'a ref -> (unit -> 'b) -> 'b val save2 : 'a ref -> 'b ref -> (unit -> 'c) -> 'c val saves : 'a ref list -> (unit -> 'b) -> 'b val post : 'a ref -> ('a -> 'a) -> 'a val pre : 'a ref -> ('a -> 'a) -> 'a val swap : 'a ref -> 'a ref -> unit val modify : 'a ref -> ('a -> 'a) -> unit
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/utils/ref.mli
ocaml
* @params r v body treat [r]'s state as [v] in [body], the value will be restored when exit * see [protect] * A weak form of [protect]. Restore the value when exit
val protect : 'a ref -> 'a -> (unit -> 'b) -> 'b val protect2 : 'a ref * 'a -> 'b ref * 'b -> (unit -> 'c) -> 'c val protects : 'a ref list -> 'a list -> (unit -> 'b) -> 'b val save : 'a ref -> (unit -> 'b) -> 'b val save2 : 'a ref -> 'b ref -> (unit -> 'c) -> 'c val saves : 'a ref list -> (unit -> 'b) -> 'b val post : 'a ref -> ('a -> 'a) -> 'a val pre : 'a ref -> ('a -> 'a) -> 'a val swap : 'a ref -> 'a ref -> unit val modify : 'a ref -> ('a -> 'a) -> unit
22e40db3cd0486cb3f95e70920844678bee1c7459b680f8dac3045c72273f7ba
BinaryAnalysisPlatform/bap
bap_c_term_attributes.mli
* BIR attributes . open Bap.Std open Bap_c_type (** Abstraction of a data representation of C value. This attribute is attached to each inserted arg term, but can be further propagated by other passes *) val data : Bap_c_data.t tag (** Function prototype. This attribute is inserted into each annotated function. *) val proto : proto tag * [ layout ] describes the layout of a C object . @since 2.5.0 @since 2.5.0 *) val layout : Bap_c_data.layout tag (** A c type associated with a term. This attribute is attached to each inserted arg term, but maybe propagated by further by other passes. *) val t : t tag
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/5a71fb10683f0d865322a9df99951c3b11ba1a50/lib/bap_c/bap_c_term_attributes.mli
ocaml
* Abstraction of a data representation of C value. This attribute is attached to each inserted arg term, but can be further propagated by other passes * Function prototype. This attribute is inserted into each annotated function. * A c type associated with a term. This attribute is attached to each inserted arg term, but maybe propagated by further by other passes.
* BIR attributes . open Bap.Std open Bap_c_type val data : Bap_c_data.t tag val proto : proto tag * [ layout ] describes the layout of a C object . @since 2.5.0 @since 2.5.0 *) val layout : Bap_c_data.layout tag val t : t tag
fa7152c33969431610b093222d6f8f06fc92d91e02988a696b41cd6c98861e43
sethfowler/pygmalion
Request.hs
# LANGUAGE DeriveGeneric # module Pygmalion.RPC.Request ( RPCRequest (..) , RPCResponse (..) ) where import Data.Serialize import qualified Data.Vector as V import Data.Vector.Serialize () import GHC.Generics import Pygmalion.Core import Pygmalion.Database.Request data RPCRequest = RPCIndexCommand !CommandInfo !Time | RPCIndexFile !SourceFile !Time | RPCGetCommandInfo !SourceFile | RPCGetSimilarCommandInfo !SourceFile | RPCGetDefinition !SourceLocation | RPCGetCallers !SourceLocation | RPCGetCallees !SourceLocation | RPCGetBases !SourceLocation | RPCGetOverrides !SourceLocation | RPCGetMembers !SourceLocation | RPCGetRefs !SourceLocation | RPCGetReferenced !SourceLocation | RPCGetDeclReferenced !SourceLocation | RPCGetHierarchy !SourceLocation | RPCGetInclusions !SourceFile | RPCGetIncluders !SourceFile | RPCGetInclusionHierarchy !SourceFile | RPCFoundUpdates !(V.Vector DBUpdate) | RPCUpdateAndFindDirtyInclusions !SourceFileHash ![Inclusion] | RPCWait | RPCPing | RPCLog !String | RPCDone | RPCStop deriving (Eq, Show, Generic) instance Serialize RPCRequest data RPCResponse a = RPCOK !a | RPCError deriving (Eq, Show, Generic) instance Serialize a => Serialize (RPCResponse a)
null
https://raw.githubusercontent.com/sethfowler/pygmalion/d58cc3411d6a17cd05c3b0263824cd6a2f862409/src/Pygmalion/RPC/Request.hs
haskell
# LANGUAGE DeriveGeneric # module Pygmalion.RPC.Request ( RPCRequest (..) , RPCResponse (..) ) where import Data.Serialize import qualified Data.Vector as V import Data.Vector.Serialize () import GHC.Generics import Pygmalion.Core import Pygmalion.Database.Request data RPCRequest = RPCIndexCommand !CommandInfo !Time | RPCIndexFile !SourceFile !Time | RPCGetCommandInfo !SourceFile | RPCGetSimilarCommandInfo !SourceFile | RPCGetDefinition !SourceLocation | RPCGetCallers !SourceLocation | RPCGetCallees !SourceLocation | RPCGetBases !SourceLocation | RPCGetOverrides !SourceLocation | RPCGetMembers !SourceLocation | RPCGetRefs !SourceLocation | RPCGetReferenced !SourceLocation | RPCGetDeclReferenced !SourceLocation | RPCGetHierarchy !SourceLocation | RPCGetInclusions !SourceFile | RPCGetIncluders !SourceFile | RPCGetInclusionHierarchy !SourceFile | RPCFoundUpdates !(V.Vector DBUpdate) | RPCUpdateAndFindDirtyInclusions !SourceFileHash ![Inclusion] | RPCWait | RPCPing | RPCLog !String | RPCDone | RPCStop deriving (Eq, Show, Generic) instance Serialize RPCRequest data RPCResponse a = RPCOK !a | RPCError deriving (Eq, Show, Generic) instance Serialize a => Serialize (RPCResponse a)
eff63ec3a99cced67434835806cfb3850614927165932a9bf38ba19c36fc357b
dmitryvk/sbcl-win32-threads
defconstant.lisp
This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!IMPL") (def!macro sb!xc:defconstant (name value &optional documentation) #!+sb-doc "Define a global constant, saying that the value is constant and may be compiled into code. If the variable already has a value, and this is not EQL to the new value, the code is not portable (undefined behavior). The third argument is an optional documentation string for the variable." `(eval-when (:compile-toplevel :load-toplevel :execute) (sb!c::%defconstant ',name ,value ',documentation (sb!c:source-location)))) the guts of (defun sb!c::%defconstant (name value doc source-location) (unless (symbolp name) (error "The constant name is not a symbol: ~S" name)) (when (looks-like-name-of-special-var-p name) (style-warn 'sb!kernel:asterisks-around-constant-variable-name :format-control "defining ~S as a constant" :format-arguments (list name))) (sb!c:with-source-location (source-location) (setf (info :source-location :constant name) source-location)) (let ((kind (info :variable :kind name))) (case kind (:constant ;; Note: This behavior (discouraging any non-EQL modification) is unpopular , but it is specified by ANSI ( i.e. ANSI says a non - EQL change has undefined consequences ) . If people really ;; want bindings which are constant in some sense other than EQL , I suggest either just using DEFVAR ( which is usually appropriate , despite the un - mnemonic name ) , or defining something like the DEFCONSTANT - EQX macro used in SBCL ( which is occasionally more appropriate ) . -- WHN 2001 - 12 - 21 (if (boundp name) (if (typep name '(or boolean keyword)) Non - continuable error . (about-to-modify-symbol-value name 'defconstant) (let ((old (symbol-value name))) (unless (eql value old) (multiple-value-bind (ignore aborted) (with-simple-restart (abort "Keep the old value.") (cerror "Go ahead and change the value." 'defconstant-uneql :name name :old-value old :new-value value)) (declare (ignore ignore)) (when aborted (return-from sb!c::%defconstant name)))))) (warn "redefining a MAKUNBOUND constant: ~S" name))) (:unknown ;; (This is OK -- undefined variables are of this kind. So we ;; don't warn or error or anything, just fall through.) ) (t (warn "redefining ~(~A~) ~S to be a constant" kind name)))) (when doc (setf (fdocumentation name 'variable) doc)) #-sb-xc-host (%set-symbol-value name value) #+sb-xc-host (progn Redefining our cross - compilation host 's CL symbols would be poor form . ;; ;; FIXME: Having to check this and then not treat it as a fatal error ;; seems like a symptom of things being pretty broken. It's also a problem ;; in and of itself, since it makes it too easy for cases of using the cross - compilation host 's CL constant values in the target Lisp to ;; slip by. I got backed into this because the cross-compiler translates DEFCONSTANT SB!XC : FOO into DEFCONSTANT CL : FOO . It would be good to ;; unscrew the cross-compilation package hacks so that that translation does n't happen . Perhaps : * with SB - CL . SB - CL exports all the symbols which ANSI requires to be exported from CL . * Make a nickname SB!CL which behaves like SB!XC . * Go through the loaded - on - the - host code making every target definition be in SB - CL . E.g. DEFCONSTANT becomes SB!CL : DEFCONSTANT . * Make IN - TARGET - COMPILATION - MODE do UNUSE - PACKAGE CL and USE - PACKAGE SB - CL in each of the target packages ( then undo it on exit ) . * Make the cross - compiler 's implementation of EVAL - WHEN (: COMPILE - TOPLEVEL ) do UNCROSS . ( This may not require any change . ) * Hack GENESIS as necessary so that it outputs SB - CL stuff as COMMON - LISP ;; stuff. * Now the code here can assert that the symbol being defined is n't in the cross - compilation host 's CL package . (unless (eql (find-symbol (symbol-name name) :cl) name) : In the cross - compiler , we use the cross - compilation host 's DEFCONSTANT macro instead of just ( SETF SYMBOL - VALUE ) , in order to ;; get whatever blessing the cross-compilation host may expect for a global ( SETF SYMBOL - VALUE ) . ( CMU CL , at least around 2.4.19 , generated full WARNINGs for code -- e.g. DEFTYPE expanders -- which referred to symbols which had been set by ( SETF SYMBOL - VALUE ) . I ;; doubt such warnings are ANSI-compliant, but I'm not sure, so I've written this in a way that CMU CL will tolerate and which ought to work elsewhere too . ) -- WHN 2001 - 03 - 24 (eval `(defconstant ,name ',value))) ;; It would certainly be awesome if this was only needed for symbols in CL . Unfortunately , that is not the case . Maybe some are moved back in CL later on ? (setf (info :variable :xc-constant-value name) value)) (setf (info :variable :kind name) :constant) name)
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/defconstant.lisp
lisp
more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. Note: This behavior (discouraging any non-EQL modification) want bindings which are constant in some sense other than (This is OK -- undefined variables are of this kind. So we don't warn or error or anything, just fall through.) FIXME: Having to check this and then not treat it as a fatal error seems like a symptom of things being pretty broken. It's also a problem in and of itself, since it makes it too easy for cases of using the slip by. I got backed into this because the cross-compiler translates unscrew the cross-compilation package hacks so that that translation stuff. * Now the code here can assert that the symbol being defined get whatever blessing the cross-compilation host may expect for a doubt such warnings are ANSI-compliant, but I'm not sure, so I've It would certainly be awesome if this was only needed for symbols
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!IMPL") (def!macro sb!xc:defconstant (name value &optional documentation) #!+sb-doc "Define a global constant, saying that the value is constant and may be compiled into code. If the variable already has a value, and this is not EQL to the new value, the code is not portable (undefined behavior). The third argument is an optional documentation string for the variable." `(eval-when (:compile-toplevel :load-toplevel :execute) (sb!c::%defconstant ',name ,value ',documentation (sb!c:source-location)))) the guts of (defun sb!c::%defconstant (name value doc source-location) (unless (symbolp name) (error "The constant name is not a symbol: ~S" name)) (when (looks-like-name-of-special-var-p name) (style-warn 'sb!kernel:asterisks-around-constant-variable-name :format-control "defining ~S as a constant" :format-arguments (list name))) (sb!c:with-source-location (source-location) (setf (info :source-location :constant name) source-location)) (let ((kind (info :variable :kind name))) (case kind (:constant is unpopular , but it is specified by ANSI ( i.e. ANSI says a non - EQL change has undefined consequences ) . If people really EQL , I suggest either just using DEFVAR ( which is usually appropriate , despite the un - mnemonic name ) , or defining something like the DEFCONSTANT - EQX macro used in SBCL ( which is occasionally more appropriate ) . -- WHN 2001 - 12 - 21 (if (boundp name) (if (typep name '(or boolean keyword)) Non - continuable error . (about-to-modify-symbol-value name 'defconstant) (let ((old (symbol-value name))) (unless (eql value old) (multiple-value-bind (ignore aborted) (with-simple-restart (abort "Keep the old value.") (cerror "Go ahead and change the value." 'defconstant-uneql :name name :old-value old :new-value value)) (declare (ignore ignore)) (when aborted (return-from sb!c::%defconstant name)))))) (warn "redefining a MAKUNBOUND constant: ~S" name))) (:unknown ) (t (warn "redefining ~(~A~) ~S to be a constant" kind name)))) (when doc (setf (fdocumentation name 'variable) doc)) #-sb-xc-host (%set-symbol-value name value) #+sb-xc-host (progn Redefining our cross - compilation host 's CL symbols would be poor form . cross - compilation host 's CL constant values in the target Lisp to DEFCONSTANT SB!XC : FOO into DEFCONSTANT CL : FOO . It would be good to does n't happen . Perhaps : * with SB - CL . SB - CL exports all the symbols which ANSI requires to be exported from CL . * Make a nickname SB!CL which behaves like SB!XC . * Go through the loaded - on - the - host code making every target definition be in SB - CL . E.g. DEFCONSTANT becomes SB!CL : DEFCONSTANT . * Make IN - TARGET - COMPILATION - MODE do UNUSE - PACKAGE CL and USE - PACKAGE SB - CL in each of the target packages ( then undo it on exit ) . * Make the cross - compiler 's implementation of EVAL - WHEN (: COMPILE - TOPLEVEL ) do UNCROSS . ( This may not require any change . ) * Hack GENESIS as necessary so that it outputs SB - CL stuff as COMMON - LISP is n't in the cross - compilation host 's CL package . (unless (eql (find-symbol (symbol-name name) :cl) name) : In the cross - compiler , we use the cross - compilation host 's DEFCONSTANT macro instead of just ( SETF SYMBOL - VALUE ) , in order to global ( SETF SYMBOL - VALUE ) . ( CMU CL , at least around 2.4.19 , generated full WARNINGs for code -- e.g. DEFTYPE expanders -- which referred to symbols which had been set by ( SETF SYMBOL - VALUE ) . I written this in a way that CMU CL will tolerate and which ought to work elsewhere too . ) -- WHN 2001 - 03 - 24 (eval `(defconstant ,name ',value))) in CL . Unfortunately , that is not the case . Maybe some are moved back in CL later on ? (setf (info :variable :xc-constant-value name) value)) (setf (info :variable :kind name) :constant) name)
cf6f0a4a0161074bd3871f44f70d5e083faa10f624145c9cd562ecf3c89babee
erlang/otp
diameter_examples_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2013 - 2022 . All Rights Reserved . %% 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. %% %% %CopyrightEnd% %% %% %% Test example code under ../examples/code. %% -module(diameter_examples_SUITE). %% testcase, no common_test dependency -export([run/0, run/1]). %% common_test wrapping -export([suite/0, all/0, dict/1, code/1]). %% rpc calls -export([install/1, start/1, traffic/1]). -include("diameter.hrl"). %% =========================================================================== -define(util, diameter_util). %% The order here is significant and causes the server to listen %% before the clients connect. -define(NODES, [server, client]). %% @inherits dependencies between example dictionaries. This is needed %% in order compile them in the right order. Can't compile to erl to %% find out since @inherits is a beam dependency. -define(INHERITS, [{rfc4006_cc, [rfc4005_nas]}, {rfc4072_eap, [rfc4005_nas]}, {rfc4740_sip, [rfc4590_digest]}]). %% Common dictionaries to inherit from examples. -define(DICT0, [rfc3588_base, rfc6733_base]). %% Transport protocols over which the example Diameter nodes are run. -define(PROTS, [sctp || ?util:have_sctp()] ++ [tcp]). -define(L, atom_to_list). -define(A, list_to_atom). %% =========================================================================== %% common_test wrapping suite() -> [{timetrap, {seconds, 75}}]. all() -> [dict, code]. dict(Config) -> run(dict, Config). code(Config) -> run(code, Config). %% =========================================================================== %% run/0 run() -> run(all()). run/1 run({dict, Dir}) -> compile_dicts(Dir); %% The example code doesn't use the example dictionaries, so a %% separate testcase. run({code, Dir}) -> run_code(Dir); run(List) when is_list(List) -> Tmp = ?util:mktemp("diameter_examples"), try run(List, Tmp) after file:del_dir_r(Tmp) end. %% run/2 Eg . erl -noinput -s diameter_examples_SUITE run code -s init stop ... run(List, Dir) when is_list(List) -> ?util:run([{[fun run/1, {F, Dir}], 60000} || F <- List]); run(F, Config) -> run([F], proplists:get_value(priv_dir, Config)). %% =========================================================================== %% compile_dicts/1 %% %% Compile example dictionaries in examples/dict. compile_dicts(Dir) -> Out = mkdir(Dir, "dict"), Dirs = [filename:join(H ++ ["examples", "dict"]) || H <- [[code:lib_dir(diameter)], [here(), ".."]]], [] = [{F,D,RC} || {_,F} <- sort(find_files(Dirs, ".*\\.dia$")), D <- ?DICT0, RC <- [make(F, D, Out)], RC /= ok]. sort([{_,_} | _] = Files) -> lists:sort(fun({A,_},{B,_}) -> sort([filename:rootname(F) || F <- [A,B]]) end, Files); sort([A,B] = L) -> [DA,DB] = [dep([D],[]) || D <- L], case {[A] -- DB, [B] -- DA} of {[], [_]} -> %% B depends on A true; {[_], []} -> %% A depends on B false; {[_],[_]} -> %% or not length(DA) < length(DB) end. %% Recursively accumulate inherited dictionaries. dep([D|Rest], Acc) -> dep(dep(D), Rest, Acc); dep([], Acc) -> Acc. dep([{Dict, _} | T], Rest, Acc) -> dep(T, [Dict | Rest], [Dict | Acc]); dep([], Rest, Acc) -> dep(Rest, Acc). make(Path, Dict0, Out) when is_atom(Dict0) -> make(Path, atom_to_list(Dict0), Out); make(Path, Dict0, Out) -> Dict = filename:rootname(filename:basename(Path)), {Mod, Pre} = make_name(Dict), {"diameter_gen_base" ++ Suf = Mod0, _} = make_name(Dict0), Name = Mod ++ Suf, try ok = to_erl(Path, [{name, Name}, {prefix, Pre}, {outdir, Out}, {inherits, "common/" ++ Mod0} | [{inherits, D ++ "/" ++ M ++ Suf} || {D,M} <- dep(Dict)]]), ok = to_beam(filename:join(Out, Name)) catch throw: {_,_} = E -> E end. to_erl(File, Opts) -> case diameter_make:codec(File, Opts) of ok -> ok; No -> throw({make, No}) end. to_beam(Name) -> case compile:file(Name ++ ".erl", [return]) of {ok, _, _} -> ok; No -> throw({compile, No}) end. dep(Dict) -> case lists:keyfind(list_to_atom(Dict), 1, ?INHERITS) of {_, Is} -> lists:map(fun inherits/1, Is); false -> [] end. inherits(Dict) when is_atom(Dict) -> inherits(atom_to_list(Dict)); inherits(Dict) -> {Name, _} = make_name(Dict), {Dict, Name}. make_name(Dict) -> {R, [$_|N]} = lists:splitwith(fun(C) -> C /= $_ end, Dict), {string:join(["diameter_gen", N, R], "_"), "diameter_" ++ N}. %% =========================================================================== %% compile_code/1 %% %% Compile example code under examples/code. compile_code(Tmpdir) -> {ok, Pid, Node} = slave(peer:random_name(), here()), try {ok, _Ebin} = rpc:call(Node, ?MODULE, install, [Tmpdir]) after peer:stop(Pid) end. %% Compile in another node since the code path is modified. install(Tmpdir) -> {Top, Dia, Ebin} = install(here(), Tmpdir), %% Prepend the created directory just so that code:lib_dir/1 finds it when compile : file/2 tries to resolve include_lib . true = code:add_patha(Ebin), Dia = code:lib_dir(diameter), %% assert Src = filename:join([Top, "examples", "code"]), Files = find_files([Src], ".*\\.erl$"), [] = [{F,T} || {_,F} <- Files, T <- [compile:file(F, [warnings_as_errors, return_errors, {outdir, Ebin}])], ok /= element(1, T)], {ok, Ebin}. %% Copy include files into a temporary directory and adjust the code %% path in order for example code to be able to include them with include_lib . This is really only required when running in the reop %% since generated includes, that the example code wants to %% include_lib, are under src/gen and there's no way to get get the %% preprocessor to find these otherwise. Generated hrls are only be %% under include in an installation. ("Installing" them locally is %% anathema.) install(Dir, Tmpdir) -> Top = top(Dir, code:lib_dir(diameter)), Create a new diameter / include in priv_dir . Copy all includes %% there, from below ../include and ../src/gen if they exist (in %% the repo). Tmp = filename:join([Tmpdir, "diameter"]), TmpInc = filename:join([Tmp, "include"]), TmpEbin = filename:join([Tmp, "ebin"]), [] = [{T,E} || T <- [Tmp, TmpInc, TmpEbin], {error, E} <- [file:make_dir(T)]], Inc = filename:join([Top, "include"]), Gen = filename:join([Top, "src", "gen"]), Files = find_files([Inc, Gen], ".*\\.hrl$"), [] = [{F,E} || {_,F} <- Files, B <- [filename:basename(F)], D <- [filename:join([TmpInc, B])], {error, E} <- [file:copy(F,D)]], {Top, Tmp, TmpEbin}. find_files(Dirs, RE) -> lists:foldl(fun(D,A) -> fold_files(D, RE, A) end, orddict:new(), Dirs). fold_files(Dir, RE, Acc) -> filelib:fold_files(Dir, RE, false, fun store/2, Acc). store(Path, Dict) -> orddict:store(filename:basename(Path), Path, Dict). %% =========================================================================== %% enslave/1 %% Start two nodes : one for the server , one for the client . enslave(Prefix) -> [{S,N} || D <- [here()], S <- ?NODES, M <- [lists:append(["diameter", Prefix, ?L(S)])], {ok, _, N} <- [slave(M,D)]]. slave(Name, Dir) -> Args = ["-pa", Dir, filename:join([Dir, "..", "ebin"])], {ok, _Pid, _Node} = ?util:peer(#{name => Name, args => Args}). here() -> filename:dirname(code:which(?MODULE)). top(Dir, LibDir) -> File = filename:join([Dir, "depend.sed"]), %% only in the repo case filelib:is_regular(File) of true -> filename:join([Dir, ".."]); false -> LibDir end. %% start/2 start({server, Prot, Ebin}) -> true = code:add_patha(Ebin), ok = diameter:start(), ok = server:start(), {ok, Ref} = server:listen({Prot, any, 3868}), [_] = ?util:lport(Prot, Ref), ok; start({client = Svc, Prot, Ebin}) -> true = code:add_patha(Ebin), ok = diameter:start(), true = diameter:subscribe(Svc), ok = client:start(), {ok, Ref} = client:connect({Prot, loopback, loopback, 3868}), receive #diameter_event{info = {up, Ref, _, _, _}} -> ok after 2000 -> timeout end; start([Prot, Ebin | Nodes]) -> [] = [RC || {S,N} <- Nodes, RC <- [rpc:call(N, ?MODULE, start, [{S, Prot, Ebin}])], RC /= ok]. %% traffic/1 %% %% Send successful messages from client to server. traffic(server) -> ok; traffic(client) -> {_, MRef} = spawn_monitor(fun() -> exit(call(100)) end), receive {'DOWN', MRef, process, _, Reason} -> Reason end; traffic({Prot, Ebin}) -> Nodes = enslave(?L(Prot)), [] = start([Prot, Ebin | Nodes]), [] = [RC || {T,N} <- Nodes, RC <- [rpc:call(N, ?MODULE, traffic, [T])], RC /= ok]. %% run_code/1 run_code(Dir) -> true = is_alive(), %% need distribution for peer nodes {ok, Ebin} = compile_code(mkdir(Dir, "code")), ?util:run([[fun traffic/1, {T, Ebin}] || T <- ?PROTS]). %% call/1 call(0) -> ok; call(N) -> {ok, _} = client:call(), call(N-1). %% mkdir/2 mkdir(Top, Dir) -> Tmp = filename:join(Top, Dir), ok = file:make_dir(Tmp), Tmp.
null
https://raw.githubusercontent.com/erlang/otp/c4d2c952fec0c4ab4ac7ff34c1a153e740fac9a6/lib/diameter/test/diameter_examples_SUITE.erl
erlang
%CopyrightBegin% 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. %CopyrightEnd% Test example code under ../examples/code. testcase, no common_test dependency common_test wrapping rpc calls =========================================================================== The order here is significant and causes the server to listen before the clients connect. @inherits dependencies between example dictionaries. This is needed in order compile them in the right order. Can't compile to erl to find out since @inherits is a beam dependency. Common dictionaries to inherit from examples. Transport protocols over which the example Diameter nodes are run. =========================================================================== common_test wrapping =========================================================================== run/0 The example code doesn't use the example dictionaries, so a separate testcase. run/2 =========================================================================== compile_dicts/1 Compile example dictionaries in examples/dict. B depends on A A depends on B or not Recursively accumulate inherited dictionaries. =========================================================================== compile_code/1 Compile example code under examples/code. Compile in another node since the code path is modified. Prepend the created directory just so that code:lib_dir/1 finds assert Copy include files into a temporary directory and adjust the code path in order for example code to be able to include them with since generated includes, that the example code wants to include_lib, are under src/gen and there's no way to get get the preprocessor to find these otherwise. Generated hrls are only be under include in an installation. ("Installing" them locally is anathema.) there, from below ../include and ../src/gen if they exist (in the repo). =========================================================================== enslave/1 only in the repo start/2 traffic/1 Send successful messages from client to server. run_code/1 need distribution for peer nodes call/1 mkdir/2
Copyright Ericsson AB 2013 - 2022 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(diameter_examples_SUITE). -export([run/0, run/1]). -export([suite/0, all/0, dict/1, code/1]). -export([install/1, start/1, traffic/1]). -include("diameter.hrl"). -define(util, diameter_util). -define(NODES, [server, client]). -define(INHERITS, [{rfc4006_cc, [rfc4005_nas]}, {rfc4072_eap, [rfc4005_nas]}, {rfc4740_sip, [rfc4590_digest]}]). -define(DICT0, [rfc3588_base, rfc6733_base]). -define(PROTS, [sctp || ?util:have_sctp()] ++ [tcp]). -define(L, atom_to_list). -define(A, list_to_atom). suite() -> [{timetrap, {seconds, 75}}]. all() -> [dict, code]. dict(Config) -> run(dict, Config). code(Config) -> run(code, Config). run() -> run(all()). run/1 run({dict, Dir}) -> compile_dicts(Dir); run({code, Dir}) -> run_code(Dir); run(List) when is_list(List) -> Tmp = ?util:mktemp("diameter_examples"), try run(List, Tmp) after file:del_dir_r(Tmp) end. Eg . erl -noinput -s diameter_examples_SUITE run code -s init stop ... run(List, Dir) when is_list(List) -> ?util:run([{[fun run/1, {F, Dir}], 60000} || F <- List]); run(F, Config) -> run([F], proplists:get_value(priv_dir, Config)). compile_dicts(Dir) -> Out = mkdir(Dir, "dict"), Dirs = [filename:join(H ++ ["examples", "dict"]) || H <- [[code:lib_dir(diameter)], [here(), ".."]]], [] = [{F,D,RC} || {_,F} <- sort(find_files(Dirs, ".*\\.dia$")), D <- ?DICT0, RC <- [make(F, D, Out)], RC /= ok]. sort([{_,_} | _] = Files) -> lists:sort(fun({A,_},{B,_}) -> sort([filename:rootname(F) || F <- [A,B]]) end, Files); sort([A,B] = L) -> [DA,DB] = [dep([D],[]) || D <- L], case {[A] -- DB, [B] -- DA} of true; false; length(DA) < length(DB) end. dep([D|Rest], Acc) -> dep(dep(D), Rest, Acc); dep([], Acc) -> Acc. dep([{Dict, _} | T], Rest, Acc) -> dep(T, [Dict | Rest], [Dict | Acc]); dep([], Rest, Acc) -> dep(Rest, Acc). make(Path, Dict0, Out) when is_atom(Dict0) -> make(Path, atom_to_list(Dict0), Out); make(Path, Dict0, Out) -> Dict = filename:rootname(filename:basename(Path)), {Mod, Pre} = make_name(Dict), {"diameter_gen_base" ++ Suf = Mod0, _} = make_name(Dict0), Name = Mod ++ Suf, try ok = to_erl(Path, [{name, Name}, {prefix, Pre}, {outdir, Out}, {inherits, "common/" ++ Mod0} | [{inherits, D ++ "/" ++ M ++ Suf} || {D,M} <- dep(Dict)]]), ok = to_beam(filename:join(Out, Name)) catch throw: {_,_} = E -> E end. to_erl(File, Opts) -> case diameter_make:codec(File, Opts) of ok -> ok; No -> throw({make, No}) end. to_beam(Name) -> case compile:file(Name ++ ".erl", [return]) of {ok, _, _} -> ok; No -> throw({compile, No}) end. dep(Dict) -> case lists:keyfind(list_to_atom(Dict), 1, ?INHERITS) of {_, Is} -> lists:map(fun inherits/1, Is); false -> [] end. inherits(Dict) when is_atom(Dict) -> inherits(atom_to_list(Dict)); inherits(Dict) -> {Name, _} = make_name(Dict), {Dict, Name}. make_name(Dict) -> {R, [$_|N]} = lists:splitwith(fun(C) -> C /= $_ end, Dict), {string:join(["diameter_gen", N, R], "_"), "diameter_" ++ N}. compile_code(Tmpdir) -> {ok, Pid, Node} = slave(peer:random_name(), here()), try {ok, _Ebin} = rpc:call(Node, ?MODULE, install, [Tmpdir]) after peer:stop(Pid) end. install(Tmpdir) -> {Top, Dia, Ebin} = install(here(), Tmpdir), it when compile : file/2 tries to resolve include_lib . true = code:add_patha(Ebin), Src = filename:join([Top, "examples", "code"]), Files = find_files([Src], ".*\\.erl$"), [] = [{F,T} || {_,F} <- Files, T <- [compile:file(F, [warnings_as_errors, return_errors, {outdir, Ebin}])], ok /= element(1, T)], {ok, Ebin}. include_lib . This is really only required when running in the reop install(Dir, Tmpdir) -> Top = top(Dir, code:lib_dir(diameter)), Create a new diameter / include in priv_dir . Copy all includes Tmp = filename:join([Tmpdir, "diameter"]), TmpInc = filename:join([Tmp, "include"]), TmpEbin = filename:join([Tmp, "ebin"]), [] = [{T,E} || T <- [Tmp, TmpInc, TmpEbin], {error, E} <- [file:make_dir(T)]], Inc = filename:join([Top, "include"]), Gen = filename:join([Top, "src", "gen"]), Files = find_files([Inc, Gen], ".*\\.hrl$"), [] = [{F,E} || {_,F} <- Files, B <- [filename:basename(F)], D <- [filename:join([TmpInc, B])], {error, E} <- [file:copy(F,D)]], {Top, Tmp, TmpEbin}. find_files(Dirs, RE) -> lists:foldl(fun(D,A) -> fold_files(D, RE, A) end, orddict:new(), Dirs). fold_files(Dir, RE, Acc) -> filelib:fold_files(Dir, RE, false, fun store/2, Acc). store(Path, Dict) -> orddict:store(filename:basename(Path), Path, Dict). Start two nodes : one for the server , one for the client . enslave(Prefix) -> [{S,N} || D <- [here()], S <- ?NODES, M <- [lists:append(["diameter", Prefix, ?L(S)])], {ok, _, N} <- [slave(M,D)]]. slave(Name, Dir) -> Args = ["-pa", Dir, filename:join([Dir, "..", "ebin"])], {ok, _Pid, _Node} = ?util:peer(#{name => Name, args => Args}). here() -> filename:dirname(code:which(?MODULE)). top(Dir, LibDir) -> case filelib:is_regular(File) of true -> filename:join([Dir, ".."]); false -> LibDir end. start({server, Prot, Ebin}) -> true = code:add_patha(Ebin), ok = diameter:start(), ok = server:start(), {ok, Ref} = server:listen({Prot, any, 3868}), [_] = ?util:lport(Prot, Ref), ok; start({client = Svc, Prot, Ebin}) -> true = code:add_patha(Ebin), ok = diameter:start(), true = diameter:subscribe(Svc), ok = client:start(), {ok, Ref} = client:connect({Prot, loopback, loopback, 3868}), receive #diameter_event{info = {up, Ref, _, _, _}} -> ok after 2000 -> timeout end; start([Prot, Ebin | Nodes]) -> [] = [RC || {S,N} <- Nodes, RC <- [rpc:call(N, ?MODULE, start, [{S, Prot, Ebin}])], RC /= ok]. traffic(server) -> ok; traffic(client) -> {_, MRef} = spawn_monitor(fun() -> exit(call(100)) end), receive {'DOWN', MRef, process, _, Reason} -> Reason end; traffic({Prot, Ebin}) -> Nodes = enslave(?L(Prot)), [] = start([Prot, Ebin | Nodes]), [] = [RC || {T,N} <- Nodes, RC <- [rpc:call(N, ?MODULE, traffic, [T])], RC /= ok]. run_code(Dir) -> {ok, Ebin} = compile_code(mkdir(Dir, "code")), ?util:run([[fun traffic/1, {T, Ebin}] || T <- ?PROTS]). call(0) -> ok; call(N) -> {ok, _} = client:call(), call(N-1). mkdir(Top, Dir) -> Tmp = filename:join(Top, Dir), ok = file:make_dir(Tmp), Tmp.
f72252368220b22d43bba7ff0b6bcb1a992752d2848a00f15deec7eaa55e4b71
static-analysis-engineering/codehawk
jCHXNativeMethodSignatures.ml
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk C Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk C Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC 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. ============================================================================= *) chlib open CHCommon open CHPretty (* chutil *) open CHLogger (* jchlib *) open JCHBasicTypes (* jchpre *) open JCHApplication open JCHCHAUtil open JCHNativeMethods open JCHSystemSettings let jars = ref [] let output_directory = ref "" let read_jar_name s = begin jars := s :: !jars ; app#add_application_jar s end let name = ref "" let speclist = [ ("-classpath", Arg.String system_settings#add_classpath_unit, "sets java classpath") ; ("-o", Arg.Set_string output_directory, "output directory where results get saved") ; ("-load", Arg.Rest read_jar_name, "list of jars to be loaded") ] let usage_msg = "get_native_signatures filename" let read_args () = Arg.parse speclist (fun s -> name := s) usage_msg let main () = try let _ = read_args () in let dir = if !output_directory = "" then "ch_native_signatures" else !output_directory in begin (if not (Sys.file_exists dir) then Unix.mkdir dir 0o750) ; save_native_signatures dir !jars ; pr_debug [ STR "Load library calls: " ; NL ] ; pr_debug (List.map (fun s -> LBLOCK [ STR " " ; STR s ; NL ]) (get_loadlibrarycalls ())) end with | CHFailure p | JCH_failure p -> pr_debug [ STR "Error in get_native_signatures: " ; p ] let _ = Printexc.print main ()
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchcmdline/jCHXNativeMethodSignatures.ml
ocaml
chutil jchlib jchpre
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk C Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk C Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC 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. ============================================================================= *) chlib open CHCommon open CHPretty open CHLogger open JCHBasicTypes open JCHApplication open JCHCHAUtil open JCHNativeMethods open JCHSystemSettings let jars = ref [] let output_directory = ref "" let read_jar_name s = begin jars := s :: !jars ; app#add_application_jar s end let name = ref "" let speclist = [ ("-classpath", Arg.String system_settings#add_classpath_unit, "sets java classpath") ; ("-o", Arg.Set_string output_directory, "output directory where results get saved") ; ("-load", Arg.Rest read_jar_name, "list of jars to be loaded") ] let usage_msg = "get_native_signatures filename" let read_args () = Arg.parse speclist (fun s -> name := s) usage_msg let main () = try let _ = read_args () in let dir = if !output_directory = "" then "ch_native_signatures" else !output_directory in begin (if not (Sys.file_exists dir) then Unix.mkdir dir 0o750) ; save_native_signatures dir !jars ; pr_debug [ STR "Load library calls: " ; NL ] ; pr_debug (List.map (fun s -> LBLOCK [ STR " " ; STR s ; NL ]) (get_loadlibrarycalls ())) end with | CHFailure p | JCH_failure p -> pr_debug [ STR "Error in get_native_signatures: " ; p ] let _ = Printexc.print main ()
79721da32b27840e32ad161412b2b33f86da07764418b758287a52ff01b4696c
replikativ/datahike
db_test.cljc
(ns datahike.test.attribute-refs.db-test (:require #?(:cljs [cljs.test :as t :refer-macros [is deftest testing]] :clj [clojure.test :as t :refer [is deftest testing]]) [datahike.api :as d])) (def ref-cfg {:store {:backend :mem :id "attr-refs-test.db"} :keep-history? true :attribute-refs? true :schema-flexibility :write :name "attr-refs-test"}) (def name-schema [{:db/ident :name :db/cardinality :db.cardinality/one :db/valueType :db.type/string}]) (defn setup-db [cfg] (d/delete-database cfg) (d/create-database cfg) (d/connect cfg)) (deftest test-partial-db (let [conn (setup-db ref-cfg) _tx0 (d/transact conn name-schema) tx1 (-> (d/transact conn [{:name "Peter"}]) :db-after :max-tx) tx2 (-> (d/transact conn [{:name "Maria"}]) :db-after :max-tx)] (testing "AsOfDB" (is (= #{["Peter"] ["Maria"]} (d/q '[:find ?v :where [?e :name ?v]] (d/as-of @conn tx2)))) (is (= #{["Peter"]} (d/q '[:find ?v :where [?e :name ?v]] (d/as-of @conn tx1))))) (testing "SinceDB" (is (= #{["Maria"] ["Peter"]} (d/q '[:find ?v :where [?e :name ?v]] (d/since @conn tx1)))) (is (= #{["Maria"]} (d/q '[:find ?v :where [?e :name ?v]] (d/since @conn tx2)))))))
null
https://raw.githubusercontent.com/replikativ/datahike/408cb0f538a837267e44b098df895fa00348fe10/test/datahike/test/attribute_refs/db_test.cljc
clojure
(ns datahike.test.attribute-refs.db-test (:require #?(:cljs [cljs.test :as t :refer-macros [is deftest testing]] :clj [clojure.test :as t :refer [is deftest testing]]) [datahike.api :as d])) (def ref-cfg {:store {:backend :mem :id "attr-refs-test.db"} :keep-history? true :attribute-refs? true :schema-flexibility :write :name "attr-refs-test"}) (def name-schema [{:db/ident :name :db/cardinality :db.cardinality/one :db/valueType :db.type/string}]) (defn setup-db [cfg] (d/delete-database cfg) (d/create-database cfg) (d/connect cfg)) (deftest test-partial-db (let [conn (setup-db ref-cfg) _tx0 (d/transact conn name-schema) tx1 (-> (d/transact conn [{:name "Peter"}]) :db-after :max-tx) tx2 (-> (d/transact conn [{:name "Maria"}]) :db-after :max-tx)] (testing "AsOfDB" (is (= #{["Peter"] ["Maria"]} (d/q '[:find ?v :where [?e :name ?v]] (d/as-of @conn tx2)))) (is (= #{["Peter"]} (d/q '[:find ?v :where [?e :name ?v]] (d/as-of @conn tx1))))) (testing "SinceDB" (is (= #{["Maria"] ["Peter"]} (d/q '[:find ?v :where [?e :name ?v]] (d/since @conn tx1)))) (is (= #{["Maria"]} (d/q '[:find ?v :where [?e :name ?v]] (d/since @conn tx2)))))))
5ff20e02f62c2e27f7d99fd37082ec6a5de30472a3c996166f6036a010e03171
chrisaddy/astronaut
core.clj
(ns astronaut.core (:require [cli-matic.core :refer [run-cmd]]) (:require [clojure.java.jdbc :refer :all]) (:require [clojure.pprint :as p]) (:require [clojure.java.jdbc :as j]) (:require [clj-time.core :as t]) (:require [clj-time.coerce :as c]) (:require [clojure.java.io :as io]) (:require [clojure.string :as str]) (:require [clojure.math.numeric-tower :as math]) (:gen-class)) (def home-directory (System/getProperty "user.home")) (def astro-directory (str home-directory "/.astronaut/")) (def cards-db-location (str astro-directory "cards.db")) (def INITIALIZE-DB (str "create table cards" "(id TEXT PRIMARY KEY," "card_id INTEGER," "front TEXT," "back TEXT," "attempt INTEGER," "confidence INTEGER," "review INTEGER," "next_attempt INTEGER," "next_review INTEGER);")) (defn review-query [ts] (str "select * from (select distinct * from (select * from cards order by next_review desc) group by card_id) where next_review <= " ts ";")) (defn current-time [] (c/to-long (t/now))) (def db {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname cards-db-location}) (defn qry "Return the result of a query from a string when the result is expected to be a single value" [q] (first (j/query db q))) (defn newest [] (p/print-table (j/query db REVIEWQUERY))) (defn count-cards "Return the current number of cards in the database" [] (:count (qry "select count(*) as count from cards;"))) (defn largest-card-id "Find the largest card id, if none exists, return 0" [] (def lgid (:max (qry "select max(card_id) as max from cards;"))) (if (nil? lgid) 0 lgid)) (defn new-card-id "Create a new integer card id by incrementing the largest id" [] (+ 1 (largest-card-id))) (defn create-id [] (first (str/split (str (java.util.UUID/randomUUID)) #"-"))) (defn insert-card-query-string [{id :id attempt :attempt card_id :card_id front :front back :back review :review next-review :next-review confidence :confidence}] (str "insert into cards" "(id,card_id,front,back,attempt,review,confidence,next_attempt,next_review) " "values('" (create-id) "'," card_id ",'" front "','" back "'," attempt "," review "," confidence "," (+ 1 attempt) "," next-review ");")) (defn schedule [{id :id attempt :attempt card_id :card_id confidence :confidence ts :ts}] (def last-attempt (first (j/query db (str "select * from cards where id = '" id "';")))) (def last-attempt-confidence (:confidence last-attempt)) (def front (:front last-attempt)) (def back (:back last-attempt)) (defn next-review [att conf, t] (+ 86400000 (* (math/expt (int att ) (Math/log conf))) t)) (println last-attempt) (def query-string (insert-card-query-string {:attempt (+ 1 attempt) :card_id card_id :confidence confidence :review ts :front front :back back :next-review (next-review attempt confidence ts) })) (j/execute! db query-string)) (defn review-card [{id :id front :front, back :back, attempt :attempt card_id :card_id}] (println (str "\u001b[32;1m" front "\u001b[0m\n")) (println "press any key when ready to flip card") (def pause (read-line)) (println (str "\u001b[34;1m" back "\u001b[0m")) (do (print "How easy was that [0-10]? ") (flush) (def confidence (read-line))) (schedule {:id id :attempt attempt :card_id card_id :confidence (Integer/parseInt confidence) :ts (current-time)})) (defn review [] (def ts (current-time)) (def cards (j/query db (review-query ts))) (let [len (count cards)] (if (= len 0) (println "Congrats you're all done for now!") (do (println (str "\u001b[33;1m" len " cards left to review.\u001b[0m\n")) (map review-card cards))))) (defn add-card [{:keys [front back]}] (def card_id (new-card-id)) (def attempt 0) (def id (create-id)) (def confidence 0) (def review (current-time)) (def query-string (str "insert into cards " "(id,card_id,front,back,attempt,review,confidence,next_attempt,next_review) " "values('" id "'," card_id ",'" front "','" back "','" attempt "','" review "','" confidence "','" (+ 1 attempt) "','" review "');")) (j/execute! db query-string) (println (str "card " id " added to ship."))) (defn list-cards [] (p/print-table (j/query db (str "select * from cards;")))) (defn init-table [{:keys [& args]}] (println (str "creating " astro-directory)) (.mkdir (java.io.File. astro-directory)) (println (str "creating " cards-db-location)) (spit cards-db-location nil) (j/execute! db INITIALIZE-DB) (println "cards db initialized")) (def CONFIGURATION {:app {:command "astronaut" :description "Command-line spaced-repition" :version "0.0.1"} ; :global-opts [{:option "tags" ; :short "t" ; :as "Card context" ; :type :string ; :default ""}] :commands [{:command "init" :description "Initialize astronaut cli" :runs init-table} {:command "add-card" :short "a" :description "Adds a card to the backlog" :opts [{:option "front" :short "f" :as "Front of the card"} {:option "back" :short "b" :as "Back of the card"}] :runs add-card} {:command "inspect" :description "Review scheduled cards" :runs review} {:command "list" :description "List all cards" :runs list-cards} ]}) (defn -main "I don't do a whole lot ... yet." [& args] (run-cmd args CONFIGURATION))
null
https://raw.githubusercontent.com/chrisaddy/astronaut/42fb7f5d83ccf0cea4d52f8cf21cbef96b805ae6/src/astronaut/core.clj
clojure
:global-opts [{:option "tags" :short "t" :as "Card context" :type :string :default ""}]
(ns astronaut.core (:require [cli-matic.core :refer [run-cmd]]) (:require [clojure.java.jdbc :refer :all]) (:require [clojure.pprint :as p]) (:require [clojure.java.jdbc :as j]) (:require [clj-time.core :as t]) (:require [clj-time.coerce :as c]) (:require [clojure.java.io :as io]) (:require [clojure.string :as str]) (:require [clojure.math.numeric-tower :as math]) (:gen-class)) (def home-directory (System/getProperty "user.home")) (def astro-directory (str home-directory "/.astronaut/")) (def cards-db-location (str astro-directory "cards.db")) (def INITIALIZE-DB (str "create table cards" "(id TEXT PRIMARY KEY," "card_id INTEGER," "front TEXT," "back TEXT," "attempt INTEGER," "confidence INTEGER," "review INTEGER," "next_attempt INTEGER," "next_review INTEGER);")) (defn review-query [ts] (str "select * from (select distinct * from (select * from cards order by next_review desc) group by card_id) where next_review <= " ts ";")) (defn current-time [] (c/to-long (t/now))) (def db {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname cards-db-location}) (defn qry "Return the result of a query from a string when the result is expected to be a single value" [q] (first (j/query db q))) (defn newest [] (p/print-table (j/query db REVIEWQUERY))) (defn count-cards "Return the current number of cards in the database" [] (:count (qry "select count(*) as count from cards;"))) (defn largest-card-id "Find the largest card id, if none exists, return 0" [] (def lgid (:max (qry "select max(card_id) as max from cards;"))) (if (nil? lgid) 0 lgid)) (defn new-card-id "Create a new integer card id by incrementing the largest id" [] (+ 1 (largest-card-id))) (defn create-id [] (first (str/split (str (java.util.UUID/randomUUID)) #"-"))) (defn insert-card-query-string [{id :id attempt :attempt card_id :card_id front :front back :back review :review next-review :next-review confidence :confidence}] (str "insert into cards" "(id,card_id,front,back,attempt,review,confidence,next_attempt,next_review) " "values('" (create-id) "'," card_id ",'" front "','" back "'," attempt "," review "," confidence "," (+ 1 attempt) "," next-review ");")) (defn schedule [{id :id attempt :attempt card_id :card_id confidence :confidence ts :ts}] (def last-attempt (first (j/query db (str "select * from cards where id = '" id "';")))) (def last-attempt-confidence (:confidence last-attempt)) (def front (:front last-attempt)) (def back (:back last-attempt)) (defn next-review [att conf, t] (+ 86400000 (* (math/expt (int att ) (Math/log conf))) t)) (println last-attempt) (def query-string (insert-card-query-string {:attempt (+ 1 attempt) :card_id card_id :confidence confidence :review ts :front front :back back :next-review (next-review attempt confidence ts) })) (j/execute! db query-string)) (defn review-card [{id :id front :front, back :back, attempt :attempt card_id :card_id}] (println (str "\u001b[32;1m" front "\u001b[0m\n")) (println "press any key when ready to flip card") (def pause (read-line)) (println (str "\u001b[34;1m" back "\u001b[0m")) (do (print "How easy was that [0-10]? ") (flush) (def confidence (read-line))) (schedule {:id id :attempt attempt :card_id card_id :confidence (Integer/parseInt confidence) :ts (current-time)})) (defn review [] (def ts (current-time)) (def cards (j/query db (review-query ts))) (let [len (count cards)] (if (= len 0) (println "Congrats you're all done for now!") (do (println (str "\u001b[33;1m" len " cards left to review.\u001b[0m\n")) (map review-card cards))))) (defn add-card [{:keys [front back]}] (def card_id (new-card-id)) (def attempt 0) (def id (create-id)) (def confidence 0) (def review (current-time)) (def query-string (str "insert into cards " "(id,card_id,front,back,attempt,review,confidence,next_attempt,next_review) " "values('" id "'," card_id ",'" front "','" back "','" attempt "','" review "','" confidence "','" (+ 1 attempt) "','" review "');")) (j/execute! db query-string) (println (str "card " id " added to ship."))) (defn list-cards [] (p/print-table (j/query db (str "select * from cards;")))) (defn init-table [{:keys [& args]}] (println (str "creating " astro-directory)) (.mkdir (java.io.File. astro-directory)) (println (str "creating " cards-db-location)) (spit cards-db-location nil) (j/execute! db INITIALIZE-DB) (println "cards db initialized")) (def CONFIGURATION {:app {:command "astronaut" :description "Command-line spaced-repition" :version "0.0.1"} :commands [{:command "init" :description "Initialize astronaut cli" :runs init-table} {:command "add-card" :short "a" :description "Adds a card to the backlog" :opts [{:option "front" :short "f" :as "Front of the card"} {:option "back" :short "b" :as "Back of the card"}] :runs add-card} {:command "inspect" :description "Review scheduled cards" :runs review} {:command "list" :description "List all cards" :runs list-cards} ]}) (defn -main "I don't do a whole lot ... yet." [& args] (run-cmd args CONFIGURATION))
0199072ef454c0649f10be9f13805fd5f8846b59df483d4fc9366d8c6923feb7
NorfairKing/feedback
Filter.hs
# LANGUAGE CPP # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # module Feedback.Loop.Filter where import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as LB8 import Data.Conduit import qualified Data.Conduit.Combinators as C import qualified Data.Conduit.List as CL import Data.List import Data.Set import qualified Data.Set as S import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Feedback.Common.OptParse import Path import Path.IO import System.Exit import System.Process.Typed as Typed #ifdef MIN_VERSION_Win32 import System.Win32.MinTTY (isMinTTYHandle) import System.Win32.Types (withHandleToHANDLE) #endif import UnliftIO #ifdef MIN_VERSION_Win32 getMinTTY :: IO Bool getMinTTY = withHandleToHANDLE stdin isMinTTYHandle #else getMinTTY :: IO Bool getMinTTY = pure False #endif data Filter = Filter { filterDirFilter :: Path Abs Dir -> Bool, filterFileFilter :: Path Abs File -> Bool } instance Semigroup Filter where f1 <> f2 = Filter { filterDirFilter = \d -> filterDirFilter f1 d && filterDirFilter f2 d, filterFileFilter = \f -> filterFileFilter f1 f && filterFileFilter f2 f } instance Monoid Filter where mempty = Filter {filterDirFilter = const True, filterFileFilter = const True} mappend = (<>) fileSetFilter :: Set (Path Abs File) -> Filter fileSetFilter fileSet = let dirSet = S.map parent fileSet in Filter { filterDirFilter = (`S.member` dirSet), filterFileFilter = (`S.member` fileSet) } mkCombinedFilter :: Path Abs Dir -> FilterSettings -> IO Filter mkCombinedFilter here filterSettings = mconcat <$> sequence [ mkGitFilter here filterSettings, mkFindFilter here filterSettings, pure $ standardFilter here ] mkStdinFilter :: Path Abs Dir -> IO Filter mkStdinFilter here = maybe mempty fileSetFilter <$> getStdinFiles here getStdinFiles :: Path Abs Dir -> IO (Maybe (Set (Path Abs File))) getStdinFiles here = do isTerminal <- hIsTerminalDevice stdin isMinTTY <- getMinTTY if isTerminal || isMinTTY then pure Nothing else (Just <$> handleFileSet here stdin) `catch` (\(_ :: IOException) -> pure Nothing) mkGitFilter :: Path Abs Dir -> FilterSettings -> IO Filter mkGitFilter here FilterSettings {..} = do if filterSettingGitignore then do mGitFiles <- gitLsFiles here pure $ maybe mempty fileSetFilter mGitFiles else pure mempty gitLsFiles :: Path Abs Dir -> IO (Maybe (Set (Path Abs File))) gitLsFiles here = do -- If there is no git directory, we'll get a 'fatal' message on stderr. -- We don't need the user to see this, so we setStderr nullStream. let processConfig = setStderr nullStream $ shell "git ls-files" (ec, out) <- readProcessStdout processConfig set <- bytesFileSet here out pure $ case ec of ExitFailure _ -> Nothing ExitSuccess -> Just set mkFindFilter :: Path Abs Dir -> FilterSettings -> IO Filter mkFindFilter here FilterSettings {..} = case filterSettingFind of Nothing -> pure mempty Just args -> fileSetFilter <$> filesFromFindArgs here args filesFromFindArgs :: Path Abs Dir -> String -> IO (Set (Path Abs File)) filesFromFindArgs here args = do let processConfig = setStdout createPipe $ shell $ "find " <> args (ec, out) <- readProcessStdout processConfig set <- bytesFileSet here out case ec of ExitFailure _ -> die $ "Find failed: " <> show ec ExitSuccess -> pure set bytesFileSet :: Path Abs Dir -> LB.ByteString -> IO (Set (Path Abs File)) bytesFileSet here lb = runConduit $ CL.sourceList (LB8.lines lb) .| C.map LB.toStrict .| fileSetBuilder here handleFileSet :: Path Abs Dir -> Handle -> IO (Set (Path Abs File)) handleFileSet here h = runConduit $ C.sourceHandle h .| C.linesUnboundedAscii .| fileSetBuilder here fileSetBuilder :: Path Abs Dir -> ConduitT ByteString Void IO (Set (Path Abs File)) fileSetBuilder here = C.concatMap TE.decodeUtf8' .| C.map T.unpack .| C.mapM (resolveFile here) .| C.foldMap S.singleton standardFilter :: Path Abs Dir -> Filter standardFilter here = Filter { filterDirFilter = not . isHiddenIn here, filterFileFilter = \f -> and [ not $ isHiddenIn here f, -- It's not one of those files that vim makes not $ "~" `isSuffixOf` fromAbsFile f, filename f /= [relfile|4913|] ] } hidden :: Path Rel File -> Bool hidden = goFile where goFile :: Path Rel File -> Bool goFile f = isHiddenIn (parent f) f || goDir (parent f) goDir :: Path Rel Dir -> Bool goDir f | parent f == f = False | otherwise = isHiddenIn (parent f) f || goDir (parent f) isHiddenIn :: Path b Dir -> Path b t -> Bool isHiddenIn curdir ad = case stripProperPrefix curdir ad of Nothing -> False Just rp -> "." `isPrefixOf` toFilePath rp
null
https://raw.githubusercontent.com/NorfairKing/feedback/3448bebcf1bad33fad4bd050f4527e3e3217f415/feedback/src/Feedback/Loop/Filter.hs
haskell
# LANGUAGE OverloadedStrings # If there is no git directory, we'll get a 'fatal' message on stderr. We don't need the user to see this, so we setStderr nullStream. It's not one of those files that vim makes
# LANGUAGE CPP # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # module Feedback.Loop.Filter where import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as LB8 import Data.Conduit import qualified Data.Conduit.Combinators as C import qualified Data.Conduit.List as CL import Data.List import Data.Set import qualified Data.Set as S import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Feedback.Common.OptParse import Path import Path.IO import System.Exit import System.Process.Typed as Typed #ifdef MIN_VERSION_Win32 import System.Win32.MinTTY (isMinTTYHandle) import System.Win32.Types (withHandleToHANDLE) #endif import UnliftIO #ifdef MIN_VERSION_Win32 getMinTTY :: IO Bool getMinTTY = withHandleToHANDLE stdin isMinTTYHandle #else getMinTTY :: IO Bool getMinTTY = pure False #endif data Filter = Filter { filterDirFilter :: Path Abs Dir -> Bool, filterFileFilter :: Path Abs File -> Bool } instance Semigroup Filter where f1 <> f2 = Filter { filterDirFilter = \d -> filterDirFilter f1 d && filterDirFilter f2 d, filterFileFilter = \f -> filterFileFilter f1 f && filterFileFilter f2 f } instance Monoid Filter where mempty = Filter {filterDirFilter = const True, filterFileFilter = const True} mappend = (<>) fileSetFilter :: Set (Path Abs File) -> Filter fileSetFilter fileSet = let dirSet = S.map parent fileSet in Filter { filterDirFilter = (`S.member` dirSet), filterFileFilter = (`S.member` fileSet) } mkCombinedFilter :: Path Abs Dir -> FilterSettings -> IO Filter mkCombinedFilter here filterSettings = mconcat <$> sequence [ mkGitFilter here filterSettings, mkFindFilter here filterSettings, pure $ standardFilter here ] mkStdinFilter :: Path Abs Dir -> IO Filter mkStdinFilter here = maybe mempty fileSetFilter <$> getStdinFiles here getStdinFiles :: Path Abs Dir -> IO (Maybe (Set (Path Abs File))) getStdinFiles here = do isTerminal <- hIsTerminalDevice stdin isMinTTY <- getMinTTY if isTerminal || isMinTTY then pure Nothing else (Just <$> handleFileSet here stdin) `catch` (\(_ :: IOException) -> pure Nothing) mkGitFilter :: Path Abs Dir -> FilterSettings -> IO Filter mkGitFilter here FilterSettings {..} = do if filterSettingGitignore then do mGitFiles <- gitLsFiles here pure $ maybe mempty fileSetFilter mGitFiles else pure mempty gitLsFiles :: Path Abs Dir -> IO (Maybe (Set (Path Abs File))) gitLsFiles here = do let processConfig = setStderr nullStream $ shell "git ls-files" (ec, out) <- readProcessStdout processConfig set <- bytesFileSet here out pure $ case ec of ExitFailure _ -> Nothing ExitSuccess -> Just set mkFindFilter :: Path Abs Dir -> FilterSettings -> IO Filter mkFindFilter here FilterSettings {..} = case filterSettingFind of Nothing -> pure mempty Just args -> fileSetFilter <$> filesFromFindArgs here args filesFromFindArgs :: Path Abs Dir -> String -> IO (Set (Path Abs File)) filesFromFindArgs here args = do let processConfig = setStdout createPipe $ shell $ "find " <> args (ec, out) <- readProcessStdout processConfig set <- bytesFileSet here out case ec of ExitFailure _ -> die $ "Find failed: " <> show ec ExitSuccess -> pure set bytesFileSet :: Path Abs Dir -> LB.ByteString -> IO (Set (Path Abs File)) bytesFileSet here lb = runConduit $ CL.sourceList (LB8.lines lb) .| C.map LB.toStrict .| fileSetBuilder here handleFileSet :: Path Abs Dir -> Handle -> IO (Set (Path Abs File)) handleFileSet here h = runConduit $ C.sourceHandle h .| C.linesUnboundedAscii .| fileSetBuilder here fileSetBuilder :: Path Abs Dir -> ConduitT ByteString Void IO (Set (Path Abs File)) fileSetBuilder here = C.concatMap TE.decodeUtf8' .| C.map T.unpack .| C.mapM (resolveFile here) .| C.foldMap S.singleton standardFilter :: Path Abs Dir -> Filter standardFilter here = Filter { filterDirFilter = not . isHiddenIn here, filterFileFilter = \f -> and [ not $ isHiddenIn here f, not $ "~" `isSuffixOf` fromAbsFile f, filename f /= [relfile|4913|] ] } hidden :: Path Rel File -> Bool hidden = goFile where goFile :: Path Rel File -> Bool goFile f = isHiddenIn (parent f) f || goDir (parent f) goDir :: Path Rel Dir -> Bool goDir f | parent f == f = False | otherwise = isHiddenIn (parent f) f || goDir (parent f) isHiddenIn :: Path b Dir -> Path b t -> Bool isHiddenIn curdir ad = case stripProperPrefix curdir ad of Nothing -> False Just rp -> "." `isPrefixOf` toFilePath rp
f7b7b49b0a144396c9c083882616ca076d394b05bb4679315d40c50fd798c6a5
kazu-yamamoto/http2
Queue.hs
# LANGUAGE RecordWildCards # module Network.HTTP2.Arch.Queue where import UnliftIO.Concurrent (forkIO) import UnliftIO.Exception (bracket) import UnliftIO.STM import Imports import Network.HTTP2.Arch.Manager import Network.HTTP2.Arch.Types # INLINE forkAndEnqueueWhenReady # forkAndEnqueueWhenReady :: IO () -> TQueue (Output Stream) -> Output Stream -> Manager -> IO () forkAndEnqueueWhenReady wait outQ out mgr = bracket setup teardown $ \_ -> void . forkIO $ do wait enqueueOutput outQ out where setup = addMyId mgr teardown _ = deleteMyId mgr # INLINE enqueueOutput # enqueueOutput :: TQueue (Output Stream) -> Output Stream -> IO () enqueueOutput outQ out = atomically $ writeTQueue outQ out # INLINE enqueueControl # enqueueControl :: TQueue Control -> Control -> IO () enqueueControl ctlQ ctl = atomically $ writeTQueue ctlQ ctl ----------------------------------------------------------------
null
https://raw.githubusercontent.com/kazu-yamamoto/http2/88b3c192c251c15fa4dc426aa0372841dc3fee49/Network/HTTP2/Arch/Queue.hs
haskell
--------------------------------------------------------------
# LANGUAGE RecordWildCards # module Network.HTTP2.Arch.Queue where import UnliftIO.Concurrent (forkIO) import UnliftIO.Exception (bracket) import UnliftIO.STM import Imports import Network.HTTP2.Arch.Manager import Network.HTTP2.Arch.Types # INLINE forkAndEnqueueWhenReady # forkAndEnqueueWhenReady :: IO () -> TQueue (Output Stream) -> Output Stream -> Manager -> IO () forkAndEnqueueWhenReady wait outQ out mgr = bracket setup teardown $ \_ -> void . forkIO $ do wait enqueueOutput outQ out where setup = addMyId mgr teardown _ = deleteMyId mgr # INLINE enqueueOutput # enqueueOutput :: TQueue (Output Stream) -> Output Stream -> IO () enqueueOutput outQ out = atomically $ writeTQueue outQ out # INLINE enqueueControl # enqueueControl :: TQueue Control -> Control -> IO () enqueueControl ctlQ ctl = atomically $ writeTQueue ctlQ ctl
ad7db188a0e1c9b46caa93ffd7b583ab01a41e6d2b980b9d5bd6ba7f2b4074cc
jonase/eastwood
recur.clj
(ns testcases.performance.red.recur (:require [clojure.string :as string])) (def ^:const vlq-base-shift 5) (def ^:const vlq-base (bit-shift-left 1 vlq-base-shift)) (def ^:const vlq-base-mask (dec vlq-base)) (def ^:const vlq-continuation-bit vlq-base) (defn to-vlq-signed [v] (if (neg? v) (inc (bit-shift-left (- v) 1)) (+ (bit-shift-left v 1) 0))) (defn from-vlq-signed [v] (let [neg? (= (bit-and v 1) 1) shifted (bit-shift-right v 1)] (if neg? (- shifted) shifted))) (defn decode [^String s] (let [l (.length s)] (loop [i 0 result 0 shift 0] (when (>= i l) (throw (Error. "Expected more digits in base 64 VLQ value."))) (let [digit (rand-int 10)] (let [i (inc i) continuation? (pos? (bit-and digit vlq-continuation-bit)) digit (bit-and digit vlq-base-mask) result (+ result (bit-shift-left digit shift)) shift (+ shift vlq-base-shift)] (if continuation? (recur i result shift) (lazy-seq (cons (from-vlq-signed result) (let [s (.substring s i)] (when-not (string/blank? s) (decode s)))))))))))
null
https://raw.githubusercontent.com/jonase/eastwood/605ab4a1d169270701200005792fa37b4c025405/cases/testcases/performance/red/recur.clj
clojure
(ns testcases.performance.red.recur (:require [clojure.string :as string])) (def ^:const vlq-base-shift 5) (def ^:const vlq-base (bit-shift-left 1 vlq-base-shift)) (def ^:const vlq-base-mask (dec vlq-base)) (def ^:const vlq-continuation-bit vlq-base) (defn to-vlq-signed [v] (if (neg? v) (inc (bit-shift-left (- v) 1)) (+ (bit-shift-left v 1) 0))) (defn from-vlq-signed [v] (let [neg? (= (bit-and v 1) 1) shifted (bit-shift-right v 1)] (if neg? (- shifted) shifted))) (defn decode [^String s] (let [l (.length s)] (loop [i 0 result 0 shift 0] (when (>= i l) (throw (Error. "Expected more digits in base 64 VLQ value."))) (let [digit (rand-int 10)] (let [i (inc i) continuation? (pos? (bit-and digit vlq-continuation-bit)) digit (bit-and digit vlq-base-mask) result (+ result (bit-shift-left digit shift)) shift (+ shift vlq-base-shift)] (if continuation? (recur i result shift) (lazy-seq (cons (from-vlq-signed result) (let [s (.substring s i)] (when-not (string/blank? s) (decode s)))))))))))
8f428d539cd263ba5bc916b1100a23955b56cbc87ea9fc876a8bee843d1c1e95
Tclv/HaskellBook
DoesItTypecheck.hs
1 data Person = Person Bool deriving Show --Did not derive show printPerson :: Person -> IO () printPerson person = putStrLn (show person) 2 Did not derive Eq settleDown :: Mood -> Mood -- No type signature settleDown x = if x == Woot then Blah else x 3 a ) Values of the type Mood due to the equality check with ` Woot ` . -- b) Type error c ) Type error that Mood is not an instance of . 4 type Subject = String type Verb = String type Object = String data Sentence = Sentence Subject Verb Object deriving (Eq, Show) s1 :: Object -> Sentence s1 = Sentence "dogs" "drool" -- This is; curried data constructor s2 :: Sentence s2 = Sentence "Julie" "loves" "dogs"
null
https://raw.githubusercontent.com/Tclv/HaskellBook/78eaa5c67579526b0f00f85a10be3156bc304c14/ch6/DoesItTypecheck.hs
haskell
Did not derive show No type signature b) Type error This is; curried data constructor
1 printPerson :: Person -> IO () printPerson person = putStrLn (show person) 2 Did not derive Eq settleDown x = if x == Woot then Blah else x 3 a ) Values of the type Mood due to the equality check with ` Woot ` . c ) Type error that Mood is not an instance of . 4 type Subject = String type Verb = String type Object = String data Sentence = Sentence Subject Verb Object deriving (Eq, Show) s1 :: Object -> Sentence s2 :: Sentence s2 = Sentence "Julie" "loves" "dogs"
3b72cf2ebd195df7861e0d426c73108116d6368b8c25a1004ff066ba7c4393ec
SimulaVR/godot-haskell
AudioStreamMicrophone.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.AudioStreamMicrophone () where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.AudioStream()
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/AudioStreamMicrophone.hs
haskell
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.AudioStreamMicrophone () where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.AudioStream()
090991d54a2428e50901f18d24beee84b3f686df005482cf8b9d7399f427330e
uwplse/PUMPKIN-PATCH
abstracters.ml
(* --- Abstraction Strategies --- *) open Constr open Environ open Evd open Utilities open Substitution open Reducers open Filters open Candidates open Convertibility open Stateutils type abstraction_dimension = Arguments | Property type abstracter = env -> types -> types -> candidates -> evar_map -> candidates state type abstraction_strategy = { reducer : reducer; abstracter : abstracter; filter : types -> types filter_strategy; to_abstract : abstraction_dimension; } (* --- Auxiliary functions --- *) (* * Count the number of applications in a term. * Do not consider lambdas. *) let rec num_apps (trm : types) : int = match kind trm with | App (f, args) -> Array.fold_left (fun n a -> n + num_apps a) (1 + num_apps f) args | _ -> 0 * Heuristic for sorting the arguments to decide which ones to abstract first . * Treats terms with more applications as larger . * Heuristic for sorting the arguments to decide which ones to abstract first. * Treats terms with more applications as larger. *) let sort_dependent args args_abstract = List.split (List.stable_sort (fun (a1, _) (a2, _) -> num_apps a1 - num_apps a2) (List.combine args args_abstract)) (* --- Top-level --- *) (* * Substitute actual args with abstract args in candidates, * using an abstracter to determine when to substitute. *) let substitute_using strategy env args args_abstract cs = let abs = strategy.abstracter in let num_args = List.length args_abstract in let (args_sorted, args_abstract_sorted) = if strategy.to_abstract = Property then TODO refactor / simplify else sort_dependent args args_abstract in if num_args > 0 then bind (abs env (last args_sorted) (last args_abstract_sorted) cs) (fun cs_abs -> fold_left2_state (fun cs t1 t2 sigma -> abs env t1 t2 cs sigma) cs_abs (List.rev (all_but_last args_sorted)) (List.rev (all_but_last args_abstract_sorted))) else ret [] (* * Reduce using the reducer in the abstraction strategy *) let reduce_all_using strategy env (cs : candidates) sigma = reduce_all strategy.reducer env sigma cs (* * Filter using the filter in the abstraction stragegy *) let filter_using strategy env (goal : types) (cs : candidates) sigma = strategy.filter goal env sigma cs (* --- Recover options from an abstraction strategy --- *) let kind_of_abstraction strategy = strategy.to_abstract (* --- Abstracters --- *) * determine how to perform the substitution step of abstraction * Abstracters determine how to perform the substitution step of abstraction *) TODO rename syntactic strategies , makes less sense given pattern (* Fully abstract each term, substituting every convertible subterm *) let syntactic_full env (arg_actual : types) (arg_abstract : types) (trms : candidates) = if equal arg_actual arg_abstract then ret trms else map_state (fun tr sigma -> all_conv_substs env sigma (arg_actual, arg_abstract) tr) trms let syntactic_full_strategy : abstracter = syntactic_full Fully abstract each term , substituting every subterm w/ convertible types let types_full env (arg_actual : types) (arg_abstract : types) (trms : candidates) = if equal arg_actual arg_abstract then ret trms else map_state (fun tr sigma -> all_typ_substs env sigma (arg_actual, arg_abstract) tr) trms let types_full_strategy : abstracter = types_full (* A pattern-based full abstraction strategy for functions *) (* TODO really just need a more flexible top-level function that lets you combine strategies *) let function_pattern_full (env : env) (arg_actual : types) (arg_abstract : types) (trms : types list)= match kind arg_abstract with | App (f, args) -> syntactic_full env arg_actual arg_abstract trms | _ -> types_full env arg_actual arg_abstract trms let function_pattern_full_strategy : abstracter = function_pattern_full (* A pattern-based full abstraction strategy for constructors *) let pattern_full (env : env) (arg_actual : types) (arg_abstract : types) (trms : types list) = let types_conv trm sigma = types_convertible env sigma arg_abstract trm in let exists_types_conv = exists_state types_conv in match map_tuple kind (arg_actual, arg_abstract) with | (App (f, args), _) -> branch_state (fun args -> exists_types_conv args) (fun args -> bind (find_state types_conv args) (fun arg -> bind (map_state (fun tr sigma -> all_constr_substs env sigma f tr) trms) (syntactic_full env arg arg_abstract))) (fun _ -> ret trms) (Array.to_list args) | _ -> ret trms let pattern_full_strategy : abstracter = pattern_full (* All combinations of abstractions of convertible subterms *) let syntactic_all_combinations env (arg_actual : types) (arg_abstract : types) (trms : candidates) = if equal arg_actual arg_abstract then ret trms else flat_map_state (fun tr sigma -> all_conv_substs_combs env sigma (arg_actual, arg_abstract) tr) trms let syntactic_all_strategy : abstracter = syntactic_all_combinations (* --- Strategies for abstracting arguments --- *) * Reduce first * Replace all convertible terms at the highest level with abstracted terms * Reduce first * Replace all convertible terms at the highest level with abstracted terms *) let syntactic_full_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = syntactic_full_strategy; filter = filter_by_type; to_abstract = Arguments; } (* * Don't reduce * Replace all convertible terms at the highest level with abstracted terms *) let syntactic_full_no_reduce : abstraction_strategy = {syntactic_full_reduce with reducer = remove_identities; } * Reduce first * Replace all terms with convertible types at the highest level * with abstracted terms * Reduce first * Replace all terms with convertible types at the highest level * with abstracted terms *) let types_full_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = types_full_strategy; filter = filter_by_type; to_abstract = Arguments; } (* * Don't reduce * Replace all convertible terms at the highest level with abstracted terms *) let types_full_no_reduce : abstraction_strategy = { types_full_reduce with reducer = remove_identities; } * Reduce first * Replace functions with abstracted functions when types are convertible * Replace applications with abstracted applications when terms are convertible * Reduce first * Replace functions with abstracted functions when types are convertible * Replace applications with abstracted applications when terms are convertible *) let function_pattern_full_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = function_pattern_full_strategy; filter = filter_by_type; to_abstract = Arguments; } (* * Don't reduce * Otherwise act like function_pattern_no_reduce *) let function_pattern_full_no_reduce : abstraction_strategy = { function_pattern_full_reduce with reducer = remove_identities; } * Reduce first * Replace all terms matching a pattern ( f , args ) with abstracted terms * Fall back to syntactic_full when the concrete argument is not a pattern * Reduce first * Replace all terms matching a pattern (f, args) with abstracted terms * Fall back to syntactic_full when the concrete argument is not a pattern *) let pattern_full_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = pattern_full_strategy; filter = filter_by_type; to_abstract = Arguments; } (* * Don't reduce * Replace all terms matching a pattern (f, args) with abstracted terms * Fall back to syntactic_full when the concrete argument is not a pattern *) let pattern_no_reduce : abstraction_strategy = { pattern_full_reduce with reducer = remove_identities; } * Reduce first * Replace all combinations of convertible subterms with abstracted terms * Reduce first * Replace all combinations of convertible subterms with abstracted terms *) let syntactic_all_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = syntactic_all_strategy; filter = filter_by_type; to_abstract = Arguments; } (* * Don't reduce * Replace all combinations of convertible subterms with abstracted terms *) let syntactic_all_no_reduce : abstraction_strategy = { syntactic_all_reduce with reducer = remove_identities; } * All strategies that reduce first * All strategies that reduce first *) let reduce_strategies : abstraction_strategy list = [syntactic_full_reduce; syntactic_all_reduce; pattern_full_reduce] * All strategies that do n't reduce first * All strategies that don't reduce first *) let no_reduce_strategies : abstraction_strategy list = [syntactic_full_no_reduce; syntactic_all_no_reduce; pattern_no_reduce] (* * List of default strategies *) let default_strategies : abstraction_strategy list = [syntactic_full_no_reduce; syntactic_full_reduce; pattern_full_reduce; syntactic_all_no_reduce; syntactic_all_reduce; pattern_no_reduce] (* * List of the simplest strategies *) let simple_strategies : abstraction_strategy list = [syntactic_full_reduce; syntactic_full_no_reduce] (* --- Strategies for abstracting properties --- *) let function_pattern_full_reduce_prop : abstraction_strategy = { function_pattern_full_reduce with to_abstract = Property } let function_pattern_full_no_reduce_prop : abstraction_strategy = { function_pattern_full_no_reduce with to_abstract = Property } let types_full_reduce_prop : abstraction_strategy = { types_full_reduce with to_abstract = Property } let types_full_no_reduce_prop : abstraction_strategy = { types_full_no_reduce with to_abstract = Property } let reduce_strategies_prop : abstraction_strategy list = [function_pattern_full_reduce_prop] let no_reduce_strategies_prop : abstraction_strategy list = [function_pattern_full_no_reduce_prop] let default_strategies_prop : abstraction_strategy list = List.append reduce_strategies_prop no_reduce_strategies_prop
null
https://raw.githubusercontent.com/uwplse/PUMPKIN-PATCH/73fd77ba49388fdc72702a252a8fa8f071a8e1ea/plugin/src/core/components/abstraction/abstracters.ml
ocaml
--- Abstraction Strategies --- --- Auxiliary functions --- * Count the number of applications in a term. * Do not consider lambdas. --- Top-level --- * Substitute actual args with abstract args in candidates, * using an abstracter to determine when to substitute. * Reduce using the reducer in the abstraction strategy * Filter using the filter in the abstraction stragegy --- Recover options from an abstraction strategy --- --- Abstracters --- Fully abstract each term, substituting every convertible subterm A pattern-based full abstraction strategy for functions TODO really just need a more flexible top-level function that lets you combine strategies A pattern-based full abstraction strategy for constructors All combinations of abstractions of convertible subterms --- Strategies for abstracting arguments --- * Don't reduce * Replace all convertible terms at the highest level with abstracted terms * Don't reduce * Replace all convertible terms at the highest level with abstracted terms * Don't reduce * Otherwise act like function_pattern_no_reduce * Don't reduce * Replace all terms matching a pattern (f, args) with abstracted terms * Fall back to syntactic_full when the concrete argument is not a pattern * Don't reduce * Replace all combinations of convertible subterms with abstracted terms * List of default strategies * List of the simplest strategies --- Strategies for abstracting properties ---
open Constr open Environ open Evd open Utilities open Substitution open Reducers open Filters open Candidates open Convertibility open Stateutils type abstraction_dimension = Arguments | Property type abstracter = env -> types -> types -> candidates -> evar_map -> candidates state type abstraction_strategy = { reducer : reducer; abstracter : abstracter; filter : types -> types filter_strategy; to_abstract : abstraction_dimension; } let rec num_apps (trm : types) : int = match kind trm with | App (f, args) -> Array.fold_left (fun n a -> n + num_apps a) (1 + num_apps f) args | _ -> 0 * Heuristic for sorting the arguments to decide which ones to abstract first . * Treats terms with more applications as larger . * Heuristic for sorting the arguments to decide which ones to abstract first. * Treats terms with more applications as larger. *) let sort_dependent args args_abstract = List.split (List.stable_sort (fun (a1, _) (a2, _) -> num_apps a1 - num_apps a2) (List.combine args args_abstract)) let substitute_using strategy env args args_abstract cs = let abs = strategy.abstracter in let num_args = List.length args_abstract in let (args_sorted, args_abstract_sorted) = if strategy.to_abstract = Property then TODO refactor / simplify else sort_dependent args args_abstract in if num_args > 0 then bind (abs env (last args_sorted) (last args_abstract_sorted) cs) (fun cs_abs -> fold_left2_state (fun cs t1 t2 sigma -> abs env t1 t2 cs sigma) cs_abs (List.rev (all_but_last args_sorted)) (List.rev (all_but_last args_abstract_sorted))) else ret [] let reduce_all_using strategy env (cs : candidates) sigma = reduce_all strategy.reducer env sigma cs let filter_using strategy env (goal : types) (cs : candidates) sigma = strategy.filter goal env sigma cs let kind_of_abstraction strategy = strategy.to_abstract * determine how to perform the substitution step of abstraction * Abstracters determine how to perform the substitution step of abstraction *) TODO rename syntactic strategies , makes less sense given pattern let syntactic_full env (arg_actual : types) (arg_abstract : types) (trms : candidates) = if equal arg_actual arg_abstract then ret trms else map_state (fun tr sigma -> all_conv_substs env sigma (arg_actual, arg_abstract) tr) trms let syntactic_full_strategy : abstracter = syntactic_full Fully abstract each term , substituting every subterm w/ convertible types let types_full env (arg_actual : types) (arg_abstract : types) (trms : candidates) = if equal arg_actual arg_abstract then ret trms else map_state (fun tr sigma -> all_typ_substs env sigma (arg_actual, arg_abstract) tr) trms let types_full_strategy : abstracter = types_full let function_pattern_full (env : env) (arg_actual : types) (arg_abstract : types) (trms : types list)= match kind arg_abstract with | App (f, args) -> syntactic_full env arg_actual arg_abstract trms | _ -> types_full env arg_actual arg_abstract trms let function_pattern_full_strategy : abstracter = function_pattern_full let pattern_full (env : env) (arg_actual : types) (arg_abstract : types) (trms : types list) = let types_conv trm sigma = types_convertible env sigma arg_abstract trm in let exists_types_conv = exists_state types_conv in match map_tuple kind (arg_actual, arg_abstract) with | (App (f, args), _) -> branch_state (fun args -> exists_types_conv args) (fun args -> bind (find_state types_conv args) (fun arg -> bind (map_state (fun tr sigma -> all_constr_substs env sigma f tr) trms) (syntactic_full env arg arg_abstract))) (fun _ -> ret trms) (Array.to_list args) | _ -> ret trms let pattern_full_strategy : abstracter = pattern_full let syntactic_all_combinations env (arg_actual : types) (arg_abstract : types) (trms : candidates) = if equal arg_actual arg_abstract then ret trms else flat_map_state (fun tr sigma -> all_conv_substs_combs env sigma (arg_actual, arg_abstract) tr) trms let syntactic_all_strategy : abstracter = syntactic_all_combinations * Reduce first * Replace all convertible terms at the highest level with abstracted terms * Reduce first * Replace all convertible terms at the highest level with abstracted terms *) let syntactic_full_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = syntactic_full_strategy; filter = filter_by_type; to_abstract = Arguments; } let syntactic_full_no_reduce : abstraction_strategy = {syntactic_full_reduce with reducer = remove_identities; } * Reduce first * Replace all terms with convertible types at the highest level * with abstracted terms * Reduce first * Replace all terms with convertible types at the highest level * with abstracted terms *) let types_full_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = types_full_strategy; filter = filter_by_type; to_abstract = Arguments; } let types_full_no_reduce : abstraction_strategy = { types_full_reduce with reducer = remove_identities; } * Reduce first * Replace functions with abstracted functions when types are convertible * Replace applications with abstracted applications when terms are convertible * Reduce first * Replace functions with abstracted functions when types are convertible * Replace applications with abstracted applications when terms are convertible *) let function_pattern_full_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = function_pattern_full_strategy; filter = filter_by_type; to_abstract = Arguments; } let function_pattern_full_no_reduce : abstraction_strategy = { function_pattern_full_reduce with reducer = remove_identities; } * Reduce first * Replace all terms matching a pattern ( f , args ) with abstracted terms * Fall back to syntactic_full when the concrete argument is not a pattern * Reduce first * Replace all terms matching a pattern (f, args) with abstracted terms * Fall back to syntactic_full when the concrete argument is not a pattern *) let pattern_full_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = pattern_full_strategy; filter = filter_by_type; to_abstract = Arguments; } let pattern_no_reduce : abstraction_strategy = { pattern_full_reduce with reducer = remove_identities; } * Reduce first * Replace all combinations of convertible subterms with abstracted terms * Reduce first * Replace all combinations of convertible subterms with abstracted terms *) let syntactic_all_reduce : abstraction_strategy = { reducer = reduce_remove_identities; abstracter = syntactic_all_strategy; filter = filter_by_type; to_abstract = Arguments; } let syntactic_all_no_reduce : abstraction_strategy = { syntactic_all_reduce with reducer = remove_identities; } * All strategies that reduce first * All strategies that reduce first *) let reduce_strategies : abstraction_strategy list = [syntactic_full_reduce; syntactic_all_reduce; pattern_full_reduce] * All strategies that do n't reduce first * All strategies that don't reduce first *) let no_reduce_strategies : abstraction_strategy list = [syntactic_full_no_reduce; syntactic_all_no_reduce; pattern_no_reduce] let default_strategies : abstraction_strategy list = [syntactic_full_no_reduce; syntactic_full_reduce; pattern_full_reduce; syntactic_all_no_reduce; syntactic_all_reduce; pattern_no_reduce] let simple_strategies : abstraction_strategy list = [syntactic_full_reduce; syntactic_full_no_reduce] let function_pattern_full_reduce_prop : abstraction_strategy = { function_pattern_full_reduce with to_abstract = Property } let function_pattern_full_no_reduce_prop : abstraction_strategy = { function_pattern_full_no_reduce with to_abstract = Property } let types_full_reduce_prop : abstraction_strategy = { types_full_reduce with to_abstract = Property } let types_full_no_reduce_prop : abstraction_strategy = { types_full_no_reduce with to_abstract = Property } let reduce_strategies_prop : abstraction_strategy list = [function_pattern_full_reduce_prop] let no_reduce_strategies_prop : abstraction_strategy list = [function_pattern_full_no_reduce_prop] let default_strategies_prop : abstraction_strategy list = List.append reduce_strategies_prop no_reduce_strategies_prop
d9137213a5064e15f2fc24183016647c553a96891198f21f6dc912762b900a74
emqx/emqx
emqx_gateway_auth_ct.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% 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(emqx_gateway_auth_ct). -compile(nowarn_export_all). -compile(export_all). -behaviour(gen_server). %% gen_server callbacks -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, format_status/2 ]). -import( emqx_gateway_test_utils, [ request/2, request/3 ] ). -include_lib("emqx_authn/include/emqx_authn.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("emqx/include/emqx_placeholder.hrl"). -define(CALL(Msg), gen_server:call(?MODULE, {?FUNCTION_NAME, Msg})). -define(AUTHN_HTTP_PORT, 37333). -define(AUTHN_HTTP_PATH, "/auth"). -define(AUTHZ_HTTP_PORT, 38333). -define(AUTHZ_HTTP_PATH, "/authz/[...]"). -define(GATEWAYS, [coap, lwm2m, mqttsn, stomp, exproto]). -define(CONFS, [ emqx_coap_SUITE, emqx_lwm2m_SUITE, emqx_sn_protocol_SUITE, emqx_stomp_SUITE, emqx_exproto_SUITE ]). -record(state, {}). -define(AUTHZ_HTTP_RESP(Result, Req), cowboy_req:reply( 200, #{<<"content-type">> => <<"application/json">>}, "{\"result\": \"" ++ atom_to_list(Result) ++ "\"}", Req ) ). %%------------------------------------------------------------------------------ %% API %%------------------------------------------------------------------------------ group_names(Auths) -> [{group, Auth} || Auth <- Auths]. init_groups(Suite, Auths) -> All = emqx_common_test_helpers:all(Suite), [{Auth, [], All} || Auth <- Auths]. start_auth(Name) -> ?CALL(Name). stop_auth(Name) -> ?CALL(Name). start() -> gen_server:start({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:stop(?MODULE). %%------------------------------------------------------------------------------ %% gen_server callbacks %%------------------------------------------------------------------------------ init([]) -> process_flag(trap_exit, true), {ok, #state{}}. handle_call({start_auth, Name}, _From, State) -> on_start_auth(Name), {reply, ok, State}; handle_call({stop_auth, Name}, _From, State) -> on_stop_auth(Name), {reply, ok, State}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast(_Request, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. format_status(_Opt, Status) -> Status. %%------------------------------------------------------------------------------ %% Authenticators %%------------------------------------------------------------------------------ on_start_auth(authn_http) -> %% start test server {ok, _} = emqx_authn_http_test_server:start_link(?AUTHN_HTTP_PORT, ?AUTHN_HTTP_PATH), timer:sleep(1000), %% set authn for gateway Setup = fun(Gateway) -> Path = io_lib:format("/gateways/~ts/authentication", [Gateway]), {204, _} = request(delete, Path), timer:sleep(200), {201, _} = request(post, Path, http_authn_config()), timer:sleep(200) end, lists:foreach(Setup, ?GATEWAYS), %% set handler for test server Handler = fun(Req0, State) -> ct:pal("Authn Req:~p~nState:~p~n", [Req0, State]), Headers = #{<<"content-type">> => <<"application/json">>}, Response = jiffy:encode(#{result => allow, is_superuser => false}), case cowboy_req:match_qs([username, password], Req0) of #{ username := <<"admin">>, password := <<"public">> } -> Req = cowboy_req:reply(200, Headers, Response, Req0); _ -> Req = cowboy_req:reply(400, Req0) end, {ok, Req, State} end, emqx_authn_http_test_server:set_handler(Handler), timer:sleep(500); on_start_auth(authz_http) -> ok = emqx_authz_test_lib:reset_authorizers(), {ok, _} = emqx_authz_http_test_server:start_link(?AUTHZ_HTTP_PORT, ?AUTHZ_HTTP_PATH), TODO set authz for gateway ok = emqx_authz_test_lib:setup_config( http_authz_config(), #{} ), %% set handler for test server Handler = fun(Req0, State) -> case cowboy_req:match_qs([topic, action, username], Req0) of #{topic := <<"/publish">>, action := <<"publish">>} -> Req = ?AUTHZ_HTTP_RESP(allow, Req0); #{topic := <<"/subscribe">>, action := <<"subscribe">>} -> Req = ?AUTHZ_HTTP_RESP(allow, Req0); %% for lwm2m #{username := <<"lwm2m">>} -> Req = ?AUTHZ_HTTP_RESP(allow, Req0); _ -> Req = cowboy_req:reply(400, Req0) end, {ok, Req, State} end, ok = emqx_authz_http_test_server:set_handler(Handler), timer:sleep(500). on_stop_auth(authn_http) -> Delete = fun(Gateway) -> Path = io_lib:format("/gateways/~ts/authentication", [Gateway]), {204, _} = request(delete, Path) end, lists:foreach(Delete, ?GATEWAYS), ok = emqx_authn_http_test_server:stop(); on_stop_auth(authz_http) -> ok = emqx_authz_http_test_server:stop(). %%------------------------------------------------------------------------------ %% Configs %%------------------------------------------------------------------------------ http_authn_config() -> #{ <<"mechanism">> => <<"password_based">>, <<"enable">> => <<"true">>, <<"backend">> => <<"http">>, <<"method">> => <<"get">>, <<"url">> => <<":37333/auth">>, <<"body">> => #{<<"username">> => ?PH_USERNAME, <<"password">> => ?PH_PASSWORD}, <<"headers">> => #{<<"X-Test-Header">> => <<"Test Value">>} }. http_authz_config() -> #{ <<"enable">> => <<"true">>, <<"type">> => <<"http">>, <<"method">> => <<"get">>, <<"url">> => <<":38333/authz/users/?topic=${topic}&action=${action}&username=${username}">>, <<"headers">> => #{<<"X-Test-Header">> => <<"Test Value">>} }. %%------------------------------------------------------------------------------ %% Helpers %%------------------------------------------------------------------------------ init_gateway_conf() -> ok = emqx_common_test_helpers:load_config( emqx_gateway_schema, merge_conf([X:default_config() || X <- ?CONFS], []) ). merge_conf([Conf | T], Acc) -> case re:run(Conf, "\s*gateway\\.(.*)", [global, {capture, all_but_first, list}, dotall]) of {match, [[Content]]} -> merge_conf(T, [Content | Acc]); _ -> merge_conf(T, Acc) end; merge_conf([], Acc) -> erlang:list_to_binary("gateway{" ++ string:join(Acc, ",") ++ "}"). with_resource(Init, Close, Fun) -> Res = case Init() of {ok, X} -> X; Other -> Other end, try Fun(Res) catch C:R:S -> erlang:raise(C, R, S) after Close(Res) end.
null
https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_gateway/test/emqx_gateway_auth_ct.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. -------------------------------------------------------------------- gen_server callbacks ------------------------------------------------------------------------------ API ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ gen_server callbacks ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Authenticators ------------------------------------------------------------------------------ start test server set authn for gateway set handler for test server set handler for test server for lwm2m ------------------------------------------------------------------------------ Configs ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Helpers ------------------------------------------------------------------------------
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_gateway_auth_ct). -compile(nowarn_export_all). -compile(export_all). -behaviour(gen_server). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, format_status/2 ]). -import( emqx_gateway_test_utils, [ request/2, request/3 ] ). -include_lib("emqx_authn/include/emqx_authn.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("emqx/include/emqx_placeholder.hrl"). -define(CALL(Msg), gen_server:call(?MODULE, {?FUNCTION_NAME, Msg})). -define(AUTHN_HTTP_PORT, 37333). -define(AUTHN_HTTP_PATH, "/auth"). -define(AUTHZ_HTTP_PORT, 38333). -define(AUTHZ_HTTP_PATH, "/authz/[...]"). -define(GATEWAYS, [coap, lwm2m, mqttsn, stomp, exproto]). -define(CONFS, [ emqx_coap_SUITE, emqx_lwm2m_SUITE, emqx_sn_protocol_SUITE, emqx_stomp_SUITE, emqx_exproto_SUITE ]). -record(state, {}). -define(AUTHZ_HTTP_RESP(Result, Req), cowboy_req:reply( 200, #{<<"content-type">> => <<"application/json">>}, "{\"result\": \"" ++ atom_to_list(Result) ++ "\"}", Req ) ). group_names(Auths) -> [{group, Auth} || Auth <- Auths]. init_groups(Suite, Auths) -> All = emqx_common_test_helpers:all(Suite), [{Auth, [], All} || Auth <- Auths]. start_auth(Name) -> ?CALL(Name). stop_auth(Name) -> ?CALL(Name). start() -> gen_server:start({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:stop(?MODULE). init([]) -> process_flag(trap_exit, true), {ok, #state{}}. handle_call({start_auth, Name}, _From, State) -> on_start_auth(Name), {reply, ok, State}; handle_call({stop_auth, Name}, _From, State) -> on_stop_auth(Name), {reply, ok, State}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast(_Request, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. format_status(_Opt, Status) -> Status. on_start_auth(authn_http) -> {ok, _} = emqx_authn_http_test_server:start_link(?AUTHN_HTTP_PORT, ?AUTHN_HTTP_PATH), timer:sleep(1000), Setup = fun(Gateway) -> Path = io_lib:format("/gateways/~ts/authentication", [Gateway]), {204, _} = request(delete, Path), timer:sleep(200), {201, _} = request(post, Path, http_authn_config()), timer:sleep(200) end, lists:foreach(Setup, ?GATEWAYS), Handler = fun(Req0, State) -> ct:pal("Authn Req:~p~nState:~p~n", [Req0, State]), Headers = #{<<"content-type">> => <<"application/json">>}, Response = jiffy:encode(#{result => allow, is_superuser => false}), case cowboy_req:match_qs([username, password], Req0) of #{ username := <<"admin">>, password := <<"public">> } -> Req = cowboy_req:reply(200, Headers, Response, Req0); _ -> Req = cowboy_req:reply(400, Req0) end, {ok, Req, State} end, emqx_authn_http_test_server:set_handler(Handler), timer:sleep(500); on_start_auth(authz_http) -> ok = emqx_authz_test_lib:reset_authorizers(), {ok, _} = emqx_authz_http_test_server:start_link(?AUTHZ_HTTP_PORT, ?AUTHZ_HTTP_PATH), TODO set authz for gateway ok = emqx_authz_test_lib:setup_config( http_authz_config(), #{} ), Handler = fun(Req0, State) -> case cowboy_req:match_qs([topic, action, username], Req0) of #{topic := <<"/publish">>, action := <<"publish">>} -> Req = ?AUTHZ_HTTP_RESP(allow, Req0); #{topic := <<"/subscribe">>, action := <<"subscribe">>} -> Req = ?AUTHZ_HTTP_RESP(allow, Req0); #{username := <<"lwm2m">>} -> Req = ?AUTHZ_HTTP_RESP(allow, Req0); _ -> Req = cowboy_req:reply(400, Req0) end, {ok, Req, State} end, ok = emqx_authz_http_test_server:set_handler(Handler), timer:sleep(500). on_stop_auth(authn_http) -> Delete = fun(Gateway) -> Path = io_lib:format("/gateways/~ts/authentication", [Gateway]), {204, _} = request(delete, Path) end, lists:foreach(Delete, ?GATEWAYS), ok = emqx_authn_http_test_server:stop(); on_stop_auth(authz_http) -> ok = emqx_authz_http_test_server:stop(). http_authn_config() -> #{ <<"mechanism">> => <<"password_based">>, <<"enable">> => <<"true">>, <<"backend">> => <<"http">>, <<"method">> => <<"get">>, <<"url">> => <<":37333/auth">>, <<"body">> => #{<<"username">> => ?PH_USERNAME, <<"password">> => ?PH_PASSWORD}, <<"headers">> => #{<<"X-Test-Header">> => <<"Test Value">>} }. http_authz_config() -> #{ <<"enable">> => <<"true">>, <<"type">> => <<"http">>, <<"method">> => <<"get">>, <<"url">> => <<":38333/authz/users/?topic=${topic}&action=${action}&username=${username}">>, <<"headers">> => #{<<"X-Test-Header">> => <<"Test Value">>} }. init_gateway_conf() -> ok = emqx_common_test_helpers:load_config( emqx_gateway_schema, merge_conf([X:default_config() || X <- ?CONFS], []) ). merge_conf([Conf | T], Acc) -> case re:run(Conf, "\s*gateway\\.(.*)", [global, {capture, all_but_first, list}, dotall]) of {match, [[Content]]} -> merge_conf(T, [Content | Acc]); _ -> merge_conf(T, Acc) end; merge_conf([], Acc) -> erlang:list_to_binary("gateway{" ++ string:join(Acc, ",") ++ "}"). with_resource(Init, Close, Fun) -> Res = case Init() of {ok, X} -> X; Other -> Other end, try Fun(Res) catch C:R:S -> erlang:raise(C, R, S) after Close(Res) end.
9563e94942d6f35772fcc4def0f2c8b9d230897ee6aa9b5abf20bd184b03bba1
pirj/ryan
couchdb.erl
Copyright ( c ) 2009 ' Dimandt < > %% %% 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. %% %% @author ' Dimandt < > 2009 %% @version 0.1 %% @doc A simple stupid wrapper for erlang_couchdb. Requires mochijson2 %% %% This module was created for the purpose of further simplifying access %% to an already simple CouchDB interface. %% This code is available as Open Source Software under the MIT license . -module(couchdb). -include("./../include/erlang_couchdb.hrl"). -compile(export_all). create_database(Name) -> erlang_couchdb:create_database(?DB_HOST, Name). create_database(Server, Name) -> erlang_couchdb:create_database(Server, Name). database_info(Name) -> erlang_couchdb:database_info(?DB_HOST, Name). database_info(Server, Name) -> erlang_couchdb:database_info(Server, Name). server_info() -> erlang_couchdb:server_info(?DB_HOST). server_info({_Host, _Port} = Server) -> erlang_couchdb:server_info(Server). create_document({ID, Doc}) -> erlang_couchdb:create_document(?DB_HOST, ?DB_DATABASE, ID, Doc); create_document(Doc) -> erlang_couchdb:create_document(?DB_HOST, ?DB_DATABASE, Doc). create_document(Db, {ID, Doc}) -> erlang_couchdb:create_document(?DB_HOST, Db, ID, Doc); create_document(Db, Doc) -> erlang_couchdb:create_document(?DB_HOST, Db, Doc). create_document(Host, Db, {ID, Doc}) -> erlang_couchdb:create_document(Host, Db, ID, Doc); create_document(Server, Db, Doc) -> erlang_couchdb:create_document(Server, Db, Doc). retrieve_document(ID) -> retrieve_document(?DB_HOST, ?DB_DATABASE, ID). retrieve_document(Db, ID) -> retrieve_document(?DB_HOST, Db, ID). retrieve_document(Server, Db, ID) -> erlang_couchdb:retrieve_document(Server, Db, ID). @spec update_document(ID::string ( ) , Doc::proplist ( ) ) - > ok | { error , Reason::any ( ) } %% %% @doc Update only several fields in a document. Leave all other fields unmodified update_document(ID, Doc) -> {json, Document} = retrieve_document(ID), Rev = get_rev(Document), Doc2 = update_doc_fields(Document, Doc), replace_document(ID, Rev, Doc2). update_document(ID, Rev, Doc) -> {json, Document} = retrieve_document(ID), Doc2 = update_doc_fields(Document, Doc), replace_document(ID, Rev, Doc2). update_document(Db, ID, Rev, Doc) -> {json, Document} = retrieve_document(ID), Doc2 = update_doc_fields(Document, Doc), replace_document(?DB_HOST, Db, ID, Rev, Doc2). update_document(Server, Db, ID, Rev, Doc) -> {json, Document} = retrieve_document(ID), Doc2 = update_doc_fields(Document, Doc), replace_document(Server, Db, ID, Rev, Doc2). @spec replace_document(ID::string ( ) , Doc::proplist ( ) ) - > ok | { error , Reason::any ( ) } %% @doc Replace the doc by a new doc ( default erlang_couchdb and couchdb behaviour for updates ) replace_document(ID, Doc) -> {json, Document} = retrieve_document(ID), Rev = get_rev(Document), replace_document(ID, Rev, Doc). erlang_couchdb : update_document ( , [ { < < " _ rev " > > , list_to_binary(Rev ) } | Doc ] ) . replace_document(ID, Rev, Doc) -> erlang_couchdb:update_document(?DB_HOST, ?DB_DATABASE, ID, [{<<"_rev">>, list_to_binary(Rev)} | Doc]). replace_document(Db, ID, Rev, Doc) -> erlang_couchdb:update_document(?DB_HOST, Db, ID, [{<<"_rev">>, list_to_binary(Rev)} | Doc]). replace_document(Server, Db, ID, Rev, Doc) -> erlang_couchdb:update_document(Server, Db, ID, [{<<"_rev">>, list_to_binary(Rev)} | Doc]). %% @spec replace_document(ID::string()) -> ok | {error, Reason::any()} %% %% @doc Delete a document delete_document(ID) -> {json, Document} = retrieve_document(ID), Rev = get_rev(Document), erlang_couchdb:delete_document(?DB_HOST, ?DB_DATABASE, ID, Rev). delete_document(ID, Rev) -> erlang_couchdb:delete_document(?DB_HOST, ?DB_DATABASE, ID, Rev). delete_document(Db, ID, Rev) -> erlang_couchdb:delete_document(?DB_HOST, Db, ID, Rev). delete_document(Server, Db, ID, Rev) -> erlang_couchdb:delete_document(Server, Db, ID, Rev). create_view(DocName, ViewList) when is_list(ViewList) -> erlang_couchdb:create_view(?DB_HOST, ?DB_DATABASE, DocName, <<"javascript">>, ViewList). create_view(DocName, ViewName, Data) -> erlang_couchdb:create_view(?DB_HOST, ?DB_DATABASE, DocName, <<"javascript">>, [{ViewName, Data}]). create_view(DocName, Type, ViewName, Data) -> erlang_couchdb:create_view(?DB_HOST, ?DB_DATABASE, DocName, Type, [{ViewName, Data}]). create_view(Db, DocName, Type, ViewName, Data) -> erlang_couchdb:create_view(?DB_HOST, Db, DocName, Type, [{ViewName, Data}]). create_view(Server, Db, DocName, Type, ViewName, Data) -> erlang_couchdb:create_view(Server, Db, DocName, Type, [{ViewName, Data}]). invoke_view(DocName, ViewName) -> erlang_couchdb:invoke_view(?DB_HOST, ?DB_DATABASE, DocName, ViewName, []). ( ) , ViewName::string ( ) , Keys::proplist ( ) ) - > result | { error , Reason::any ( ) } %% %% @doc Invoke a CouchDB view invoke_view(DocName, ViewName, Keys) -> erlang_couchdb:invoke_view(?DB_HOST, ?DB_DATABASE, DocName, ViewName, Keys). invoke_view(Db, DocName, ViewName, Keys) -> erlang_couchdb:invoke_view(?DB_HOST, Db, DocName, ViewName, Keys). invoke_view(Server, Db, DocName, ViewName, Keys) -> erlang_couchdb:invoke_view(Server, Db, DocName, ViewName, Keys). ( ) , Key::binary ( ) ) - > empty_string | { error , Reason::any ( ) } %% %% @type document() = json_struct() %% %% @doc Invoke a CouchDB view get_value(Doc, Key) -> get_value(Doc, Key, ""). get_value({struct, L}, Key, DefaultValue) -> Values = proplists:get_value(<<"value">>, L, []), case Values of [] -> proplists:get_value(Key, L, DefaultValue); {struct, ValueList} -> proplists:get_value(Key, ValueList, DefaultValue) end; get_value({json, {struct, ValueList}}, Key, DefaultValue) -> proplists:get_value(Key, ValueList, DefaultValue); get_value(_, _Key, DefaultValue) -> DefaultValue. get_id(Doc) -> get_id(Doc, ""). get_id({struct, L}, DefaultValue) -> binary_to_list(proplists:get_value(<<"id">>, L, DefaultValue)); get_id({json, {struct, L}}, DefaultValue) -> binary_to_list(proplists:get_value(<<"id">>, L, DefaultValue)); get_id(_, DefaultValue) -> DefaultValue. get_rev(Doc) -> get_rev(Doc, ""). get_rev(Doc, DefaultValue) -> binary_to_list(get_value(Doc, <<"_rev">>, DefaultValue)). get_revs(ID) -> get_revs(?DB_HOST, ?DB_DATABASE, ID). get_revs(Db, ID) -> get_revs(?DB_HOST, Db, ID). get_revs(Server, Db, ID) -> {ServerName, Port} = Server, Type = "GET", URI = lists:concat(["/", Db, "/", ID, "?", "revs_info=true"]), Body = <<>>, Rows = erlang_couchdb:raw_request(Type, ServerName, Port, URI, Body), case Rows of {json, {struct, PropList}} -> Revs = proplists:get_value(<<"_revs_info">>, PropList, []), case Revs of [] -> []; RevList -> get_revision_list(RevList) end; _ -> [] end. get_revision_list(RevList) -> get_revision_list(RevList, []). get_revision_list([{struct, PropList}|T], Acc) -> Rev = binary_to_list(proplists:get_value(<<"rev">>, PropList, <<"">>)), Status = binary_to_list(proplists:get_value(<<"status">>, PropList, <<"">>)), get_revision_list( T, Acc ++ [{Rev, Status}] ); get_revision_list([], Acc) -> Acc. get_total({json, {struct, L}}) -> proplists:get_value(<<"total_rows">>, L, 0); get_total(_Any) -> 0. get_offset({json, {struct, L}}) -> proplists:get_value(<<"offset">>, L, 0); get_offset(_Any) -> 0. get_rows({json, {struct, L}}) -> proplists:get_value(<<"rows">>, L, []); get_rows(_Any) -> []. @private %% Update document fields wih new values. %% %% @see update_document update_doc_fields({struct, Doc}, NewFields) -> update_doc_fields(Doc, NewFields); update_doc_fields(OldDoc, []) -> OldDoc; update_doc_fields(OldDoc, [{Key, Value}|T]) -> case proplists:get_value(Key, OldDoc) of undefined -> update_doc_fields([{Key, Value}] ++ OldDoc, T); _ -> NewDoc = proplists:delete(Key, OldDoc), update_doc_fields([{Key, Value}] ++ NewDoc, T) end.
null
https://raw.githubusercontent.com/pirj/ryan/4df9ed791c3663c1de7864f62524e6f49700cda0/deps/erlang_couchdb/src/couchdb.erl
erlang
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 Software is 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. @version 0.1 @doc A simple stupid wrapper for erlang_couchdb. Requires mochijson2 This module was created for the purpose of further simplifying access to an already simple CouchDB interface. @doc Update only several fields in a document. Leave all other fields unmodified @spec replace_document(ID::string()) -> ok | {error, Reason::any()} @doc Delete a document @doc Invoke a CouchDB view @type document() = json_struct() @doc Invoke a CouchDB view Update document fields wih new values. @see update_document
Copyright ( c ) 2009 ' Dimandt < > files ( the " Software " ) , to deal in the Software without copies of the Software , and to permit persons to whom the included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , @author ' Dimandt < > 2009 This code is available as Open Source Software under the MIT license . -module(couchdb). -include("./../include/erlang_couchdb.hrl"). -compile(export_all). create_database(Name) -> erlang_couchdb:create_database(?DB_HOST, Name). create_database(Server, Name) -> erlang_couchdb:create_database(Server, Name). database_info(Name) -> erlang_couchdb:database_info(?DB_HOST, Name). database_info(Server, Name) -> erlang_couchdb:database_info(Server, Name). server_info() -> erlang_couchdb:server_info(?DB_HOST). server_info({_Host, _Port} = Server) -> erlang_couchdb:server_info(Server). create_document({ID, Doc}) -> erlang_couchdb:create_document(?DB_HOST, ?DB_DATABASE, ID, Doc); create_document(Doc) -> erlang_couchdb:create_document(?DB_HOST, ?DB_DATABASE, Doc). create_document(Db, {ID, Doc}) -> erlang_couchdb:create_document(?DB_HOST, Db, ID, Doc); create_document(Db, Doc) -> erlang_couchdb:create_document(?DB_HOST, Db, Doc). create_document(Host, Db, {ID, Doc}) -> erlang_couchdb:create_document(Host, Db, ID, Doc); create_document(Server, Db, Doc) -> erlang_couchdb:create_document(Server, Db, Doc). retrieve_document(ID) -> retrieve_document(?DB_HOST, ?DB_DATABASE, ID). retrieve_document(Db, ID) -> retrieve_document(?DB_HOST, Db, ID). retrieve_document(Server, Db, ID) -> erlang_couchdb:retrieve_document(Server, Db, ID). @spec update_document(ID::string ( ) , Doc::proplist ( ) ) - > ok | { error , Reason::any ( ) } update_document(ID, Doc) -> {json, Document} = retrieve_document(ID), Rev = get_rev(Document), Doc2 = update_doc_fields(Document, Doc), replace_document(ID, Rev, Doc2). update_document(ID, Rev, Doc) -> {json, Document} = retrieve_document(ID), Doc2 = update_doc_fields(Document, Doc), replace_document(ID, Rev, Doc2). update_document(Db, ID, Rev, Doc) -> {json, Document} = retrieve_document(ID), Doc2 = update_doc_fields(Document, Doc), replace_document(?DB_HOST, Db, ID, Rev, Doc2). update_document(Server, Db, ID, Rev, Doc) -> {json, Document} = retrieve_document(ID), Doc2 = update_doc_fields(Document, Doc), replace_document(Server, Db, ID, Rev, Doc2). @spec replace_document(ID::string ( ) , Doc::proplist ( ) ) - > ok | { error , Reason::any ( ) } @doc Replace the doc by a new doc ( default erlang_couchdb and couchdb behaviour for updates ) replace_document(ID, Doc) -> {json, Document} = retrieve_document(ID), Rev = get_rev(Document), replace_document(ID, Rev, Doc). erlang_couchdb : update_document ( , [ { < < " _ rev " > > , list_to_binary(Rev ) } | Doc ] ) . replace_document(ID, Rev, Doc) -> erlang_couchdb:update_document(?DB_HOST, ?DB_DATABASE, ID, [{<<"_rev">>, list_to_binary(Rev)} | Doc]). replace_document(Db, ID, Rev, Doc) -> erlang_couchdb:update_document(?DB_HOST, Db, ID, [{<<"_rev">>, list_to_binary(Rev)} | Doc]). replace_document(Server, Db, ID, Rev, Doc) -> erlang_couchdb:update_document(Server, Db, ID, [{<<"_rev">>, list_to_binary(Rev)} | Doc]). delete_document(ID) -> {json, Document} = retrieve_document(ID), Rev = get_rev(Document), erlang_couchdb:delete_document(?DB_HOST, ?DB_DATABASE, ID, Rev). delete_document(ID, Rev) -> erlang_couchdb:delete_document(?DB_HOST, ?DB_DATABASE, ID, Rev). delete_document(Db, ID, Rev) -> erlang_couchdb:delete_document(?DB_HOST, Db, ID, Rev). delete_document(Server, Db, ID, Rev) -> erlang_couchdb:delete_document(Server, Db, ID, Rev). create_view(DocName, ViewList) when is_list(ViewList) -> erlang_couchdb:create_view(?DB_HOST, ?DB_DATABASE, DocName, <<"javascript">>, ViewList). create_view(DocName, ViewName, Data) -> erlang_couchdb:create_view(?DB_HOST, ?DB_DATABASE, DocName, <<"javascript">>, [{ViewName, Data}]). create_view(DocName, Type, ViewName, Data) -> erlang_couchdb:create_view(?DB_HOST, ?DB_DATABASE, DocName, Type, [{ViewName, Data}]). create_view(Db, DocName, Type, ViewName, Data) -> erlang_couchdb:create_view(?DB_HOST, Db, DocName, Type, [{ViewName, Data}]). create_view(Server, Db, DocName, Type, ViewName, Data) -> erlang_couchdb:create_view(Server, Db, DocName, Type, [{ViewName, Data}]). invoke_view(DocName, ViewName) -> erlang_couchdb:invoke_view(?DB_HOST, ?DB_DATABASE, DocName, ViewName, []). ( ) , ViewName::string ( ) , Keys::proplist ( ) ) - > result | { error , Reason::any ( ) } invoke_view(DocName, ViewName, Keys) -> erlang_couchdb:invoke_view(?DB_HOST, ?DB_DATABASE, DocName, ViewName, Keys). invoke_view(Db, DocName, ViewName, Keys) -> erlang_couchdb:invoke_view(?DB_HOST, Db, DocName, ViewName, Keys). invoke_view(Server, Db, DocName, ViewName, Keys) -> erlang_couchdb:invoke_view(Server, Db, DocName, ViewName, Keys). ( ) , Key::binary ( ) ) - > empty_string | { error , Reason::any ( ) } get_value(Doc, Key) -> get_value(Doc, Key, ""). get_value({struct, L}, Key, DefaultValue) -> Values = proplists:get_value(<<"value">>, L, []), case Values of [] -> proplists:get_value(Key, L, DefaultValue); {struct, ValueList} -> proplists:get_value(Key, ValueList, DefaultValue) end; get_value({json, {struct, ValueList}}, Key, DefaultValue) -> proplists:get_value(Key, ValueList, DefaultValue); get_value(_, _Key, DefaultValue) -> DefaultValue. get_id(Doc) -> get_id(Doc, ""). get_id({struct, L}, DefaultValue) -> binary_to_list(proplists:get_value(<<"id">>, L, DefaultValue)); get_id({json, {struct, L}}, DefaultValue) -> binary_to_list(proplists:get_value(<<"id">>, L, DefaultValue)); get_id(_, DefaultValue) -> DefaultValue. get_rev(Doc) -> get_rev(Doc, ""). get_rev(Doc, DefaultValue) -> binary_to_list(get_value(Doc, <<"_rev">>, DefaultValue)). get_revs(ID) -> get_revs(?DB_HOST, ?DB_DATABASE, ID). get_revs(Db, ID) -> get_revs(?DB_HOST, Db, ID). get_revs(Server, Db, ID) -> {ServerName, Port} = Server, Type = "GET", URI = lists:concat(["/", Db, "/", ID, "?", "revs_info=true"]), Body = <<>>, Rows = erlang_couchdb:raw_request(Type, ServerName, Port, URI, Body), case Rows of {json, {struct, PropList}} -> Revs = proplists:get_value(<<"_revs_info">>, PropList, []), case Revs of [] -> []; RevList -> get_revision_list(RevList) end; _ -> [] end. get_revision_list(RevList) -> get_revision_list(RevList, []). get_revision_list([{struct, PropList}|T], Acc) -> Rev = binary_to_list(proplists:get_value(<<"rev">>, PropList, <<"">>)), Status = binary_to_list(proplists:get_value(<<"status">>, PropList, <<"">>)), get_revision_list( T, Acc ++ [{Rev, Status}] ); get_revision_list([], Acc) -> Acc. get_total({json, {struct, L}}) -> proplists:get_value(<<"total_rows">>, L, 0); get_total(_Any) -> 0. get_offset({json, {struct, L}}) -> proplists:get_value(<<"offset">>, L, 0); get_offset(_Any) -> 0. get_rows({json, {struct, L}}) -> proplists:get_value(<<"rows">>, L, []); get_rows(_Any) -> []. @private update_doc_fields({struct, Doc}, NewFields) -> update_doc_fields(Doc, NewFields); update_doc_fields(OldDoc, []) -> OldDoc; update_doc_fields(OldDoc, [{Key, Value}|T]) -> case proplists:get_value(Key, OldDoc) of undefined -> update_doc_fields([{Key, Value}] ++ OldDoc, T); _ -> NewDoc = proplists:delete(Key, OldDoc), update_doc_fields([{Key, Value}] ++ NewDoc, T) end.
77d7c3787bf3d0cc16a58383f65f408f2f8d2735bc24ae828af60fc02e5ea79f
ocaml-multicore/ocaml-tsan
exception_handler.ml
TEST * frame_pointers * * native readonly_files = " " all_modules = " $ { readonly_files } exception_handler.ml " * frame_pointers ** native readonly_files = "fp_backtrace.c" all_modules = "${readonly_files} exception_handler.ml" *) external fp_backtrace : unit -> unit = "fp_backtrace" [@@noalloc] exception Exn1 exception Exn2 (* We want to be sure to use some stack space so that rbp is shifted, * preventing inlining seems enough *) let[@inline never] raiser i = match i with | 1 -> raise Exn1 | 2 -> raise Exn2 | _ -> 42 (* shouldn't happen *) let[@inline never][@local never] f x = x (* This give us a chance to overwrite the memory address pointed by rbp if it * is still within 'raiser' stack frame. * Technically we don't need to overwrite it but by doing so we avoid some * infinite loop while walking the stack. *) let[@inline never] handler () = Force spilling of , x1 , x2 0xdeadbeef 0xdeadbeef 0xdeadbeef let _ = f x0 in let _ = f x1 in let _ = f x2 in let _ = Sys.opaque_identity x0 in let _ = Sys.opaque_identity x1 in let _ = Sys.opaque_identity x2 in fp_backtrace () let[@inline never] nested i = begin try try ignore (raiser i) with Exn1 -> handler () with | Exn2 -> handler () end; i (* Check that we haven't broken anything by raising directly from this * function, it doesn't require rbp to be adjusted *) let[@inline never] bare i = begin try try (if i == 1 then raise Exn1 else raise Exn2) with | Exn1 -> handler () with | Exn2 -> handler () end; i let () = ignore (bare 1); ignore (bare 2); ignore (nested 1); ignore (nested 2)
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/f54002470cc6ab780963cc81b11a85a820a40819/testsuite/tests/frame-pointers/exception_handler.ml
ocaml
We want to be sure to use some stack space so that rbp is shifted, * preventing inlining seems enough shouldn't happen This give us a chance to overwrite the memory address pointed by rbp if it * is still within 'raiser' stack frame. * Technically we don't need to overwrite it but by doing so we avoid some * infinite loop while walking the stack. Check that we haven't broken anything by raising directly from this * function, it doesn't require rbp to be adjusted
TEST * frame_pointers * * native readonly_files = " " all_modules = " $ { readonly_files } exception_handler.ml " * frame_pointers ** native readonly_files = "fp_backtrace.c" all_modules = "${readonly_files} exception_handler.ml" *) external fp_backtrace : unit -> unit = "fp_backtrace" [@@noalloc] exception Exn1 exception Exn2 let[@inline never] raiser i = match i with | 1 -> raise Exn1 | 2 -> raise Exn2 let[@inline never][@local never] f x = x let[@inline never] handler () = Force spilling of , x1 , x2 0xdeadbeef 0xdeadbeef 0xdeadbeef let _ = f x0 in let _ = f x1 in let _ = f x2 in let _ = Sys.opaque_identity x0 in let _ = Sys.opaque_identity x1 in let _ = Sys.opaque_identity x2 in fp_backtrace () let[@inline never] nested i = begin try try ignore (raiser i) with Exn1 -> handler () with | Exn2 -> handler () end; i let[@inline never] bare i = begin try try (if i == 1 then raise Exn1 else raise Exn2) with | Exn1 -> handler () with | Exn2 -> handler () end; i let () = ignore (bare 1); ignore (bare 2); ignore (nested 1); ignore (nested 2)
9b4dd91bc105efff63e9384bfaebf8b68a0118e4fe031754a25696fb0a29e400
MyDataFlow/ttalk-server
pgsql_util.erl
%%% File : pgsql_util.erl Author : %%% Description : utility functions used in implementation of %%% postgresql driver. Created : 11 May 2005 by Blah < cos@local > -module(pgsql_util). %% Key-Value handling -export([option/3]). Networking -export([socket/1]). -export([send/2, send_int/2, send_msg/3]). -export([recv_msg/2, recv_msg/1, recv_byte/2, recv_byte/1]). Protocol packing -export([string/1, make_pair/2, split_pair/2]). -export([split_pair_rec/2]). -export([count_string/1, to_string/2]). -export([oids/2, coldescs/3, datacoldescs/3]). -export([decode_row/3, decode_descs/2]). -export([errordesc/2]). -export([to_integer/1, to_atom/1]). -export([zip/2]). %% Constructing authentication messages. -export([pass_plain/1, pass_md5/3]). -import(erlang, [md5/1]). -export([hexlist/2]). %% Lookup key in a plist stored in process dictionary under 'options'. %% Default is returned if there is no value for Key in the plist. option(Opts, Key, Default) -> case proplists:get_value(Key, Opts, Default) of Default -> Default; Value when is_binary(Value) -> binary_to_list(Value); Value -> Value end. %% Open a TCP connection socket({tcp, Host, Port}) -> gen_tcp:connect(Host, Port, [{active, false}, binary, {packet, raw}], 5000). send(Sock, Packet) -> gen_tcp:send(Sock, Packet). send_int(Sock, Int) -> Packet = <<Int:32/integer>>, gen_tcp:send(Sock, Packet). send_msg(Sock, Code, Packet) when is_binary(Packet) -> Len = size(Packet) + 4, Msg = <<Code:8/integer, Len:4/integer-unit:8, Packet/binary>>, gen_tcp:send(Sock, Msg). recv_msg(Sock, Timeout) -> {ok, Head} = gen_tcp:recv(Sock, 5, Timeout), <<Code:8/integer, Size:4/integer-unit:8>> = Head, io : format("Code : ~p , : ~p ~ n " , [ Code , Size ] ) , if Size > 4 -> {ok, Packet} = gen_tcp:recv(Sock, Size-4, Timeout), {ok, Code, Packet}; true -> {ok, Code, <<>>} end. recv_msg(Sock) -> recv_msg(Sock, infinity). recv_byte(Sock) -> recv_byte(Sock, infinity). recv_byte(Sock, Timeout) -> case gen_tcp:recv(Sock, 1, Timeout) of {ok, <<Byte:1/integer-unit:8>>} -> {ok, Byte}; E={error, _Reason} -> throw(E) end. %% Convert String to binary string(String) when is_list(String) -> Bin = list_to_binary(String), <<Bin/binary, 0/integer>>; string(Bin) when is_binary(Bin) -> <<Bin/binary, 0/integer>>. Two zero terminated strings . make_pair(Key, Value) when is_atom(Key) -> make_pair(atom_to_list(Key), Value); make_pair(Key, Value) when is_atom(Value) -> make_pair(Key, atom_to_list(Value)); make_pair(Key, Value) when is_list(Key), is_list(Value) -> BinKey = list_to_binary(Key), BinValue = list_to_binary(Value), make_pair(BinKey, BinValue); make_pair(Key, Value) when is_binary(Key), is_binary(Value) -> <<Key/binary, 0/integer, Value/binary, 0/integer>>. split_pair(Bin, AsBin) when is_binary(Bin) -> split_pair(binary_to_list(Bin), AsBin); split_pair(Str, AsBin) -> split_pair_rec(Str, norec, AsBin). split_pair_rec(Bin, AsBin) when is_binary(Bin) -> split_pair_rec(binary_to_list(Bin), AsBin); split_pair_rec(Arg, AsBin) -> split_pair_rec(Arg,[], AsBin). split_pair_rec([], Acc, _AsBin) -> lists:reverse(Acc); split_pair_rec([0], Acc, _AsBin) -> lists:reverse(Acc); split_pair_rec(S, Acc, AsBin) -> Fun = fun(C) -> C /= 0 end, {K, [0|S1]} = lists:splitwith(Fun, S), {V, [0|Tail]} = lists:splitwith(Fun, S1), {Key, Value} = if AsBin -> {list_to_binary(K), list_to_binary(V)}; true -> {K, V} end, case Acc of norec -> {Key, Value}; _ -> split_pair_rec(Tail, [{Key, Value}| Acc], AsBin) end. count_string(Bin) when is_binary(Bin) -> count_string(Bin, 0). count_string(<<>>, N) -> {N, <<>>}; count_string(<<0/integer, Rest/binary>>, N) -> {N, Rest}; count_string(<<_C/integer, Rest/binary>>, N) -> count_string(Rest, N+1). to_string(Bin, AsBin) when is_binary(Bin) -> {Count, _} = count_string(Bin, 0), <<String:Count/binary, _/binary>> = Bin, if AsBin -> {String, Count}; true -> {binary_to_list(String), Count} end. oids(<<>>, Oids) -> lists:reverse(Oids); oids(<<Oid:32/integer, Rest/binary>>, Oids) -> oids(Rest, [Oid|Oids]). coldescs(<<>>, Descs, _AsBin) -> lists:reverse(Descs); coldescs(Bin, Descs, AsBin) -> {Name, Count} = to_string(Bin, AsBin), <<_:Count/binary, 0/integer, TableOID:32/integer, ColumnNumber:16/integer, TypeId:32/integer, TypeSize:16/integer-signed, TypeMod:32/integer-signed, FormatCode:16/integer, Rest/binary>> = Bin, Format = case FormatCode of 0 -> text; 1 -> binary end, Desc = {Name, Format, ColumnNumber, TypeId, TypeSize, TypeMod, TableOID}, coldescs(Rest, [Desc|Descs], AsBin). datacoldescs(N, <<16#ffffffff:32, Rest/binary>>, Descs) when N >= 0 -> datacoldescs(N-1, Rest, [null|Descs]); datacoldescs(N, <<Len:32/integer, Data:Len/binary, Rest/binary>>, Descs) when N >= 0 -> datacoldescs(N-1, Rest, [Data|Descs]); datacoldescs(_N, _, Descs) -> lists:reverse(Descs). decode_descs(OidMap, Cols) -> decode_descs(OidMap, Cols, []). decode_descs(_OidMap, [], Descs) -> {ok, lists:reverse(Descs)}; decode_descs(OidMap, [Col|ColTail], Descs) -> {Name, Format, ColNumber, Oid, _, _, _} = Col, OidName = dict:fetch(Oid, OidMap), decode_descs(OidMap, ColTail, [{Name, Format, ColNumber, OidName, [], [], []}|Descs]). decode_row(Types, Values, AsBin) -> decode_row(Types, Values, [], AsBin). decode_row([], [], Out, _AsBin) -> {ok, lists:reverse(Out)}; decode_row([Type|TypeTail], [Value|ValueTail], Out0, AsBin) -> Out1 = decode_col(Type, Value, AsBin), decode_row(TypeTail, ValueTail, [Out1|Out0], AsBin). decode_col({_, text, _, _, _, _, _}, Value, AsBin) -> if AsBin -> Value; true -> binary_to_list(Value) end; decode_col({_Name, _Format, _ColNumber, varchar, _Size, _Modifier, _TableOID}, Value, AsBin) -> if AsBin -> Value; true -> binary_to_list(Value) end; decode_col({_Name, _Format, _ColNumber, int4, _Size, _Modifier, _TableOID}, Value, _AsBin) -> <<Int4:32/integer>> = Value, Int4; decode_col({_Name, _Format, _ColNumber, Oid, _Size, _Modifier, _TableOID}, Value, _AsBin) -> {Oid, Value}. -spec errordesc(binary(), boolean()) -> [{atom(), term()}]. errordesc(Bin, AsBin) -> errordesc(Bin, [], AsBin). errordesc(<<0/integer, _Rest/binary>>, Lines, _AsBin) -> lists:reverse(Lines); errordesc(<<Code/integer, Rest/binary>>, Lines, AsBin) -> {String, Count} = to_string(Rest, AsBin), <<_:Count/binary, 0, Rest1/binary>> = Rest, Msg = case Code of $S -> {severity, to_atom(String)}; $C -> {code, String}; $M -> {message, String}; $D -> {detail, String}; $H -> {hint, String}; $P -> {position, to_integer(String)}; $p -> {internal_position, to_integer(String)}; $W -> {where, String}; $F -> {file, String}; $L -> {line, to_integer(String)}; $R -> {routine, String}; Unknown -> {Unknown, String} end, errordesc(Rest1, [Msg|Lines], AsBin). Zip two lists together zip(List1, List2) -> zip(List1, List2, []). zip(List1, List2, Result) when List1 =:= []; List2 =:= [] -> lists:reverse(Result); zip([H1|List1], [H2|List2], Result) -> zip(List1, List2, [{H1, H2}|Result]). %%% Authentication utils pass_plain(Password) -> Pass = [Password, 0], list_to_binary(Pass). %% MD5 authentication patch from < > ( patch slightly rewritten , new bugs are mine ) %% %% MD5(MD5(password + user) + salt) %% pass_md5(User, Password, Salt) -> Digest = hex(md5([Password, User])), Encrypt = hex(md5([Digest, Salt])), Pass = ["md5", Encrypt, 0], list_to_binary(Pass). to_integer(B) when is_binary(B) -> to_integer(binary_to_list(B)); to_integer(S) -> list_to_integer(S). to_atom(B) when is_binary(B) -> to_atom(binary_to_list(B)); to_atom(S) -> list_to_atom(S). hex(B) when is_binary(B) -> hexlist(binary_to_list(B), []). hexlist([], Acc) -> lists:reverse(Acc); hexlist([N|Rest], Acc) -> HighNibble = (N band 16#f0) bsr 4, LowNibble = (N band 16#0f), hexlist(Rest, [hexdigit(LowNibble), hexdigit(HighNibble)|Acc]). hexdigit(0) -> $0; hexdigit(1) -> $1; hexdigit(2) -> $2; hexdigit(3) -> $3; hexdigit(4) -> $4; hexdigit(5) -> $5; hexdigit(6) -> $6; hexdigit(7) -> $7; hexdigit(8) -> $8; hexdigit(9) -> $9; hexdigit(10) -> $a; hexdigit(11) -> $b; hexdigit(12) -> $c; hexdigit(13) -> $d; hexdigit(14) -> $e; hexdigit(15) -> $f.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/apps/pgsql/src/pgsql_util.erl
erlang
File : pgsql_util.erl Description : utility functions used in implementation of postgresql driver. Key-Value handling Constructing authentication messages. Lookup key in a plist stored in process dictionary under 'options'. Default is returned if there is no value for Key in the plist. Open a TCP connection Convert String to binary Authentication utils MD5 authentication patch from MD5(MD5(password + user) + salt)
Author : Created : 11 May 2005 by Blah < cos@local > -module(pgsql_util). -export([option/3]). Networking -export([socket/1]). -export([send/2, send_int/2, send_msg/3]). -export([recv_msg/2, recv_msg/1, recv_byte/2, recv_byte/1]). Protocol packing -export([string/1, make_pair/2, split_pair/2]). -export([split_pair_rec/2]). -export([count_string/1, to_string/2]). -export([oids/2, coldescs/3, datacoldescs/3]). -export([decode_row/3, decode_descs/2]). -export([errordesc/2]). -export([to_integer/1, to_atom/1]). -export([zip/2]). -export([pass_plain/1, pass_md5/3]). -import(erlang, [md5/1]). -export([hexlist/2]). option(Opts, Key, Default) -> case proplists:get_value(Key, Opts, Default) of Default -> Default; Value when is_binary(Value) -> binary_to_list(Value); Value -> Value end. socket({tcp, Host, Port}) -> gen_tcp:connect(Host, Port, [{active, false}, binary, {packet, raw}], 5000). send(Sock, Packet) -> gen_tcp:send(Sock, Packet). send_int(Sock, Int) -> Packet = <<Int:32/integer>>, gen_tcp:send(Sock, Packet). send_msg(Sock, Code, Packet) when is_binary(Packet) -> Len = size(Packet) + 4, Msg = <<Code:8/integer, Len:4/integer-unit:8, Packet/binary>>, gen_tcp:send(Sock, Msg). recv_msg(Sock, Timeout) -> {ok, Head} = gen_tcp:recv(Sock, 5, Timeout), <<Code:8/integer, Size:4/integer-unit:8>> = Head, io : format("Code : ~p , : ~p ~ n " , [ Code , Size ] ) , if Size > 4 -> {ok, Packet} = gen_tcp:recv(Sock, Size-4, Timeout), {ok, Code, Packet}; true -> {ok, Code, <<>>} end. recv_msg(Sock) -> recv_msg(Sock, infinity). recv_byte(Sock) -> recv_byte(Sock, infinity). recv_byte(Sock, Timeout) -> case gen_tcp:recv(Sock, 1, Timeout) of {ok, <<Byte:1/integer-unit:8>>} -> {ok, Byte}; E={error, _Reason} -> throw(E) end. string(String) when is_list(String) -> Bin = list_to_binary(String), <<Bin/binary, 0/integer>>; string(Bin) when is_binary(Bin) -> <<Bin/binary, 0/integer>>. Two zero terminated strings . make_pair(Key, Value) when is_atom(Key) -> make_pair(atom_to_list(Key), Value); make_pair(Key, Value) when is_atom(Value) -> make_pair(Key, atom_to_list(Value)); make_pair(Key, Value) when is_list(Key), is_list(Value) -> BinKey = list_to_binary(Key), BinValue = list_to_binary(Value), make_pair(BinKey, BinValue); make_pair(Key, Value) when is_binary(Key), is_binary(Value) -> <<Key/binary, 0/integer, Value/binary, 0/integer>>. split_pair(Bin, AsBin) when is_binary(Bin) -> split_pair(binary_to_list(Bin), AsBin); split_pair(Str, AsBin) -> split_pair_rec(Str, norec, AsBin). split_pair_rec(Bin, AsBin) when is_binary(Bin) -> split_pair_rec(binary_to_list(Bin), AsBin); split_pair_rec(Arg, AsBin) -> split_pair_rec(Arg,[], AsBin). split_pair_rec([], Acc, _AsBin) -> lists:reverse(Acc); split_pair_rec([0], Acc, _AsBin) -> lists:reverse(Acc); split_pair_rec(S, Acc, AsBin) -> Fun = fun(C) -> C /= 0 end, {K, [0|S1]} = lists:splitwith(Fun, S), {V, [0|Tail]} = lists:splitwith(Fun, S1), {Key, Value} = if AsBin -> {list_to_binary(K), list_to_binary(V)}; true -> {K, V} end, case Acc of norec -> {Key, Value}; _ -> split_pair_rec(Tail, [{Key, Value}| Acc], AsBin) end. count_string(Bin) when is_binary(Bin) -> count_string(Bin, 0). count_string(<<>>, N) -> {N, <<>>}; count_string(<<0/integer, Rest/binary>>, N) -> {N, Rest}; count_string(<<_C/integer, Rest/binary>>, N) -> count_string(Rest, N+1). to_string(Bin, AsBin) when is_binary(Bin) -> {Count, _} = count_string(Bin, 0), <<String:Count/binary, _/binary>> = Bin, if AsBin -> {String, Count}; true -> {binary_to_list(String), Count} end. oids(<<>>, Oids) -> lists:reverse(Oids); oids(<<Oid:32/integer, Rest/binary>>, Oids) -> oids(Rest, [Oid|Oids]). coldescs(<<>>, Descs, _AsBin) -> lists:reverse(Descs); coldescs(Bin, Descs, AsBin) -> {Name, Count} = to_string(Bin, AsBin), <<_:Count/binary, 0/integer, TableOID:32/integer, ColumnNumber:16/integer, TypeId:32/integer, TypeSize:16/integer-signed, TypeMod:32/integer-signed, FormatCode:16/integer, Rest/binary>> = Bin, Format = case FormatCode of 0 -> text; 1 -> binary end, Desc = {Name, Format, ColumnNumber, TypeId, TypeSize, TypeMod, TableOID}, coldescs(Rest, [Desc|Descs], AsBin). datacoldescs(N, <<16#ffffffff:32, Rest/binary>>, Descs) when N >= 0 -> datacoldescs(N-1, Rest, [null|Descs]); datacoldescs(N, <<Len:32/integer, Data:Len/binary, Rest/binary>>, Descs) when N >= 0 -> datacoldescs(N-1, Rest, [Data|Descs]); datacoldescs(_N, _, Descs) -> lists:reverse(Descs). decode_descs(OidMap, Cols) -> decode_descs(OidMap, Cols, []). decode_descs(_OidMap, [], Descs) -> {ok, lists:reverse(Descs)}; decode_descs(OidMap, [Col|ColTail], Descs) -> {Name, Format, ColNumber, Oid, _, _, _} = Col, OidName = dict:fetch(Oid, OidMap), decode_descs(OidMap, ColTail, [{Name, Format, ColNumber, OidName, [], [], []}|Descs]). decode_row(Types, Values, AsBin) -> decode_row(Types, Values, [], AsBin). decode_row([], [], Out, _AsBin) -> {ok, lists:reverse(Out)}; decode_row([Type|TypeTail], [Value|ValueTail], Out0, AsBin) -> Out1 = decode_col(Type, Value, AsBin), decode_row(TypeTail, ValueTail, [Out1|Out0], AsBin). decode_col({_, text, _, _, _, _, _}, Value, AsBin) -> if AsBin -> Value; true -> binary_to_list(Value) end; decode_col({_Name, _Format, _ColNumber, varchar, _Size, _Modifier, _TableOID}, Value, AsBin) -> if AsBin -> Value; true -> binary_to_list(Value) end; decode_col({_Name, _Format, _ColNumber, int4, _Size, _Modifier, _TableOID}, Value, _AsBin) -> <<Int4:32/integer>> = Value, Int4; decode_col({_Name, _Format, _ColNumber, Oid, _Size, _Modifier, _TableOID}, Value, _AsBin) -> {Oid, Value}. -spec errordesc(binary(), boolean()) -> [{atom(), term()}]. errordesc(Bin, AsBin) -> errordesc(Bin, [], AsBin). errordesc(<<0/integer, _Rest/binary>>, Lines, _AsBin) -> lists:reverse(Lines); errordesc(<<Code/integer, Rest/binary>>, Lines, AsBin) -> {String, Count} = to_string(Rest, AsBin), <<_:Count/binary, 0, Rest1/binary>> = Rest, Msg = case Code of $S -> {severity, to_atom(String)}; $C -> {code, String}; $M -> {message, String}; $D -> {detail, String}; $H -> {hint, String}; $P -> {position, to_integer(String)}; $p -> {internal_position, to_integer(String)}; $W -> {where, String}; $F -> {file, String}; $L -> {line, to_integer(String)}; $R -> {routine, String}; Unknown -> {Unknown, String} end, errordesc(Rest1, [Msg|Lines], AsBin). Zip two lists together zip(List1, List2) -> zip(List1, List2, []). zip(List1, List2, Result) when List1 =:= []; List2 =:= [] -> lists:reverse(Result); zip([H1|List1], [H2|List2], Result) -> zip(List1, List2, [{H1, H2}|Result]). pass_plain(Password) -> Pass = [Password, 0], list_to_binary(Pass). < > ( patch slightly rewritten , new bugs are mine ) pass_md5(User, Password, Salt) -> Digest = hex(md5([Password, User])), Encrypt = hex(md5([Digest, Salt])), Pass = ["md5", Encrypt, 0], list_to_binary(Pass). to_integer(B) when is_binary(B) -> to_integer(binary_to_list(B)); to_integer(S) -> list_to_integer(S). to_atom(B) when is_binary(B) -> to_atom(binary_to_list(B)); to_atom(S) -> list_to_atom(S). hex(B) when is_binary(B) -> hexlist(binary_to_list(B), []). hexlist([], Acc) -> lists:reverse(Acc); hexlist([N|Rest], Acc) -> HighNibble = (N band 16#f0) bsr 4, LowNibble = (N band 16#0f), hexlist(Rest, [hexdigit(LowNibble), hexdigit(HighNibble)|Acc]). hexdigit(0) -> $0; hexdigit(1) -> $1; hexdigit(2) -> $2; hexdigit(3) -> $3; hexdigit(4) -> $4; hexdigit(5) -> $5; hexdigit(6) -> $6; hexdigit(7) -> $7; hexdigit(8) -> $8; hexdigit(9) -> $9; hexdigit(10) -> $a; hexdigit(11) -> $b; hexdigit(12) -> $c; hexdigit(13) -> $d; hexdigit(14) -> $e; hexdigit(15) -> $f.
4cf94dacad02d125697154c1b7a73ce1612008f03e3e69578525b20896773198
simmone/racket-simple-qr
separator.rkt
#lang racket (require "../func/func.rkt") (require "../../../share/func.rkt") (require "../../../share/separator.rkt") (provide (contract-out [draw-separator (-> exact-nonnegative-integer? hash? hash? void?)] )) (define (draw-separator modules points_map type_map) (let* ([finder_pattern_start_points (locate-finder-pattern modules)] [top_left_point (first finder_pattern_start_points)] [top_right_point (second finder_pattern_start_points)] [bottom_left_point (third finder_pattern_start_points)] [new_top_right_point (cons (car top_right_point) (sub1 (cdr top_right_point)))] [new_bottom_left_point (cons (sub1 (car bottom_left_point)) (cdr bottom_left_point))]) (for-each (lambda (point_pair) (add-point point_pair "0" "separator" points_map type_map)) (transform-points-list (first (get-separator)) top_left_point)) (for-each (lambda (point_pair) (add-point point_pair "0" "separator" points_map type_map)) (transform-points-list (second (get-separator)) new_top_right_point)) (for-each (lambda (point_pair) (add-point point_pair "0" "separator" points_map type_map)) (transform-points-list (third (get-separator)) new_bottom_left_point)) ))
null
https://raw.githubusercontent.com/simmone/racket-simple-qr/904f1491bc521badeafeabd0d7d7e97e3d0ee958/simple-qr/write/lib/separator/separator.rkt
racket
#lang racket (require "../func/func.rkt") (require "../../../share/func.rkt") (require "../../../share/separator.rkt") (provide (contract-out [draw-separator (-> exact-nonnegative-integer? hash? hash? void?)] )) (define (draw-separator modules points_map type_map) (let* ([finder_pattern_start_points (locate-finder-pattern modules)] [top_left_point (first finder_pattern_start_points)] [top_right_point (second finder_pattern_start_points)] [bottom_left_point (third finder_pattern_start_points)] [new_top_right_point (cons (car top_right_point) (sub1 (cdr top_right_point)))] [new_bottom_left_point (cons (sub1 (car bottom_left_point)) (cdr bottom_left_point))]) (for-each (lambda (point_pair) (add-point point_pair "0" "separator" points_map type_map)) (transform-points-list (first (get-separator)) top_left_point)) (for-each (lambda (point_pair) (add-point point_pair "0" "separator" points_map type_map)) (transform-points-list (second (get-separator)) new_top_right_point)) (for-each (lambda (point_pair) (add-point point_pair "0" "separator" points_map type_map)) (transform-points-list (third (get-separator)) new_bottom_left_point)) ))
f395c5627563dd07e04e7b0246bd90b88b45f68b1369edc95a6caffad52a50d0
ThoughtWorksInc/DeepDarkFantasy
Double.hs
# LANGUAGE NoImplicitPrelude , NoMonomorphismRestriction , FlexibleInstances , MultiParamTypeClasses , UndecidableInstances , UndecidableSuperClasses # NoImplicitPrelude, NoMonomorphismRestriction, FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, UndecidableSuperClasses #-} module DDF.Double (module DDF.Double, module DDF.Ordering) where import DDF.Ordering import qualified Prelude as M class (OrdC r M.Double, Ordering r) => Double r where double :: M.Double -> r h M.Double doubleZero :: r h M.Double doubleZero = double 0 doubleOne :: r h M.Double doubleOne = double 1 doublePlus :: r h (M.Double -> M.Double -> M.Double) doubleMinus :: r h (M.Double -> M.Double -> M.Double) doubleMult :: r h (M.Double -> M.Double -> M.Double) doubleDivide :: r h (M.Double -> M.Double -> M.Double) doubleExp :: r h (M.Double -> M.Double) doubleCmp :: r h (M.Double -> M.Double -> M.Ordering) instance Double r => Ord r M.Double where cmp = doubleCmp getOrdC _ = Dict doublePlus1 = app doublePlus doublePlus2 = app2 doublePlus doubleMinus2 = app2 doubleMinus doubleMult2 = app2 doubleMult doubleDivide2 = app2 doubleDivide doubleExp1 = app doubleExp
null
https://raw.githubusercontent.com/ThoughtWorksInc/DeepDarkFantasy/4c569aefc03a2bcfb6113b65367201d30077f2b6/DDF/Double.hs
haskell
# LANGUAGE NoImplicitPrelude , NoMonomorphismRestriction , FlexibleInstances , MultiParamTypeClasses , UndecidableInstances , UndecidableSuperClasses # NoImplicitPrelude, NoMonomorphismRestriction, FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, UndecidableSuperClasses #-} module DDF.Double (module DDF.Double, module DDF.Ordering) where import DDF.Ordering import qualified Prelude as M class (OrdC r M.Double, Ordering r) => Double r where double :: M.Double -> r h M.Double doubleZero :: r h M.Double doubleZero = double 0 doubleOne :: r h M.Double doubleOne = double 1 doublePlus :: r h (M.Double -> M.Double -> M.Double) doubleMinus :: r h (M.Double -> M.Double -> M.Double) doubleMult :: r h (M.Double -> M.Double -> M.Double) doubleDivide :: r h (M.Double -> M.Double -> M.Double) doubleExp :: r h (M.Double -> M.Double) doubleCmp :: r h (M.Double -> M.Double -> M.Ordering) instance Double r => Ord r M.Double where cmp = doubleCmp getOrdC _ = Dict doublePlus1 = app doublePlus doublePlus2 = app2 doublePlus doubleMinus2 = app2 doubleMinus doubleMult2 = app2 doubleMult doubleDivide2 = app2 doubleDivide doubleExp1 = app doubleExp
2239a881f510e4caf5f0a36be6ad1c5c22a22c149951c0a0450d029ffff8bf67
ds-wizard/engine-backend
Common.hs
module Wizard.Service.Migration.Metamodel.Migrator.Common ( convertValueToOject, getField, getArrayField, migrateMetamodelVersionField, migrateEventsField, validateMetamodelVersionField, ) where import Data.Aeson import qualified Data.Aeson.KeyMap as KM import Data.String (fromString) import qualified Data.Vector as Vector import Shared.Constant.KnowledgeModel import Shared.Model.Error.Error import Shared.Util.JSON (convertValueToOject, getArrayField, getField) import Shared.Util.List (foldEither) import Wizard.Localization.Messages.Public import qualified Wizard.Metamodel.Migration.MigrationContext as EventMigrator import qualified Wizard.Metamodel.Migrator.EventMigrator as EventMigrator validateMetamodelVersionField :: Value -> Either AppError Value validateMetamodelVersionField value = convertValueToOject value $ \object -> getField "metamodelVersion" object $ \metamodelVersion -> if metamodelVersion <= kmMetamodelVersion then Right value else Left . UserError $ _ERROR_VALIDATION__PKG_UNSUPPORTED_METAMODEL_VERSION metamodelVersion kmMetamodelVersion migrateMetamodelVersionField :: Value -> Either AppError Value migrateMetamodelVersionField value = convertValueToOject value $ \object -> Right . Object $ KM.insert "metamodelVersion" (toJSON kmMetamodelVersion) object migrateEventsField :: String -> Value -> Either AppError Value migrateEventsField eventsFieldName value = convertValueToOject value $ \object -> getField "metamodelVersion" object $ \oldMetamodelVersion -> getField "createdAt" object $ \createdAt -> getArrayField eventsFieldName object $ \events -> case foldEither $ EventMigrator.migrate (EventMigrator.MigrationContext createdAt) oldMetamodelVersion kmMetamodelVersion <$> Vector.toList events of Right updatedEvents -> Right . Object $ KM.insert (fromString eventsFieldName) (toJSON . concat $ updatedEvents) object Left error -> Left . GeneralServerError $ error
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Service/Migration/Metamodel/Migrator/Common.hs
haskell
module Wizard.Service.Migration.Metamodel.Migrator.Common ( convertValueToOject, getField, getArrayField, migrateMetamodelVersionField, migrateEventsField, validateMetamodelVersionField, ) where import Data.Aeson import qualified Data.Aeson.KeyMap as KM import Data.String (fromString) import qualified Data.Vector as Vector import Shared.Constant.KnowledgeModel import Shared.Model.Error.Error import Shared.Util.JSON (convertValueToOject, getArrayField, getField) import Shared.Util.List (foldEither) import Wizard.Localization.Messages.Public import qualified Wizard.Metamodel.Migration.MigrationContext as EventMigrator import qualified Wizard.Metamodel.Migrator.EventMigrator as EventMigrator validateMetamodelVersionField :: Value -> Either AppError Value validateMetamodelVersionField value = convertValueToOject value $ \object -> getField "metamodelVersion" object $ \metamodelVersion -> if metamodelVersion <= kmMetamodelVersion then Right value else Left . UserError $ _ERROR_VALIDATION__PKG_UNSUPPORTED_METAMODEL_VERSION metamodelVersion kmMetamodelVersion migrateMetamodelVersionField :: Value -> Either AppError Value migrateMetamodelVersionField value = convertValueToOject value $ \object -> Right . Object $ KM.insert "metamodelVersion" (toJSON kmMetamodelVersion) object migrateEventsField :: String -> Value -> Either AppError Value migrateEventsField eventsFieldName value = convertValueToOject value $ \object -> getField "metamodelVersion" object $ \oldMetamodelVersion -> getField "createdAt" object $ \createdAt -> getArrayField eventsFieldName object $ \events -> case foldEither $ EventMigrator.migrate (EventMigrator.MigrationContext createdAt) oldMetamodelVersion kmMetamodelVersion <$> Vector.toList events of Right updatedEvents -> Right . Object $ KM.insert (fromString eventsFieldName) (toJSON . concat $ updatedEvents) object Left error -> Left . GeneralServerError $ error
c3b2456f9f8922d493af319543b1a6e8eb8b71932dfb6aa71343608cf658e9ce
imandra-ai/imandra-ros
tf_to_json.ml
open Json_utils;; open Basic_types_to_json;; open Ros_messages.Tf;; let tfMessage_to_json x = [ ( "transforms" , x.transforms |> (mklist Geometry_msgs_to_json.transformStamped_to_json) ); ] |> assoc_filter_nulls
null
https://raw.githubusercontent.com/imandra-ai/imandra-ros/e1380c267ee319dd4f86c4b54e0b270bc0738796/imandra_model/src-messages-pp/tf_to_json.ml
ocaml
open Json_utils;; open Basic_types_to_json;; open Ros_messages.Tf;; let tfMessage_to_json x = [ ( "transforms" , x.transforms |> (mklist Geometry_msgs_to_json.transformStamped_to_json) ); ] |> assoc_filter_nulls
93d9db86208702219bcd9c4fd373f29e6d23fdc753d4d08be78c93fabc9a9376
namin/reflection-schemes
os_tests.scm
(define (factorial-process n) (full-copy `((:exp . (begin (if (= n 0) (set! :done #t) (begin (set! result (* n result)) (set! n (- n 1)))) result)) (:env . ((result . 1) (n . ,n)))))) (define (double-process p) (full-copy-but (list p) `((:exp . (begin (block p) (set! result (* 2 (get (get p ':env) ':result #f))) (set! :done #t) result)) (:env . ((:result . #f) (p . ,p)))))) (eg (run (factorial-process 6)) '((result . 6) (n . 5) (:result . 6) )) (eg (let ((f6 (factorial-process 6))) (step* (list f6)) (get (get f6 ':env) ':result)) 720) (eg (run-only (factorial-process 6)) 720) (eg (let ((f6 (factorial-process 6)) (f5 (factorial-process 5))) (step* (list f6 f5)) (list (get (get f6 ':env) ':result) (get (get f5 ':env) ':result))) '(720 120)) (eg (let ((d6 (double-process (factorial-process 6)))) (set! alive-processes (list d6)) (step*!) (get (get d6 ':env) ':result)) 1440) (eg (run-program-once '(* 1 2 3)) 6)
null
https://raw.githubusercontent.com/namin/reflection-schemes/d3fd61aa7edc8af5f7f2c9783b4e3c5356cd2bd5/01-toyos-jit/os_tests.scm
scheme
(define (factorial-process n) (full-copy `((:exp . (begin (if (= n 0) (set! :done #t) (begin (set! result (* n result)) (set! n (- n 1)))) result)) (:env . ((result . 1) (n . ,n)))))) (define (double-process p) (full-copy-but (list p) `((:exp . (begin (block p) (set! result (* 2 (get (get p ':env) ':result #f))) (set! :done #t) result)) (:env . ((:result . #f) (p . ,p)))))) (eg (run (factorial-process 6)) '((result . 6) (n . 5) (:result . 6) )) (eg (let ((f6 (factorial-process 6))) (step* (list f6)) (get (get f6 ':env) ':result)) 720) (eg (run-only (factorial-process 6)) 720) (eg (let ((f6 (factorial-process 6)) (f5 (factorial-process 5))) (step* (list f6 f5)) (list (get (get f6 ':env) ':result) (get (get f5 ':env) ':result))) '(720 120)) (eg (let ((d6 (double-process (factorial-process 6)))) (set! alive-processes (list d6)) (step*!) (get (get d6 ':env) ':result)) 1440) (eg (run-program-once '(* 1 2 3)) 6)
5d08bd16cf643c3c01547d962102537d09a501471a450030655ba2357acd6681
ekmett/reactive
Merge.hs
-- Tracking down a problem with event merging import Data.Monoid (mappend) import Control.Applicative ((<$>)) import FRP.Reactive.Improving import FRP.Reactive.Future import FRP.Reactive.PrimReactive import FRP.Reactive.Reactive import FRP.Reactive.Internal.Future import FRP.Reactive.Internal.Reactive -- (Imp 1.0,1)->(Imp 2.0,2)->(Imp 3.0,3)->(Imp *** Exception: Prelude.undefined e1 = listEG [(exactly 1,1),(exactly 2,2),(exactly 3,3),(after 4,17)] ( Imp 1.5,100)->(Imp 2.5,200 ) e2 = listEG [(exactly 1.5, 100), (exactly 2.5, 200)] -- (Imp *** Exception: Prelude.undefined e3 = listEG [(after 2.5, 200)] -- (Imp 1.5,100)->(Imp 2.3,200)->(Imp *** Exception: Prelude.undefined e3' = listEG [(exactly 1.5, 100), (exactly 2.3, 200), (after 2.5, 300)] -- (Imp 1.0,1)->(Imp 1.5,100)->(Imp 2.0,2)->(Imp 2.5,200)->(Imp 3.0,3)->(Imp *** Exception: Prelude.undefined e4 = e1 `mappend` e2 -- (Imp 1.0,1)->(Imp 2.0,2)<interactive>: after: comparing after e5 = e1 `mappend` e3 ( Imp 1.0,1)->(Imp 1.5,100)->(Imp 2.0,2)->(Imp 2.3,200)<interactive > : after : comparing after e5' = e1 `mappend` e3' < 1.0,1 ` Stepper ` ( Imp 2.0,2)->(Imp 3.0,3)->(Imp * * * Exception : Prelude.undefined f1 = eFuture e1 < 1.5,100 ` Stepper ` ( Imp 2.5,200 ) > f2 = eFuture e2 < * * * Exception : Prelude.undefined f3 = eFuture e3 < 1.0,1 ` Stepper ` ( Imp 2.0,2)->(Imp 3.0,3)->(Imp * * * Exception : Prelude.undefined f4 = f1 `mappend` f3 < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f5 = f1 `merge` f3 < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f5' = eFuture e5 -- type Binop a = a -> a -> a mergeLR, mergeL, mergeR :: (Ord s) => Binop (FutureG s (ReactiveG s b)) -- Same as 'merge' u `mergeLR` v = (inFutR (`merge` v) <$> u) `mappend` (inFutR (u `merge`) <$> v) u `mergeL` v = inFutR (`merge` v) <$> u u `mergeR` v = inFutR (u `merge`) <$> v inFutR : : ( FutureG s ( ReactiveG s b ) - > FutureG t ( ReactiveG t b ) ) -- -> (ReactiveG s b -> ReactiveG t b) < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f6 = f1 `mergeLR` f3 < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f7 :: Future (Reactive Integer) f7 = f1 `mergeL` f3 < * * * Exception : Prelude.undefined f8 = f1 `mergeR` f3 f7' :: Future (Reactive Integer) < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f7' = q <$> f1 where q (a `Stepper` Event u') = a `Stepper` Event (u' `merge` f3)
null
https://raw.githubusercontent.com/ekmett/reactive/61b20b7a2e92af372b5bd9a2af294db0fbdfa9d8/src/Test/Merge.hs
haskell
Tracking down a problem with event merging (Imp 1.0,1)->(Imp 2.0,2)->(Imp 3.0,3)->(Imp *** Exception: Prelude.undefined (Imp *** Exception: Prelude.undefined (Imp 1.5,100)->(Imp 2.3,200)->(Imp *** Exception: Prelude.undefined (Imp 1.0,1)->(Imp 1.5,100)->(Imp 2.0,2)->(Imp 2.5,200)->(Imp 3.0,3)->(Imp *** Exception: Prelude.undefined (Imp 1.0,1)->(Imp 2.0,2)<interactive>: after: comparing after Same as 'merge' -> (ReactiveG s b -> ReactiveG t b)
import Data.Monoid (mappend) import Control.Applicative ((<$>)) import FRP.Reactive.Improving import FRP.Reactive.Future import FRP.Reactive.PrimReactive import FRP.Reactive.Reactive import FRP.Reactive.Internal.Future import FRP.Reactive.Internal.Reactive e1 = listEG [(exactly 1,1),(exactly 2,2),(exactly 3,3),(after 4,17)] ( Imp 1.5,100)->(Imp 2.5,200 ) e2 = listEG [(exactly 1.5, 100), (exactly 2.5, 200)] e3 = listEG [(after 2.5, 200)] e3' = listEG [(exactly 1.5, 100), (exactly 2.3, 200), (after 2.5, 300)] e4 = e1 `mappend` e2 e5 = e1 `mappend` e3 ( Imp 1.0,1)->(Imp 1.5,100)->(Imp 2.0,2)->(Imp 2.3,200)<interactive > : after : comparing after e5' = e1 `mappend` e3' < 1.0,1 ` Stepper ` ( Imp 2.0,2)->(Imp 3.0,3)->(Imp * * * Exception : Prelude.undefined f1 = eFuture e1 < 1.5,100 ` Stepper ` ( Imp 2.5,200 ) > f2 = eFuture e2 < * * * Exception : Prelude.undefined f3 = eFuture e3 < 1.0,1 ` Stepper ` ( Imp 2.0,2)->(Imp 3.0,3)->(Imp * * * Exception : Prelude.undefined f4 = f1 `mappend` f3 < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f5 = f1 `merge` f3 < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f5' = eFuture e5 type Binop a = a -> a -> a mergeLR, mergeL, mergeR :: (Ord s) => Binop (FutureG s (ReactiveG s b)) u `mergeLR` v = (inFutR (`merge` v) <$> u) `mappend` (inFutR (u `merge`) <$> v) u `mergeL` v = inFutR (`merge` v) <$> u u `mergeR` v = inFutR (u `merge`) <$> v inFutR : : ( FutureG s ( ReactiveG s b ) - > FutureG t ( ReactiveG t b ) ) < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f6 = f1 `mergeLR` f3 < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f7 :: Future (Reactive Integer) f7 = f1 `mergeL` f3 < * * * Exception : Prelude.undefined f8 = f1 `mergeR` f3 f7' :: Future (Reactive Integer) < 1.0,1 ` Stepper ` ( Imp 2.0,2)<interactive > : after : comparing after f7' = q <$> f1 where q (a `Stepper` Event u') = a `Stepper` Event (u' `merge` f3)
c1d80f19e70222062fe214554ea62948119ad601c81c5ddbbbea3f490a607315
fluentpython/lispy
chap9f.scm
$ I d : chap9f.scm , v 4.0 1995/07/10 06:52:22 queinnec Exp $ ;;;(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) ;;; This file is part of the files that accompany the book: LISP Implantation Semantique Programmation ( InterEditions , France ) By Christian Queinnec < > ;;; Newest version may be retrieved from: ( IP 128.93.2.54 ) ftp.inria.fr : INRIA / Projects / icsla / Books / LiSP*.tar.gz ;;; Check the README file before using this file. ;;;(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) Only one world (define (make-macro-environment current-level) (let ((metalevel (delay current-level))) (list (make-Magic-Keyword 'eval-in-abbreviation-world (special-eval-in-abbreviation-world metalevel) ) (make-Magic-Keyword 'define-abbreviation (special-define-abbreviation metalevel)) (make-Magic-Keyword 'let-abbreviation (special-let-abbreviation metalevel)) (make-Magic-Keyword 'with-aliases (special-with-aliases metalevel) ) ) ) ) ;;; end of chap9f.scm
null
https://raw.githubusercontent.com/fluentpython/lispy/6b995c398e2d100fc3fc292e34ba1a00c0ae9b5a/references/LiSP-2ndEdition-2006Dec11/src/chap9f.scm
scheme
(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) This file is part of the files that accompany the book: Newest version may be retrieved from: Check the README file before using this file. (((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) end of chap9f.scm
$ I d : chap9f.scm , v 4.0 1995/07/10 06:52:22 queinnec Exp $ LISP Implantation Semantique Programmation ( InterEditions , France ) By Christian Queinnec < > ( IP 128.93.2.54 ) ftp.inria.fr : INRIA / Projects / icsla / Books / LiSP*.tar.gz Only one world (define (make-macro-environment current-level) (let ((metalevel (delay current-level))) (list (make-Magic-Keyword 'eval-in-abbreviation-world (special-eval-in-abbreviation-world metalevel) ) (make-Magic-Keyword 'define-abbreviation (special-define-abbreviation metalevel)) (make-Magic-Keyword 'let-abbreviation (special-let-abbreviation metalevel)) (make-Magic-Keyword 'with-aliases (special-with-aliases metalevel) ) ) ) )
0d7d50e5bf92f467287eda80690d1ead4b243e7b6769019eb96c258eae3b54e9
satori-com/mzbench
mzb_staticcloud_plugin.erl
-module(mzb_staticcloud_plugin). -behaviour(gen_server). -export([ start/2, create_cluster/3, destroy_cluster/1 ]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %%%=================================================================== %%% API %%%=================================================================== start(Name, Opts) -> Spec = {Name, _MFA = {gen_server, start_link, [?MODULE, [Opts], []]}, permanent, 5000, worker, [?MODULE]}, case supervisor:start_child(mzb_api_sup, Spec) of {ok, Child} -> Child; {error, {already_started, Child}} -> Child end. create_cluster(Pid, N, _Config) -> case lock_hosts(Pid, N) of {ok, User, L} -> {ok, {Pid, L}, User, L}; {error, locked} -> erlang:error(hosts_are_busy) end. destroy_cluster({Pid, Hosts}) -> gen_server:call(Pid, {unlock_hosts, Hosts}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== init([Opts]) -> Hosts = mzb_bc:maps_get(hosts, Opts, ["localhost"]), {Hostnames, Username} = parse_hosts(Hosts), {ok, #{hosts => Hostnames, user_name => Username, hosts_locked => []}}. handle_call({lock_hosts, _}, _, #{hosts:= [Host], hosts_locked:= [], user_name:= User} = State) -> {reply, {ok, User, [Host]}, State#{hosts_locked => [Host]}}; handle_call({lock_hosts, N}, _, #{hosts:= Hosts, hosts_locked:= Locked, user_name:= User} = State) -> Available = lists:subtract(Hosts, Locked), case erlang:length(Available) of A when A < N -> {reply, {error, locked}, State}; _ -> {Result, _} = lists:split(N, Available), {reply, {ok, User, Result}, State#{hosts_locked => Locked ++ Result}} end; handle_call({unlock_hosts, Hosts}, _, #{hosts_locked := Locked} = State) -> {reply, ok, State#{hosts_locked => lists:subtract(Locked, Hosts)}}; handle_call(Request, _From, State) -> lager:error("Unhandled call: ~p ~p", [Request, State]), {noreply, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== parse_hosts(Hosts) -> lists:mapfoldl( fun (Host, Acc) -> case string:tokens(Host, "@") of [U, H] -> {H, U}; [H] -> {H, Acc} end end, undefined, lists:reverse(Hosts)). lock_hosts(Pid, N) -> lock_hosts(Pid, N, 60). lock_hosts(_Pid, _, Attempts) when Attempts =< 0 -> {error, locked}; lock_hosts(Pid, N, Attempts) -> case gen_server:call(Pid, {lock_hosts, N}) of {ok, U, L} when is_list(L) -> {ok, U, L}; {error, locked} -> timer:sleep(1000), lock_hosts(Pid, N, Attempts - 1) end.
null
https://raw.githubusercontent.com/satori-com/mzbench/02be2684655cde94d537c322bb0611e258ae9718/server/src/mzb_staticcloud_plugin.erl
erlang
gen_server callbacks =================================================================== API =================================================================== =================================================================== gen_server callbacks =================================================================== =================================================================== ===================================================================
-module(mzb_staticcloud_plugin). -behaviour(gen_server). -export([ start/2, create_cluster/3, destroy_cluster/1 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). start(Name, Opts) -> Spec = {Name, _MFA = {gen_server, start_link, [?MODULE, [Opts], []]}, permanent, 5000, worker, [?MODULE]}, case supervisor:start_child(mzb_api_sup, Spec) of {ok, Child} -> Child; {error, {already_started, Child}} -> Child end. create_cluster(Pid, N, _Config) -> case lock_hosts(Pid, N) of {ok, User, L} -> {ok, {Pid, L}, User, L}; {error, locked} -> erlang:error(hosts_are_busy) end. destroy_cluster({Pid, Hosts}) -> gen_server:call(Pid, {unlock_hosts, Hosts}). init([Opts]) -> Hosts = mzb_bc:maps_get(hosts, Opts, ["localhost"]), {Hostnames, Username} = parse_hosts(Hosts), {ok, #{hosts => Hostnames, user_name => Username, hosts_locked => []}}. handle_call({lock_hosts, _}, _, #{hosts:= [Host], hosts_locked:= [], user_name:= User} = State) -> {reply, {ok, User, [Host]}, State#{hosts_locked => [Host]}}; handle_call({lock_hosts, N}, _, #{hosts:= Hosts, hosts_locked:= Locked, user_name:= User} = State) -> Available = lists:subtract(Hosts, Locked), case erlang:length(Available) of A when A < N -> {reply, {error, locked}, State}; _ -> {Result, _} = lists:split(N, Available), {reply, {ok, User, Result}, State#{hosts_locked => Locked ++ Result}} end; handle_call({unlock_hosts, Hosts}, _, #{hosts_locked := Locked} = State) -> {reply, ok, State#{hosts_locked => lists:subtract(Locked, Hosts)}}; handle_call(Request, _From, State) -> lager:error("Unhandled call: ~p ~p", [Request, State]), {noreply, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions parse_hosts(Hosts) -> lists:mapfoldl( fun (Host, Acc) -> case string:tokens(Host, "@") of [U, H] -> {H, U}; [H] -> {H, Acc} end end, undefined, lists:reverse(Hosts)). lock_hosts(Pid, N) -> lock_hosts(Pid, N, 60). lock_hosts(_Pid, _, Attempts) when Attempts =< 0 -> {error, locked}; lock_hosts(Pid, N, Attempts) -> case gen_server:call(Pid, {lock_hosts, N}) of {ok, U, L} when is_list(L) -> {ok, U, L}; {error, locked} -> timer:sleep(1000), lock_hosts(Pid, N, Attempts - 1) end.
3eee23d667c51b828182df7078994e999dc379590065be42150ff593bd57ad57
gs0510/ofronds
b_type_declarations.ml
(* OCaml is strongly typed; types are often inferred by the compiler. It's possible to declare types inline as done in this exercise, but that's not a common practice. *) let x : int = 5 let y : float = "hello"
null
https://raw.githubusercontent.com/gs0510/ofronds/e2f614dbdafab1ac5088afbd29b45451784ea896/exercises/1.variables/b_type_declarations/b_type_declarations.ml
ocaml
OCaml is strongly typed; types are often inferred by the compiler. It's possible to declare types inline as done in this exercise, but that's not a common practice.
let x : int = 5 let y : float = "hello"
7fa40ea77fa699691d0500cfabc9946afdd7115f8faefc1d851633532cee5c34
racketscript/racketscript
info.rkt
#lang info (define collection 'multi) (define version "0.1") (define deps '("base" ["racket" "6.4"] "typed-racket-lib" "typed-racket-more" "threading-lib" "graph-lib" "anaphoric")) (define build-deps '("base" "typed-racket-lib" "typed-racket-more" "rackunit-lib")) (define pkg-authors '(vishesh)) (define pkg-desc "Racket to JavaScript compiler") (define post-install-collection "") ;; Test configuration (define test-omit-paths '("racketscript/browser.rkt" "racketscript/compiler/runtime/")) ;; Coverage (define cover-omit-paths '("racketscript/browser.rkt" "racketscript/compiler/runtime/kernel.rkt" "racketscript/compiler/runtime/paramz.rkt" "racketscript/compiler/runtime/unsafe.rkt"))
null
https://raw.githubusercontent.com/racketscript/racketscript/07e908679fe1f86b812a30d5b91314dd5c500e4f/racketscript-compiler/info.rkt
racket
Test configuration Coverage
#lang info (define collection 'multi) (define version "0.1") (define deps '("base" ["racket" "6.4"] "typed-racket-lib" "typed-racket-more" "threading-lib" "graph-lib" "anaphoric")) (define build-deps '("base" "typed-racket-lib" "typed-racket-more" "rackunit-lib")) (define pkg-authors '(vishesh)) (define pkg-desc "Racket to JavaScript compiler") (define post-install-collection "") (define test-omit-paths '("racketscript/browser.rkt" "racketscript/compiler/runtime/")) (define cover-omit-paths '("racketscript/browser.rkt" "racketscript/compiler/runtime/kernel.rkt" "racketscript/compiler/runtime/paramz.rkt" "racketscript/compiler/runtime/unsafe.rkt"))
fbe81f437e85f4487de3c116d225c9307b92c23e9651777a2246cbbed7f04966
raptazure/experiments
Main.hs
import qualified Data.Map as Map data Bool = False | True deriving ( ) data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) surface :: Shape -> Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1) nudge :: Shape -> Float -> Float -> Shape nudge (Circle (Point x y) r) a b = Circle (Point (x + a) (y + b)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = Rectangle (Point (x1 + a) (y1 + b)) (Point (x2 + a) (y2 + b)) nudge ( Circle ( Point 34 34 ) 10 ) 5 10 baseCircle :: Float -> Shape baseCircle r = Circle (Point 0 0) r baseRect :: Float -> Float -> Shape baseRect width height = Rectangle (Point 0 0) (Point width height) -- module Shapes -- ( Point(..) -- , Shape(..) -- , surface -- , nudge , baseCircle -- , baseRect -- ) where data Person = Person { firstName :: String, lastName :: String, age :: Int } deriving (Show, Eq, Read) -- :t age read " Person { firstName = \"Michael\ " , lastName = \"Diamond\ " , age = 43 } " = = mikeD data Car = Car {company :: String, model :: String, year :: Int} deriving (Show) -- Car {company="Ford", model="Mustang", year=1967} tellCar :: Car -> String tellCar (Car {company = c, model = m, year = y}) = "This " ++ c ++ " " ++ m ++ " was made in " ++ show y data Vector a = Vector a a a deriving (Show) vplus :: (Num t) => Vector t -> Vector t -> Vector t (Vector i j k) `vplus` (Vector l m n) = Vector (i + l) (j + m) (k + n) vectMult :: (Num t) => Vector t -> t -> Vector t (Vector i j k) `vectMult` m = Vector (i * m) (j * m) (k * m) scalarMult :: (Num t) => Vector t -> Vector t -> t (Vector i j k) `scalarMult` (Vector l m n) = i * l + j * m + k * n data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Ord, Show, Read, Bounded, Enum) [ minBound .. maxBound ] : : [ Day ] succ Monday type String = [ ] type PhoneNumber = String type Name = String type PhoneBook = [(Name, PhoneNumber)] inPhoneBook :: Name -> PhoneNumber -> PhoneBook -> Bool inPhoneBook name pnumber pbook = (name, pnumber) `elem` pbook type AssocList k v = [(k, v)] data Either a b = Left a | Right b deriving ( Eq , Ord , Read , Show ) data LockerState = Taken | Free deriving (Show, Eq) type Code = String type LockerMap = Map.Map Int (LockerState, Code) lockerLookup :: Int -> LockerMap -> Either String Code lockerLookup lockerNumber map = case Map.lookup lockerNumber map of Nothing -> Left $ "Locker number " ++ show lockerNumber ++ " doesn't exist!" Just (state, code) -> if state /= Taken then Right code else Left $ "Locker " ++ show lockerNumber ++ " is already taken!" lockers :: LockerMap lockers = Map.fromList [ (100, (Taken, "ZD39I")), (101, (Free, "JAH3I")), (103, (Free, "IQSA9")), (105, (Free, "QOTSA")), (109, (Taken, "893JJ")), (110, (Taken, "99292")) ] lockerLookup 100 lockers lockerLookup 102 lockers data List a = Empty | Cons { listHead : : a , listTail : : List a } deriving ( Show , Read , Eq , Ord ) infixr 5 :-: data List a = Empty | a :-: (List a) deriving (Show, Read, Eq, Ord) 3 : - : 4 : - : 5 : - : Empty infixr 5 + + -- (++) :: [a] -> [a] -> [a] -- [] ++ ys = ys -- (x:xs) ++ ys = x : (xs ++ ys) infixr 5 .++ (.++) :: List a -> List a -> List a Empty .++ ys = ys (x :-: xs) .++ ys = x :-: (xs .++ ys) data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) singleton :: a -> Tree a singleton x = Node x EmptyTree EmptyTree treeInsert :: (Ord a) => a -> Tree a -> Tree a treeInsert x EmptyTree = singleton x treeInsert x (Node a left right) | x == a = Node x left right | x < a = Node a (treeInsert x left) right | x > a = Node a left (treeInsert x right) treeElem :: (Ord a) => a -> Tree a -> Bool treeElem x EmptyTree = False treeElem x (Node a left right) | x == a = True | x < a = treeElem x left | x > a = treeElem x right nums = [8, 6, 4, 1, 7, 3, 5] numsTree = foldr treeInsert EmptyTree nums insideTree = 1 `treeElem` numsTree class Eq a where -- (==) :: a -> a -> Bool -- (/=) :: a -> a -> Bool -- x == y = not (x /= y) -- x /= y = not (x == y) data TrafficLight = Red | Yellow | Green instance Eq TrafficLight where Red == Red = True Green == Green = True Yellow == Yellow = True _ == _ = False instance Show TrafficLight where show Red = "Red light" show Yellow = "Yellow light" show Green = "Green light" class ( Eq a ) = > a where -- instance (Eq m) => Eq (Maybe m) where -- Just x == Just y = x == y -- Nothing == Nothing = True -- _ == _ = False : info class YesNo a where yesno :: a -> Bool instance YesNo Int where yesno 0 = False yesno _ = True instance YesNo [a] where yesno [] = False yesno _ = True instance YesNo Bool where -- id return the same as input yesno = id instance YesNo (Maybe a) where yesno (Just _) = True yesno Nothing = False instance YesNo (Tree a) where yesno EmptyTree = False yesno _ = True instance YesNo TrafficLight where yesno Red = False yesno _ = True ysenoIf :: (YesNo y) => y -> a -> a -> a ysenoIf yesnoVal yesResult noResult = if yesno yesnoVal then yesResult else noResult functor ( map over ? ) -- class Functor f where -- fmap :: (a -> b) -> f a -> f b -- instance Functor [] where -- fmap = map -- instance Functor Maybe where -- fmap f (Just x) = Just (f x) -- fmap f Nothing = Nothing instance Functor Tree where fmap f EmptyTree = EmptyTree fmap f (Node x leftsub rightsub) = Node (f x) (fmap f leftsub) (fmap f rightsub) mapTree = fmap (* 4) (foldr treeInsert EmptyTree [5, 7, 3, 2, 1, 7]) instance ( Either a ) where -- fmap f (Right x) = Right (f x) -- fmap f (Left x) = Left x -- :k Int class Tofu t where tofu :: j a -> t a j data Frank a b = Frank {frankField :: b a} deriving (Show) instance Tofu Frank where tofu x = Frank x tofu ( Just ' a ' ) : : Maybe tofu [ " HELLO " ] : : ] [ ] data Barry t k p = Barry {yabba :: p, dabba :: t k} instance Functor (Barry a b) where fmap f (Barry {yabba = x, dabba = y}) = Barry {yabba = f x, dabba = y}
null
https://raw.githubusercontent.com/raptazure/experiments/c48263980d1ce22ee9407ff8dcf0cf5091b01c70/haskell/learnyouahaskell/ch08/Main.hs
haskell
module Shapes ( Point(..) , Shape(..) , surface , nudge , baseRect ) where :t age Car {company="Ford", model="Mustang", year=1967} (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) (==) :: a -> a -> Bool (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y) instance (Eq m) => Eq (Maybe m) where Just x == Just y = x == y Nothing == Nothing = True _ == _ = False id return the same as input class Functor f where fmap :: (a -> b) -> f a -> f b instance Functor [] where fmap = map instance Functor Maybe where fmap f (Just x) = Just (f x) fmap f Nothing = Nothing fmap f (Right x) = Right (f x) fmap f (Left x) = Left x :k Int
import qualified Data.Map as Map data Bool = False | True deriving ( ) data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) surface :: Shape -> Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1) nudge :: Shape -> Float -> Float -> Shape nudge (Circle (Point x y) r) a b = Circle (Point (x + a) (y + b)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = Rectangle (Point (x1 + a) (y1 + b)) (Point (x2 + a) (y2 + b)) nudge ( Circle ( Point 34 34 ) 10 ) 5 10 baseCircle :: Float -> Shape baseCircle r = Circle (Point 0 0) r baseRect :: Float -> Float -> Shape baseRect width height = Rectangle (Point 0 0) (Point width height) , baseCircle data Person = Person { firstName :: String, lastName :: String, age :: Int } deriving (Show, Eq, Read) read " Person { firstName = \"Michael\ " , lastName = \"Diamond\ " , age = 43 } " = = mikeD data Car = Car {company :: String, model :: String, year :: Int} deriving (Show) tellCar :: Car -> String tellCar (Car {company = c, model = m, year = y}) = "This " ++ c ++ " " ++ m ++ " was made in " ++ show y data Vector a = Vector a a a deriving (Show) vplus :: (Num t) => Vector t -> Vector t -> Vector t (Vector i j k) `vplus` (Vector l m n) = Vector (i + l) (j + m) (k + n) vectMult :: (Num t) => Vector t -> t -> Vector t (Vector i j k) `vectMult` m = Vector (i * m) (j * m) (k * m) scalarMult :: (Num t) => Vector t -> Vector t -> t (Vector i j k) `scalarMult` (Vector l m n) = i * l + j * m + k * n data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Ord, Show, Read, Bounded, Enum) [ minBound .. maxBound ] : : [ Day ] succ Monday type String = [ ] type PhoneNumber = String type Name = String type PhoneBook = [(Name, PhoneNumber)] inPhoneBook :: Name -> PhoneNumber -> PhoneBook -> Bool inPhoneBook name pnumber pbook = (name, pnumber) `elem` pbook type AssocList k v = [(k, v)] data Either a b = Left a | Right b deriving ( Eq , Ord , Read , Show ) data LockerState = Taken | Free deriving (Show, Eq) type Code = String type LockerMap = Map.Map Int (LockerState, Code) lockerLookup :: Int -> LockerMap -> Either String Code lockerLookup lockerNumber map = case Map.lookup lockerNumber map of Nothing -> Left $ "Locker number " ++ show lockerNumber ++ " doesn't exist!" Just (state, code) -> if state /= Taken then Right code else Left $ "Locker " ++ show lockerNumber ++ " is already taken!" lockers :: LockerMap lockers = Map.fromList [ (100, (Taken, "ZD39I")), (101, (Free, "JAH3I")), (103, (Free, "IQSA9")), (105, (Free, "QOTSA")), (109, (Taken, "893JJ")), (110, (Taken, "99292")) ] lockerLookup 100 lockers lockerLookup 102 lockers data List a = Empty | Cons { listHead : : a , listTail : : List a } deriving ( Show , Read , Eq , Ord ) infixr 5 :-: data List a = Empty | a :-: (List a) deriving (Show, Read, Eq, Ord) 3 : - : 4 : - : 5 : - : Empty infixr 5 + + infixr 5 .++ (.++) :: List a -> List a -> List a Empty .++ ys = ys (x :-: xs) .++ ys = x :-: (xs .++ ys) data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) singleton :: a -> Tree a singleton x = Node x EmptyTree EmptyTree treeInsert :: (Ord a) => a -> Tree a -> Tree a treeInsert x EmptyTree = singleton x treeInsert x (Node a left right) | x == a = Node x left right | x < a = Node a (treeInsert x left) right | x > a = Node a left (treeInsert x right) treeElem :: (Ord a) => a -> Tree a -> Bool treeElem x EmptyTree = False treeElem x (Node a left right) | x == a = True | x < a = treeElem x left | x > a = treeElem x right nums = [8, 6, 4, 1, 7, 3, 5] numsTree = foldr treeInsert EmptyTree nums insideTree = 1 `treeElem` numsTree class Eq a where data TrafficLight = Red | Yellow | Green instance Eq TrafficLight where Red == Red = True Green == Green = True Yellow == Yellow = True _ == _ = False instance Show TrafficLight where show Red = "Red light" show Yellow = "Yellow light" show Green = "Green light" class ( Eq a ) = > a where : info class YesNo a where yesno :: a -> Bool instance YesNo Int where yesno 0 = False yesno _ = True instance YesNo [a] where yesno [] = False yesno _ = True instance YesNo Bool where yesno = id instance YesNo (Maybe a) where yesno (Just _) = True yesno Nothing = False instance YesNo (Tree a) where yesno EmptyTree = False yesno _ = True instance YesNo TrafficLight where yesno Red = False yesno _ = True ysenoIf :: (YesNo y) => y -> a -> a -> a ysenoIf yesnoVal yesResult noResult = if yesno yesnoVal then yesResult else noResult functor ( map over ? ) instance Functor Tree where fmap f EmptyTree = EmptyTree fmap f (Node x leftsub rightsub) = Node (f x) (fmap f leftsub) (fmap f rightsub) mapTree = fmap (* 4) (foldr treeInsert EmptyTree [5, 7, 3, 2, 1, 7]) instance ( Either a ) where class Tofu t where tofu :: j a -> t a j data Frank a b = Frank {frankField :: b a} deriving (Show) instance Tofu Frank where tofu x = Frank x tofu ( Just ' a ' ) : : Maybe tofu [ " HELLO " ] : : ] [ ] data Barry t k p = Barry {yabba :: p, dabba :: t k} instance Functor (Barry a b) where fmap f (Barry {yabba = x, dabba = y}) = Barry {yabba = f x, dabba = y}
fd1b512ecd85942d6b3ce36025007d26994496d60670045c5bd67ba9652cef38
protz/mezzo
Types.mli
(*****************************************************************************) (* Mezzo, a programming language based on permissions *) Copyright ( C ) 2011 , 2012 and (* *) (* This program is free software: you can redistribute it and/or modify *) it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or (* (at your option) any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) You should have received a copy of the GNU General Public License (* along with this program. If not, see </>. *) (* *) (*****************************************************************************) * This module provides a variety of functions for dealing with types , mostly * built on top of { ! } and { ! TypeCore } . * built on top of {!DeBruijn} and {!TypeCore}. *) open Kind open TypeCore (* -------------------------------------------------------------------------- *) (** {1 Convenient combinators.} *) * { 2 Dealing with triples . } val fst3 : 'a * 'b * 'c -> 'a val snd3 : 'a * 'b * 'c -> 'b val thd3 : 'a * 'b * 'c -> 'c * { 2 Operators } (** Asserts that this type is actually a [TyOpen]. *) val ( !! ) : typ -> var * Asserts that this type is actually a [ ( TyOpen ... ) ] . val ( !!= ) : typ -> var * This is { ! } . val ( !* ) : 'a Lazy.t -> 'a (** [bind] for the option monad. *) val ( >>= ) : 'a option -> ('a -> 'b option) -> 'b option (** [either] operator for the option monad *) val ( ||| ) : 'a option -> 'a option -> 'a option (** The standard implication connector, with the right associativity. *) val ( ^=> ) : bool -> bool -> bool (** The pipe operator. *) val ( |> ) : 'a -> ('a -> 'b) -> 'b (* -------------------------------------------------------------------------- *) * { 1 Normalizing types . } * These functions , when combined with { ! TypeCore.modulo_flex } , allow one to * manipulate a " canonical " representation of a type , where permissions have * been stripped out and unfoldings have been performed . One will still want to * use { ! Permissions.open_all_rigid_in } , though . * manipulate a "canonical" representation of a type, where permissions have * been stripped out and unfoldings have been performed. One will still want to * use {!Permissions.open_all_rigid_in}, though. *) * [ expand_if_one_branch env t ] expands [ t ] when [ t ] is either a type * abbreviation , or a data type with one branch . * abbreviation, or a data type with one branch. *) val expand_if_one_branch : env -> typ -> typ (** [collect t] syntactically separates [t] into a structural part and a * permission part, i.e. it extracts all the permissions hidden inside [t] and * returns them as a separate list. *) val collect : typ -> typ * typ list (* -------------------------------------------------------------------------- *) * { 1 Branches . } (** Data types have branches. A branch has a _parent_ data type. [branch] is the * type that represents an actual branch under a [TyConcrete]; a branch in a * data type definition can be any type, most functions return a [typ]. *) (** Given a [branch], get all the other branches of the parent type. *) val branches_for_branch: env -> branch -> typ list (** Given a [resolved_datacon], get all the other branches of the parent type. *) val branches_for_datacon: env -> resolved_datacon -> typ list (** Given a [resolved_datacon], get the corresponding branch. *) val branch_for_datacon: env -> resolved_datacon -> typ (** Given a [resolved_datacon], get all its fields. *) val fields_for_datacon: env -> resolved_datacon -> Field.name list (** Given a [resolved_datacon], get its flavor. *) val flavor_for_datacon: env -> resolved_datacon -> DataTypeFlavor.flavor (* -------------------------------------------------------------------------- *) (** {1 Manipulating types.} *) * { 2 Building types . } (** We provide a set of wrappers to easily build types. These often perform * extra checks. *) (** Shortcut for the empty tuple [TyTuple []]. *) val ty_unit : typ (** A tuple. *) val ty_tuple : typ list -> typ (** An arrow. The operator has the right associativity. *) val ( @-> ) : typ -> typ -> typ * [ ty_bar t1 t2 ] is [ TyBar ( t1 , t2 ) ] is [ t2 ] is not [ ] , [ t1 ] otherwise . val ty_bar : typ -> typ -> typ * [ ty_app t ts ] is [ TyApp ( t , ts ) ] if [ ts > 0 ] , [ t ] otherwise . val ty_app : typ -> typ list -> typ * Shortcut for [ ( TyOpen _ ) ] . val ty_equals : var -> typ (** A open variable. *) val ty_open : var -> typ (** {2 Inspecting} *) (** We provide a set of wrappers to inspect types. *) (** Works with either [TyOpen] or [TyApp]. *) val is_tyapp : typ -> (var * typ list) option (** Calls [modulo_flex] and [expand_if_one_branch] before determining whether * it's a [TyStar] or not. *) val is_star : env -> typ -> bool (** Is this a concrete type? *) val is_concrete : typ -> bool (** If you know this is a concrete type, extract the [branch]. *) val assert_concrete : typ -> branch (** Is this an open variable? *) val is_tyopen : typ -> bool (** Determines whether a variable corresponds to a type abbreviation definition. *) val is_abbrev: env -> var -> bool (** Has this variable kind [term]? *) val is_term : env -> var -> bool (** Has this variable kind [perm]? *) val is_perm : env -> var -> bool (** Has this variable kind [type]? *) val is_type : env -> var -> bool (** Is this name user-provided? *) val is_user : name -> bool (** {2 Folding and flattening} *) (** Transform a [TyStar] into a flat list of permissions. This function performs * quite a bit of work to make sure there are no nested permissions: it calls * [modulo_flex] and [expand_if_one_branch] and extract all permissions nested * in [t] when it encounters [x @ t]. *) val flatten_star : env -> typ -> typ list * This function has a special case to make sure it does n't introduce useless * [ TyEmpty]s . * [TyEmpty]s. *) val fold_star : typ list -> typ (** Fold a type under a series of universal bindings. *) val fold_forall : (type_binding * flavor) list -> typ -> typ (** Fold a type under a series of existential bindings. *) val fold_exists : (type_binding * flavor) list -> typ -> typ (* -------------------------------------------------------------------------- *) * { 1 Type traversals } * all type variables reachable from a type , including via the ambient permissions . ambient permissions. *) val mark_reachable : env -> typ -> env (* -------------------------------------------------------------------------- *) (** {1 Binding and instantiating} *) * { 2 Binding types } (** [bind_datacon_parameters env k ts] takes the kind of the parent data type * [k], its branches [ts], and introduces open variables that stand for the data * type's parameters in all the branches. *) val bind_datacon_parameters : env -> kind -> typ list -> env * var list * typ list (** {2 Instantiation} *) (** [instantiate_type t ts] substitutes the givens types [t0, ..., tn] for * [TyBound 0, ... TyBound n] in [t]. *) val instantiate_type: typ -> typ list -> typ (** Find the branch and substitute the data type's parameters in it. *) val find_and_instantiate_branch : env -> var -> Datacon.name -> typ list -> typ (* -------------------------------------------------------------------------- *) (** {1 Miscellaneous} *) * { 2 Various getters } val get_location : env -> var -> location val get_adopts_clause : env -> var -> typ val get_arity : env -> var -> int val get_kind_for_type : env -> typ -> kind (** Get the variance of the i-th parameter of a data type. *) val variance : env -> var -> int -> variance val fresh_auto_name : string -> name val make_datacon_letters : env -> kind -> bool -> env * var list (** Our not-so-pretty printer for types. *) module TypePrinter : sig * Everything comes in two version : one that is suitable for use with * [ PPrint ] , another one that 's suitable for [ MzString . * " % a " ] . * [PPrint], another one that's suitable for [MzString.* "%a"]. *) val string_of_name: env -> name -> string (** Print the name of a variable, and pick the user-provided name, if any. *) val print_name : env -> name -> MzPprint.document val pname : Buffer.t -> env * name -> unit * Print a human - readable thing like " the subexpression blah " if blah is an * [ Auto ] name , or " the variable bli " if bli is a [ User ] name . * [Auto] name, or "the variable bli" if bli is a [User] name. *) val print_uservar : env -> var -> MzPprint.document val puvar : Buffer.t -> env * var -> unit (** Same thing as [print_name], except it's for a [var]. *) val print_var : env -> var -> MzPprint.document val pvar : Buffer.t -> env * var -> unit (** All the names. *) val print_names : env -> name list -> MzPprint.document val pnames : Buffer.t -> env * name list -> unit (** Print a set of permissions. *) val print_permission_list : env * typ list -> MzPprint.document val ppermission_list : Buffer.t -> env * var -> unit (** Print all the permissions from the environment. *) val print_permissions : env -> MzPprint.document val ppermissions : Buffer.t -> env -> unit val print_datacon : Datacon.name -> MzPprint.document val print_field_name : Field.name -> MzPprint.document val print_field : SurfaceSyntax.field -> MzPprint.document val p_kind : Buffer.t -> kind -> unit val print_quantified : env -> string -> name -> kind -> typ -> MzPprint.document val print_type : env -> typ -> MzPprint.document val print_constraint : env -> mode_constraint -> MzPprint.document val print_data_field_def : env -> data_field_def -> MzPprint.document val print_branch : env -> TypeCore.branch -> MzPprint.document val pfact : Buffer.t -> Fact.fact -> unit val print_facts : env -> MzPprint.document val ptype : Buffer.t -> env * typ -> unit val penv : Buffer.t -> env -> unit val pconstraint : Buffer.t -> env * mode_constraint -> unit val print_binders : env -> MzPprint.document end
null
https://raw.githubusercontent.com/protz/mezzo/4e9d917558bd96067437116341b7a6ea02ab9c39/typing/Types.mli
ocaml
*************************************************************************** Mezzo, a programming language based on permissions 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 GNU General Public License for more details. along with this program. If not, see </>. *************************************************************************** -------------------------------------------------------------------------- * {1 Convenient combinators.} * Asserts that this type is actually a [TyOpen]. * [bind] for the option monad. * [either] operator for the option monad * The standard implication connector, with the right associativity. * The pipe operator. -------------------------------------------------------------------------- * [collect t] syntactically separates [t] into a structural part and a * permission part, i.e. it extracts all the permissions hidden inside [t] and * returns them as a separate list. -------------------------------------------------------------------------- * Data types have branches. A branch has a _parent_ data type. [branch] is the * type that represents an actual branch under a [TyConcrete]; a branch in a * data type definition can be any type, most functions return a [typ]. * Given a [branch], get all the other branches of the parent type. * Given a [resolved_datacon], get all the other branches of the parent type. * Given a [resolved_datacon], get the corresponding branch. * Given a [resolved_datacon], get all its fields. * Given a [resolved_datacon], get its flavor. -------------------------------------------------------------------------- * {1 Manipulating types.} * We provide a set of wrappers to easily build types. These often perform * extra checks. * Shortcut for the empty tuple [TyTuple []]. * A tuple. * An arrow. The operator has the right associativity. * A open variable. * {2 Inspecting} * We provide a set of wrappers to inspect types. * Works with either [TyOpen] or [TyApp]. * Calls [modulo_flex] and [expand_if_one_branch] before determining whether * it's a [TyStar] or not. * Is this a concrete type? * If you know this is a concrete type, extract the [branch]. * Is this an open variable? * Determines whether a variable corresponds to a type abbreviation definition. * Has this variable kind [term]? * Has this variable kind [perm]? * Has this variable kind [type]? * Is this name user-provided? * {2 Folding and flattening} * Transform a [TyStar] into a flat list of permissions. This function performs * quite a bit of work to make sure there are no nested permissions: it calls * [modulo_flex] and [expand_if_one_branch] and extract all permissions nested * in [t] when it encounters [x @ t]. * Fold a type under a series of universal bindings. * Fold a type under a series of existential bindings. -------------------------------------------------------------------------- -------------------------------------------------------------------------- * {1 Binding and instantiating} * [bind_datacon_parameters env k ts] takes the kind of the parent data type * [k], its branches [ts], and introduces open variables that stand for the data * type's parameters in all the branches. * {2 Instantiation} * [instantiate_type t ts] substitutes the givens types [t0, ..., tn] for * [TyBound 0, ... TyBound n] in [t]. * Find the branch and substitute the data type's parameters in it. -------------------------------------------------------------------------- * {1 Miscellaneous} * Get the variance of the i-th parameter of a data type. * Our not-so-pretty printer for types. * Print the name of a variable, and pick the user-provided name, if any. * Same thing as [print_name], except it's for a [var]. * All the names. * Print a set of permissions. * Print all the permissions from the environment.
Copyright ( C ) 2011 , 2012 and it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License * This module provides a variety of functions for dealing with types , mostly * built on top of { ! } and { ! TypeCore } . * built on top of {!DeBruijn} and {!TypeCore}. *) open Kind open TypeCore * { 2 Dealing with triples . } val fst3 : 'a * 'b * 'c -> 'a val snd3 : 'a * 'b * 'c -> 'b val thd3 : 'a * 'b * 'c -> 'c * { 2 Operators } val ( !! ) : typ -> var * Asserts that this type is actually a [ ( TyOpen ... ) ] . val ( !!= ) : typ -> var * This is { ! } . val ( !* ) : 'a Lazy.t -> 'a val ( >>= ) : 'a option -> ('a -> 'b option) -> 'b option val ( ||| ) : 'a option -> 'a option -> 'a option val ( ^=> ) : bool -> bool -> bool val ( |> ) : 'a -> ('a -> 'b) -> 'b * { 1 Normalizing types . } * These functions , when combined with { ! TypeCore.modulo_flex } , allow one to * manipulate a " canonical " representation of a type , where permissions have * been stripped out and unfoldings have been performed . One will still want to * use { ! Permissions.open_all_rigid_in } , though . * manipulate a "canonical" representation of a type, where permissions have * been stripped out and unfoldings have been performed. One will still want to * use {!Permissions.open_all_rigid_in}, though. *) * [ expand_if_one_branch env t ] expands [ t ] when [ t ] is either a type * abbreviation , or a data type with one branch . * abbreviation, or a data type with one branch. *) val expand_if_one_branch : env -> typ -> typ val collect : typ -> typ * typ list * { 1 Branches . } val branches_for_branch: env -> branch -> typ list val branches_for_datacon: env -> resolved_datacon -> typ list val branch_for_datacon: env -> resolved_datacon -> typ val fields_for_datacon: env -> resolved_datacon -> Field.name list val flavor_for_datacon: env -> resolved_datacon -> DataTypeFlavor.flavor * { 2 Building types . } val ty_unit : typ val ty_tuple : typ list -> typ val ( @-> ) : typ -> typ -> typ * [ ty_bar t1 t2 ] is [ TyBar ( t1 , t2 ) ] is [ t2 ] is not [ ] , [ t1 ] otherwise . val ty_bar : typ -> typ -> typ * [ ty_app t ts ] is [ TyApp ( t , ts ) ] if [ ts > 0 ] , [ t ] otherwise . val ty_app : typ -> typ list -> typ * Shortcut for [ ( TyOpen _ ) ] . val ty_equals : var -> typ val ty_open : var -> typ val is_tyapp : typ -> (var * typ list) option val is_star : env -> typ -> bool val is_concrete : typ -> bool val assert_concrete : typ -> branch val is_tyopen : typ -> bool val is_abbrev: env -> var -> bool val is_term : env -> var -> bool val is_perm : env -> var -> bool val is_type : env -> var -> bool val is_user : name -> bool val flatten_star : env -> typ -> typ list * This function has a special case to make sure it does n't introduce useless * [ TyEmpty]s . * [TyEmpty]s. *) val fold_star : typ list -> typ val fold_forall : (type_binding * flavor) list -> typ -> typ val fold_exists : (type_binding * flavor) list -> typ -> typ * { 1 Type traversals } * all type variables reachable from a type , including via the ambient permissions . ambient permissions. *) val mark_reachable : env -> typ -> env * { 2 Binding types } val bind_datacon_parameters : env -> kind -> typ list -> env * var list * typ list val instantiate_type: typ -> typ list -> typ val find_and_instantiate_branch : env -> var -> Datacon.name -> typ list -> typ * { 2 Various getters } val get_location : env -> var -> location val get_adopts_clause : env -> var -> typ val get_arity : env -> var -> int val get_kind_for_type : env -> typ -> kind val variance : env -> var -> int -> variance val fresh_auto_name : string -> name val make_datacon_letters : env -> kind -> bool -> env * var list module TypePrinter : sig * Everything comes in two version : one that is suitable for use with * [ PPrint ] , another one that 's suitable for [ MzString . * " % a " ] . * [PPrint], another one that's suitable for [MzString.* "%a"]. *) val string_of_name: env -> name -> string val print_name : env -> name -> MzPprint.document val pname : Buffer.t -> env * name -> unit * Print a human - readable thing like " the subexpression blah " if blah is an * [ Auto ] name , or " the variable bli " if bli is a [ User ] name . * [Auto] name, or "the variable bli" if bli is a [User] name. *) val print_uservar : env -> var -> MzPprint.document val puvar : Buffer.t -> env * var -> unit val print_var : env -> var -> MzPprint.document val pvar : Buffer.t -> env * var -> unit val print_names : env -> name list -> MzPprint.document val pnames : Buffer.t -> env * name list -> unit val print_permission_list : env * typ list -> MzPprint.document val ppermission_list : Buffer.t -> env * var -> unit val print_permissions : env -> MzPprint.document val ppermissions : Buffer.t -> env -> unit val print_datacon : Datacon.name -> MzPprint.document val print_field_name : Field.name -> MzPprint.document val print_field : SurfaceSyntax.field -> MzPprint.document val p_kind : Buffer.t -> kind -> unit val print_quantified : env -> string -> name -> kind -> typ -> MzPprint.document val print_type : env -> typ -> MzPprint.document val print_constraint : env -> mode_constraint -> MzPprint.document val print_data_field_def : env -> data_field_def -> MzPprint.document val print_branch : env -> TypeCore.branch -> MzPprint.document val pfact : Buffer.t -> Fact.fact -> unit val print_facts : env -> MzPprint.document val ptype : Buffer.t -> env * typ -> unit val penv : Buffer.t -> env -> unit val pconstraint : Buffer.t -> env * mode_constraint -> unit val print_binders : env -> MzPprint.document end
4af6f30af4fc2de5426a80622ffbb7c65fe45d7feb0ec65a62bcf584d9b39217
GumTreeDiff/cgum
parsing_consistency_c.mli
* Copyright 2014 , INRIA * * This file is part of Cgen . Much of it comes from Coccinelle , which is * also available under the GPLv2 license * * Cgen 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 , according to version 2 of the License . * * Cgen is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with Cgen . If not , see < / > . * * The authors reserve the right to distribute this or future versions of * Cgen under other licenses . * Copyright 2014, INRIA * Julia Lawall * This file is part of Cgen. Much of it comes from Coccinelle, which is * also available under the GPLv2 license * * Cgen 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, according to version 2 of the License. * * Cgen is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cgen. If not, see </>. * * The authors reserve the right to distribute this or future versions of * Cgen under other licenses. *) # 0 "./parsing_consistency_c.mli" (* check consistency and possibly change some Ident expression into * TypeName, especially in argument to functions. *) val consistency_checking: Ast_c.program -> Ast_c.program
null
https://raw.githubusercontent.com/GumTreeDiff/cgum/8521aa80fcf4873a19e60ce8c846c886aaefb41b/parsing_c/parsing_consistency_c.mli
ocaml
check consistency and possibly change some Ident expression into * TypeName, especially in argument to functions.
* Copyright 2014 , INRIA * * This file is part of Cgen . Much of it comes from Coccinelle , which is * also available under the GPLv2 license * * Cgen 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 , according to version 2 of the License . * * Cgen is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with Cgen . If not , see < / > . * * The authors reserve the right to distribute this or future versions of * Cgen under other licenses . * Copyright 2014, INRIA * Julia Lawall * This file is part of Cgen. Much of it comes from Coccinelle, which is * also available under the GPLv2 license * * Cgen 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, according to version 2 of the License. * * Cgen is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cgen. If not, see </>. * * The authors reserve the right to distribute this or future versions of * Cgen under other licenses. *) # 0 "./parsing_consistency_c.mli" val consistency_checking: Ast_c.program -> Ast_c.program
0f3097f848b7d2c0291e2811e86ad4c2100165f2d7a7303a899ce1f929fff0cf
janestreet/file_path
relative.mli
* @inline
null
https://raw.githubusercontent.com/janestreet/file_path/ba8b499a6cc0e47bf949b292c07afd853b6b9a4a/src/relative.mli
ocaml
* @inline
56494537a2bf48b07b1c5108efb1b8b0588e36938a76cee034aab9647d7bc2d5
triffon/fp-2019-20
b-tests.rkt
#lang racket (require rackunit) (require "describe.rkt") (display "=== b - 1 ===\n") (describe sum-digit-divisors (check-equal? (sum-digit-divisors 46) 0) (check-equal? (sum-digit-divisors 52) 2) (check-equal? (sum-digit-divisors 222) 6) (check-equal? (sum-digit-divisors 123) 4) (check-equal? (sum-digit-divisors 3210) 6) (check-equal? (sum-digit-divisors 76398743) 0)) (describe same-sum (check-equal? (same-sum 42 42) 0) (check-equal? (same-sum 28 35) 2) (check-equal? (same-sum 1 30) 57)) (display "\n=== b - 2 ===\n") (define (prod* l) (apply * l)) (define (sum* l) (apply + l)) (describe best-metric? (check-equal? (best-metric? (list sum* prod*) '((0 1 2) (3 -4 5) (1337 0))) #t) (check-equal? (best-metric? (list car sum*) '((100 -100) (29 1) (42))) #f)) (display "\n=== b - 3 ===\n") (describe deep-delete (check-equal? (deep-delete '()) '()) (check-equal? (deep-delete '(())) '(())) ; the tricky test (check-equal? (deep-delete '(1 (2 (2 4) 1) 0 (3 (1)))) '(1 (2 (4)) (3 ()))))
null
https://raw.githubusercontent.com/triffon/fp-2019-20/7efb13ff4de3ea13baa2c5c59eb57341fac15641/exercises/computer-science-2/exam-01/b-tests.rkt
racket
the tricky test
#lang racket (require rackunit) (require "describe.rkt") (display "=== b - 1 ===\n") (describe sum-digit-divisors (check-equal? (sum-digit-divisors 46) 0) (check-equal? (sum-digit-divisors 52) 2) (check-equal? (sum-digit-divisors 222) 6) (check-equal? (sum-digit-divisors 123) 4) (check-equal? (sum-digit-divisors 3210) 6) (check-equal? (sum-digit-divisors 76398743) 0)) (describe same-sum (check-equal? (same-sum 42 42) 0) (check-equal? (same-sum 28 35) 2) (check-equal? (same-sum 1 30) 57)) (display "\n=== b - 2 ===\n") (define (prod* l) (apply * l)) (define (sum* l) (apply + l)) (describe best-metric? (check-equal? (best-metric? (list sum* prod*) '((0 1 2) (3 -4 5) (1337 0))) #t) (check-equal? (best-metric? (list car sum*) '((100 -100) (29 1) (42))) #f)) (display "\n=== b - 3 ===\n") (describe deep-delete (check-equal? (deep-delete '()) '()) (check-equal? (deep-delete '(1 (2 (2 4) 1) 0 (3 (1)))) '(1 (2 (4)) (3 ()))))
8af7c386e43cf8063bb3274445738000e52d6ecb7f47f09a6190a4d8889a3731
techascent/tech.parallel
next_item_fn.clj
(ns tech.parallel.next-item-fn) (defn create-next-item-fn "Given a sequence return a function that each time called (with no arguments) returns the next item in the sequence in a mutable fashion." [item-sequence] (let [primary-sequence (atom item-sequence)] (fn [] (loop [sequence @primary-sequence] (when-let [next-item (first sequence)] (if-not (compare-and-set! primary-sequence sequence (rest sequence)) (recur @primary-sequence) next-item))))))
null
https://raw.githubusercontent.com/techascent/tech.parallel/3d25ebe0e7260a4ebcc9ae48167c6a0937212ddd/src/tech/parallel/next_item_fn.clj
clojure
(ns tech.parallel.next-item-fn) (defn create-next-item-fn "Given a sequence return a function that each time called (with no arguments) returns the next item in the sequence in a mutable fashion." [item-sequence] (let [primary-sequence (atom item-sequence)] (fn [] (loop [sequence @primary-sequence] (when-let [next-item (first sequence)] (if-not (compare-and-set! primary-sequence sequence (rest sequence)) (recur @primary-sequence) next-item))))))
2296fb5817fb7531f0c9bc6ed3cb2a863bfb01ae524b43720d9f6f34ec689b84
haskell/hackage-server
Repo.hs
# LANGUAGE RecordWildCards # module Distribution.Client.Mirror.Repo ( -- * Repository types SourceRepo(..) , TargetRepo(..) -- ** Initialization , withSourceRepo , withTargetRepo -- ** Operations on source repos , downloadSourceIndex , downloadPackage -- ** Operations on target repos , readCachedTargetIndex , authenticate , uploadPackage , packageExists -- ** Finalizing a mirror , finalizeMirror , cacheTargetIndex ) where -- stdlib import Control.Exception import Control.Monad import System.Directory Cabal import Distribution.Package (PackageId) import Distribution.Verbosity -- hackage import Distribution.Client hiding (downloadIndex) import Distribution.Client.Mirror.Config import Distribution.Client.Mirror.Session import Distribution.Client.Mirror.Repo.Types import Distribution.Client.Mirror.Repo.Util import qualified Distribution.Client.Mirror.Repo.Hackage2 as Hackage2 import qualified Distribution.Client.Mirror.Repo.Local as Local import qualified Distribution.Client.Mirror.Repo.Secure as Secure -- hackage-security import qualified Hackage.Security.Client.Repository.HttpLib as Sec {------------------------------------------------------------------------------- Initialization TODO: Should really call validateHackageURI'. -------------------------------------------------------------------------------} withSourceRepo :: Verbosity -> Sec.HttpLib -> FilePath -> PreRepo -> (SourceRepo -> IO a) -> IO a withSourceRepo verbosity httpLib cacheDir PreRepo{..} callback = case (preRepoType, preRepoURI) of (Nothing, _) -> repoError "Missing type" (_, Nothing) -> repoError "Missing URI" (Just "hackage2", Just uri) -> Hackage2.withSourceRepo uri cacheDir callback (Just "secure", Just uri) -> do Secure.withSourceRepo verbosity httpLib uri cacheDir preRepoThreshold preRepoKeys callback _otherwise -> repoError "Unknown repo type" where repoError :: String -> IO a repoError msg = throwIO $ userError $ "Repository " ++ show preRepoName ++ ": " ++ msg withTargetRepo :: FilePath -> PreRepo -> (TargetRepo -> IO a) -> IO a withTargetRepo cacheDir PreRepo{..} callback = case (preRepoType, preRepoURI) of (Nothing, _) -> repoError "missing type" (_, Nothing) -> repoError "Missing URI" (Just "hackage2", Just uri) -> Hackage2.withTargetRepo uri cacheDir callback (Just "local", Just uri) -> Local.withTargetRepo uri cacheDir callback _otherwise -> repoError "Unknown repo type" where repoError :: String -> IO a repoError msg = throwIO $ userError $ "Repository " ++ show preRepoName ++ ": " ++ msg {------------------------------------------------------------------------------- Operations on source repositories -------------------------------------------------------------------------------} -- | Download the index from the source repo downloadSourceIndex :: SourceRepo -> MirrorSession [PkgIndexInfo] downloadSourceIndex SourceHackage2{..} = Hackage2.downloadIndex sourceRepoURI sourceRepoCachePath downloadSourceIndex SourceSecure{..} = Secure.downloadIndex sourceRepository sourceRepoCache sourceRepoRootKeys sourceRepoThreshold -- | Download a package downloadPackage :: SourceRepo -> PackageId -> FilePath -> FilePath -> MirrorSession (Maybe GetError) downloadPackage SourceHackage2{..} = Hackage2.downloadPackage sourceRepoURI downloadPackage SourceSecure{..} = Secure.downloadPackage sourceRepository {------------------------------------------------------------------------------- Operations on target repositories -------------------------------------------------------------------------------} -- | Read cached index from a target repo -- -- (Download it if it's not available) readCachedTargetIndex :: Verbosity -> TargetRepo -> MirrorSession [PkgIndexInfo] readCachedTargetIndex verbosity targetRepo = do cachedExists <- liftIO $ doesFileExist cachedIndex if cachedExists then do when (verbosity >= verbose) $ liftIO $ putStrLn "Reading cached index for target repo" readIndex "cached index" cachedIndex else do when (verbosity >= normal) $ liftIO $ putStrLn "No cached index available for target repo" downloadTargetIndex targetRepo where cachedIndex :: FilePath cachedIndex = targetCachedIndexPath (targetRepoCachePath targetRepo) -- | Download the index from a target repo downloadTargetIndex :: TargetRepo -> MirrorSession [PkgIndexInfo] downloadTargetIndex TargetHackage2{..} = Hackage2.downloadIndex targetRepoURI targetRepoCachePath downloadTargetIndex TargetLocal{..} = Local.downloadIndex targetRepoPath targetRepoCachePath -- | Authenticate (if required) authenticate :: TargetRepo -> MirrorSession () authenticate TargetHackage2{..} = Hackage2.authenticate targetRepoURI authenticate TargetLocal{..} = return () -- no authentication required -- | Upload a package uploadPackage :: TargetRepo -> Bool -> PkgIndexInfo -> FilePath -> FilePath -> MirrorSession () uploadPackage targetRepo doMirrorUploaders pkgInfo locCab locTgz = case targetRepo of TargetHackage2{..} -> Hackage2.uploadPackage targetRepoURI doMirrorUploaders pkgInfo locCab locTgz TargetLocal{..} -> -- doMirrorUploaders and locCab not relevant for local repo Local.uploadPackage targetRepoPath pkgInfo locTgz -- | Check if a package already exists -- -- Currently always returns 'False' for remote repos. packageExists :: TargetRepo -> PkgIndexInfo -> MirrorSession Bool packageExists targetRepo pkgInfo = case targetRepo of TargetHackage2{} -> return False TargetLocal{..} -> Local.packageExists targetRepoPath pkgInfo {------------------------------------------------------------------------------- Finalizing -------------------------------------------------------------------------------} -- | Finalize the mirror -- -- That is, now that the packages have been uploaded to the target repo, -- update the index and security files (if applicable). This is only necessary -- "dumb" target repositories. finalizeMirror :: SourceRepo -> TargetRepo -> MirrorSession () finalizeMirror _ TargetHackage2{} = return () -- Nothing to do finalizeMirror SourceHackage2{..} TargetLocal{..} = Hackage2.finalizeLocalMirror sourceRepoCachePath targetRepoPath finalizeMirror SourceSecure{..} TargetLocal{..} = Secure.finalizeLocalMirror sourceRepoCache targetRepoPath -- | Cache the the index for the target repo cacheTargetIndex :: SourceRepo -> TargetRepo -> MirrorSession () cacheTargetIndex SourceHackage2{..} targetRepo = do Hackage2.cacheTargetIndex sourceRepoCachePath (targetRepoCachePath targetRepo) cacheTargetIndex SourceSecure{..} targetRepo = do Secure.cacheTargetIndex sourceRepoCache (targetRepoCachePath targetRepo)
null
https://raw.githubusercontent.com/haskell/hackage-server/6c53b708ded21bef40ce04a43741fc921ecafcaa/src/Distribution/Client/Mirror/Repo.hs
haskell
* Repository types ** Initialization ** Operations on source repos ** Operations on target repos ** Finalizing a mirror stdlib hackage hackage-security ------------------------------------------------------------------------------ Initialization TODO: Should really call validateHackageURI'. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Operations on source repositories ------------------------------------------------------------------------------ | Download the index from the source repo | Download a package ------------------------------------------------------------------------------ Operations on target repositories ------------------------------------------------------------------------------ | Read cached index from a target repo (Download it if it's not available) | Download the index from a target repo | Authenticate (if required) no authentication required | Upload a package doMirrorUploaders and locCab not relevant for local repo | Check if a package already exists Currently always returns 'False' for remote repos. ------------------------------------------------------------------------------ Finalizing ------------------------------------------------------------------------------ | Finalize the mirror That is, now that the packages have been uploaded to the target repo, update the index and security files (if applicable). This is only necessary "dumb" target repositories. Nothing to do | Cache the the index for the target repo
# LANGUAGE RecordWildCards # module Distribution.Client.Mirror.Repo ( SourceRepo(..) , TargetRepo(..) , withSourceRepo , withTargetRepo , downloadSourceIndex , downloadPackage , readCachedTargetIndex , authenticate , uploadPackage , packageExists , finalizeMirror , cacheTargetIndex ) where import Control.Exception import Control.Monad import System.Directory Cabal import Distribution.Package (PackageId) import Distribution.Verbosity import Distribution.Client hiding (downloadIndex) import Distribution.Client.Mirror.Config import Distribution.Client.Mirror.Session import Distribution.Client.Mirror.Repo.Types import Distribution.Client.Mirror.Repo.Util import qualified Distribution.Client.Mirror.Repo.Hackage2 as Hackage2 import qualified Distribution.Client.Mirror.Repo.Local as Local import qualified Distribution.Client.Mirror.Repo.Secure as Secure import qualified Hackage.Security.Client.Repository.HttpLib as Sec withSourceRepo :: Verbosity -> Sec.HttpLib -> FilePath -> PreRepo -> (SourceRepo -> IO a) -> IO a withSourceRepo verbosity httpLib cacheDir PreRepo{..} callback = case (preRepoType, preRepoURI) of (Nothing, _) -> repoError "Missing type" (_, Nothing) -> repoError "Missing URI" (Just "hackage2", Just uri) -> Hackage2.withSourceRepo uri cacheDir callback (Just "secure", Just uri) -> do Secure.withSourceRepo verbosity httpLib uri cacheDir preRepoThreshold preRepoKeys callback _otherwise -> repoError "Unknown repo type" where repoError :: String -> IO a repoError msg = throwIO $ userError $ "Repository " ++ show preRepoName ++ ": " ++ msg withTargetRepo :: FilePath -> PreRepo -> (TargetRepo -> IO a) -> IO a withTargetRepo cacheDir PreRepo{..} callback = case (preRepoType, preRepoURI) of (Nothing, _) -> repoError "missing type" (_, Nothing) -> repoError "Missing URI" (Just "hackage2", Just uri) -> Hackage2.withTargetRepo uri cacheDir callback (Just "local", Just uri) -> Local.withTargetRepo uri cacheDir callback _otherwise -> repoError "Unknown repo type" where repoError :: String -> IO a repoError msg = throwIO $ userError $ "Repository " ++ show preRepoName ++ ": " ++ msg downloadSourceIndex :: SourceRepo -> MirrorSession [PkgIndexInfo] downloadSourceIndex SourceHackage2{..} = Hackage2.downloadIndex sourceRepoURI sourceRepoCachePath downloadSourceIndex SourceSecure{..} = Secure.downloadIndex sourceRepository sourceRepoCache sourceRepoRootKeys sourceRepoThreshold downloadPackage :: SourceRepo -> PackageId -> FilePath -> FilePath -> MirrorSession (Maybe GetError) downloadPackage SourceHackage2{..} = Hackage2.downloadPackage sourceRepoURI downloadPackage SourceSecure{..} = Secure.downloadPackage sourceRepository readCachedTargetIndex :: Verbosity -> TargetRepo -> MirrorSession [PkgIndexInfo] readCachedTargetIndex verbosity targetRepo = do cachedExists <- liftIO $ doesFileExist cachedIndex if cachedExists then do when (verbosity >= verbose) $ liftIO $ putStrLn "Reading cached index for target repo" readIndex "cached index" cachedIndex else do when (verbosity >= normal) $ liftIO $ putStrLn "No cached index available for target repo" downloadTargetIndex targetRepo where cachedIndex :: FilePath cachedIndex = targetCachedIndexPath (targetRepoCachePath targetRepo) downloadTargetIndex :: TargetRepo -> MirrorSession [PkgIndexInfo] downloadTargetIndex TargetHackage2{..} = Hackage2.downloadIndex targetRepoURI targetRepoCachePath downloadTargetIndex TargetLocal{..} = Local.downloadIndex targetRepoPath targetRepoCachePath authenticate :: TargetRepo -> MirrorSession () authenticate TargetHackage2{..} = Hackage2.authenticate targetRepoURI authenticate TargetLocal{..} = uploadPackage :: TargetRepo -> Bool -> PkgIndexInfo -> FilePath -> FilePath -> MirrorSession () uploadPackage targetRepo doMirrorUploaders pkgInfo locCab locTgz = case targetRepo of TargetHackage2{..} -> Hackage2.uploadPackage targetRepoURI doMirrorUploaders pkgInfo locCab locTgz TargetLocal{..} -> Local.uploadPackage targetRepoPath pkgInfo locTgz packageExists :: TargetRepo -> PkgIndexInfo -> MirrorSession Bool packageExists targetRepo pkgInfo = case targetRepo of TargetHackage2{} -> return False TargetLocal{..} -> Local.packageExists targetRepoPath pkgInfo finalizeMirror :: SourceRepo -> TargetRepo -> MirrorSession () finalizeMirror _ TargetHackage2{} = finalizeMirror SourceHackage2{..} TargetLocal{..} = Hackage2.finalizeLocalMirror sourceRepoCachePath targetRepoPath finalizeMirror SourceSecure{..} TargetLocal{..} = Secure.finalizeLocalMirror sourceRepoCache targetRepoPath cacheTargetIndex :: SourceRepo -> TargetRepo -> MirrorSession () cacheTargetIndex SourceHackage2{..} targetRepo = do Hackage2.cacheTargetIndex sourceRepoCachePath (targetRepoCachePath targetRepo) cacheTargetIndex SourceSecure{..} targetRepo = do Secure.cacheTargetIndex sourceRepoCache (targetRepoCachePath targetRepo)
0390f40fe4ce90431e2440f958ddb01bd66f8e546dabb43bd24f9fec716bcbc5
serras/lambdaconf-2015-web
Main.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE QuasiQuotes # module Main where import Control.Monad.IO.Class import Control.Monad.Logger import Data.Monoid import Database.Persist hiding (get) import Database.Persist.Sql hiding (get) import qualified Database.Persist as Db import qualified Database.Persist.Sqlite as Sqlite import Data.Text (pack) import Network.HTTP.Types.Status import Web.Spock.Safe import Db main :: IO () main = do -- Create the database Sqlite.runSqlite "example.db" $ Sqlite.runMigration migrateAll Initialize the connection pool runNoLoggingT $ Sqlite.withSqlitePool "example.db" 10 $ \pool -> NoLoggingT $ runSpock 8080 $ spockT id $ do -- small function for running db let withDb f = liftIO $ runSqlPersistMPool f pool -- create new user get ("user" <//> "new" <//> var <//> var) $ \fname lname -> do user <- withDb $ insertUnique (User fname lname) case user of Nothing -> text "Duplicate user" Just k -> text ("New user with id " <> pack (show k)) -- obtain user by id get ("user" <//> var) $ \userId -> do user <- withDb $ Db.get (UserKey $ SqlBackendKey userId) case user of Nothing -> setStatus status404 Just u -> json u -- obtain users with a certain username get ("user" <//> "by-name" <//> var) $ \name -> do users <- withDb $ selectList ([UserFirstName ==. name] ||. [UserLastName ==. name]) [] json users -- obtain users with a certain username get ("user" <//> "by-name" <//> var <//> var <//> var) $ \name offset limit -> do users <- withDb $ selectList ([UserFirstName ==. name] ||. [UserLastName ==. name]) [Asc UserFirstName, Asc UserLastName, OffsetBy offset, LimitTo limit] json users
null
https://raw.githubusercontent.com/serras/lambdaconf-2015-web/ec29b8b47dfb8ee33b09a0c18caceb6247e5a413/p3-db/src/Main.hs
haskell
# LANGUAGE OverloadedStrings # Create the database small function for running db create new user obtain user by id obtain users with a certain username obtain users with a certain username
# LANGUAGE ScopedTypeVariables # # LANGUAGE QuasiQuotes # module Main where import Control.Monad.IO.Class import Control.Monad.Logger import Data.Monoid import Database.Persist hiding (get) import Database.Persist.Sql hiding (get) import qualified Database.Persist as Db import qualified Database.Persist.Sqlite as Sqlite import Data.Text (pack) import Network.HTTP.Types.Status import Web.Spock.Safe import Db main :: IO () main = do Sqlite.runSqlite "example.db" $ Sqlite.runMigration migrateAll Initialize the connection pool runNoLoggingT $ Sqlite.withSqlitePool "example.db" 10 $ \pool -> NoLoggingT $ runSpock 8080 $ spockT id $ do let withDb f = liftIO $ runSqlPersistMPool f pool get ("user" <//> "new" <//> var <//> var) $ \fname lname -> do user <- withDb $ insertUnique (User fname lname) case user of Nothing -> text "Duplicate user" Just k -> text ("New user with id " <> pack (show k)) get ("user" <//> var) $ \userId -> do user <- withDb $ Db.get (UserKey $ SqlBackendKey userId) case user of Nothing -> setStatus status404 Just u -> json u get ("user" <//> "by-name" <//> var) $ \name -> do users <- withDb $ selectList ([UserFirstName ==. name] ||. [UserLastName ==. name]) [] json users get ("user" <//> "by-name" <//> var <//> var <//> var) $ \name offset limit -> do users <- withDb $ selectList ([UserFirstName ==. name] ||. [UserLastName ==. name]) [Asc UserFirstName, Asc UserLastName, OffsetBy offset, LimitTo limit] json users
a072a0feac57372efe17e2a945f401afd665cc24a53ce6e7aac16d69c9dbc504
DerekCuevas/interview-cake-clj
core_test.clj
(ns find-rotation-point.core-test (:require [clojure.test :refer :all] [find-rotation-point.core :refer :all])) (def words-a ["ptolemaic" "retrograde" "supplant" "undulate" "xenoepist" "asymptote" "babka" "banoffee" "engender" "karpatka" "othellolagkage"]) (def words-b ["ptolemaic" "retrograde" "asymptote" "babka" "banoffee" "engender" "karpatka" "othellolagkage"]) (def words-c ["ptolemaic" "supplant" "undulate" "xenoepist" "banoffee" "engender" "othellolagkage"]) (def words-d ["ptolemaic" "asymptote" "babka" "banoffee" "engender" "karpatka" "othellolagkage"]) (def words-e ["ptolemaic" "retrograde" "supplant" "undulate" "xenoepist" "asymptote"]) (def words-f ["undulate" "xenoepist" "asymptote" "banoffee"]) (deftest find-rotation-point-test (testing "should return index of rotation, assuming rotation exists" (is (= (find-rotation-point words-a) 5)) (is (= (find-rotation-point words-b) 2)) (is (= (find-rotation-point words-c) 4)) (is (= (find-rotation-point words-d) 1)) (is (= (find-rotation-point words-e) 5)) (is (= (find-rotation-point words-f) 2))))
null
https://raw.githubusercontent.com/DerekCuevas/interview-cake-clj/f17d3239bb30bcc17ced473f055a9859f9d1fb8d/find-rotation-point/test/find_rotation_point/core_test.clj
clojure
(ns find-rotation-point.core-test (:require [clojure.test :refer :all] [find-rotation-point.core :refer :all])) (def words-a ["ptolemaic" "retrograde" "supplant" "undulate" "xenoepist" "asymptote" "babka" "banoffee" "engender" "karpatka" "othellolagkage"]) (def words-b ["ptolemaic" "retrograde" "asymptote" "babka" "banoffee" "engender" "karpatka" "othellolagkage"]) (def words-c ["ptolemaic" "supplant" "undulate" "xenoepist" "banoffee" "engender" "othellolagkage"]) (def words-d ["ptolemaic" "asymptote" "babka" "banoffee" "engender" "karpatka" "othellolagkage"]) (def words-e ["ptolemaic" "retrograde" "supplant" "undulate" "xenoepist" "asymptote"]) (def words-f ["undulate" "xenoepist" "asymptote" "banoffee"]) (deftest find-rotation-point-test (testing "should return index of rotation, assuming rotation exists" (is (= (find-rotation-point words-a) 5)) (is (= (find-rotation-point words-b) 2)) (is (= (find-rotation-point words-c) 4)) (is (= (find-rotation-point words-d) 1)) (is (= (find-rotation-point words-e) 5)) (is (= (find-rotation-point words-f) 2))))
14cab2488842dd908c1d08595ec3b1574c8c55b309326bcb0a2ce24bf03791df
threatgrid/ctia
store.clj
(ns ctia.store) (defprotocol IStore (create-record [this new-records ident params]) (read-record [this id ident params]) (read-records [this ids ident params]) (update-record [this id record ident params]) (delete-record [this id ident params]) (bulk-delete [this ids ident params]) (bulk-update [this records ident params]) (list-records [this filtermap ident params]) (close [this])) (defprotocol IJudgementStore (calculate-verdict [this observable ident] [this observable ident params]) (list-judgements-by-observable [this observable ident params])) (defprotocol ISightingStore (list-sightings-by-observables [this observable ident params])) (defprotocol IIdentityStore (read-identity [this login]) (create-identity [this new-identity]) (delete-identity [this org-id role])) (defprotocol IEventStore (create-events [this new-events])) (defprotocol IQueryStringSearchableStore TODO uncomment when s / defprotocol is available via schema upgrade (query-string-search [this args #_#_:- QueryStringSearchArgs]) (query-string-count [this search-query ident]) (aggregate [this search-query agg-query ident]) (delete-search [this search-query ident params])) (defprotocol IPaginateableStore "Protocol that can implement lazy iteration over some number of calls to impure `fetch-page-fn` using `init-page-params` for the first call." (paginate [this fetch-page-fn] [this fetch-page-fn init-page-params])) (def empty-stores {:actor [] :asset [] :asset-mapping [] :asset-properties [] :attack-pattern [] :campaign [] :casebook [] :coa [] :data-table [] :event [] :feed [] :feedback [] :identity [] :identity-assertion [] :incident [] :indicator [] :investigation [] :judgement [] :malware [] :note [] :relationship [] :sighting [] :target-record [] :tool [] :vulnerability [] :weakness []})
null
https://raw.githubusercontent.com/threatgrid/ctia/6c11ba6a7c57a44de64c16601d3914f5b0cf308e/src/ctia/store.clj
clojure
(ns ctia.store) (defprotocol IStore (create-record [this new-records ident params]) (read-record [this id ident params]) (read-records [this ids ident params]) (update-record [this id record ident params]) (delete-record [this id ident params]) (bulk-delete [this ids ident params]) (bulk-update [this records ident params]) (list-records [this filtermap ident params]) (close [this])) (defprotocol IJudgementStore (calculate-verdict [this observable ident] [this observable ident params]) (list-judgements-by-observable [this observable ident params])) (defprotocol ISightingStore (list-sightings-by-observables [this observable ident params])) (defprotocol IIdentityStore (read-identity [this login]) (create-identity [this new-identity]) (delete-identity [this org-id role])) (defprotocol IEventStore (create-events [this new-events])) (defprotocol IQueryStringSearchableStore TODO uncomment when s / defprotocol is available via schema upgrade (query-string-search [this args #_#_:- QueryStringSearchArgs]) (query-string-count [this search-query ident]) (aggregate [this search-query agg-query ident]) (delete-search [this search-query ident params])) (defprotocol IPaginateableStore "Protocol that can implement lazy iteration over some number of calls to impure `fetch-page-fn` using `init-page-params` for the first call." (paginate [this fetch-page-fn] [this fetch-page-fn init-page-params])) (def empty-stores {:actor [] :asset [] :asset-mapping [] :asset-properties [] :attack-pattern [] :campaign [] :casebook [] :coa [] :data-table [] :event [] :feed [] :feedback [] :identity [] :identity-assertion [] :incident [] :indicator [] :investigation [] :judgement [] :malware [] :note [] :relationship [] :sighting [] :target-record [] :tool [] :vulnerability [] :weakness []})
379c93b555a312d7f1b35faf7bd643471d4b8ccf591f1be28cc83e1927f6ccc5
WorksHub/client
config.clj
;; This is placeholder code. Do not add config here. (ns wh.config (:refer-clojure :exclude [get get-in])) (def config {}) (defn get-in [ks] (clojure.core/get-in config ks)) (defn get [k] (clojure.core/get config k))
null
https://raw.githubusercontent.com/WorksHub/client/a51729585c2b9d7692e57b3edcd5217c228cf47c/server/src/wh/config.clj
clojure
This is placeholder code. Do not add config here.
(ns wh.config (:refer-clojure :exclude [get get-in])) (def config {}) (defn get-in [ks] (clojure.core/get-in config ks)) (defn get [k] (clojure.core/get config k))
2fc39e2f47eb49b89954c94c249107881cb4134095b3db379fb2da5eb3f9b855
8c6794b6/guile-tjit
compare.scm
Copyright ( c ) 2011 Free Software Foundation , Inc. Copyright ( c ) 2005 and . ; ; 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. ; ; ----------------------------------------------------------------------- ; ; Compare procedures SRFI (reference implementation) ; , ; history of this file: SE , 14 - Oct-2004 : first version SE , 18 - Oct-2004 : 1st redesign : axioms for ' compare function ' SE , 29 - Oct-2004 : 2nd redesign : higher order reverse / map / refine / unite SE , 2 - Nov-2004 : 3rd redesign : macros cond / refine - compare replace h.o.f 's SE , 10 - Nov-2004 : ( im , re ) replaced by ( re , im ) in complex - compare SE , 11 - Nov-2004 : case - compare by case ( not by cond ) ; select - compare added SE , 12 - Jan-2005 : pair - compare - cdr SE , 15 - Feb-2005 : stricter typing for compare-<type > ; pairwise - not= ? SE , 16 - Feb-2005 : case - compare - > if - compare - > if3 ; < ? < / < ? chain < ? etc . JS , 24 - Feb-2005 : selection - compare added SE , 25 - Feb-2005 : selection - compare - > kth - largest modified ; if < ? etc . JS , 28 - Feb-2005 : kth - largest modified - is " stable " now SE , 28 - Feb-2005 : simplified pairwise - not=?/kth - largest ; min / max debugged SE , 07 - Apr-2005 : compare - based type checks made explicit SE , 18 - Apr-2005 : added ( rel ? compare ) and eq?-test SE , 16 - May-2005 : naming convention changed ; compare - by < etc . optional x y ; ============================================================================= ; Reference Implementation ; ======================== ; in R5RS ( including hygienic macros ) ( case - lambda ) ; + SRFI-23 (error) ; + SRFI-27 (random-integer) ; Implementation remarks: ; * In general, the emphasis of this implementation is on correctness ; and portability, not on efficiency. ; * Variable arity procedures are expressed in terms of case-lambda ; in the hope that this will produce efficient code for the case ; where the arity is statically known at the call site. ; * In procedures that are required to type-check their arguments, ; we use (compare x x) for executing extra checks. This relies on ; the assumption that eq? is used to catch this case quickly. * Care has been taken to reference comparison procedures of R5RS ; only at the time the operations here are being defined. This ; makes it possible to redefine these operations, if need be. ; * For the sake of efficiency, some inlining has been done by hand. ; This is mainly expressed by macros producing defines. ; * Identifiers of the form compare:<something> are private. ; ; Hints for low-level implementation: * The basis of this SRFI are the atomic compare procedures , ; i.e. boolean-compare, char-compare, etc. and the conditionals if3 , if= ? , if < ? etc . , and default - compare . These should make ; optimal use of the available type information. ; * For the sake of speed, the reference implementation does not ; use a LET to save the comparison value c for the ERROR call. ; This can be fixed in a low-level implementation at no cost. ; * Type-checks based on (compare x x) are made explicit by the ; expression (compare:check result compare x ...). ; * Eq? should can used to speed up built-in compare procedures, but it can only be used after type - checking at least one of ; the arguments. (define (compare:checked result compare . args) (for-each (lambda (x) (compare x x)) args) result) 3 - sided conditional (define-syntax-rule (if3 c less equal greater) (case c ((-1) less) (( 0) equal) (( 1) greater) (else (error "comparison value not in {-1,0,1}")))) 2 - sided conditionals for comparisons (define-syntax compare:if-rel? (syntax-rules () ((compare:if-rel? c-cases a-cases c consequence) (compare:if-rel? c-cases a-cases c consequence (if #f #f))) ((compare:if-rel? c-cases a-cases c consequence alternate) (case c (c-cases consequence) (a-cases alternate) (else (error "comparison value not in {-1,0,1}")))))) (define-syntax-rule (if=? arg ...) (compare:if-rel? (0) (-1 1) arg ...)) (define-syntax-rule (if<? arg ...) (compare:if-rel? (-1) (0 1) arg ...)) (define-syntax-rule (if>? arg ...) (compare:if-rel? (1) (-1 0) arg ...)) (define-syntax-rule (if<=? arg ...) (compare:if-rel? (-1 0) (1) arg ...)) (define-syntax-rule (if>=? arg ...) (compare:if-rel? (0 1) (-1) arg ...)) (define-syntax-rule (if-not=? arg ...) (compare:if-rel? (-1 1) (0) arg ...)) ; predicates from compare procedures (define-syntax-rule (compare:define-rel? rel? if-rel?) (define rel? (case-lambda (() (lambda (x y) (if-rel? (default-compare x y) #t #f))) ((compare) (lambda (x y) (if-rel? (compare x y) #t #f))) ((x y) (if-rel? (default-compare x y) #t #f)) ((compare x y) (if (procedure? compare) (if-rel? (compare x y) #t #f) (error "not a procedure (Did you mean rel/rel??): " compare)))))) (compare:define-rel? =? if=?) (compare:define-rel? <? if<?) (compare:define-rel? >? if>?) (compare:define-rel? <=? if<=?) (compare:define-rel? >=? if>=?) (compare:define-rel? not=? if-not=?) chains of length 3 (define-syntax-rule (compare:define-rel1/rel2? rel1/rel2? if-rel1? if-rel2?) (define rel1/rel2? (case-lambda (() (lambda (x y z) (if-rel1? (default-compare x y) (if-rel2? (default-compare y z) #t #f) (compare:checked #f default-compare z)))) ((compare) (lambda (x y z) (if-rel1? (compare x y) (if-rel2? (compare y z) #t #f) (compare:checked #f compare z)))) ((x y z) (if-rel1? (default-compare x y) (if-rel2? (default-compare y z) #t #f) (compare:checked #f default-compare z))) ((compare x y z) (if-rel1? (compare x y) (if-rel2? (compare y z) #t #f) (compare:checked #f compare z)))))) (compare:define-rel1/rel2? </<? if<? if<?) (compare:define-rel1/rel2? </<=? if<? if<=?) (compare:define-rel1/rel2? <=/<? if<=? if<?) (compare:define-rel1/rel2? <=/<=? if<=? if<=?) (compare:define-rel1/rel2? >/>? if>? if>?) (compare:define-rel1/rel2? >/>=? if>? if>=?) (compare:define-rel1/rel2? >=/>? if>=? if>?) (compare:define-rel1/rel2? >=/>=? if>=? if>=?) ; chains of arbitrary length (define-syntax-rule (compare:define-chain-rel? chain-rel? if-rel?) (define chain-rel? (case-lambda ((compare) #t) ((compare x1) (compare:checked #t compare x1)) ((compare x1 x2) (if-rel? (compare x1 x2) #t #f)) ((compare x1 x2 x3) (if-rel? (compare x1 x2) (if-rel? (compare x2 x3) #t #f) (compare:checked #f compare x3))) ((compare x1 x2 . x3+) (if-rel? (compare x1 x2) (let chain? ((head x2) (tail x3+)) (if (null? tail) #t (if-rel? (compare head (car tail)) (chain? (car tail) (cdr tail)) (apply compare:checked #f compare (cdr tail))))) (apply compare:checked #f compare x3+)))))) (compare:define-chain-rel? chain=? if=?) (compare:define-chain-rel? chain<? if<?) (compare:define-chain-rel? chain>? if>?) (compare:define-chain-rel? chain<=? if<=?) (compare:define-chain-rel? chain>=? if>=?) ; pairwise inequality (define pairwise-not=? (let ((= =) (<= <=)) (case-lambda ((compare) #t) ((compare x1) (compare:checked #t compare x1)) ((compare x1 x2) (if-not=? (compare x1 x2) #t #f)) ((compare x1 x2 x3) (if-not=? (compare x1 x2) (if-not=? (compare x2 x3) (if-not=? (compare x1 x3) #t #f) #f) (compare:checked #f compare x3))) ((compare . x1+) (let unequal? ((x x1+) (n (length x1+)) (unchecked? #t)) (if (< n 2) (if (and unchecked? (= n 1)) (compare:checked #t compare (car x)) #t) (let* ((i-pivot (random-integer n)) (x-pivot (list-ref x i-pivot))) (let split ((i 0) (x x) (x< '()) (x> '())) (if (null? x) (and (unequal? x< (length x<) #f) (unequal? x> (length x>) #f)) (if (= i i-pivot) (split (+ i 1) (cdr x) x< x>) (if3 (compare (car x) x-pivot) (split (+ i 1) (cdr x) (cons (car x) x<) x>) (if unchecked? (apply compare:checked #f compare (cdr x)) #f) (split (+ i 1) (cdr x) x< (cons (car x) x>))))))))))))) ; min/max (define min-compare (case-lambda ((compare x1) (compare:checked x1 compare x1)) ((compare x1 x2) (if<=? (compare x1 x2) x1 x2)) ((compare x1 x2 x3) (if<=? (compare x1 x2) (if<=? (compare x1 x3) x1 x3) (if<=? (compare x2 x3) x2 x3))) ((compare x1 x2 x3 x4) (if<=? (compare x1 x2) (if<=? (compare x1 x3) (if<=? (compare x1 x4) x1 x4) (if<=? (compare x3 x4) x3 x4)) (if<=? (compare x2 x3) (if<=? (compare x2 x4) x2 x4) (if<=? (compare x3 x4) x3 x4)))) ((compare x1 x2 . x3+) (let min ((xmin (if<=? (compare x1 x2) x1 x2)) (xs x3+)) (if (null? xs) xmin (min (if<=? (compare xmin (car xs)) xmin (car xs)) (cdr xs))))))) (define max-compare (case-lambda ((compare x1) (compare:checked x1 compare x1)) ((compare x1 x2) (if>=? (compare x1 x2) x1 x2)) ((compare x1 x2 x3) (if>=? (compare x1 x2) (if>=? (compare x1 x3) x1 x3) (if>=? (compare x2 x3) x2 x3))) ((compare x1 x2 x3 x4) (if>=? (compare x1 x2) (if>=? (compare x1 x3) (if>=? (compare x1 x4) x1 x4) (if>=? (compare x3 x4) x3 x4)) (if>=? (compare x2 x3) (if>=? (compare x2 x4) x2 x4) (if>=? (compare x3 x4) x3 x4)))) ((compare x1 x2 . x3+) (let max ((xmax (if>=? (compare x1 x2) x1 x2)) (xs x3+)) (if (null? xs) xmax (max (if>=? (compare xmax (car xs)) xmax (car xs)) (cdr xs))))))) ; kth-largest (define kth-largest (let ((= =) (< <)) (case-lambda ((compare k x0) (case (modulo k 1) ((0) (compare:checked x0 compare x0)) (else (error "bad index" k)))) ((compare k x0 x1) (case (modulo k 2) ((0) (if<=? (compare x0 x1) x0 x1)) ((1) (if<=? (compare x0 x1) x1 x0)) (else (error "bad index" k)))) ((compare k x0 x1 x2) (case (modulo k 3) ((0) (if<=? (compare x0 x1) (if<=? (compare x0 x2) x0 x2) (if<=? (compare x1 x2) x1 x2))) ((1) (if3 (compare x0 x1) (if<=? (compare x1 x2) x1 (if<=? (compare x0 x2) x2 x0)) (if<=? (compare x0 x2) x1 x0) (if<=? (compare x0 x2) x0 (if<=? (compare x1 x2) x2 x1)))) ((2) (if<=? (compare x0 x1) (if<=? (compare x1 x2) x2 x1) (if<=? (compare x0 x2) x2 x0))) (else (error "bad index" k)))) |x1+| > = 1 (if (not (and (integer? k) (exact? k))) (error "bad index" k)) (let ((n (+ 1 (length x1+)))) (let kth ((k (modulo k n)) = |x| (rev #t) ; are x<, x=, x> reversed? (x (cons x0 x1+))) (let ((pivot (list-ref x (random-integer n)))) (let split ((x x) (x< '()) (n< 0) (x= '()) (n= 0) (x> '()) (n> 0)) (if (null? x) (cond ((< k n<) (kth k n< (not rev) x<)) ((< k (+ n< n=)) (if rev (list-ref x= (- (- n= 1) (- k n<))) (list-ref x= (- k n<)))) (else (kth (- k (+ n< n=)) n> (not rev) x>))) (if3 (compare (car x) pivot) (split (cdr x) (cons (car x) x<) (+ n< 1) x= n= x> n>) (split (cdr x) x< n< (cons (car x) x=) (+ n= 1) x> n>) (split (cdr x) x< n< x= n= (cons (car x) x>) (+ n> 1)))))))))))) ; compare functions from predicates (define compare-by< (case-lambda ((lt) (lambda (x y) (if (lt x y) -1 (if (lt y x) 1 0)))) ((lt x y) (if (lt x y) -1 (if (lt y x) 1 0))))) (define compare-by> (case-lambda ((gt) (lambda (x y) (if (gt x y) 1 (if (gt y x) -1 0)))) ((gt x y) (if (gt x y) 1 (if (gt y x) -1 0))))) (define compare-by<= (case-lambda ((le) (lambda (x y) (if (le x y) (if (le y x) 0 -1) 1))) ((le x y) (if (le x y) (if (le y x) 0 -1) 1)))) (define compare-by>= (case-lambda ((ge) (lambda (x y) (if (ge x y) (if (ge y x) 0 1) -1))) ((ge x y) (if (ge x y) (if (ge y x) 0 1) -1)))) (define compare-by=/< (case-lambda ((eq lt) (lambda (x y) (if (eq x y) 0 (if (lt x y) -1 1)))) ((eq lt x y) (if (eq x y) 0 (if (lt x y) -1 1))))) (define compare-by=/> (case-lambda ((eq gt) (lambda (x y) (if (eq x y) 0 (if (gt x y) 1 -1)))) ((eq gt x y) (if (eq x y) 0 (if (gt x y) 1 -1))))) ; refine and extend construction (define-syntax refine-compare (syntax-rules () ((refine-compare) 0) ((refine-compare c1) c1) ((refine-compare c1 c2 cs ...) (if3 c1 -1 (refine-compare c2 cs ...) 1)))) (define-syntax select-compare (syntax-rules (else) ((select-compare x y clause ...) (let ((x-val x) (y-val y)) (select-compare (x-val y-val clause ...)))) ; used internally: (select-compare (x y clause ...)) ((select-compare (x y)) 0) ((select-compare (x y (else c ...))) (refine-compare c ...)) ((select-compare (x y (t? c ...) clause ...)) (let ((t?-val t?)) (let ((tx (t?-val x)) (ty (t?-val y))) (if tx (if ty (refine-compare c ...) -1) (if ty 1 (select-compare (x y clause ...))))))))) (define-syntax cond-compare (syntax-rules (else) ((cond-compare) 0) ((cond-compare (else cs ...)) (refine-compare cs ...)) ((cond-compare ((tx ty) cs ...) clause ...) (let ((tx-val tx) (ty-val ty)) (if tx-val (if ty-val (refine-compare cs ...) -1) (if ty-val 1 (cond-compare clause ...))))))) R5RS atomic types (define-syntax compare:type-check (syntax-rules () ((compare:type-check type? type-name x) (if (not (type? x)) (error (string-append "not " type-name ":") x))) ((compare:type-check type? type-name x y) (begin (compare:type-check type? type-name x) (compare:type-check type? type-name y))))) (define-syntax-rule (compare:define-by=/< compare = < type? type-name) (define compare (let ((= =) (< <)) (lambda (x y) (if (type? x) (if (eq? x y) 0 (if (type? y) (if (= x y) 0 (if (< x y) -1 1)) (error (string-append "not " type-name ":") y))) (error (string-append "not " type-name ":") x)))))) (define (boolean-compare x y) (compare:type-check boolean? "boolean" x y) (if x (if y 0 1) (if y -1 0))) (compare:define-by=/< char-compare char=? char<? char? "char") (compare:define-by=/< char-compare-ci char-ci=? char-ci<? char? "char") (compare:define-by=/< string-compare string=? string<? string? "string") (compare:define-by=/< string-compare-ci string-ci=? string-ci<? string? "string") (define (symbol-compare x y) (compare:type-check symbol? "symbol" x y) (string-compare (symbol->string x) (symbol->string y))) (compare:define-by=/< integer-compare = < integer? "integer") (compare:define-by=/< rational-compare = < rational? "rational") (compare:define-by=/< real-compare = < real? "real") (define (complex-compare x y) (compare:type-check complex? "complex" x y) (if (and (real? x) (real? y)) (real-compare x y) (refine-compare (real-compare (real-part x) (real-part y)) (real-compare (imag-part x) (imag-part y))))) (define (number-compare x y) (compare:type-check number? "number" x y) (complex-compare x y)) R5RS compound data structures : dotted pair , list , vector (define (pair-compare-car compare) (lambda (x y) (compare (car x) (car y)))) (define (pair-compare-cdr compare) (lambda (x y) (compare (cdr x) (cdr y)))) (define pair-compare (case-lambda ; dotted pair ((pair-compare-car pair-compare-cdr x y) (refine-compare (pair-compare-car (car x) (car y)) (pair-compare-cdr (cdr x) (cdr y)))) ; possibly improper lists ((compare x y) (cond-compare (((null? x) (null? y)) 0) (((pair? x) (pair? y)) (compare (car x) (car y)) (pair-compare compare (cdr x) (cdr y))) (else (compare x y)))) ; for convenience ((x y) (pair-compare default-compare x y)))) (define list-compare (case-lambda ((compare x y empty? head tail) (cond-compare (((empty? x) (empty? y)) 0) (else (compare (head x) (head y)) (list-compare compare (tail x) (tail y) empty? head tail)))) ; for convenience (( x y empty? head tail) (list-compare default-compare x y empty? head tail)) ((compare x y ) (list-compare compare x y null? car cdr)) (( x y ) (list-compare default-compare x y null? car cdr)))) (define list-compare-as-vector (case-lambda ((compare x y empty? head tail) (refine-compare (let compare-length ((x x) (y y)) (cond-compare (((empty? x) (empty? y)) 0) (else (compare-length (tail x) (tail y))))) (list-compare compare x y empty? head tail))) ; for convenience (( x y empty? head tail) (list-compare-as-vector default-compare x y empty? head tail)) ((compare x y ) (list-compare-as-vector compare x y null? car cdr)) (( x y ) (list-compare-as-vector default-compare x y null? car cdr)))) (define vector-compare (let ((= =)) (case-lambda ((compare x y size ref) (let ((n (size x)) (m (size y))) (refine-compare (integer-compare n m) compare x[i .. n-1 ] y[i .. n-1 ] (if (= i n) 0 (refine-compare (compare (ref x i) (ref y i)) (compare-rest (+ i 1)))))))) ; for convenience (( x y size ref) (vector-compare default-compare x y size ref)) ((compare x y ) (vector-compare compare x y vector-length vector-ref)) (( x y ) (vector-compare default-compare x y vector-length vector-ref))))) (define vector-compare-as-list (let ((= =)) (case-lambda ((compare x y size ref) (let ((nx (size x)) (ny (size y))) (let ((n (min nx ny))) compare x[i .. n-1 ] y[i .. n-1 ] (if (= i n) (integer-compare nx ny) (refine-compare (compare (ref x i) (ref y i)) (compare-rest (+ i 1)))))))) ; for convenience (( x y size ref) (vector-compare-as-list default-compare x y size ref)) ((compare x y ) (vector-compare-as-list compare x y vector-length vector-ref)) (( x y ) (vector-compare-as-list default-compare x y vector-length vector-ref))))) ; default compare (define (default-compare x y) (select-compare x y (null? 0) (pair? (default-compare (car x) (car y)) (default-compare (cdr x) (cdr y))) (boolean? (boolean-compare x y)) (char? (char-compare x y)) (string? (string-compare x y)) (symbol? (symbol-compare x y)) (number? (number-compare x y)) (vector? (vector-compare default-compare x y)) (else (error "unrecognized type in default-compare" x y)))) ; Note that we pass default-compare to compare-{pair,vector} explictly. ; This makes sure recursion proceeds with this default-compare, which ; need not be the one in the lexical scope of compare-{pair,vector}. ; debug compare (define (debug-compare c) (define (checked-value c x y) (let ((c-xy (c x y))) (if (or (eqv? c-xy -1) (eqv? c-xy 0) (eqv? c-xy 1)) c-xy (error "compare value not in {-1,0,1}" c-xy (list c x y))))) (define (random-boolean) (zero? (random-integer 2))) (define q ; (u v w) such that u <= v, v <= w, and not u <= w '#( ;x < y x = y x > y [x < z] 0 0 0 ; y < z 0 (z y x) (z y x) ; y = z 0 (z y x) (z y x) ; y > z ;x < y x = y x > y [x = z] (y z x) (z x y) 0 ; y < z (y z x) 0 (x z y) ; y = z 0 (y x z) (x z y) ; y > z ;x < y x = y x > y [x > z] (x y z) (x y z) 0 ; y < z (x y z) (x y z) 0 ; y = z 0 0 0 ; y > z )) (let ((z? #f) (z #f)) ; stored element from previous call (lambda (x y) (let ((c-xx (checked-value c x x)) (c-yy (checked-value c y y)) (c-xy (checked-value c x y)) (c-yx (checked-value c y x))) (if (not (zero? c-xx)) (error "compare error: not reflexive" c x)) (if (not (zero? c-yy)) (error "compare error: not reflexive" c y)) (if (not (zero? (+ c-xy c-yx))) (error "compare error: not anti-symmetric" c x y)) (if z? (let ((c-xz (checked-value c x z)) (c-zx (checked-value c z x)) (c-yz (checked-value c y z)) (c-zy (checked-value c z y))) (if (not (zero? (+ c-xz c-zx))) (error "compare error: not anti-symmetric" c x z)) (if (not (zero? (+ c-yz c-zy))) (error "compare error: not anti-symmetric" c y z)) (let ((ijk (vector-ref q (+ c-xy (* 3 c-yz) (* 9 c-xz) 13)))) (if (list? ijk) (apply error "compare error: not transitive" c (map (lambda (i) (case i ((x) x) ((y) y) ((z) z))) ijk))))) (set! z? #t)) (set! z (if (random-boolean) x y)) ; randomized testing c-xy))))
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/srfi/srfi-67/compare.scm
scheme
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the without limitation the rights to use, copy, modify, merge, publish, the following conditions: The above copyright notice and this permission notice shall be 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 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------- Compare procedures SRFI (reference implementation) , history of this file: select - compare added pairwise - not= ? < ? < / < ? chain < ? etc . if < ? etc . min / max debugged compare - by < etc . optional x y ============================================================================= Reference Implementation ======================== + SRFI-23 (error) + SRFI-27 (random-integer) Implementation remarks: * In general, the emphasis of this implementation is on correctness and portability, not on efficiency. * Variable arity procedures are expressed in terms of case-lambda in the hope that this will produce efficient code for the case where the arity is statically known at the call site. * In procedures that are required to type-check their arguments, we use (compare x x) for executing extra checks. This relies on the assumption that eq? is used to catch this case quickly. only at the time the operations here are being defined. This makes it possible to redefine these operations, if need be. * For the sake of efficiency, some inlining has been done by hand. This is mainly expressed by macros producing defines. * Identifiers of the form compare:<something> are private. Hints for low-level implementation: i.e. boolean-compare, char-compare, etc. and the conditionals optimal use of the available type information. * For the sake of speed, the reference implementation does not use a LET to save the comparison value c for the ERROR call. This can be fixed in a low-level implementation at no cost. * Type-checks based on (compare x x) are made explicit by the expression (compare:check result compare x ...). * Eq? should can used to speed up built-in compare procedures, the arguments. predicates from compare procedures chains of arbitrary length pairwise inequality min/max kth-largest are x<, x=, x> reversed? compare functions from predicates refine and extend construction used internally: (select-compare (x y clause ...)) dotted pair possibly improper lists for convenience for convenience for convenience for convenience for convenience default compare Note that we pass default-compare to compare-{pair,vector} explictly. This makes sure recursion proceeds with this default-compare, which need not be the one in the lexical scope of compare-{pair,vector}. debug compare (u v w) such that u <= v, v <= w, and not u <= w x < y x = y x > y [x < z] y < z y = z y > z x < y x = y x > y [x = z] y < z y = z y > z x < y x = y x > y [x > z] y < z y = z y > z stored element from previous call randomized testing
Copyright ( c ) 2011 Free Software Foundation , Inc. Copyright ( c ) 2005 and . ` ` Software '' ) , to deal in the Software without restriction , including distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to included in all copies or substantial portions of the Software . LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION SE , 14 - Oct-2004 : first version SE , 18 - Oct-2004 : 1st redesign : axioms for ' compare function ' SE , 29 - Oct-2004 : 2nd redesign : higher order reverse / map / refine / unite SE , 2 - Nov-2004 : 3rd redesign : macros cond / refine - compare replace h.o.f 's SE , 10 - Nov-2004 : ( im , re ) replaced by ( re , im ) in complex - compare SE , 12 - Jan-2005 : pair - compare - cdr JS , 24 - Feb-2005 : selection - compare added JS , 28 - Feb-2005 : kth - largest modified - is " stable " now SE , 07 - Apr-2005 : compare - based type checks made explicit SE , 18 - Apr-2005 : added ( rel ? compare ) and eq?-test in R5RS ( including hygienic macros ) ( case - lambda ) * Care has been taken to reference comparison procedures of R5RS * The basis of this SRFI are the atomic compare procedures , if3 , if= ? , if < ? etc . , and default - compare . These should make but it can only be used after type - checking at least one of (define (compare:checked result compare . args) (for-each (lambda (x) (compare x x)) args) result) 3 - sided conditional (define-syntax-rule (if3 c less equal greater) (case c ((-1) less) (( 0) equal) (( 1) greater) (else (error "comparison value not in {-1,0,1}")))) 2 - sided conditionals for comparisons (define-syntax compare:if-rel? (syntax-rules () ((compare:if-rel? c-cases a-cases c consequence) (compare:if-rel? c-cases a-cases c consequence (if #f #f))) ((compare:if-rel? c-cases a-cases c consequence alternate) (case c (c-cases consequence) (a-cases alternate) (else (error "comparison value not in {-1,0,1}")))))) (define-syntax-rule (if=? arg ...) (compare:if-rel? (0) (-1 1) arg ...)) (define-syntax-rule (if<? arg ...) (compare:if-rel? (-1) (0 1) arg ...)) (define-syntax-rule (if>? arg ...) (compare:if-rel? (1) (-1 0) arg ...)) (define-syntax-rule (if<=? arg ...) (compare:if-rel? (-1 0) (1) arg ...)) (define-syntax-rule (if>=? arg ...) (compare:if-rel? (0 1) (-1) arg ...)) (define-syntax-rule (if-not=? arg ...) (compare:if-rel? (-1 1) (0) arg ...)) (define-syntax-rule (compare:define-rel? rel? if-rel?) (define rel? (case-lambda (() (lambda (x y) (if-rel? (default-compare x y) #t #f))) ((compare) (lambda (x y) (if-rel? (compare x y) #t #f))) ((x y) (if-rel? (default-compare x y) #t #f)) ((compare x y) (if (procedure? compare) (if-rel? (compare x y) #t #f) (error "not a procedure (Did you mean rel/rel??): " compare)))))) (compare:define-rel? =? if=?) (compare:define-rel? <? if<?) (compare:define-rel? >? if>?) (compare:define-rel? <=? if<=?) (compare:define-rel? >=? if>=?) (compare:define-rel? not=? if-not=?) chains of length 3 (define-syntax-rule (compare:define-rel1/rel2? rel1/rel2? if-rel1? if-rel2?) (define rel1/rel2? (case-lambda (() (lambda (x y z) (if-rel1? (default-compare x y) (if-rel2? (default-compare y z) #t #f) (compare:checked #f default-compare z)))) ((compare) (lambda (x y z) (if-rel1? (compare x y) (if-rel2? (compare y z) #t #f) (compare:checked #f compare z)))) ((x y z) (if-rel1? (default-compare x y) (if-rel2? (default-compare y z) #t #f) (compare:checked #f default-compare z))) ((compare x y z) (if-rel1? (compare x y) (if-rel2? (compare y z) #t #f) (compare:checked #f compare z)))))) (compare:define-rel1/rel2? </<? if<? if<?) (compare:define-rel1/rel2? </<=? if<? if<=?) (compare:define-rel1/rel2? <=/<? if<=? if<?) (compare:define-rel1/rel2? <=/<=? if<=? if<=?) (compare:define-rel1/rel2? >/>? if>? if>?) (compare:define-rel1/rel2? >/>=? if>? if>=?) (compare:define-rel1/rel2? >=/>? if>=? if>?) (compare:define-rel1/rel2? >=/>=? if>=? if>=?) (define-syntax-rule (compare:define-chain-rel? chain-rel? if-rel?) (define chain-rel? (case-lambda ((compare) #t) ((compare x1) (compare:checked #t compare x1)) ((compare x1 x2) (if-rel? (compare x1 x2) #t #f)) ((compare x1 x2 x3) (if-rel? (compare x1 x2) (if-rel? (compare x2 x3) #t #f) (compare:checked #f compare x3))) ((compare x1 x2 . x3+) (if-rel? (compare x1 x2) (let chain? ((head x2) (tail x3+)) (if (null? tail) #t (if-rel? (compare head (car tail)) (chain? (car tail) (cdr tail)) (apply compare:checked #f compare (cdr tail))))) (apply compare:checked #f compare x3+)))))) (compare:define-chain-rel? chain=? if=?) (compare:define-chain-rel? chain<? if<?) (compare:define-chain-rel? chain>? if>?) (compare:define-chain-rel? chain<=? if<=?) (compare:define-chain-rel? chain>=? if>=?) (define pairwise-not=? (let ((= =) (<= <=)) (case-lambda ((compare) #t) ((compare x1) (compare:checked #t compare x1)) ((compare x1 x2) (if-not=? (compare x1 x2) #t #f)) ((compare x1 x2 x3) (if-not=? (compare x1 x2) (if-not=? (compare x2 x3) (if-not=? (compare x1 x3) #t #f) #f) (compare:checked #f compare x3))) ((compare . x1+) (let unequal? ((x x1+) (n (length x1+)) (unchecked? #t)) (if (< n 2) (if (and unchecked? (= n 1)) (compare:checked #t compare (car x)) #t) (let* ((i-pivot (random-integer n)) (x-pivot (list-ref x i-pivot))) (let split ((i 0) (x x) (x< '()) (x> '())) (if (null? x) (and (unequal? x< (length x<) #f) (unequal? x> (length x>) #f)) (if (= i i-pivot) (split (+ i 1) (cdr x) x< x>) (if3 (compare (car x) x-pivot) (split (+ i 1) (cdr x) (cons (car x) x<) x>) (if unchecked? (apply compare:checked #f compare (cdr x)) #f) (split (+ i 1) (cdr x) x< (cons (car x) x>))))))))))))) (define min-compare (case-lambda ((compare x1) (compare:checked x1 compare x1)) ((compare x1 x2) (if<=? (compare x1 x2) x1 x2)) ((compare x1 x2 x3) (if<=? (compare x1 x2) (if<=? (compare x1 x3) x1 x3) (if<=? (compare x2 x3) x2 x3))) ((compare x1 x2 x3 x4) (if<=? (compare x1 x2) (if<=? (compare x1 x3) (if<=? (compare x1 x4) x1 x4) (if<=? (compare x3 x4) x3 x4)) (if<=? (compare x2 x3) (if<=? (compare x2 x4) x2 x4) (if<=? (compare x3 x4) x3 x4)))) ((compare x1 x2 . x3+) (let min ((xmin (if<=? (compare x1 x2) x1 x2)) (xs x3+)) (if (null? xs) xmin (min (if<=? (compare xmin (car xs)) xmin (car xs)) (cdr xs))))))) (define max-compare (case-lambda ((compare x1) (compare:checked x1 compare x1)) ((compare x1 x2) (if>=? (compare x1 x2) x1 x2)) ((compare x1 x2 x3) (if>=? (compare x1 x2) (if>=? (compare x1 x3) x1 x3) (if>=? (compare x2 x3) x2 x3))) ((compare x1 x2 x3 x4) (if>=? (compare x1 x2) (if>=? (compare x1 x3) (if>=? (compare x1 x4) x1 x4) (if>=? (compare x3 x4) x3 x4)) (if>=? (compare x2 x3) (if>=? (compare x2 x4) x2 x4) (if>=? (compare x3 x4) x3 x4)))) ((compare x1 x2 . x3+) (let max ((xmax (if>=? (compare x1 x2) x1 x2)) (xs x3+)) (if (null? xs) xmax (max (if>=? (compare xmax (car xs)) xmax (car xs)) (cdr xs))))))) (define kth-largest (let ((= =) (< <)) (case-lambda ((compare k x0) (case (modulo k 1) ((0) (compare:checked x0 compare x0)) (else (error "bad index" k)))) ((compare k x0 x1) (case (modulo k 2) ((0) (if<=? (compare x0 x1) x0 x1)) ((1) (if<=? (compare x0 x1) x1 x0)) (else (error "bad index" k)))) ((compare k x0 x1 x2) (case (modulo k 3) ((0) (if<=? (compare x0 x1) (if<=? (compare x0 x2) x0 x2) (if<=? (compare x1 x2) x1 x2))) ((1) (if3 (compare x0 x1) (if<=? (compare x1 x2) x1 (if<=? (compare x0 x2) x2 x0)) (if<=? (compare x0 x2) x1 x0) (if<=? (compare x0 x2) x0 (if<=? (compare x1 x2) x2 x1)))) ((2) (if<=? (compare x0 x1) (if<=? (compare x1 x2) x2 x1) (if<=? (compare x0 x2) x2 x0))) (else (error "bad index" k)))) |x1+| > = 1 (if (not (and (integer? k) (exact? k))) (error "bad index" k)) (let ((n (+ 1 (length x1+)))) (let kth ((k (modulo k n)) = |x| (x (cons x0 x1+))) (let ((pivot (list-ref x (random-integer n)))) (let split ((x x) (x< '()) (n< 0) (x= '()) (n= 0) (x> '()) (n> 0)) (if (null? x) (cond ((< k n<) (kth k n< (not rev) x<)) ((< k (+ n< n=)) (if rev (list-ref x= (- (- n= 1) (- k n<))) (list-ref x= (- k n<)))) (else (kth (- k (+ n< n=)) n> (not rev) x>))) (if3 (compare (car x) pivot) (split (cdr x) (cons (car x) x<) (+ n< 1) x= n= x> n>) (split (cdr x) x< n< (cons (car x) x=) (+ n= 1) x> n>) (split (cdr x) x< n< x= n= (cons (car x) x>) (+ n> 1)))))))))))) (define compare-by< (case-lambda ((lt) (lambda (x y) (if (lt x y) -1 (if (lt y x) 1 0)))) ((lt x y) (if (lt x y) -1 (if (lt y x) 1 0))))) (define compare-by> (case-lambda ((gt) (lambda (x y) (if (gt x y) 1 (if (gt y x) -1 0)))) ((gt x y) (if (gt x y) 1 (if (gt y x) -1 0))))) (define compare-by<= (case-lambda ((le) (lambda (x y) (if (le x y) (if (le y x) 0 -1) 1))) ((le x y) (if (le x y) (if (le y x) 0 -1) 1)))) (define compare-by>= (case-lambda ((ge) (lambda (x y) (if (ge x y) (if (ge y x) 0 1) -1))) ((ge x y) (if (ge x y) (if (ge y x) 0 1) -1)))) (define compare-by=/< (case-lambda ((eq lt) (lambda (x y) (if (eq x y) 0 (if (lt x y) -1 1)))) ((eq lt x y) (if (eq x y) 0 (if (lt x y) -1 1))))) (define compare-by=/> (case-lambda ((eq gt) (lambda (x y) (if (eq x y) 0 (if (gt x y) 1 -1)))) ((eq gt x y) (if (eq x y) 0 (if (gt x y) 1 -1))))) (define-syntax refine-compare (syntax-rules () ((refine-compare) 0) ((refine-compare c1) c1) ((refine-compare c1 c2 cs ...) (if3 c1 -1 (refine-compare c2 cs ...) 1)))) (define-syntax select-compare (syntax-rules (else) ((select-compare x y clause ...) (let ((x-val x) (y-val y)) (select-compare (x-val y-val clause ...)))) ((select-compare (x y)) 0) ((select-compare (x y (else c ...))) (refine-compare c ...)) ((select-compare (x y (t? c ...) clause ...)) (let ((t?-val t?)) (let ((tx (t?-val x)) (ty (t?-val y))) (if tx (if ty (refine-compare c ...) -1) (if ty 1 (select-compare (x y clause ...))))))))) (define-syntax cond-compare (syntax-rules (else) ((cond-compare) 0) ((cond-compare (else cs ...)) (refine-compare cs ...)) ((cond-compare ((tx ty) cs ...) clause ...) (let ((tx-val tx) (ty-val ty)) (if tx-val (if ty-val (refine-compare cs ...) -1) (if ty-val 1 (cond-compare clause ...))))))) R5RS atomic types (define-syntax compare:type-check (syntax-rules () ((compare:type-check type? type-name x) (if (not (type? x)) (error (string-append "not " type-name ":") x))) ((compare:type-check type? type-name x y) (begin (compare:type-check type? type-name x) (compare:type-check type? type-name y))))) (define-syntax-rule (compare:define-by=/< compare = < type? type-name) (define compare (let ((= =) (< <)) (lambda (x y) (if (type? x) (if (eq? x y) 0 (if (type? y) (if (= x y) 0 (if (< x y) -1 1)) (error (string-append "not " type-name ":") y))) (error (string-append "not " type-name ":") x)))))) (define (boolean-compare x y) (compare:type-check boolean? "boolean" x y) (if x (if y 0 1) (if y -1 0))) (compare:define-by=/< char-compare char=? char<? char? "char") (compare:define-by=/< char-compare-ci char-ci=? char-ci<? char? "char") (compare:define-by=/< string-compare string=? string<? string? "string") (compare:define-by=/< string-compare-ci string-ci=? string-ci<? string? "string") (define (symbol-compare x y) (compare:type-check symbol? "symbol" x y) (string-compare (symbol->string x) (symbol->string y))) (compare:define-by=/< integer-compare = < integer? "integer") (compare:define-by=/< rational-compare = < rational? "rational") (compare:define-by=/< real-compare = < real? "real") (define (complex-compare x y) (compare:type-check complex? "complex" x y) (if (and (real? x) (real? y)) (real-compare x y) (refine-compare (real-compare (real-part x) (real-part y)) (real-compare (imag-part x) (imag-part y))))) (define (number-compare x y) (compare:type-check number? "number" x y) (complex-compare x y)) R5RS compound data structures : dotted pair , list , vector (define (pair-compare-car compare) (lambda (x y) (compare (car x) (car y)))) (define (pair-compare-cdr compare) (lambda (x y) (compare (cdr x) (cdr y)))) (define pair-compare (case-lambda ((pair-compare-car pair-compare-cdr x y) (refine-compare (pair-compare-car (car x) (car y)) (pair-compare-cdr (cdr x) (cdr y)))) ((compare x y) (cond-compare (((null? x) (null? y)) 0) (((pair? x) (pair? y)) (compare (car x) (car y)) (pair-compare compare (cdr x) (cdr y))) (else (compare x y)))) ((x y) (pair-compare default-compare x y)))) (define list-compare (case-lambda ((compare x y empty? head tail) (cond-compare (((empty? x) (empty? y)) 0) (else (compare (head x) (head y)) (list-compare compare (tail x) (tail y) empty? head tail)))) (( x y empty? head tail) (list-compare default-compare x y empty? head tail)) ((compare x y ) (list-compare compare x y null? car cdr)) (( x y ) (list-compare default-compare x y null? car cdr)))) (define list-compare-as-vector (case-lambda ((compare x y empty? head tail) (refine-compare (let compare-length ((x x) (y y)) (cond-compare (((empty? x) (empty? y)) 0) (else (compare-length (tail x) (tail y))))) (list-compare compare x y empty? head tail))) (( x y empty? head tail) (list-compare-as-vector default-compare x y empty? head tail)) ((compare x y ) (list-compare-as-vector compare x y null? car cdr)) (( x y ) (list-compare-as-vector default-compare x y null? car cdr)))) (define vector-compare (let ((= =)) (case-lambda ((compare x y size ref) (let ((n (size x)) (m (size y))) (refine-compare (integer-compare n m) compare x[i .. n-1 ] y[i .. n-1 ] (if (= i n) 0 (refine-compare (compare (ref x i) (ref y i)) (compare-rest (+ i 1)))))))) (( x y size ref) (vector-compare default-compare x y size ref)) ((compare x y ) (vector-compare compare x y vector-length vector-ref)) (( x y ) (vector-compare default-compare x y vector-length vector-ref))))) (define vector-compare-as-list (let ((= =)) (case-lambda ((compare x y size ref) (let ((nx (size x)) (ny (size y))) (let ((n (min nx ny))) compare x[i .. n-1 ] y[i .. n-1 ] (if (= i n) (integer-compare nx ny) (refine-compare (compare (ref x i) (ref y i)) (compare-rest (+ i 1)))))))) (( x y size ref) (vector-compare-as-list default-compare x y size ref)) ((compare x y ) (vector-compare-as-list compare x y vector-length vector-ref)) (( x y ) (vector-compare-as-list default-compare x y vector-length vector-ref))))) (define (default-compare x y) (select-compare x y (null? 0) (pair? (default-compare (car x) (car y)) (default-compare (cdr x) (cdr y))) (boolean? (boolean-compare x y)) (char? (char-compare x y)) (string? (string-compare x y)) (symbol? (symbol-compare x y)) (number? (number-compare x y)) (vector? (vector-compare default-compare x y)) (else (error "unrecognized type in default-compare" x y)))) (define (debug-compare c) (define (checked-value c x y) (let ((c-xy (c x y))) (if (or (eqv? c-xy -1) (eqv? c-xy 0) (eqv? c-xy 1)) c-xy (error "compare value not in {-1,0,1}" c-xy (list c x y))))) (define (random-boolean) (zero? (random-integer 2))) '#( )) (lambda (x y) (let ((c-xx (checked-value c x x)) (c-yy (checked-value c y y)) (c-xy (checked-value c x y)) (c-yx (checked-value c y x))) (if (not (zero? c-xx)) (error "compare error: not reflexive" c x)) (if (not (zero? c-yy)) (error "compare error: not reflexive" c y)) (if (not (zero? (+ c-xy c-yx))) (error "compare error: not anti-symmetric" c x y)) (if z? (let ((c-xz (checked-value c x z)) (c-zx (checked-value c z x)) (c-yz (checked-value c y z)) (c-zy (checked-value c z y))) (if (not (zero? (+ c-xz c-zx))) (error "compare error: not anti-symmetric" c x z)) (if (not (zero? (+ c-yz c-zy))) (error "compare error: not anti-symmetric" c y z)) (let ((ijk (vector-ref q (+ c-xy (* 3 c-yz) (* 9 c-xz) 13)))) (if (list? ijk) (apply error "compare error: not transitive" c (map (lambda (i) (case i ((x) x) ((y) y) ((z) z))) ijk))))) (set! z? #t)) c-xy))))