_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 |
|---|---|---|---|---|---|---|---|---|
d2884a6892b744c7387f9226d0b0b6b4a81534176bf9d25746fd8ab23886d333 | circleci/stefon | coffeescript.clj | (ns stefon.asset.coffeescript
(:refer-clojure :exclude [compile])
(:require [stefon.jsengine :as jsengine]
[stefon.asset :as asset]))
(def processor (jsengine/compiler "compileCoffeeScript"
["coffee-script.js" "coffee-wrapper.js"]))
(asset/register "cs" processor)
(asset/register "coffee" processor)
| null | https://raw.githubusercontent.com/circleci/stefon/7c36114923ef7ec41316e22354d2e31217a1a416/stefon-core/src/stefon/asset/coffeescript.clj | clojure | (ns stefon.asset.coffeescript
(:refer-clojure :exclude [compile])
(:require [stefon.jsengine :as jsengine]
[stefon.asset :as asset]))
(def processor (jsengine/compiler "compileCoffeeScript"
["coffee-script.js" "coffee-wrapper.js"]))
(asset/register "cs" processor)
(asset/register "coffee" processor)
| |
a28c6be36c801c7d75044a98c19ddb5ff626109f9fd8b4cb6cc8a3610482b587 | zcaudate/hara | raise.clj | (ns hara.event.condition.raise
(:require [hara.data.base.map :as map]
[hara.event.handler :as handler]
[hara.event.condition.data :as data]
[hara.event.condition.manage :as manage]))
(defn default-unhandled-fn
"raises an unhandled exception"
{:added "3.0"}
[issue]
(let [ex (data/exception issue)]
(throw ex)))
(declare raise-loop)
(defn raise-catch
"raises a catch exception"
{:added "3.0"}
[manager value]
(throw (data/catch-condition (:id manager) value)))
(defn raise-choose
"raises a choose exception"
{:added "3.0"}
[issue label args optmap]
(let [target (get optmap label)]
(cond (nil? target)
(throw (ex-info "Label has not been implemented." {:label label}))
(= target (:id issue))
(manage/manage-apply (-> issue :options label) args label)
:else
(throw (data/choose-condition target label args)))))
(defn- raise-unhandled [issue optmap]
(if-let [[label & args] (:default issue)]
(raise-choose issue label args optmap)
(default-unhandled-fn issue)))
(defn raise-fail
"raises a fail exception"
{:added "3.0"}
[issue data]
(throw (data/exception issue (handler/expand-data data))))
(defn- raise-escalate [issue res managers optmap]
(let [ndata (handler/expand-data (:data res))
noptions (:options res)
noptmap (zipmap (keys noptions) (repeat (:id issue)))
ndefault (:default res)
nissue (-> issue
(update-in [:data] merge ndata)
(update-in [:options] merge noptions)
(map/assoc-if :default ndefault))]
(raise-loop nissue (next managers) (merge noptmap optmap))))
(defn raise-loop
"makes sure that the issue has been handled by all managers"
{:added "3.0"}
[issue [manager & more :as managers] optmap]
(if manager
(if-let [handler (first (handler/match-handlers manager (:data issue)))]
(let [data (:data issue)
result ((:fn handler) data)]
(condp = (:type result)
:continue (:value result)
:choose (raise-choose issue (:label result) (:args result) optmap)
:default (raise-unhandled issue optmap)
:fail (raise-fail issue (:data result))
:escalate (raise-escalate issue result managers optmap)
(raise-catch manager result)))
(recur issue more optmap))
(raise-unhandled issue optmap)))
| null | https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/src/hara/event/condition/raise.clj | clojure | (ns hara.event.condition.raise
(:require [hara.data.base.map :as map]
[hara.event.handler :as handler]
[hara.event.condition.data :as data]
[hara.event.condition.manage :as manage]))
(defn default-unhandled-fn
"raises an unhandled exception"
{:added "3.0"}
[issue]
(let [ex (data/exception issue)]
(throw ex)))
(declare raise-loop)
(defn raise-catch
"raises a catch exception"
{:added "3.0"}
[manager value]
(throw (data/catch-condition (:id manager) value)))
(defn raise-choose
"raises a choose exception"
{:added "3.0"}
[issue label args optmap]
(let [target (get optmap label)]
(cond (nil? target)
(throw (ex-info "Label has not been implemented." {:label label}))
(= target (:id issue))
(manage/manage-apply (-> issue :options label) args label)
:else
(throw (data/choose-condition target label args)))))
(defn- raise-unhandled [issue optmap]
(if-let [[label & args] (:default issue)]
(raise-choose issue label args optmap)
(default-unhandled-fn issue)))
(defn raise-fail
"raises a fail exception"
{:added "3.0"}
[issue data]
(throw (data/exception issue (handler/expand-data data))))
(defn- raise-escalate [issue res managers optmap]
(let [ndata (handler/expand-data (:data res))
noptions (:options res)
noptmap (zipmap (keys noptions) (repeat (:id issue)))
ndefault (:default res)
nissue (-> issue
(update-in [:data] merge ndata)
(update-in [:options] merge noptions)
(map/assoc-if :default ndefault))]
(raise-loop nissue (next managers) (merge noptmap optmap))))
(defn raise-loop
"makes sure that the issue has been handled by all managers"
{:added "3.0"}
[issue [manager & more :as managers] optmap]
(if manager
(if-let [handler (first (handler/match-handlers manager (:data issue)))]
(let [data (:data issue)
result ((:fn handler) data)]
(condp = (:type result)
:continue (:value result)
:choose (raise-choose issue (:label result) (:args result) optmap)
:default (raise-unhandled issue optmap)
:fail (raise-fail issue (:data result))
:escalate (raise-escalate issue result managers optmap)
(raise-catch manager result)))
(recur issue more optmap))
(raise-unhandled issue optmap)))
| |
64fbe5c5d12ce06f2fb35b0ffee94d2d286b81dbda994557a32c9f21e9c82fd9 | philnguyen/soft-contract | morse-code-table.rkt | #lang racket
Copyright 2014 , except the portion that comes from wikipedia !
(provide (contract-out [char-table hash?]))
(require racket/match)
(define wikipedia-text
#<<#
| {{Audio-nohelp|A morse code.ogg|A}} || '''· –'''
| {{Audio-nohelp|J morse code.ogg|J}} || '''· – – –'''
· & nbsp ; · '' '
| {{Audio-nohelp|1 number morse code.ogg|1}} || '''· – – – –'''
| [[Full stop|Period]] [.] || '''· – · – · –'''
| [[Colon (punctuation)|Colon]] [:] || '''– – – · · ·'''
· & nbsp;·  ; · '' '
· & nbsp ; – '' '
| {{Audio-nohelp|T morse code.ogg|T}} || '''–'''
· & nbsp;– –  ; – '' '
| [[Comma (punctuation)|Comma]] [,] || '''– – · · – –'''
| [[Semicolon]] [;] || '''– · – · – ·'''
· & nbsp;–  ; · '' '
| {{Audio-nohelp|L morse code.ogg|L}} || '''· – · ·'''
· & nbsp ; – '' '
· & nbsp;· –  ; – '' '
· & nbsp;– – ·  ; · '' '
· & nbsp;· ·  ; – '' '
· & nbsp ; · '' '
| {{Audio-nohelp|M morse code.ogg|M}} || '''– –'''
· & nbsp;·  ; – '' '
· & nbsp;· ·  ; – '' '
| [[Apostrophe (punctuation)|Apostrophe]] ['] || '''· – – – – ·'''
| [[Plus and minus signs|Plus]] [+] || '''· – · – ·'''
| {{Audio-nohelp|E morse code.ogg|E}} || '''·'''
| {{Audio-nohelp|N morse code.ogg|N}} || '''– ·'''
| {{Audio-nohelp|W morse code.ogg|W}} || '''· – –'''
· & nbsp;· ·  ; · '' '
· & nbsp;– · –  ; – '' '
· & nbsp;· · ·  ; – '' '
· & nbsp;–  ; · '' '
| {{Audio-nohelp|O morse code.ogg|O}} || '''– – –'''
· & nbsp;·  ; – '' '
· & nbsp;· ·  ; · '' '
· & nbsp;· –  ; · '' '
· & nbsp;– – ·  ; – '' '
| {{Audio-nohelp|G morse code.ogg|G}} || '''– – ·'''
| {{Audio-nohelp|P morse code.ogg|P}} || '''· – – ·'''
· & nbsp;–  ; – '' '
| {{Audio-nohelp|7 number morse code.ogg|7}} || '''– – · · ·'''
· & nbsp;– –  ; · '' '
| [[Quotation mark]] ["] || '''· – · · – ·'''
· & nbsp;·  ; · '' '
| {{Audio-nohelp|Q morse code.ogg|Q}} || '''– – · –'''
| {{Audio-nohelp|Z morse code.ogg|Z}} || '''– – · ·'''
| {{Audio-nohelp|8 number morse code.ogg|8}} || '''– – – · ·'''
· & nbsp;– – ·  ; – '' '
| [[Dollar sign]] [$] || '''· · · – · · –'''
| {{Audio-nohelp|I morse code.ogg|I}} || '''· ·'''
| {{Audio-nohelp|R morse code.ogg|R}} || '''· – ·'''
| {{Audio-nohelp|0 number morse code.ogg|0}} || '''– – – – –'''
| {{Audio-nohelp|9 number morse code.ogg|9}} || '''– – – – ·'''
| [[Ampersand]] [&] || '''· – · · ·'''
– & nbsp;– · –  ; · '' '
#
)
;; the lines of the wikipedia text
(define lines (regexp-split #px"\n" wikipedia-text))
;; replace some unicode chars with ascii ones in the wikipedia patterns
(define (clean-pattern pat)
(regexp-replace*
#px"·"
(regexp-replace*
#px"–"
(apply string-append (regexp-split (regexp-quote " ") pat))
"-")
"."))
;; parse the wikipedia text into a table mapping characters to their morse code representations
(define char-table
(make-hash
(for/list
([l lines])
(match
(regexp-match #px"^\\| \\{\\{[^|]*\\|[^|]*\\|(.)\\}\\} \\|\\| '''([^']*)'''" l)
[#f
(match
(regexp-match #px"^\\| \\[\\[[^]]*\\]\\] \\[([^]]*)\\] \\|\\| '''([^']*)'''" l)
[(list whole-match char pattern)
(cond [(and char pattern)
(cons (car (string->list char)) (clean-pattern pattern))]
[else
(error 'char-table "broken regexp")])]
[#f (error 'char-table "what goes here?")])
]
[(list whole-match letter pattern)
(cond [(and letter pattern)
(cons (char-downcase (car (string->list letter))) (clean-pattern pattern))]
[else (error 'char-table "broken regexp 2")])]))))
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/gradual-typing-benchmarks/morsecode/morse-code-table.rkt | racket | –'''
– – –'''
· '' '
– – – –'''
– · – · –'''
– – · · ·'''
·  ; · '' '
– '' '
– –  ; – '' '
– · · – –'''
] || '''– · – · – ·'''
–  ; · '' '
– · ·'''
– '' '
· –  ; – '' '
– – ·  ; · '' '
· ·  ; – '' '
· '' '
–'''
·  ; – '' '
· ·  ; – '' '
– – – – ·'''
– · – ·'''
·'''
– –'''
· ·  ; · '' '
– · –  ; – '' '
· · ·  ; – '' '
–  ; · '' '
– –'''
·  ; – '' '
· ·  ; · '' '
· –  ; · '' '
– – ·  ; – '' '
– ·'''
– – ·'''
–  ; – '' '
– · · ·'''
– –  ; · '' '
– · · – ·'''
·  ; · '' '
– · –'''
– · ·'''
– – · ·'''
– – ·  ; – '' '
· · – · · –'''
·'''
– ·'''
– – – –'''
– – – ·'''
– · · ·'''
– · –  ; · '' '
the lines of the wikipedia text
replace some unicode chars with ascii ones in the wikipedia patterns
parse the wikipedia text into a table mapping characters to their morse code representations | #lang racket
Copyright 2014 , except the portion that comes from wikipedia !
(provide (contract-out [char-table hash?]))
(require racket/match)
(define wikipedia-text
#<<#
| {{Audio-nohelp|T morse code.ogg|T}} || '''–'''
| {{Audio-nohelp|E morse code.ogg|E}} || '''·'''
#
)
(define lines (regexp-split #px"\n" wikipedia-text))
(define (clean-pattern pat)
(regexp-replace*
#px"·"
(regexp-replace*
#px"–"
(apply string-append (regexp-split (regexp-quote " ") pat))
"-")
"."))
(define char-table
(make-hash
(for/list
([l lines])
(match
(regexp-match #px"^\\| \\{\\{[^|]*\\|[^|]*\\|(.)\\}\\} \\|\\| '''([^']*)'''" l)
[#f
(match
(regexp-match #px"^\\| \\[\\[[^]]*\\]\\] \\[([^]]*)\\] \\|\\| '''([^']*)'''" l)
[(list whole-match char pattern)
(cond [(and char pattern)
(cons (car (string->list char)) (clean-pattern pattern))]
[else
(error 'char-table "broken regexp")])]
[#f (error 'char-table "what goes here?")])
]
[(list whole-match letter pattern)
(cond [(and letter pattern)
(cons (char-downcase (car (string->list letter))) (clean-pattern pattern))]
[else (error 'char-table "broken regexp 2")])]))))
|
c566918627a3cf640f02aaf0f0532bc3929d4284f5f5fd036d4dea88dd0b17b1 | quoll/raphael | core.cljc | (ns ^{:doc "A namespace for manually parsing Turtle. Entry point is parse-doc."
:author "Paula Gearon"}
quoll.raphael.core
(:require [clojure.string :as str]
[quoll.raphael.m :refer [throw-unex] :include-macros true]
[quoll.raphael.text :as text :refer [char-at]]
[quoll.raphael.triples :as triples])
#?(:clj (:import [clojure.lang ExceptionInfo])))
(def RDF "-rdf-syntax-ns#")
(def ^:dynamic *loc* (volatile! [1 0]))
(defn reset-pos! [] (vreset! *loc* [0 0]))
(defn update-pos!
[n]
(vswap! *loc* (fn [loc] [(inc (nth loc 0)) n])))
(defprotocol IRI
(as-iri-string [iri generator] "Returns this object as an iri string."))
(defprotocol NodeGenerator
(new-node [generator] [generator label]
"Generate a new node, optionally with a label indicating a reusable node. Return the next generator and node")
(add-base [generator iri]
"Adds a base iri for the document")
(add-prefix [generator prefix iri]
"Adds a prefix/iri pair to the namespace map")
(iri-for [generator prefix]
"Gets the stored iri for a given prefix")
(get-namespaces [generator]
"Returns a map of all the namespaces recorded by this generator")
(get-base [generator]
"Returns the base of this generator, if one has been set")
(new-qname [generator prefix local]
"Returns a Qualified Name object.")
(new-iri [generator iri]
"Returns an IRI object.")
(new-literal [generator s] [generator s t]
"Returns a literal. Either simple, or with a type")
(new-lang-string [generator s l]
"Returns a string literal, with a language tag")
(rdf-type [generator] "Returns the rdf:type qname")
(rdf-first [generator] "Returns the rdf:first qname")
(rdf-rest [generator] "Returns the rdf:rest qname")
(rdf-nil [generator] "Returns the rdf:nil qname"))
(defrecord BlankNode [n]
Object
(toString [this] (str "_:b" n)))
(defrecord Iri [prefix local iri]
IRI
(as-iri-string [this generator] (or iri (str (iri-for generator prefix) local)))
Object
(toString [this] (if prefix
(str prefix ":" local)
(str "<" iri ">"))))
(extend-protocol IRI
#?(:clj String :cljs string)
(as-iri-string [this generator] this))
(def RDF-TYPE (->Iri "rdf" "type" "-rdf-syntax-ns#type"))
(def RDF-FIRST (->Iri "rdf" "first" "-rdf-syntax-ns#first"))
(def RDF-REST (->Iri "rdf" "rest" "-rdf-syntax-ns#rest"))
(def RDF-NIL (->Iri "rdf" "nil" "-rdf-syntax-ns#nil"))
(defn iri-string
"Converts an IRI to a string form for printing"
[iri-ref]
(if (string? iri-ref)
(str \< iri-ref \>)
(str iri-ref)))
(def echar-map {\newline "\\n"
\return "\\r"
\tab "\\t"
\formfeed "\\f"
\backspace "\\b"
\" "\\\""
\\ "\\\\"})
(defn print-escape
"Escapes a string for printing"
[s]
(str \"
(-> s
(str/replace #"[\n\r\t\f\"\\]" #(echar-map (char-at % 0)))
(str/replace "\b" "\\b"))
\"))
(defrecord Literal [value lang type]
Object
(toString [this]
(cond
lang (str (print-escape value) "@" lang)
type (str (print-escape value) "^^" (iri-string type))
:default (print-escape value))))
(defrecord Generator [counter bnode-cache namespaces]
NodeGenerator
(new-node [this]
[(update this :counter inc) (->BlankNode counter)])
(new-node [this label]
(if-let [node (get bnode-cache label)]
[this node]
(let [node (->BlankNode counter)]
[(-> this
(update :counter inc)
(update :bnode-cache assoc label node))
node])))
(add-base [this iri]
(update this :namespaces assoc :base (as-iri-string iri this)))
(add-prefix [this prefix iri]
(update this :namespaces assoc prefix (as-iri-string iri this)))
(iri-for [this prefix]
(get namespaces prefix))
(get-namespaces [this]
(dissoc namespaces :base))
(get-base [this]
(:base namespaces))
(new-qname [this prefix local]
(->Iri prefix local (str (get namespaces prefix) local)))
(new-iri [this iri]
(->Iri nil nil iri))
(new-literal [this s]
(->Literal s nil nil))
(new-literal [this s t]
(->Literal s nil t))
(new-lang-string [this s lang]
(->Literal s lang nil))
(rdf-type [this] RDF-TYPE)
(rdf-first [this] RDF-FIRST)
(rdf-rest [this] RDF-REST)
(rdf-nil [this] RDF-NIL))
(defn new-generator [] (->Generator 0 {} {}))
(defn add-range
"Adds a range of characters into set.
chars - the set of characters.
low - the low end of the character range to add, inclusive.
high - the high end of the character range to add, inclusive.
return - the set with the new range of characters added."
[chars low high]
(into chars (map char) (range (text/char-code low) (inc (text/char-code high)))))
(def whitespace? #{\space \tab \return \newline})
(def hex? (-> #{} (add-range \0 \9) (add-range \A \F) (add-range \a \f)))
(def pn-chars-base?
(-> #{}
(add-range \A \Z) (add-range \a \z) (add-range \u00C0 \u00D6) (add-range \u00D8 \u00F6)
(add-range \u00F8 \u02FF) (add-range \u0370 \u037D) (add-range \u037F \u1FFF)
(add-range \u200C \u200D) (add-range \u2070 \u218F) (add-range \u2C00 \u2FEF)
(add-range \u3001 \uD7FF) (add-range \uF900 \uFDCF) (add-range \uFDF0 \uFFFD)))
( range 0x10000 0xEFFFF ) will be taken care of by the high / low surrogate tests
(def pn-chars-u? (conj pn-chars-base? \_))
(def pn-chars-ud? (add-range pn-chars-u? \0 \9))
(def pn-chars?
(-> pn-chars-u?
(conj \-)
(add-range \0 \9)
(conj \u00B7)
(add-range \u0300 \u036F)
(add-range \u203F \u2040)))
(def pn-chars-dot? (conj pn-chars? \.))
(def local-chars? (-> pn-chars-u?
(add-range \0 \9)
(conj \:)
(conj \%)
(conj \\)))
(def local-chars2? (-> pn-chars?
(conj \:)
(conj \.)
(conj \%)
(conj \\)))
(def local-esc? #{\_ \~ \. \- \! \$ \& \' \( \) \* \+ \, \; \= \/ \? \# \@ \%})
(def non-iri-char? #{\< \> \" \{ \} \| \^ \` \space :eof})
(defn dot? [c] (= \. c))
(defn newline? [c] (= \newline c))
(def end-comment? #{\newline :eof})
(defn skip-whitespace
"Skip over the whitespace starting from a position in a string.
s - The string to read.
n - The starting position.
c - The character at position n.
return: [n c]
n - the new offset after skipping whitespace.
c - the first non-whitespace character, found at position n"
[s n c]
(loop [n n c c]
(if (= :eof c)
[n :eof]
(if (whitespace? c)
(let [n' (inc n)]
(when (= \newline c) (update-pos! n))
(recur n' (char-at s n')))
(if (= \# c)
(let [n' (loop [nn (inc n)]
(let [cc (char-at s nn)
nn' (inc nn)]
(if (end-comment? cc)
(do
(when (= \newline cc) (update-pos! nn))
nn')
(recur nn'))))]
(recur n' (char-at s n')))
[n c])))))
(defn skip-to
"Skip over the whitespace to the required character. If there are nonwhitespace characters, this is an error.
s - The string to read.
n - The starting position.
c - The character at position n.
chars - the set of chars to skip to.
return: [n c]
n - the new offset after skipping whitespace to the end of the line.
c - the first non-whitespace character, found at position n"
[s n c chars]
(loop [n n c c]
(cond
(chars c) (let [n' (inc n)]
[n' (char-at s n')])
(whitespace? c) (let [n' (inc n)]
(when (= \newline c) (update-pos! n))
(recur n' (char-at s n')))
(= \# c) (let [n' (loop [nn (inc n)]
(let [cc (char-at s nn)
nn' (inc nn)]
(if (end-comment? cc)
(do
(when (= \newline cc) (update-pos! nn))
nn')
(recur nn'))))]
(recur n' (char-at s n')))
:default (throw-unex *loc* "Unexpected characters after end of line: " s n))))
(defn skip-past-dot
"Skip to the terminating dot. If non-whitespace is found, then report an error.
s - The string to parse.
n - The position in the string.
return: [n c]"
[s n c]
(let [[n c] (skip-whitespace s n c)]
(if (= \. c)
(let [n' (inc n)]
[n' (char-at s n')])
(throw (ex-info (str "Unexpected character found at offset: " n) {:offset n :character c})))))
(defn parse-prefix
"Parse a prefix. This is a simple string terminated with a ':'. The : character is not part of the prefix.
s - The string to parse.
n - The offset to parse from.
c - The character at offset n.
return: [n c prefix]
n - The offset immediately after the prefix.
c - The character at offset n.
prefix - The prefix string."
[s n c]
(let [sb (text/string-builder)]
(loop [n' n c (char-at s n)]
(cond
(= \: c) (if (= \. (text/last-char sb))
(throw-unex *loc* "Unexpected '.' at end of prefix: " s n)
(let [nn' (inc n')]
[nn' (char-at s nn') (str sb)]))
(= n n') (cond
(pn-chars-base? c) (let [n' (inc n')]
(text/append! sb c)
(recur n' (char-at s n')))
(text/high-surrogate? c) (let [nn (+ n' 2)
c2 (char-at s (inc n'))]
(when-not (text/low-surrogate? c2)
(throw-unex *loc* "Bad Unicode characters at start of prefix: " s n))
(text/append! sb c)
(text/append! sb c2)
(recur nn (char-at s nn)))
:default (throw-unex *loc* "Unexpected character at start of prefix: " s n))
(pn-chars? c) (let [n' (inc n')]
(text/append! sb c)
(recur n' (char-at s n')))
(text/high-surrogate? c) (let [nn (+ n' 2)
c2 (char-at s (inc n'))]
(when-not (text/low-surrogate? c2)
(throw-unex *loc* "Bad Unicode characters in prefix: " s n))
(text/append! sb c)
(text/append! sb c2)
(recur nn (char-at s nn)))
:default (throw-unex *loc* (str "Unexpected character '" c "' (" (text/char-code c) ") in prefix: ") s n)))))
(defn parse-u-char
"Parse a an unescapped code of uxxxx or Uxxxxxxxx. A preceding \\ character was just parsed.
s - the string to parse.
n - the offset within the string to parse from.
f - the character found at position n. Must be u or U.
return: [n char]
n - the offset immediately after the ucode
char - the character code that was parsed"
[s n f]
(case f
\u (let [end (+ n 5)]
[end (char-at s end) (char (text/parse-hex (subs s (inc n) end)))])
\U (let [end (+ n 9)
unicode (text/parse-hex (subs s (inc n) end))
[high low] (text/surrogates unicode)]
[end (char-at s end) (str (char high) (char low))])
(throw-unex *loc* "Unexpected non-U character when processing unicode escape" s n)))
A regex to find the scheme at the start of an IRI
(def scheme-re #"^[A-Za-z][A-Za-z0-9.+-]*:")
(defn relative-iri?
"Indicates if an IRI is relative."
[s]
(nil? (re-find scheme-re s)))
(defn parse-iri-ref
"Parse an iri references. This is an iri string surrounded by <> characters. The <> characters are not returned.
s - The string to parse.
n - The offset to parse from.
c - the first character of the iri reference.
gen - the current generator
triples - the current triples
return: [n c iri gen triples]
n - The offset immediately after the prefix.
c - the character at offset n.
iri - The iri string.
gen - the generator.
triples - the current triples."
[s n c gen triples]
(when-not (= c \<)
(throw-unex *loc* "Unexpected character commencing an IRI Reference: " s n))
(let [sb (text/string-builder)]
(loop [n (inc n) c (char-at s n)]
(if (= c \>)
(let [i (str sb)
iri (new-iri gen (if (relative-iri? i)
(if-let [base (get-base gen)] (str base i) i)
i))
n' (inc n)]
[n' (char-at s n') iri gen triples])
(if (non-iri-char? c)
(throw-unex *loc* "Unexpected character in IRI: " s n)
(if (= c \\)
(if-let [[n' c' ch] (let [nn (inc n)] (parse-u-char s nn (char-at s nn)))]
(do
(text/append! sb ch)
(recur n' c'))
(throw-unex *loc* "Unexpected \\ character in IRI: " s n))
(let [n' (inc n)]
(text/append! sb c)
(recur n' (char-at s n')))))))))
(defn parse-local
"Parse a local into a string.
s - The string to parse.
n - The offset to parse from.
return: [n c local]
n - the offset immediately after the local name.
c - the character at offset n.
local - the parsed local name."
[s n]
(let [sb (text/string-builder)
add-char (fn [c n] ;; adds a char, looking ahead if this is an escape sequence
(case c
\% (let [a (char-at s (inc n))
b (char-at s (+ n 2))]
(if (and (hex? a) (hex? b))
(do
(text/append! sb c)
(text/append! sb a)
(text/append! sb b)
(+ n 3))
(throw-unex *loc* "Bad escape code in localname: " s n)))
\\ (let [a (char-at s (inc n))]
(if (local-esc? a)
(do
(text/append! sb a)
(+ n 2))
(throw-unex *loc* "Bad escape code in localname: " s n)))
(do
(text/append! sb c)
(inc n))))
f (char-at s n)
_ (when-not (local-chars? f) (throw-unex *loc* (str "Unexpected character '" f "' in local name: ") s n))
n (add-char f n)]
(loop [n n c (char-at s n)]
(if (= \. c) ;; at a dot. Check if this is inside a local name or terminating it
(let [n' (inc n) ;; look ahead
c' (char-at s n')]
(if (local-chars2? c')
;; the next character is a valid local name character, so save and continue parsing
(do
a dot , so do n't need to check for PLX ( % hh or \ escape )
(recur n' c'))
;; no, this must mean the local name ended already, and the dot is terminating a line
;; return the current name, along with the position of the dot
[n c (str sb)]))
(if (local-chars2? c)
;; a valid local name char, so save and continue
(let [n' (add-char c n)]
(recur n' (char-at s n')))
[n c (str sb)])))))
(defn parse-prefixed-name
"Parse a prefix:local-name pair.
s - The string to parse.
n - The offset to parse from.
c - the first character of the prefixed name.
gen - the generator
triples - the current triples.
return: [n c prefix]
n - The offset immediately after the prefixed name.
c - The character immediately after the prefixed name.
qname - The prefixed name as a Iri.
gen - the updated generator.
triples - the triples generated in parsing the node."
[s n c gen triples]
(when-not (or (pn-chars-base? c) (= \: c))
(throw-unex *loc* "Prefix char starts with illegal character" s n))
(let [sb (text/string-builder)
[n prefix] (loop [n n c c dot false]
(if (= \: c)
(if dot
(throw-unex *loc* "Prefix illegally ends with a '.': " s n)
[(inc n) (str sb)])
(if (pn-chars-dot? c)
(let [n' (inc n)]
(text/append! sb c)
(recur n' (char-at s n') (dot? c)))
(if (and (whitespace? c) (= "a" (str sb)))
[(inc n) nil]
(throw-unex *loc* (str "Illegal character '" c "' in prefix: ") s n)))))]
(if prefix
(let [[n c local] (parse-local s n)]
[n c (new-qname gen prefix local) gen triples])
[n (char-at s n) (rdf-type gen) gen triples])))
(defn parse-iri
"Parse an iri.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n.
gen - the generator to use.
triples - the current triples.
return: [n c iri]
n - the offset immediately after the iri.
c - the character at offset n.
iri - the node for the parsed iri. Either an IRI string or an Iri.
gen - the updated generator.
triples - the triples generated in parsing the node."
[s n c gen triples]
(if (= \< c)
(parse-iri-ref s n c gen triples)
(parse-prefixed-name s n c gen triples)))
(def echars "Maps ascii characters into their escape code"
{\b \backspace
\t \tab
\n \newline
\r \return
\f \formfeed
\\ \\})
(defn escape
"Reads an escaped code from the input starting at the current position.
s - the string to parse
n - the position of the beginning of the already escaped sequence (after the \\ character)
c - the character at position n
return: [n c value]
n - the position immediately following the escaped sequence
c - the character at n
value - the unescaped character."
[s n c]
(if-let [e (echars c)]
(let [n' (inc n)]
[n' (char-at s n') e])
(if (#{\u \U} c)
(parse-u-char s n c)
(throw-unex *loc* (str "Unexpected escape character <" c "> found in literal: ") s n))))
(defn parse-long-string
"Parse a triple-quoted string form. Because this is already identified as a triple quote
the offset of n and the character represent the first character after the quotes.
end-q - the ending quote character to terminate on.
s - the string to parse.
n - the offset to parse from. After the quotes.
c - the char found at position n.
c - the char found at position n.
gen - the node generator.
return: [n c value]
n - the offset immediately after the closing quotes.
c - the character at offset n.
value - the parsed string. "
[end-q s n c]
(let [sb (text/string-builder)]
(loop [n n esc false current (char-at s n)]
(cond
(= end-q current)
(if esc
(throw-unex *loc* "Unexpected escape sequence in long-form string: " s (dec n))
(let [n' (inc n)
next-char (char-at s n')
n2 (inc n')
c2 (char-at s n2)]
(if (= end-q next-char)
(let [n3 (inc n2)
c3 (char-at s n3)]
(if (= end-q c2)
[n3 c3 (str sb)]
third character was not a third quote
(text/append! sb current)
(text/append! sb next-char)
(if (= \\ c2)
(recur n3 true c3)
(do
(when (= \newline current) (update-pos! n))
(text/append! sb c2)
(recur n3 false c3))))))
second character was not a second quote
(text/append! sb current)
(if (= \\ next-char)
(recur n2 true c2)
(do
(when (= \newline current) (update-pos! n))
(text/append! sb next-char)
(recur n2 false c2)))))))
(= :eof current)
(throw-unex *loc* "Improperly terminated long literal: " s n)
:default
(if esc
(let [[n2 c2 ecode] (escape s n current)]
(text/append! sb ecode)
(recur n2 false c2))
(let [n' (inc n)
next-char (char-at s n')]
(if (= \\ current)
(recur n' true next-char)
(do
(text/append! sb current)
(recur n' false next-char)))))))))
(defn parse-string
"Parse a single-quoted string form.
end-q - the ending quote character to terminate on.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n. This is after the opening quote character.
gen - the node generator.
triples - the current triples.
return: [n c value]
n - the offset immediately after the subject.
c - the character at offset n.
value - the parsed string. "
[end-q s n c]
(let [sb (text/string-builder)]
(loop [n n esc false current c]
(cond
(= end-q current) ;; end of the string, unless escaped
(let [n' (inc n)
next-char (char-at s n')]
(if esc
(do
(text/append! sb current)
(recur n' false next-char))
[n' next-char (str sb)]))
(= :eof current)
(throw-unex *loc* "Improperly terminated literal: " s n)
:default
(if esc
(let [[n2 c2 ecode] (escape s n current)]
(text/append! sb ecode)
(recur n2 false c2))
(let [n' (inc n)
next-char (char-at s n')]
(if (= \\ current)
(recur n' true next-char)
(do
(when (= \newline current) (update-pos! n))
(text/append! sb current)
(recur n' false next-char)))))))))
(defn parse-literal
"Parse a literal that starts with a quote character. This also includes the
triple quote form that allows for raw unescaped strings.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n. This is a quote: either ' or \"
gen - the node generator.
triples - the current triples.
return: [n c value]
n - the offset immediately after the subject.
c - the character at offset n.
value - the parsed value, in string form if it is plain.
gen - the updated generator.
triples - the triples generated in parsing the node."
[s n c gen triples]
(let [n' (inc n)
c' (char-at s n')
startlong (+ 2 n)
[n c lit-str] (if (= c' c)
(let [n2 (inc n')
c2 (char-at s n2)]
(if (= c2 c)
(let [n3 (inc n2)]
(parse-long-string c s n3 (char-at s n3)))
[n2 c2 ""]))
(parse-string c s n' c'))]
(case c
\^ (if (= \^ (char-at s (inc n)))
(let [n2 (+ n 2)
[n' c' iri gen triples] (parse-iri s n2 (char-at s n2) gen triples)]
[n' c' (new-literal gen lit-str iri) gen triples])
(throw-unex *loc* "Badly formed type expression on literal. Expected ^^: " s n))
\@ (let [n' (inc n)]
(if-let [[lang] (re-find #"^[a-zA-Z]+(-[a-zA-Z0-9]+)*" (subs s n'))]
(let [end (+ n' (count lang))]
[end (char-at s end) (new-lang-string gen lit-str lang) gen triples])
(throw-unex *loc* "Bad language tag on literal: " s n')))
[n c lit-str gen triples])))
(def end-mantissa? #{\e \E :eof})
(defn parse-number
"Parse a numeric literal.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n.
gen - the node generator.
triples - the current triples.
return: [n c value]
n - the offset immediately after the subject.
c - the character at offset n.
value - the parsed number.
gen - the updated generator
triples - the triples generated in parsing the node."
[s n c gen triples]
;; at a minimum, up-to-dot will be populated by at least a sign, a digit, or a dot
(let [up-to-dot (re-find #"[+-]?[0-9]*\.?" (subs s n))
nd (+ n (count up-to-dot))
[after-dot exp] (re-find #"^[0-9]*([eE][+-]?[0-9]+)?" (subs s nd))
n' (+ nd (count after-dot))
nextc (char-at s n')
full-nr (subs s n n')
;; test here to avoid catching an exception in the core parser
_ (when (let [frst (.charAt up-to-dot 0)]
(or (and (#{\+ \-} frst)
(let [sec (char-at full-nr 1)]
(or (end-mantissa? sec)
(and (= \. sec) (end-mantissa? (char-at full-nr 2))))))
(and (= \. frst) (end-mantissa? (char-at full-nr 1)))
(and (nil? exp) (#{\e \E} nextc))))
(throw-unex *loc* (str "Invalid number: '" full-nr "' in:") s n))
nr (if (or (= \. (text/last-char-str up-to-dot)) (re-find #"[eE]" after-dot))
(parse-double full-nr)
(parse-long full-nr))]
[n' nextc nr gen triples]))
(declare parse-predicate parse-object)
(defn parse-collection
"Parses a collection. This creates a linked list in the triples.
s - The string to parse.
n - The offset to parse from.
c - the first character of the collection
gen - the current generator
triples - the current triples
return: [n c node gen triples]
n - The offset immediately after the prefix.
c - the character at offset n.
node - The node representing the collection.
gen - the generator.
triples - the current triples."
[s n c gen triples]
(let [n' (inc n)
[n c] (skip-whitespace s (inc n) (char-at s n'))
rfirst (rdf-first gen)
rrest (rdf-rest gen)
rnil (rdf-nil gen)]
(if (= \) c)
(let [n' (inc n)]
[n' (char-at s n') rnil gen triples])
(let [[gen head] (new-node gen)]
(loop [last-node head [n c node gen triples] (parse-object s n c gen triples)]
(let [triples (triples/append! triples last-node rfirst node)
[n c] (skip-whitespace s n c)]
(if (= \) c)
(let [n' (inc n)
triples (triples/append! triples last-node rrest rnil)]
[n' (char-at s n') head gen triples])
(let [[gen node] (new-node gen)
triples (triples/append! triples last-node rrest node)]
(recur node (parse-object s n c gen triples))))))))))
(defn parse-blank-node
"Parses a blank node label.
s - The string to parse.
n - The offset to parse from.
c - the first character of the blank node
gen - the current generator
triples - the current triples
return: [n c node gen triples]
n - The offset immediately after the prefix.
c - the character at offset n.
node - The blank node.
gen - the generator.
triples - the current triples."
[s n c gen triples]
(when-not (= \: (char-at s (inc n)))
(throw-unex *loc* "Illegal underscore (_) at start of symbol: " s n))
(let [c (char-at s (+ n 2))
_ (when-not (pn-chars-ud? c)
(throw-unex *loc* "Illegal character at start of blank node label: " s n))
sb (text/string-builder)
_ (text/append! sb c)
[n c label] (loop [n (+ 3 n) c (char-at s n) dot false]
(if (pn-chars-dot? c)
(let [n' (inc n)]
(text/append! sb c)
(recur n' (char-at s n') (dot? c)))
(if dot
(throw-unex *loc* "blank node illegally ends with a '.': " s n)
[n c (str sb)])))
[gen node] (new-node gen label)]
[n c node gen triples]))
(def end-list? #{\] \.})
(defn maybe-parse-predicate
"Parses an IRI as a predicate if one is available. Otherwise return a nil as the IRI.
s - The string to parse.
n - The offset to parse from.
c - the first character of the iri reference.
gen - the current generator
triples - the current triples
return: [n c iri gen triples]
n - The offset immediately after the prefix.
c - the character at offset n.
iri - The iri string.
gen - the generator.
triples - the current triples."
[s n c gen triples]
(if (end-list? c)
[n c nil gen triples]
(parse-iri s n c gen triples)))
(defn parse-predicate-object-list
"Parse a predicate-object list
s - The string to parse from
n - The offset in the string to start at.
c - The character at position n
gen - The generator for blank nodes and namespace resolution
triples - An accumulating transient of triples.
return [n c gen triples]
n - the new parse position
c - the character at position n
gen - the updated generator
triples - the updated triples sequence."
[s n c subject gen triples]
(loop [[n c pred gen triples :as all] (maybe-parse-predicate s n c gen triples)]
(if-not pred
[n c gen triples]
(let [[n c] (skip-whitespace s n c)
[n c gen triples] (loop [[n c obj gen triples] (parse-object s n c gen triples)]
(let [[n c] (skip-whitespace s n c)
triples (triples/append! triples subject pred obj)]
(case c
(\] \. \;) [n c gen triples]
\, (let [n' (inc n)
[n c] (skip-whitespace s n' (char-at s n'))]
(if-let [parse-result (try
(parse-object s n c gen triples)
(catch ExceptionInfo e nil))]
(recur parse-result)
[n c gen triples]))
(throw-unex *loc* "Unexpected separator in predicate-object list: " s n))))]
(if (= c \;)
(let [n' (inc n)
[n c] (skip-whitespace s n' (char-at s n'))]
(recur (maybe-parse-predicate s n c gen triples)))
[n c gen triples])))))
(defn anon-blank-node
"Generates a new blank node with no properties. Already passed the opening [ character, and whitespace.
This function just steps to the next position.
s - The string to parse. Not read by this function.
n - The position in the string.
c - The character at position n. This must be a ]
g - The generator.
triples - An accumulating transient of triples.
return: [n c node gen triples more?]
n - The next character position after the blank node.
c - the character found at n
node - the new anonymous blank node
gen - the updated generator
triples - the updated triples sequence
enf? - If this is a subject, then is this is not enough and properties are required. Always false."
[s n c g triples]
(let [n' (inc n)
[g node] (new-node g)]
[n' (char-at s n') node g triples false]))
(defn parse-blank-node-entity
"Parse a blank node property/value list. Already past the opening [ character and whitespace.
s - The string to parse from
n - The offset in the string to start at.
c - The character at position n
gen - The generator for blank nodes and namespace resolution
triples - An accumulating transient of triples.
return [n c node gen triples]
n - the new parse position
c - the character at position n
node - the root blank node that is being parsed
gen - the updated generator
triples - the updated triples sequence
enf? - is this enough if this is a subject? A predicateObject sequence is not needed. true."
[s n c gen triples]
(let [[gen node] (new-node gen)
[n c gen triples] (parse-predicate-object-list s n c node gen triples)
[n c] (skip-whitespace s n c)]
(if (= c \])
(let [n' (inc n)]
[n' (char-at s n') node gen triples true])
(throw-unex *loc* "Structured blank node entity improperly terminated: " s n))))
(defn parse-subject
"Parse a subject entity, including any triples.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n.
gen - the node generator.
triples - the current triples.
return: [n c subject gen triples]
n - the offset immediately after the subject.
c - the character at offset n.
subject - the node for the parsed subject.
gen - the updated generator
triples - the triples generated in parsing the node.
enf? - indicates if this subject is enough and a predicateObject list is not needed.
Most types return nil for this (falsey)."
[s n c gen triples]
(case c
\< (parse-iri-ref s n c gen triples)
\( (parse-collection s n c gen triples)
\_ (parse-blank-node s n c gen triples)
\[ (let [n' (inc n)
[n c] (skip-whitespace s n' (char-at s n'))]
(if (= \] c)
(anon-blank-node s n c gen triples)
(parse-blank-node-entity s n c gen triples)))
(parse-prefixed-name s n c gen triples)))
(defn parse-object
"Parse an object entity, including any triples.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n.
gen - the node generator.
triples - the current triples.
return: [n c object gen triples]
n - the offset immediately after the object.
c - the character at offset n.
object - the node for the parsed object.
gen - the updated generator.
triples - the triples generated in parsing the node.
Blank node entities can also return a true at the end of the vector, but this should be ignored."
[s n c gen triples]
(case c
\< (parse-iri-ref s n c gen triples)
\( (parse-collection s n c gen triples)
\_ (parse-blank-node s n c gen triples)
\[ (let [n' (inc n)
[n c] (skip-whitespace s n' (char-at s n'))]
(if (= \] c)
(anon-blank-node s n c gen triples)
(parse-blank-node-entity s n c gen triples)))
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \. \+ \-) (parse-number s n c gen triples)
(\' \") (parse-literal s n c gen triples)
(cond
(and (= c \f)
(= "alse" (text/ssubs s (inc n) (+ n 5)))
(not (pn-chars? (char-at s (+ n 5))))) (let [n' (+ n 5)]
[n' (char-at s n') false gen triples])
(and (= c \t)
(= "rue" (text/ssubs s (inc n) (+ n 4)))
(not (pn-chars? (char-at s (+ n 4))))) (let [n' (+ n 4)]
[n' (char-at s n') true gen triples])
:default (parse-prefixed-name s n c gen triples))))
(defn parse-triples
"Parse a top level triples from a string.
s - the string to parse from.
n - the offset in the string to retrieve from.
c - the character found at position n.
gen - the generator to use for blank nodes.
triples - A transient vector of triples.
return: [n c gen triples]
n - the new offset after parsing.
c - the character at offset n.
gen - the next generator state.
triples - the triples generated from parsing this line."
[s n c gen triples]
(let [initial-count (count triples)
[n c] (skip-whitespace s n c)]
(if (= :eof c)
[n :eof gen triples]
(let [[n c subject gen triples enf?] (parse-subject s n c gen triples)
[n c] (skip-whitespace s n c)
[n c gen triples] (parse-predicate-object-list s n c subject gen triples)]
(when-not (= \. c)
(throw-unex *loc* "Statements invalidly terminated: " s n))
(when (and (not enf?) (= initial-count (count triples)))
(throw-unex *loc* "Subjects require predicates and objects: " s n))
(let [n' (inc n)]
[n' (char-at s n') gen triples])))))
(defn parse-prefix-iri-end
"Parse an iri and a newline for a PREFIX or BASE directive.
NOTE: THIS FUNCTION DOES NOT USE AN INCOMING CHARACTER
s - The string to parse from.
n - The offset to start the parse from.
gen - The generator to update.
end-char - A test for the final character
skip - The number of characters to skip over before looking for the first whitespace
return: [n c gen]
n - the position of the end of the line.
c - character at position n
gen - the new generator."
[s n gen end-char skip]
(let [nskip (+ n skip)
c (char-at s nskip)]
(if (whitespace? c)
(let [[n c] (skip-whitespace s nskip c)
[n c prefix] (parse-prefix s n c)
[n c] (skip-whitespace s n c)
[n c iri] (parse-iri-ref s n c gen nil)
[n c] (skip-to s n c end-char)]
[n c (add-prefix gen prefix iri)])
(throw-unex *loc* "Unknown statement: " s n))))
(defn parse-base-end
"Parse an iri and a dot.
NOTE: THIS FUNCTION DOES NOT USE AN INCOMING CHARACTER
s - The string to parse from.
n - The offset to start the parse from.
gen - The generator to update.
end-char - A test for the final character
skip - The number of characters to skip over before looking for the first whitespace
return: [n c gen]
n - the position of the end of the line.
c - character at position n
gen - the new generator."
[s n gen end-char skip]
(let [nskip (+ n skip)
c (char-at s nskip)]
(if (whitespace? c)
(let [[n c] (skip-whitespace s nskip c)
;; nil triples, since triples are not being generated during a directive
[n c iri] (parse-iri-ref s n c gen nil)
[n c] (skip-to s n c end-char)]
[n c (add-base gen iri)])
(throw-unex *loc* "Unknown statement: " s n))))
(defn parse-statement
"Parse a directive or triples.
s - The string to parse.
n - The position in the string to parse from.
c - the character at position n. (Optional: can be inferred)
gen - The current generator.
triples - The current triples.
return: [n c gen triples]
n - the new offset after parsing.
c - the character at position n.
gen - the next generator state.
triples - the triples generated from parsing this line."
([s n gen triples] (parse-statement s n (char-at s n) gen triples))
([s n c gen triples]
(let [[n c] (skip-whitespace s n c)
[n' c' gen'] (case c
\@ (cond
(= (str/lower-case (subs s (inc n) (+ n 5))) "base") (parse-base-end s n gen dot? 5)
(= (str/lower-case (subs s (inc n) (+ n 7))) "prefix") (parse-prefix-iri-end s n gen dot? 7)
:default (throw-unex *loc* "Unknown statement: " s n))
(\B \b) (when (and (= (str/lower-case (subs s (inc n) (+ n 4))) "ase")
(whitespace? (char-at s (+ n 4))))
(parse-base-end s n gen newline? 4))
(\P \p) (when (and (= (str/lower-case (subs s (inc n) (+ n 6))) "refix")
(whitespace? (char-at s (+ n 6))))
(parse-prefix-iri-end s n gen newline? 6))
:eof [n c gen triples]
nil)]
(if n'
[n' c' gen' triples]
(parse-triples s n c gen triples)))))
(defn parse
"parse a string as a turtle document
s - the stirng containing the document.
g - an implementation of the Generator protocol for assigning blank nodes, IRIs and Literals,
and managing namespaces. Optional.
return: {:base <optional IRI>
:namespaces <prefixes mapped to IRIs>
:triples <vector of 3 element vectors>}"
([s] (parse s (new-generator)))
([s generator]
(reset-pos!)
(let [triples (triples/triple-accumulator)
[n gen triples] (binding [*loc* (volatile! [1 0])]
(loop [[n c gen triples] (parse-statement s 0 generator triples)]
(if (= :eof c)
[n gen triples]
(recur (parse-statement s n c gen triples)))))
result {:namespaces (get-namespaces gen)
:triples (seq triples)}
base (get-base gen)]
(if base
(assoc result :base base)
result))))
| null | https://raw.githubusercontent.com/quoll/raphael/eb69299b6e6c288ff7828f2d4279b0b3209d1c58/src/quoll/raphael/core.cljc | clojure | \= \/ \? \# \@ \%})
adds a char, looking ahead if this is an escape sequence
at a dot. Check if this is inside a local name or terminating it
look ahead
the next character is a valid local name character, so save and continue parsing
no, this must mean the local name ended already, and the dot is terminating a line
return the current name, along with the position of the dot
a valid local name char, so save and continue
end of the string, unless escaped
at a minimum, up-to-dot will be populated by at least a sign, a digit, or a dot
test here to avoid catching an exception in the core parser
) [n c gen triples]
)
nil triples, since triples are not being generated during a directive | (ns ^{:doc "A namespace for manually parsing Turtle. Entry point is parse-doc."
:author "Paula Gearon"}
quoll.raphael.core
(:require [clojure.string :as str]
[quoll.raphael.m :refer [throw-unex] :include-macros true]
[quoll.raphael.text :as text :refer [char-at]]
[quoll.raphael.triples :as triples])
#?(:clj (:import [clojure.lang ExceptionInfo])))
(def RDF "-rdf-syntax-ns#")
(def ^:dynamic *loc* (volatile! [1 0]))
(defn reset-pos! [] (vreset! *loc* [0 0]))
(defn update-pos!
[n]
(vswap! *loc* (fn [loc] [(inc (nth loc 0)) n])))
(defprotocol IRI
(as-iri-string [iri generator] "Returns this object as an iri string."))
(defprotocol NodeGenerator
(new-node [generator] [generator label]
"Generate a new node, optionally with a label indicating a reusable node. Return the next generator and node")
(add-base [generator iri]
"Adds a base iri for the document")
(add-prefix [generator prefix iri]
"Adds a prefix/iri pair to the namespace map")
(iri-for [generator prefix]
"Gets the stored iri for a given prefix")
(get-namespaces [generator]
"Returns a map of all the namespaces recorded by this generator")
(get-base [generator]
"Returns the base of this generator, if one has been set")
(new-qname [generator prefix local]
"Returns a Qualified Name object.")
(new-iri [generator iri]
"Returns an IRI object.")
(new-literal [generator s] [generator s t]
"Returns a literal. Either simple, or with a type")
(new-lang-string [generator s l]
"Returns a string literal, with a language tag")
(rdf-type [generator] "Returns the rdf:type qname")
(rdf-first [generator] "Returns the rdf:first qname")
(rdf-rest [generator] "Returns the rdf:rest qname")
(rdf-nil [generator] "Returns the rdf:nil qname"))
(defrecord BlankNode [n]
Object
(toString [this] (str "_:b" n)))
(defrecord Iri [prefix local iri]
IRI
(as-iri-string [this generator] (or iri (str (iri-for generator prefix) local)))
Object
(toString [this] (if prefix
(str prefix ":" local)
(str "<" iri ">"))))
(extend-protocol IRI
#?(:clj String :cljs string)
(as-iri-string [this generator] this))
(def RDF-TYPE (->Iri "rdf" "type" "-rdf-syntax-ns#type"))
(def RDF-FIRST (->Iri "rdf" "first" "-rdf-syntax-ns#first"))
(def RDF-REST (->Iri "rdf" "rest" "-rdf-syntax-ns#rest"))
(def RDF-NIL (->Iri "rdf" "nil" "-rdf-syntax-ns#nil"))
(defn iri-string
"Converts an IRI to a string form for printing"
[iri-ref]
(if (string? iri-ref)
(str \< iri-ref \>)
(str iri-ref)))
(def echar-map {\newline "\\n"
\return "\\r"
\tab "\\t"
\formfeed "\\f"
\backspace "\\b"
\" "\\\""
\\ "\\\\"})
(defn print-escape
"Escapes a string for printing"
[s]
(str \"
(-> s
(str/replace #"[\n\r\t\f\"\\]" #(echar-map (char-at % 0)))
(str/replace "\b" "\\b"))
\"))
(defrecord Literal [value lang type]
Object
(toString [this]
(cond
lang (str (print-escape value) "@" lang)
type (str (print-escape value) "^^" (iri-string type))
:default (print-escape value))))
(defrecord Generator [counter bnode-cache namespaces]
NodeGenerator
(new-node [this]
[(update this :counter inc) (->BlankNode counter)])
(new-node [this label]
(if-let [node (get bnode-cache label)]
[this node]
(let [node (->BlankNode counter)]
[(-> this
(update :counter inc)
(update :bnode-cache assoc label node))
node])))
(add-base [this iri]
(update this :namespaces assoc :base (as-iri-string iri this)))
(add-prefix [this prefix iri]
(update this :namespaces assoc prefix (as-iri-string iri this)))
(iri-for [this prefix]
(get namespaces prefix))
(get-namespaces [this]
(dissoc namespaces :base))
(get-base [this]
(:base namespaces))
(new-qname [this prefix local]
(->Iri prefix local (str (get namespaces prefix) local)))
(new-iri [this iri]
(->Iri nil nil iri))
(new-literal [this s]
(->Literal s nil nil))
(new-literal [this s t]
(->Literal s nil t))
(new-lang-string [this s lang]
(->Literal s lang nil))
(rdf-type [this] RDF-TYPE)
(rdf-first [this] RDF-FIRST)
(rdf-rest [this] RDF-REST)
(rdf-nil [this] RDF-NIL))
(defn new-generator [] (->Generator 0 {} {}))
(defn add-range
"Adds a range of characters into set.
chars - the set of characters.
low - the low end of the character range to add, inclusive.
high - the high end of the character range to add, inclusive.
return - the set with the new range of characters added."
[chars low high]
(into chars (map char) (range (text/char-code low) (inc (text/char-code high)))))
(def whitespace? #{\space \tab \return \newline})
(def hex? (-> #{} (add-range \0 \9) (add-range \A \F) (add-range \a \f)))
(def pn-chars-base?
(-> #{}
(add-range \A \Z) (add-range \a \z) (add-range \u00C0 \u00D6) (add-range \u00D8 \u00F6)
(add-range \u00F8 \u02FF) (add-range \u0370 \u037D) (add-range \u037F \u1FFF)
(add-range \u200C \u200D) (add-range \u2070 \u218F) (add-range \u2C00 \u2FEF)
(add-range \u3001 \uD7FF) (add-range \uF900 \uFDCF) (add-range \uFDF0 \uFFFD)))
( range 0x10000 0xEFFFF ) will be taken care of by the high / low surrogate tests
(def pn-chars-u? (conj pn-chars-base? \_))
(def pn-chars-ud? (add-range pn-chars-u? \0 \9))
(def pn-chars?
(-> pn-chars-u?
(conj \-)
(add-range \0 \9)
(conj \u00B7)
(add-range \u0300 \u036F)
(add-range \u203F \u2040)))
(def pn-chars-dot? (conj pn-chars? \.))
(def local-chars? (-> pn-chars-u?
(add-range \0 \9)
(conj \:)
(conj \%)
(conj \\)))
(def local-chars2? (-> pn-chars?
(conj \:)
(conj \.)
(conj \%)
(conj \\)))
(def non-iri-char? #{\< \> \" \{ \} \| \^ \` \space :eof})
(defn dot? [c] (= \. c))
(defn newline? [c] (= \newline c))
(def end-comment? #{\newline :eof})
(defn skip-whitespace
"Skip over the whitespace starting from a position in a string.
s - The string to read.
n - The starting position.
c - The character at position n.
return: [n c]
n - the new offset after skipping whitespace.
c - the first non-whitespace character, found at position n"
[s n c]
(loop [n n c c]
(if (= :eof c)
[n :eof]
(if (whitespace? c)
(let [n' (inc n)]
(when (= \newline c) (update-pos! n))
(recur n' (char-at s n')))
(if (= \# c)
(let [n' (loop [nn (inc n)]
(let [cc (char-at s nn)
nn' (inc nn)]
(if (end-comment? cc)
(do
(when (= \newline cc) (update-pos! nn))
nn')
(recur nn'))))]
(recur n' (char-at s n')))
[n c])))))
(defn skip-to
"Skip over the whitespace to the required character. If there are nonwhitespace characters, this is an error.
s - The string to read.
n - The starting position.
c - The character at position n.
chars - the set of chars to skip to.
return: [n c]
n - the new offset after skipping whitespace to the end of the line.
c - the first non-whitespace character, found at position n"
[s n c chars]
(loop [n n c c]
(cond
(chars c) (let [n' (inc n)]
[n' (char-at s n')])
(whitespace? c) (let [n' (inc n)]
(when (= \newline c) (update-pos! n))
(recur n' (char-at s n')))
(= \# c) (let [n' (loop [nn (inc n)]
(let [cc (char-at s nn)
nn' (inc nn)]
(if (end-comment? cc)
(do
(when (= \newline cc) (update-pos! nn))
nn')
(recur nn'))))]
(recur n' (char-at s n')))
:default (throw-unex *loc* "Unexpected characters after end of line: " s n))))
(defn skip-past-dot
"Skip to the terminating dot. If non-whitespace is found, then report an error.
s - The string to parse.
n - The position in the string.
return: [n c]"
[s n c]
(let [[n c] (skip-whitespace s n c)]
(if (= \. c)
(let [n' (inc n)]
[n' (char-at s n')])
(throw (ex-info (str "Unexpected character found at offset: " n) {:offset n :character c})))))
(defn parse-prefix
"Parse a prefix. This is a simple string terminated with a ':'. The : character is not part of the prefix.
s - The string to parse.
n - The offset to parse from.
c - The character at offset n.
return: [n c prefix]
n - The offset immediately after the prefix.
c - The character at offset n.
prefix - The prefix string."
[s n c]
(let [sb (text/string-builder)]
(loop [n' n c (char-at s n)]
(cond
(= \: c) (if (= \. (text/last-char sb))
(throw-unex *loc* "Unexpected '.' at end of prefix: " s n)
(let [nn' (inc n')]
[nn' (char-at s nn') (str sb)]))
(= n n') (cond
(pn-chars-base? c) (let [n' (inc n')]
(text/append! sb c)
(recur n' (char-at s n')))
(text/high-surrogate? c) (let [nn (+ n' 2)
c2 (char-at s (inc n'))]
(when-not (text/low-surrogate? c2)
(throw-unex *loc* "Bad Unicode characters at start of prefix: " s n))
(text/append! sb c)
(text/append! sb c2)
(recur nn (char-at s nn)))
:default (throw-unex *loc* "Unexpected character at start of prefix: " s n))
(pn-chars? c) (let [n' (inc n')]
(text/append! sb c)
(recur n' (char-at s n')))
(text/high-surrogate? c) (let [nn (+ n' 2)
c2 (char-at s (inc n'))]
(when-not (text/low-surrogate? c2)
(throw-unex *loc* "Bad Unicode characters in prefix: " s n))
(text/append! sb c)
(text/append! sb c2)
(recur nn (char-at s nn)))
:default (throw-unex *loc* (str "Unexpected character '" c "' (" (text/char-code c) ") in prefix: ") s n)))))
(defn parse-u-char
"Parse a an unescapped code of uxxxx or Uxxxxxxxx. A preceding \\ character was just parsed.
s - the string to parse.
n - the offset within the string to parse from.
f - the character found at position n. Must be u or U.
return: [n char]
n - the offset immediately after the ucode
char - the character code that was parsed"
[s n f]
(case f
\u (let [end (+ n 5)]
[end (char-at s end) (char (text/parse-hex (subs s (inc n) end)))])
\U (let [end (+ n 9)
unicode (text/parse-hex (subs s (inc n) end))
[high low] (text/surrogates unicode)]
[end (char-at s end) (str (char high) (char low))])
(throw-unex *loc* "Unexpected non-U character when processing unicode escape" s n)))
A regex to find the scheme at the start of an IRI
(def scheme-re #"^[A-Za-z][A-Za-z0-9.+-]*:")
(defn relative-iri?
"Indicates if an IRI is relative."
[s]
(nil? (re-find scheme-re s)))
(defn parse-iri-ref
"Parse an iri references. This is an iri string surrounded by <> characters. The <> characters are not returned.
s - The string to parse.
n - The offset to parse from.
c - the first character of the iri reference.
gen - the current generator
triples - the current triples
return: [n c iri gen triples]
n - The offset immediately after the prefix.
c - the character at offset n.
iri - The iri string.
gen - the generator.
triples - the current triples."
[s n c gen triples]
(when-not (= c \<)
(throw-unex *loc* "Unexpected character commencing an IRI Reference: " s n))
(let [sb (text/string-builder)]
(loop [n (inc n) c (char-at s n)]
(if (= c \>)
(let [i (str sb)
iri (new-iri gen (if (relative-iri? i)
(if-let [base (get-base gen)] (str base i) i)
i))
n' (inc n)]
[n' (char-at s n') iri gen triples])
(if (non-iri-char? c)
(throw-unex *loc* "Unexpected character in IRI: " s n)
(if (= c \\)
(if-let [[n' c' ch] (let [nn (inc n)] (parse-u-char s nn (char-at s nn)))]
(do
(text/append! sb ch)
(recur n' c'))
(throw-unex *loc* "Unexpected \\ character in IRI: " s n))
(let [n' (inc n)]
(text/append! sb c)
(recur n' (char-at s n')))))))))
(defn parse-local
"Parse a local into a string.
s - The string to parse.
n - The offset to parse from.
return: [n c local]
n - the offset immediately after the local name.
c - the character at offset n.
local - the parsed local name."
[s n]
(let [sb (text/string-builder)
(case c
\% (let [a (char-at s (inc n))
b (char-at s (+ n 2))]
(if (and (hex? a) (hex? b))
(do
(text/append! sb c)
(text/append! sb a)
(text/append! sb b)
(+ n 3))
(throw-unex *loc* "Bad escape code in localname: " s n)))
\\ (let [a (char-at s (inc n))]
(if (local-esc? a)
(do
(text/append! sb a)
(+ n 2))
(throw-unex *loc* "Bad escape code in localname: " s n)))
(do
(text/append! sb c)
(inc n))))
f (char-at s n)
_ (when-not (local-chars? f) (throw-unex *loc* (str "Unexpected character '" f "' in local name: ") s n))
n (add-char f n)]
(loop [n n c (char-at s n)]
c' (char-at s n')]
(if (local-chars2? c')
(do
a dot , so do n't need to check for PLX ( % hh or \ escape )
(recur n' c'))
[n c (str sb)]))
(if (local-chars2? c)
(let [n' (add-char c n)]
(recur n' (char-at s n')))
[n c (str sb)])))))
(defn parse-prefixed-name
"Parse a prefix:local-name pair.
s - The string to parse.
n - The offset to parse from.
c - the first character of the prefixed name.
gen - the generator
triples - the current triples.
return: [n c prefix]
n - The offset immediately after the prefixed name.
c - The character immediately after the prefixed name.
qname - The prefixed name as a Iri.
gen - the updated generator.
triples - the triples generated in parsing the node."
[s n c gen triples]
(when-not (or (pn-chars-base? c) (= \: c))
(throw-unex *loc* "Prefix char starts with illegal character" s n))
(let [sb (text/string-builder)
[n prefix] (loop [n n c c dot false]
(if (= \: c)
(if dot
(throw-unex *loc* "Prefix illegally ends with a '.': " s n)
[(inc n) (str sb)])
(if (pn-chars-dot? c)
(let [n' (inc n)]
(text/append! sb c)
(recur n' (char-at s n') (dot? c)))
(if (and (whitespace? c) (= "a" (str sb)))
[(inc n) nil]
(throw-unex *loc* (str "Illegal character '" c "' in prefix: ") s n)))))]
(if prefix
(let [[n c local] (parse-local s n)]
[n c (new-qname gen prefix local) gen triples])
[n (char-at s n) (rdf-type gen) gen triples])))
(defn parse-iri
"Parse an iri.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n.
gen - the generator to use.
triples - the current triples.
return: [n c iri]
n - the offset immediately after the iri.
c - the character at offset n.
iri - the node for the parsed iri. Either an IRI string or an Iri.
gen - the updated generator.
triples - the triples generated in parsing the node."
[s n c gen triples]
(if (= \< c)
(parse-iri-ref s n c gen triples)
(parse-prefixed-name s n c gen triples)))
(def echars "Maps ascii characters into their escape code"
{\b \backspace
\t \tab
\n \newline
\r \return
\f \formfeed
\\ \\})
(defn escape
"Reads an escaped code from the input starting at the current position.
s - the string to parse
n - the position of the beginning of the already escaped sequence (after the \\ character)
c - the character at position n
return: [n c value]
n - the position immediately following the escaped sequence
c - the character at n
value - the unescaped character."
[s n c]
(if-let [e (echars c)]
(let [n' (inc n)]
[n' (char-at s n') e])
(if (#{\u \U} c)
(parse-u-char s n c)
(throw-unex *loc* (str "Unexpected escape character <" c "> found in literal: ") s n))))
(defn parse-long-string
"Parse a triple-quoted string form. Because this is already identified as a triple quote
the offset of n and the character represent the first character after the quotes.
end-q - the ending quote character to terminate on.
s - the string to parse.
n - the offset to parse from. After the quotes.
c - the char found at position n.
c - the char found at position n.
gen - the node generator.
return: [n c value]
n - the offset immediately after the closing quotes.
c - the character at offset n.
value - the parsed string. "
[end-q s n c]
(let [sb (text/string-builder)]
(loop [n n esc false current (char-at s n)]
(cond
(= end-q current)
(if esc
(throw-unex *loc* "Unexpected escape sequence in long-form string: " s (dec n))
(let [n' (inc n)
next-char (char-at s n')
n2 (inc n')
c2 (char-at s n2)]
(if (= end-q next-char)
(let [n3 (inc n2)
c3 (char-at s n3)]
(if (= end-q c2)
[n3 c3 (str sb)]
third character was not a third quote
(text/append! sb current)
(text/append! sb next-char)
(if (= \\ c2)
(recur n3 true c3)
(do
(when (= \newline current) (update-pos! n))
(text/append! sb c2)
(recur n3 false c3))))))
second character was not a second quote
(text/append! sb current)
(if (= \\ next-char)
(recur n2 true c2)
(do
(when (= \newline current) (update-pos! n))
(text/append! sb next-char)
(recur n2 false c2)))))))
(= :eof current)
(throw-unex *loc* "Improperly terminated long literal: " s n)
:default
(if esc
(let [[n2 c2 ecode] (escape s n current)]
(text/append! sb ecode)
(recur n2 false c2))
(let [n' (inc n)
next-char (char-at s n')]
(if (= \\ current)
(recur n' true next-char)
(do
(text/append! sb current)
(recur n' false next-char)))))))))
(defn parse-string
"Parse a single-quoted string form.
end-q - the ending quote character to terminate on.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n. This is after the opening quote character.
gen - the node generator.
triples - the current triples.
return: [n c value]
n - the offset immediately after the subject.
c - the character at offset n.
value - the parsed string. "
[end-q s n c]
(let [sb (text/string-builder)]
(loop [n n esc false current c]
(cond
(let [n' (inc n)
next-char (char-at s n')]
(if esc
(do
(text/append! sb current)
(recur n' false next-char))
[n' next-char (str sb)]))
(= :eof current)
(throw-unex *loc* "Improperly terminated literal: " s n)
:default
(if esc
(let [[n2 c2 ecode] (escape s n current)]
(text/append! sb ecode)
(recur n2 false c2))
(let [n' (inc n)
next-char (char-at s n')]
(if (= \\ current)
(recur n' true next-char)
(do
(when (= \newline current) (update-pos! n))
(text/append! sb current)
(recur n' false next-char)))))))))
(defn parse-literal
"Parse a literal that starts with a quote character. This also includes the
triple quote form that allows for raw unescaped strings.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n. This is a quote: either ' or \"
gen - the node generator.
triples - the current triples.
return: [n c value]
n - the offset immediately after the subject.
c - the character at offset n.
value - the parsed value, in string form if it is plain.
gen - the updated generator.
triples - the triples generated in parsing the node."
[s n c gen triples]
(let [n' (inc n)
c' (char-at s n')
startlong (+ 2 n)
[n c lit-str] (if (= c' c)
(let [n2 (inc n')
c2 (char-at s n2)]
(if (= c2 c)
(let [n3 (inc n2)]
(parse-long-string c s n3 (char-at s n3)))
[n2 c2 ""]))
(parse-string c s n' c'))]
(case c
\^ (if (= \^ (char-at s (inc n)))
(let [n2 (+ n 2)
[n' c' iri gen triples] (parse-iri s n2 (char-at s n2) gen triples)]
[n' c' (new-literal gen lit-str iri) gen triples])
(throw-unex *loc* "Badly formed type expression on literal. Expected ^^: " s n))
\@ (let [n' (inc n)]
(if-let [[lang] (re-find #"^[a-zA-Z]+(-[a-zA-Z0-9]+)*" (subs s n'))]
(let [end (+ n' (count lang))]
[end (char-at s end) (new-lang-string gen lit-str lang) gen triples])
(throw-unex *loc* "Bad language tag on literal: " s n')))
[n c lit-str gen triples])))
(def end-mantissa? #{\e \E :eof})
(defn parse-number
"Parse a numeric literal.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n.
gen - the node generator.
triples - the current triples.
return: [n c value]
n - the offset immediately after the subject.
c - the character at offset n.
value - the parsed number.
gen - the updated generator
triples - the triples generated in parsing the node."
[s n c gen triples]
(let [up-to-dot (re-find #"[+-]?[0-9]*\.?" (subs s n))
nd (+ n (count up-to-dot))
[after-dot exp] (re-find #"^[0-9]*([eE][+-]?[0-9]+)?" (subs s nd))
n' (+ nd (count after-dot))
nextc (char-at s n')
full-nr (subs s n n')
_ (when (let [frst (.charAt up-to-dot 0)]
(or (and (#{\+ \-} frst)
(let [sec (char-at full-nr 1)]
(or (end-mantissa? sec)
(and (= \. sec) (end-mantissa? (char-at full-nr 2))))))
(and (= \. frst) (end-mantissa? (char-at full-nr 1)))
(and (nil? exp) (#{\e \E} nextc))))
(throw-unex *loc* (str "Invalid number: '" full-nr "' in:") s n))
nr (if (or (= \. (text/last-char-str up-to-dot)) (re-find #"[eE]" after-dot))
(parse-double full-nr)
(parse-long full-nr))]
[n' nextc nr gen triples]))
(declare parse-predicate parse-object)
(defn parse-collection
"Parses a collection. This creates a linked list in the triples.
s - The string to parse.
n - The offset to parse from.
c - the first character of the collection
gen - the current generator
triples - the current triples
return: [n c node gen triples]
n - The offset immediately after the prefix.
c - the character at offset n.
node - The node representing the collection.
gen - the generator.
triples - the current triples."
[s n c gen triples]
(let [n' (inc n)
[n c] (skip-whitespace s (inc n) (char-at s n'))
rfirst (rdf-first gen)
rrest (rdf-rest gen)
rnil (rdf-nil gen)]
(if (= \) c)
(let [n' (inc n)]
[n' (char-at s n') rnil gen triples])
(let [[gen head] (new-node gen)]
(loop [last-node head [n c node gen triples] (parse-object s n c gen triples)]
(let [triples (triples/append! triples last-node rfirst node)
[n c] (skip-whitespace s n c)]
(if (= \) c)
(let [n' (inc n)
triples (triples/append! triples last-node rrest rnil)]
[n' (char-at s n') head gen triples])
(let [[gen node] (new-node gen)
triples (triples/append! triples last-node rrest node)]
(recur node (parse-object s n c gen triples))))))))))
(defn parse-blank-node
"Parses a blank node label.
s - The string to parse.
n - The offset to parse from.
c - the first character of the blank node
gen - the current generator
triples - the current triples
return: [n c node gen triples]
n - The offset immediately after the prefix.
c - the character at offset n.
node - The blank node.
gen - the generator.
triples - the current triples."
[s n c gen triples]
(when-not (= \: (char-at s (inc n)))
(throw-unex *loc* "Illegal underscore (_) at start of symbol: " s n))
(let [c (char-at s (+ n 2))
_ (when-not (pn-chars-ud? c)
(throw-unex *loc* "Illegal character at start of blank node label: " s n))
sb (text/string-builder)
_ (text/append! sb c)
[n c label] (loop [n (+ 3 n) c (char-at s n) dot false]
(if (pn-chars-dot? c)
(let [n' (inc n)]
(text/append! sb c)
(recur n' (char-at s n') (dot? c)))
(if dot
(throw-unex *loc* "blank node illegally ends with a '.': " s n)
[n c (str sb)])))
[gen node] (new-node gen label)]
[n c node gen triples]))
(def end-list? #{\] \.})
(defn maybe-parse-predicate
"Parses an IRI as a predicate if one is available. Otherwise return a nil as the IRI.
s - The string to parse.
n - The offset to parse from.
c - the first character of the iri reference.
gen - the current generator
triples - the current triples
return: [n c iri gen triples]
n - The offset immediately after the prefix.
c - the character at offset n.
iri - The iri string.
gen - the generator.
triples - the current triples."
[s n c gen triples]
(if (end-list? c)
[n c nil gen triples]
(parse-iri s n c gen triples)))
(defn parse-predicate-object-list
"Parse a predicate-object list
s - The string to parse from
n - The offset in the string to start at.
c - The character at position n
gen - The generator for blank nodes and namespace resolution
triples - An accumulating transient of triples.
return [n c gen triples]
n - the new parse position
c - the character at position n
gen - the updated generator
triples - the updated triples sequence."
[s n c subject gen triples]
(loop [[n c pred gen triples :as all] (maybe-parse-predicate s n c gen triples)]
(if-not pred
[n c gen triples]
(let [[n c] (skip-whitespace s n c)
[n c gen triples] (loop [[n c obj gen triples] (parse-object s n c gen triples)]
(let [[n c] (skip-whitespace s n c)
triples (triples/append! triples subject pred obj)]
(case c
\, (let [n' (inc n)
[n c] (skip-whitespace s n' (char-at s n'))]
(if-let [parse-result (try
(parse-object s n c gen triples)
(catch ExceptionInfo e nil))]
(recur parse-result)
[n c gen triples]))
(throw-unex *loc* "Unexpected separator in predicate-object list: " s n))))]
(let [n' (inc n)
[n c] (skip-whitespace s n' (char-at s n'))]
(recur (maybe-parse-predicate s n c gen triples)))
[n c gen triples])))))
(defn anon-blank-node
"Generates a new blank node with no properties. Already passed the opening [ character, and whitespace.
This function just steps to the next position.
s - The string to parse. Not read by this function.
n - The position in the string.
c - The character at position n. This must be a ]
g - The generator.
triples - An accumulating transient of triples.
return: [n c node gen triples more?]
n - The next character position after the blank node.
c - the character found at n
node - the new anonymous blank node
gen - the updated generator
triples - the updated triples sequence
enf? - If this is a subject, then is this is not enough and properties are required. Always false."
[s n c g triples]
(let [n' (inc n)
[g node] (new-node g)]
[n' (char-at s n') node g triples false]))
(defn parse-blank-node-entity
"Parse a blank node property/value list. Already past the opening [ character and whitespace.
s - The string to parse from
n - The offset in the string to start at.
c - The character at position n
gen - The generator for blank nodes and namespace resolution
triples - An accumulating transient of triples.
return [n c node gen triples]
n - the new parse position
c - the character at position n
node - the root blank node that is being parsed
gen - the updated generator
triples - the updated triples sequence
enf? - is this enough if this is a subject? A predicateObject sequence is not needed. true."
[s n c gen triples]
(let [[gen node] (new-node gen)
[n c gen triples] (parse-predicate-object-list s n c node gen triples)
[n c] (skip-whitespace s n c)]
(if (= c \])
(let [n' (inc n)]
[n' (char-at s n') node gen triples true])
(throw-unex *loc* "Structured blank node entity improperly terminated: " s n))))
(defn parse-subject
"Parse a subject entity, including any triples.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n.
gen - the node generator.
triples - the current triples.
return: [n c subject gen triples]
n - the offset immediately after the subject.
c - the character at offset n.
subject - the node for the parsed subject.
gen - the updated generator
triples - the triples generated in parsing the node.
enf? - indicates if this subject is enough and a predicateObject list is not needed.
Most types return nil for this (falsey)."
[s n c gen triples]
(case c
\< (parse-iri-ref s n c gen triples)
\( (parse-collection s n c gen triples)
\_ (parse-blank-node s n c gen triples)
\[ (let [n' (inc n)
[n c] (skip-whitespace s n' (char-at s n'))]
(if (= \] c)
(anon-blank-node s n c gen triples)
(parse-blank-node-entity s n c gen triples)))
(parse-prefixed-name s n c gen triples)))
(defn parse-object
"Parse an object entity, including any triples.
s - the string to parse.
n - the offset to parse from.
c - the char found at position n.
gen - the node generator.
triples - the current triples.
return: [n c object gen triples]
n - the offset immediately after the object.
c - the character at offset n.
object - the node for the parsed object.
gen - the updated generator.
triples - the triples generated in parsing the node.
Blank node entities can also return a true at the end of the vector, but this should be ignored."
[s n c gen triples]
(case c
\< (parse-iri-ref s n c gen triples)
\( (parse-collection s n c gen triples)
\_ (parse-blank-node s n c gen triples)
\[ (let [n' (inc n)
[n c] (skip-whitespace s n' (char-at s n'))]
(if (= \] c)
(anon-blank-node s n c gen triples)
(parse-blank-node-entity s n c gen triples)))
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \. \+ \-) (parse-number s n c gen triples)
(\' \") (parse-literal s n c gen triples)
(cond
(and (= c \f)
(= "alse" (text/ssubs s (inc n) (+ n 5)))
(not (pn-chars? (char-at s (+ n 5))))) (let [n' (+ n 5)]
[n' (char-at s n') false gen triples])
(and (= c \t)
(= "rue" (text/ssubs s (inc n) (+ n 4)))
(not (pn-chars? (char-at s (+ n 4))))) (let [n' (+ n 4)]
[n' (char-at s n') true gen triples])
:default (parse-prefixed-name s n c gen triples))))
(defn parse-triples
"Parse a top level triples from a string.
s - the string to parse from.
n - the offset in the string to retrieve from.
c - the character found at position n.
gen - the generator to use for blank nodes.
triples - A transient vector of triples.
return: [n c gen triples]
n - the new offset after parsing.
c - the character at offset n.
gen - the next generator state.
triples - the triples generated from parsing this line."
[s n c gen triples]
(let [initial-count (count triples)
[n c] (skip-whitespace s n c)]
(if (= :eof c)
[n :eof gen triples]
(let [[n c subject gen triples enf?] (parse-subject s n c gen triples)
[n c] (skip-whitespace s n c)
[n c gen triples] (parse-predicate-object-list s n c subject gen triples)]
(when-not (= \. c)
(throw-unex *loc* "Statements invalidly terminated: " s n))
(when (and (not enf?) (= initial-count (count triples)))
(throw-unex *loc* "Subjects require predicates and objects: " s n))
(let [n' (inc n)]
[n' (char-at s n') gen triples])))))
(defn parse-prefix-iri-end
"Parse an iri and a newline for a PREFIX or BASE directive.
NOTE: THIS FUNCTION DOES NOT USE AN INCOMING CHARACTER
s - The string to parse from.
n - The offset to start the parse from.
gen - The generator to update.
end-char - A test for the final character
skip - The number of characters to skip over before looking for the first whitespace
return: [n c gen]
n - the position of the end of the line.
c - character at position n
gen - the new generator."
[s n gen end-char skip]
(let [nskip (+ n skip)
c (char-at s nskip)]
(if (whitespace? c)
(let [[n c] (skip-whitespace s nskip c)
[n c prefix] (parse-prefix s n c)
[n c] (skip-whitespace s n c)
[n c iri] (parse-iri-ref s n c gen nil)
[n c] (skip-to s n c end-char)]
[n c (add-prefix gen prefix iri)])
(throw-unex *loc* "Unknown statement: " s n))))
(defn parse-base-end
"Parse an iri and a dot.
NOTE: THIS FUNCTION DOES NOT USE AN INCOMING CHARACTER
s - The string to parse from.
n - The offset to start the parse from.
gen - The generator to update.
end-char - A test for the final character
skip - The number of characters to skip over before looking for the first whitespace
return: [n c gen]
n - the position of the end of the line.
c - character at position n
gen - the new generator."
[s n gen end-char skip]
(let [nskip (+ n skip)
c (char-at s nskip)]
(if (whitespace? c)
(let [[n c] (skip-whitespace s nskip c)
[n c iri] (parse-iri-ref s n c gen nil)
[n c] (skip-to s n c end-char)]
[n c (add-base gen iri)])
(throw-unex *loc* "Unknown statement: " s n))))
(defn parse-statement
"Parse a directive or triples.
s - The string to parse.
n - The position in the string to parse from.
c - the character at position n. (Optional: can be inferred)
gen - The current generator.
triples - The current triples.
return: [n c gen triples]
n - the new offset after parsing.
c - the character at position n.
gen - the next generator state.
triples - the triples generated from parsing this line."
([s n gen triples] (parse-statement s n (char-at s n) gen triples))
([s n c gen triples]
(let [[n c] (skip-whitespace s n c)
[n' c' gen'] (case c
\@ (cond
(= (str/lower-case (subs s (inc n) (+ n 5))) "base") (parse-base-end s n gen dot? 5)
(= (str/lower-case (subs s (inc n) (+ n 7))) "prefix") (parse-prefix-iri-end s n gen dot? 7)
:default (throw-unex *loc* "Unknown statement: " s n))
(\B \b) (when (and (= (str/lower-case (subs s (inc n) (+ n 4))) "ase")
(whitespace? (char-at s (+ n 4))))
(parse-base-end s n gen newline? 4))
(\P \p) (when (and (= (str/lower-case (subs s (inc n) (+ n 6))) "refix")
(whitespace? (char-at s (+ n 6))))
(parse-prefix-iri-end s n gen newline? 6))
:eof [n c gen triples]
nil)]
(if n'
[n' c' gen' triples]
(parse-triples s n c gen triples)))))
(defn parse
"parse a string as a turtle document
s - the stirng containing the document.
g - an implementation of the Generator protocol for assigning blank nodes, IRIs and Literals,
and managing namespaces. Optional.
return: {:base <optional IRI>
:namespaces <prefixes mapped to IRIs>
:triples <vector of 3 element vectors>}"
([s] (parse s (new-generator)))
([s generator]
(reset-pos!)
(let [triples (triples/triple-accumulator)
[n gen triples] (binding [*loc* (volatile! [1 0])]
(loop [[n c gen triples] (parse-statement s 0 generator triples)]
(if (= :eof c)
[n gen triples]
(recur (parse-statement s n c gen triples)))))
result {:namespaces (get-namespaces gen)
:triples (seq triples)}
base (get-base gen)]
(if base
(assoc result :base base)
result))))
|
2be3deff723f232eae20e939f5f5216677c83189081329fee625565f5609becf | s-cerevisiae/leetcode-racket | 692-top-k-frequent-words.rkt | #lang racket
(define (top-k-frequent words k)
(define (count-word words)
(define table (make-hash))
(for ([word (in-list words)])
(hash-update! table word add1 0))
(hash->list table))
(define (sort-count counts)
(sort counts
(match-lambda**
[((cons w1 c1) (cons w2 c2))
(or (> c1 c2)
(and (= c1 c2) (string<? w1 w2)))])))
(map car (take (sort-count (count-word words)) k)))
| null | https://raw.githubusercontent.com/s-cerevisiae/leetcode-racket/9cc641bad5399df06a1b29bdd5fe4ca656563f0a/692-top-k-frequent-words.rkt | racket | #lang racket
(define (top-k-frequent words k)
(define (count-word words)
(define table (make-hash))
(for ([word (in-list words)])
(hash-update! table word add1 0))
(hash->list table))
(define (sort-count counts)
(sort counts
(match-lambda**
[((cons w1 c1) (cons w2 c2))
(or (> c1 c2)
(and (= c1 c2) (string<? w1 w2)))])))
(map car (take (sort-count (count-word words)) k)))
| |
9b9563c0d2ff6aa6bb4a87c38a93e026546c776cf21ff2a13f5e715ba824fad5 | DavidAlphaFox/aiwiki | aiwiki.erl | -module(aiwiki).
%% API
-export([start/0]).
start() ->
ok = application:start(crypto),
ok = application:start(asn1),
ok = application:start(public_key),
ok = application:start(ssl),
ok = application:start(inets),
ok = application:start(xmerl),
ok = application:start(ranch),
ok = application:start(cowlib),
ok = application:start(cowboy),
ok = application:start(jiffy),
ok = application:start(bcrypt),
ok = application:start(ailib),
ok = application:start(aiconf),
ok = application:start(aicow),
ok = application:start(aiwiki).
| null | https://raw.githubusercontent.com/DavidAlphaFox/aiwiki/3a2a78668d4a708fda4af35430f25a69c4b91a7e/src/aiwiki.erl | erlang | API | -module(aiwiki).
-export([start/0]).
start() ->
ok = application:start(crypto),
ok = application:start(asn1),
ok = application:start(public_key),
ok = application:start(ssl),
ok = application:start(inets),
ok = application:start(xmerl),
ok = application:start(ranch),
ok = application:start(cowlib),
ok = application:start(cowboy),
ok = application:start(jiffy),
ok = application:start(bcrypt),
ok = application:start(ailib),
ok = application:start(aiconf),
ok = application:start(aicow),
ok = application:start(aiwiki).
|
9b114d29c7e7bc91f78059c8ee9f0b48fc48b690607b4f321d29577c641147df | darrenldl/ProVerif-ATP | pievent.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Types
open Pitypes
open Stringmap
let get_event_status_internal event_status_table f =
try
Hashtbl.find event_status_table f
with Not_found ->
Parsing_helper.internal_error ("event not found " ^ f.f_name)
let get_event_status pi_state f =
match pi_state.pi_event_status_table with
| Unset ->
Parsing_helper.internal_error "event_status_table should be set before Pievent.get_event_status"
| Set event_status_table ->
get_event_status_internal event_status_table f
let set_event_status state =
let event_status_table = Hashtbl.create 7 in
let set_event_status_e set_end set_begin = function
QSEvent(b, FunApp(f,_)) ->
let fstatus = get_event_status_internal event_status_table f in
if set_end then
begin
if b then fstatus.end_status <- Inj else
if fstatus.end_status = No then fstatus.end_status <- NonInj
end;
if set_begin then
begin
if b then fstatus.begin_status <- Inj else
if fstatus.begin_status = No then fstatus.begin_status <- NonInj
end
| _ -> ()
in
let rec set_event_status_r set_begin = function
| Before(e, ll) ->
List.iter (set_event_status_e true set_begin) e;
List.iter (List.iter (function
QEvent e -> set_event_status_e false true e
| NestedQuery q -> set_event_status_r true q)) ll
in
let set_event_status1 = function
| PutBegin(i, l) ->
List.iter (fun f ->
let fstatus = get_event_status_internal event_status_table f in
if i then fstatus.begin_status <- Inj else
if fstatus.begin_status = No then fstatus.begin_status <- NonInj) l
| RealQuery (q,_) ->
set_event_status_r false q
| QSecret _ ->
()
in
let set_event_status_q = function
| QueryToTranslate _ ->
Parsing_helper.internal_error "query should be translated before Pievent.set_event_status"
| CorrespQuery(ql) ->
List.iter set_event_status1 ql
| CorrespQEnc(qql) ->
List.iter (fun (_,q) -> set_event_status1 q) qql
| ChoiceQEnc _ | ChoiceQuery | NonInterfQuery _ | WeakSecret _ ->
()
in
List.iter (fun d ->
Hashtbl.add event_status_table d { end_status = No; begin_status = No }
) state.pi_events;
begin
match state.pi_process_query with
Equivalence _ -> ()
| SingleProcess(p, ql) ->
List.iter set_event_status_q ql
| SingleProcessSingleQuery(_, q) ->
set_event_status_q q
end;
{ state with pi_event_status_table = Set event_status_table }
| null | https://raw.githubusercontent.com/darrenldl/ProVerif-ATP/7af6cfb9e0550ecdb072c471e15b8f22b07408bd/proverif2.00/src/pievent.ml | ocaml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Types
open Pitypes
open Stringmap
let get_event_status_internal event_status_table f =
try
Hashtbl.find event_status_table f
with Not_found ->
Parsing_helper.internal_error ("event not found " ^ f.f_name)
let get_event_status pi_state f =
match pi_state.pi_event_status_table with
| Unset ->
Parsing_helper.internal_error "event_status_table should be set before Pievent.get_event_status"
| Set event_status_table ->
get_event_status_internal event_status_table f
let set_event_status state =
let event_status_table = Hashtbl.create 7 in
let set_event_status_e set_end set_begin = function
QSEvent(b, FunApp(f,_)) ->
let fstatus = get_event_status_internal event_status_table f in
if set_end then
begin
if b then fstatus.end_status <- Inj else
if fstatus.end_status = No then fstatus.end_status <- NonInj
end;
if set_begin then
begin
if b then fstatus.begin_status <- Inj else
if fstatus.begin_status = No then fstatus.begin_status <- NonInj
end
| _ -> ()
in
let rec set_event_status_r set_begin = function
| Before(e, ll) ->
List.iter (set_event_status_e true set_begin) e;
List.iter (List.iter (function
QEvent e -> set_event_status_e false true e
| NestedQuery q -> set_event_status_r true q)) ll
in
let set_event_status1 = function
| PutBegin(i, l) ->
List.iter (fun f ->
let fstatus = get_event_status_internal event_status_table f in
if i then fstatus.begin_status <- Inj else
if fstatus.begin_status = No then fstatus.begin_status <- NonInj) l
| RealQuery (q,_) ->
set_event_status_r false q
| QSecret _ ->
()
in
let set_event_status_q = function
| QueryToTranslate _ ->
Parsing_helper.internal_error "query should be translated before Pievent.set_event_status"
| CorrespQuery(ql) ->
List.iter set_event_status1 ql
| CorrespQEnc(qql) ->
List.iter (fun (_,q) -> set_event_status1 q) qql
| ChoiceQEnc _ | ChoiceQuery | NonInterfQuery _ | WeakSecret _ ->
()
in
List.iter (fun d ->
Hashtbl.add event_status_table d { end_status = No; begin_status = No }
) state.pi_events;
begin
match state.pi_process_query with
Equivalence _ -> ()
| SingleProcess(p, ql) ->
List.iter set_event_status_q ql
| SingleProcessSingleQuery(_, q) ->
set_event_status_q q
end;
{ state with pi_event_status_table = Set event_status_table }
| |
89e583778edea03c1c6067cd0629be2bbcac2cb58f5f6ddec3861a6a2d189348 | austinhaas/kanren | miniKanren_operators.clj | (ns pettomato.kanren.cKanren.miniKanren-operators
(:require
[pettomato.kanren.cKanren.lvar :refer [lvar]]
[pettomato.kanren.cKanren.streams :refer [mzero]]
[pettomato.kanren.cKanren.operators :refer [mplus bind]]
[pettomato.kanren.cKanren.case-inf :refer [case-inf]]))
(defmacro mplus*
([e] e)
([e & es] `(mplus ~e (delay (mplus* ~@es)))))
(defmacro bind*
([e] e)
([e g & gs] `(bind* (bind ~e ~g) ~@gs)))
(defmacro conde
[& clauses]
(let [a (gensym)]
`(fn [~a]
(delay
(mplus*
~@(for [[g & gs] clauses]
`(bind* (~g ~a) ~@gs)))))))
(defmacro fresh
[[& vars] g & gs]
`(fn [a#]
(delay
(let [~@(interleave vars (repeat `(lvar)))]
(bind* (~g a#) ~@gs)))))
(defmacro all
[g & gs]
`(fn [a#]
(delay
(bind* (~g a#) ~@gs))))
;;; Impure control operators.
(defmacro if-u
([] mzero)
([[e & gs] & bs]
`(letfn [(step# [a-inf#]
(case-inf a-inf#
[] (if-u ~@bs)
[f#] (delay (step# (force f#)))
[a#] (bind* a-inf# ~@gs)
[a# f#] (bind* a# ~@gs)))]
(step# ~e))))
(defmacro condu
[& clauses]
(let [a (gensym)]
`(fn [~a]
(delay
(if-u ~@(for [[g & gs] clauses]
`[(~g ~a) ~@gs]))))))
| null | https://raw.githubusercontent.com/austinhaas/kanren/f55b68279ade01dbaae67a074ea3441370a27f9e/src/pettomato/kanren/cKanren/miniKanren_operators.clj | clojure | Impure control operators. | (ns pettomato.kanren.cKanren.miniKanren-operators
(:require
[pettomato.kanren.cKanren.lvar :refer [lvar]]
[pettomato.kanren.cKanren.streams :refer [mzero]]
[pettomato.kanren.cKanren.operators :refer [mplus bind]]
[pettomato.kanren.cKanren.case-inf :refer [case-inf]]))
(defmacro mplus*
([e] e)
([e & es] `(mplus ~e (delay (mplus* ~@es)))))
(defmacro bind*
([e] e)
([e g & gs] `(bind* (bind ~e ~g) ~@gs)))
(defmacro conde
[& clauses]
(let [a (gensym)]
`(fn [~a]
(delay
(mplus*
~@(for [[g & gs] clauses]
`(bind* (~g ~a) ~@gs)))))))
(defmacro fresh
[[& vars] g & gs]
`(fn [a#]
(delay
(let [~@(interleave vars (repeat `(lvar)))]
(bind* (~g a#) ~@gs)))))
(defmacro all
[g & gs]
`(fn [a#]
(delay
(bind* (~g a#) ~@gs))))
(defmacro if-u
([] mzero)
([[e & gs] & bs]
`(letfn [(step# [a-inf#]
(case-inf a-inf#
[] (if-u ~@bs)
[f#] (delay (step# (force f#)))
[a#] (bind* a-inf# ~@gs)
[a# f#] (bind* a# ~@gs)))]
(step# ~e))))
(defmacro condu
[& clauses]
(let [a (gensym)]
`(fn [~a]
(delay
(if-u ~@(for [[g & gs] clauses]
`[(~g ~a) ~@gs]))))))
|
ad7c219b4f0a7981821f1c7dd9cc3bd8bc59b05e10a440c272282d0ac3404082 | processone/eturnal | eturnal_SUITE.erl | eturnal STUN / TURN server .
%%%
Copyright ( c ) 2020 - 2022 < > .
Copyright ( c ) 2020 - 2022 ProcessOne , SARL .
%%% 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(eturnal_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-type info() :: ct_suite:ct_info().
-type config() :: ct_suite:ct_config().
-type test_def() :: ct_suite:ct_test_def().
-type test_name() :: ct_suite:ct_testname().
-type group_def() :: ct_suite:ct_group_def().
-type group_name() :: ct_suite:ct_groupname().
%% API.
-spec suite() -> [info()].
suite() ->
[{timetrap, {seconds, 120}}].
-spec init_per_suite(config()) -> config().
init_per_suite(Config) ->
Config.
-spec end_per_suite(config()) -> ok.
end_per_suite(_Config) ->
ok.
-spec init_per_group(group_name(), config()) -> config().
init_per_group(_GroupName, Config) ->
Config.
-spec end_per_group(group_name(), config()) -> ok.
end_per_group(_GroupName, _Config) ->
ok.
-spec init_per_testcase(test_name(), config()) -> config().
-ifdef(old_inet_backend).
init_per_testcase(start_eturnal, Config) ->
set_eturnal_env("eturnal-old-otp.yml", Config);
init_per_testcase(stun_tcp_auto, _Config) ->
{skip, otp_version_unsupported};
init_per_testcase(stun_tls_auto, _Config) ->
{skip, otp_version_unsupported};
init_per_testcase(_TestCase, Config) ->
Config.
-else.
init_per_testcase(start_eturnal, Config) ->
set_eturnal_env("eturnal-new-otp.yml", Config);
init_per_testcase(_TestCase, Config) ->
Config.
-endif.
-spec end_per_testcase(test_name(), config()) -> ok.
end_per_testcase(_TestCase, _Config) ->
ok.
-spec groups() -> [group_def()].
groups() ->
[].
-spec all() -> [test_def()] | {skip, term()}.
all() ->
[start_eturnal,
check_info,
check_all_sessions,
check_user_sessions,
check_disconnect,
check_credentials,
check_loglevel,
check_version,
reload,
connect_tcp,
connect_tls,
turn_udp,
stun_udp,
stun_tcp,
stun_tls,
stun_tcp_auto,
stun_tls_auto,
stop_eturnal].
-spec start_eturnal(config()) -> any().
start_eturnal(_Config) ->
ct:pal("Starting up eturnal"),
ok = eturnal:start().
-spec check_info(config()) -> any().
check_info(_Config) ->
ct:pal("Checking eturnal statistics"),
{ok, Info} = eturnal_ctl:get_info(),
ct:pal("Got eturnal statistics: ~p", [Info]),
true = is_list(Info).
-spec check_all_sessions(config()) -> any().
check_all_sessions(_Config) ->
ct:pal("Checking active TURN sessions"),
{ok, Sessions} = eturnal_ctl:get_sessions(),
ct:pal("Got active TURN sessions: ~p", [Sessions]),
true = is_list(Sessions).
-spec check_user_sessions(config()) -> any().
check_user_sessions(_Config) ->
ct:pal("Checking active TURN sessions of user"),
{ok, Sessions} = eturnal_ctl:get_sessions("alice"),
ct:pal("Got active TURN sessions of user: ~p", [Sessions]),
true = is_list(Sessions),
ct:pal("Checking active TURN sessions of invalid user"),
{error, Reason} = eturnal_ctl:disconnect(alice),
ct:pal("Got an error, as expected: ~p", [Reason]).
-spec check_disconnect(config()) -> any().
check_disconnect(_Config) ->
ct:pal("Checking disconnection of TURN user"),
{ok, Msg} = eturnal_ctl:disconnect("alice"),
ct:pal("Got result for disconnecting TURN user: ~p", [Msg]),
true = is_list(Msg),
ct:pal("Checking disconnection of invalid TURN user"),
{error, Reason} = eturnal_ctl:disconnect(alice),
ct:pal("Got an error, as expected: ~p", [Reason]).
-spec check_credentials(config()) -> any().
check_credentials(_Config) ->
Timestamp = "2009-10-30 11:00:00Z",
Username = 1256900400,
Password = "uEKlpcME7MNMMVRV8rUFPCTIFEs=",
ct:pal("Checking credentials valid until ~s", [Timestamp]),
{ok, Credentials} = eturnal_ctl:get_credentials(Timestamp, []),
{ok, [Username, Password], []} =
io_lib:fread("Username: ~u~~nPassword: ~s", Credentials),
lists:foreach(
fun(Lifetime) ->
ct:pal("Checking credentials valid for ~s", [Lifetime]),
{ok, Creds} = eturnal_ctl:get_credentials(Lifetime, "alice"),
{ok, [Time, Pass], []} =
io_lib:fread("Username: ~u:alice~~nPassword: ~s", Creds),
{ok, Pass} =
eturnal_ctl:get_password(integer_to_list(Time) ++ ":alice"),
true = erlang:system_time(second) + 86400 - Time < 5
end, ["86400", "86400s", "1440m", "24h", "1d"]),
ct:pal("Checking invalid expiry"),
lists:foreach(
fun(Invalid) ->
{error, _Reason1} = eturnal_ctl:get_password(Invalid),
{error, _Reason2} = eturnal_ctl:get_credentials(Invalid, [])
end, ["Invalid", invalid, [invalid]]),
ct:pal("Checking invalid suffix"),
{error, _Reason} = eturnal_ctl:get_credentials(Username, invalid).
-spec check_loglevel(config()) -> any().
check_loglevel(_Config) ->
Level = "debug",
ct:pal("Setting log level to ~s", [Level]),
ok = eturnal_ctl:set_loglevel(list_to_atom(Level)),
ct:pal("Checking whether log level is set to ~s", [Level]),
{ok, Level} = eturnal_ctl:get_loglevel(),
ct:pal("Setting invalid log level"),
{error, _Reason} = eturnal_ctl:set_loglevel(invalid),
ct:pal("Checking whether log level is still set to ~s", [Level]),
{ok, Level} = eturnal_ctl:get_loglevel().
-spec check_version(config()) -> any().
check_version(_Config) ->
ct:pal("Checking eturnal version"),
{ok, Version} = eturnal_ctl:get_version(),
ct:pal("Got eturnal version: ~p", [Version]),
match = re:run(Version, "^[0-9]+\\.[0-9]+\\.[0-9](\\+[0-9]+)?",
[{capture, none}]).
-spec reload(config()) -> any().
reload(_Config) ->
CertFile = <<"run/cert.pem">>,
ct:pal("Deleting TLS certificate"),
ok = file:delete(CertFile),
ct:pal("Reloading eturnal"),
ok = eturnal_ctl:reload(),
ct:pal("Checking whether new TLS certificate was created"),
{ok, _} = file:read_file_info(CertFile),
ct:pal("Reloading eturnal without changes"),
ok = eturnal_ctl:reload().
-spec connect_tcp(config()) -> any().
connect_tcp(_Config) ->
Port = 34780,
ct:pal("Connecting to 127.0.0.1:~B (TCP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
{ok, Sock} = gen_tcp:connect(Addr, Port, []),
ok = gen_tcp:close(Sock).
-spec connect_tls(config()) -> any().
connect_tls(_Config) ->
Port = 53490,
ct:pal("Connecting to 127.0.0.1:~B (TLS)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
{ok, TCPSock} = gen_tcp:connect(Addr, Port, []),
{ok, TLSSock} = fast_tls:tcp_to_tls(TCPSock, [connect]),
ok = fast_tls:close(TLSSock).
-spec turn_udp(config()) -> any().
turn_udp(_Config) ->
Port = 34780,
Username = <<"2145913200">>,
Password = <<"cLwpKS2/9bWHf+agUImD47PIXNE=">>,
Realm = <<"eturnal.net">>,
ct:pal("Allocating TURN relay on 127.0.0.1:~B (UDP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
ok = stun_test:allocate_udp(Addr, Port, Username, Realm, Password).
-spec stun_udp(config()) -> any().
stun_udp(_Config) ->
Port = 34780,
ct:pal("Performing STUN query against 127.0.0.1:~B (UDP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_udp(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stun_tcp(config()) -> any().
stun_tcp(_Config) ->
Port = 34780,
ct:pal("Performing STUN query against 127.0.0.1:~B (TCP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_tcp(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stun_tls(config()) -> any().
stun_tls(_Config) ->
Port = 53490,
ct:pal("Performing STUN query against 127.0.0.1:~B (TLS)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_tls(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stun_tcp_auto(config()) -> any().
stun_tcp_auto(_Config) ->
Port = 34781,
ct:pal("Performing STUN query against 127.0.0.1:~B (TCP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_tcp(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stun_tls_auto(config()) -> any().
stun_tls_auto(_Config) ->
Port = 34781,
ct:pal("Performing STUN query against 127.0.0.1:~B (TLS)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_tls(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stop_eturnal(config()) -> any().
stop_eturnal(_Config) ->
ct:pal("Stopping eturnal"),
ok = eturnal:stop().
Internal functions .
-spec set_eturnal_env(file:filename_all(), config()) -> config().
set_eturnal_env(ConfName, Config) ->
DataDir = ?config(data_dir, Config),
ConfFile = filename:join(DataDir, ConfName),
ok = application:set_env(conf, file, ConfFile),
ok = application:set_env(conf, on_fail, stop),
ok = application:set_env(eturnal, on_fail, exit),
Config.
| null | https://raw.githubusercontent.com/processone/eturnal/9b32bbe86f8b0dae7437059b113167c62abd769e/test/eturnal_SUITE.erl | erlang |
All rights reserved.
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.
API. | eturnal STUN / TURN server .
Copyright ( c ) 2020 - 2022 < > .
Copyright ( c ) 2020 - 2022 ProcessOne , SARL .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(eturnal_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-type info() :: ct_suite:ct_info().
-type config() :: ct_suite:ct_config().
-type test_def() :: ct_suite:ct_test_def().
-type test_name() :: ct_suite:ct_testname().
-type group_def() :: ct_suite:ct_group_def().
-type group_name() :: ct_suite:ct_groupname().
-spec suite() -> [info()].
suite() ->
[{timetrap, {seconds, 120}}].
-spec init_per_suite(config()) -> config().
init_per_suite(Config) ->
Config.
-spec end_per_suite(config()) -> ok.
end_per_suite(_Config) ->
ok.
-spec init_per_group(group_name(), config()) -> config().
init_per_group(_GroupName, Config) ->
Config.
-spec end_per_group(group_name(), config()) -> ok.
end_per_group(_GroupName, _Config) ->
ok.
-spec init_per_testcase(test_name(), config()) -> config().
-ifdef(old_inet_backend).
init_per_testcase(start_eturnal, Config) ->
set_eturnal_env("eturnal-old-otp.yml", Config);
init_per_testcase(stun_tcp_auto, _Config) ->
{skip, otp_version_unsupported};
init_per_testcase(stun_tls_auto, _Config) ->
{skip, otp_version_unsupported};
init_per_testcase(_TestCase, Config) ->
Config.
-else.
init_per_testcase(start_eturnal, Config) ->
set_eturnal_env("eturnal-new-otp.yml", Config);
init_per_testcase(_TestCase, Config) ->
Config.
-endif.
-spec end_per_testcase(test_name(), config()) -> ok.
end_per_testcase(_TestCase, _Config) ->
ok.
-spec groups() -> [group_def()].
groups() ->
[].
-spec all() -> [test_def()] | {skip, term()}.
all() ->
[start_eturnal,
check_info,
check_all_sessions,
check_user_sessions,
check_disconnect,
check_credentials,
check_loglevel,
check_version,
reload,
connect_tcp,
connect_tls,
turn_udp,
stun_udp,
stun_tcp,
stun_tls,
stun_tcp_auto,
stun_tls_auto,
stop_eturnal].
-spec start_eturnal(config()) -> any().
start_eturnal(_Config) ->
ct:pal("Starting up eturnal"),
ok = eturnal:start().
-spec check_info(config()) -> any().
check_info(_Config) ->
ct:pal("Checking eturnal statistics"),
{ok, Info} = eturnal_ctl:get_info(),
ct:pal("Got eturnal statistics: ~p", [Info]),
true = is_list(Info).
-spec check_all_sessions(config()) -> any().
check_all_sessions(_Config) ->
ct:pal("Checking active TURN sessions"),
{ok, Sessions} = eturnal_ctl:get_sessions(),
ct:pal("Got active TURN sessions: ~p", [Sessions]),
true = is_list(Sessions).
-spec check_user_sessions(config()) -> any().
check_user_sessions(_Config) ->
ct:pal("Checking active TURN sessions of user"),
{ok, Sessions} = eturnal_ctl:get_sessions("alice"),
ct:pal("Got active TURN sessions of user: ~p", [Sessions]),
true = is_list(Sessions),
ct:pal("Checking active TURN sessions of invalid user"),
{error, Reason} = eturnal_ctl:disconnect(alice),
ct:pal("Got an error, as expected: ~p", [Reason]).
-spec check_disconnect(config()) -> any().
check_disconnect(_Config) ->
ct:pal("Checking disconnection of TURN user"),
{ok, Msg} = eturnal_ctl:disconnect("alice"),
ct:pal("Got result for disconnecting TURN user: ~p", [Msg]),
true = is_list(Msg),
ct:pal("Checking disconnection of invalid TURN user"),
{error, Reason} = eturnal_ctl:disconnect(alice),
ct:pal("Got an error, as expected: ~p", [Reason]).
-spec check_credentials(config()) -> any().
check_credentials(_Config) ->
Timestamp = "2009-10-30 11:00:00Z",
Username = 1256900400,
Password = "uEKlpcME7MNMMVRV8rUFPCTIFEs=",
ct:pal("Checking credentials valid until ~s", [Timestamp]),
{ok, Credentials} = eturnal_ctl:get_credentials(Timestamp, []),
{ok, [Username, Password], []} =
io_lib:fread("Username: ~u~~nPassword: ~s", Credentials),
lists:foreach(
fun(Lifetime) ->
ct:pal("Checking credentials valid for ~s", [Lifetime]),
{ok, Creds} = eturnal_ctl:get_credentials(Lifetime, "alice"),
{ok, [Time, Pass], []} =
io_lib:fread("Username: ~u:alice~~nPassword: ~s", Creds),
{ok, Pass} =
eturnal_ctl:get_password(integer_to_list(Time) ++ ":alice"),
true = erlang:system_time(second) + 86400 - Time < 5
end, ["86400", "86400s", "1440m", "24h", "1d"]),
ct:pal("Checking invalid expiry"),
lists:foreach(
fun(Invalid) ->
{error, _Reason1} = eturnal_ctl:get_password(Invalid),
{error, _Reason2} = eturnal_ctl:get_credentials(Invalid, [])
end, ["Invalid", invalid, [invalid]]),
ct:pal("Checking invalid suffix"),
{error, _Reason} = eturnal_ctl:get_credentials(Username, invalid).
-spec check_loglevel(config()) -> any().
check_loglevel(_Config) ->
Level = "debug",
ct:pal("Setting log level to ~s", [Level]),
ok = eturnal_ctl:set_loglevel(list_to_atom(Level)),
ct:pal("Checking whether log level is set to ~s", [Level]),
{ok, Level} = eturnal_ctl:get_loglevel(),
ct:pal("Setting invalid log level"),
{error, _Reason} = eturnal_ctl:set_loglevel(invalid),
ct:pal("Checking whether log level is still set to ~s", [Level]),
{ok, Level} = eturnal_ctl:get_loglevel().
-spec check_version(config()) -> any().
check_version(_Config) ->
ct:pal("Checking eturnal version"),
{ok, Version} = eturnal_ctl:get_version(),
ct:pal("Got eturnal version: ~p", [Version]),
match = re:run(Version, "^[0-9]+\\.[0-9]+\\.[0-9](\\+[0-9]+)?",
[{capture, none}]).
-spec reload(config()) -> any().
reload(_Config) ->
CertFile = <<"run/cert.pem">>,
ct:pal("Deleting TLS certificate"),
ok = file:delete(CertFile),
ct:pal("Reloading eturnal"),
ok = eturnal_ctl:reload(),
ct:pal("Checking whether new TLS certificate was created"),
{ok, _} = file:read_file_info(CertFile),
ct:pal("Reloading eturnal without changes"),
ok = eturnal_ctl:reload().
-spec connect_tcp(config()) -> any().
connect_tcp(_Config) ->
Port = 34780,
ct:pal("Connecting to 127.0.0.1:~B (TCP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
{ok, Sock} = gen_tcp:connect(Addr, Port, []),
ok = gen_tcp:close(Sock).
-spec connect_tls(config()) -> any().
connect_tls(_Config) ->
Port = 53490,
ct:pal("Connecting to 127.0.0.1:~B (TLS)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
{ok, TCPSock} = gen_tcp:connect(Addr, Port, []),
{ok, TLSSock} = fast_tls:tcp_to_tls(TCPSock, [connect]),
ok = fast_tls:close(TLSSock).
-spec turn_udp(config()) -> any().
turn_udp(_Config) ->
Port = 34780,
Username = <<"2145913200">>,
Password = <<"cLwpKS2/9bWHf+agUImD47PIXNE=">>,
Realm = <<"eturnal.net">>,
ct:pal("Allocating TURN relay on 127.0.0.1:~B (UDP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
ok = stun_test:allocate_udp(Addr, Port, Username, Realm, Password).
-spec stun_udp(config()) -> any().
stun_udp(_Config) ->
Port = 34780,
ct:pal("Performing STUN query against 127.0.0.1:~B (UDP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_udp(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stun_tcp(config()) -> any().
stun_tcp(_Config) ->
Port = 34780,
ct:pal("Performing STUN query against 127.0.0.1:~B (TCP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_tcp(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stun_tls(config()) -> any().
stun_tls(_Config) ->
Port = 53490,
ct:pal("Performing STUN query against 127.0.0.1:~B (TLS)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_tls(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stun_tcp_auto(config()) -> any().
stun_tcp_auto(_Config) ->
Port = 34781,
ct:pal("Performing STUN query against 127.0.0.1:~B (TCP)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_tcp(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stun_tls_auto(config()) -> any().
stun_tls_auto(_Config) ->
Port = 34781,
ct:pal("Performing STUN query against 127.0.0.1:~B (TLS)", [Port]),
{ok, Addr} = inet:parse_address("127.0.0.1"),
Result = stun_test:bind_tls(Addr, Port),
ct:pal("Got query result: ~p", [Result]),
true = is_tuple(Result),
true = element(1, Result) =:= stun.
-spec stop_eturnal(config()) -> any().
stop_eturnal(_Config) ->
ct:pal("Stopping eturnal"),
ok = eturnal:stop().
Internal functions .
-spec set_eturnal_env(file:filename_all(), config()) -> config().
set_eturnal_env(ConfName, Config) ->
DataDir = ?config(data_dir, Config),
ConfFile = filename:join(DataDir, ConfName),
ok = application:set_env(conf, file, ConfFile),
ok = application:set_env(conf, on_fail, stop),
ok = application:set_env(eturnal, on_fail, exit),
Config.
|
5bd9392bb7114cf52c59a87144ab05e884ba2120fa1f871cd3a8fdaea043e3ab | vascokk/NumEr | numer_app.erl | -module(numer_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%% ===================================================================
%% Application callbacks
%% ===================================================================
start(_StartType, _StartArgs) ->
numer_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/vascokk/NumEr/0d22c31633ef2ab43dde50809a9dbbb6a736f5b7/src/numer_app.erl | erlang | Application callbacks
===================================================================
Application callbacks
=================================================================== | -module(numer_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
numer_sup:start_link().
stop(_State) ->
ok.
|
7dd3cdce3860bca8acfc73e1a87ce0268092c359cc8c81a83275b9725877287f | ghilesZ/geoml | polygon.mli | (** This module provides basic functions for any concave, convex
and convex regular polygon (Does not handle complex polygon and polygon with
holes) *)
type t = private Point.t list
type polygon = t
val make : Point.t list -> t
val first_point : t -> Point.t
val to_list : t -> Point.t list
val fold : ('a -> Point.t -> Point.t -> 'a) -> 'a -> t -> 'a
(** Same function as [List.fold_left] but on segments of a given polygon *)
val fold_filter : (Point.t -> Point.t -> bool) -> ('b -> Point.t -> Point.t -> 'b) -> 'b -> t -> 'b
* Same function as [ fold ] but filters segments with the first argument
val perimeter : t -> float
val area : t -> float
val proj_x : t -> float * float
val proj_y : t -> float * float
val translate : float -> float -> t -> t
val transform : Affine.t -> t -> t
val minmax_xy : t -> float * float * float * float
(** returns the intersection point of a line and a polygon *)
val intersect_line : t -> Line.t -> Point.t list
val contains : t -> Point.t -> bool
* Returns true if a polygon contains a point .
code for raycasting
Randolph Franklin code for raycasting *)
val segments_intersection_points : Point.t list Segment.Tbl.t -> t -> t -> Point.t list
* Get a list of the intersections
points of the edges of two polygons
points of the edges of two polygons *)
val intersection_polygons : t -> t -> t list
* Implementation of Weiler Atherton Algorithm for
concave / convexe polygons clipping . Complexity is O(m*n ) .
concave/convexe polygons clipping. Complexity is O(m*n). *)
val triangulation : t -> (Point.t * Point.t * Point.t) list
module Convex: sig
type nonrec t = private t
val to_list : t -> Point.t list
val fold : ('a -> Point.t -> Point.t -> 'a) -> 'a -> t -> 'a
(** hull pts returns the smallest convex polygon that contains all the points
in pts*)
val hull : Point.t list -> t
(** alias for hull *)
val bounding : Point.t list -> t
module Regular: sig
(** Module for Regular polygons *)
type t = private {
center : Point.t;
fst : Point.t;
snd : Point.t;
len : float;
* Distance between the center and the middle of one of the edges
edges : int;
}
val make : Point.t -> Point.t -> int -> t
(** Create a regular polygon from the center, an arbitrary point and the
number of edges *)
val next_point : ?nth:int -> t -> Point.t
val fold_stop : (Point.t -> Point.t -> bool) ->
(int -> 'a -> Point.t -> Point.t -> 'a) -> 'a -> t -> 'a
val perimeter : t -> float
val area : t -> float
val to_polygon : t -> polygon
val to_randomized_polygon : ?minp:int -> ?prob:float -> t -> polygon
val translate : float -> float -> t -> t
val transform : Affine.t -> t -> t
val is_square : t -> bool
val contains : t -> Point.t -> bool
val map : (Point.t -> Point.t) -> t -> t
end
end
| null | https://raw.githubusercontent.com/ghilesZ/geoml/a239499dabbbfbf74bae73a105ed567546f43312/src/polygon.mli | ocaml | * This module provides basic functions for any concave, convex
and convex regular polygon (Does not handle complex polygon and polygon with
holes)
* Same function as [List.fold_left] but on segments of a given polygon
* returns the intersection point of a line and a polygon
* hull pts returns the smallest convex polygon that contains all the points
in pts
* alias for hull
* Module for Regular polygons
* Create a regular polygon from the center, an arbitrary point and the
number of edges |
type t = private Point.t list
type polygon = t
val make : Point.t list -> t
val first_point : t -> Point.t
val to_list : t -> Point.t list
val fold : ('a -> Point.t -> Point.t -> 'a) -> 'a -> t -> 'a
val fold_filter : (Point.t -> Point.t -> bool) -> ('b -> Point.t -> Point.t -> 'b) -> 'b -> t -> 'b
* Same function as [ fold ] but filters segments with the first argument
val perimeter : t -> float
val area : t -> float
val proj_x : t -> float * float
val proj_y : t -> float * float
val translate : float -> float -> t -> t
val transform : Affine.t -> t -> t
val minmax_xy : t -> float * float * float * float
val intersect_line : t -> Line.t -> Point.t list
val contains : t -> Point.t -> bool
* Returns true if a polygon contains a point .
code for raycasting
Randolph Franklin code for raycasting *)
val segments_intersection_points : Point.t list Segment.Tbl.t -> t -> t -> Point.t list
* Get a list of the intersections
points of the edges of two polygons
points of the edges of two polygons *)
val intersection_polygons : t -> t -> t list
* Implementation of Weiler Atherton Algorithm for
concave / convexe polygons clipping . Complexity is O(m*n ) .
concave/convexe polygons clipping. Complexity is O(m*n). *)
val triangulation : t -> (Point.t * Point.t * Point.t) list
module Convex: sig
type nonrec t = private t
val to_list : t -> Point.t list
val fold : ('a -> Point.t -> Point.t -> 'a) -> 'a -> t -> 'a
val hull : Point.t list -> t
val bounding : Point.t list -> t
module Regular: sig
type t = private {
center : Point.t;
fst : Point.t;
snd : Point.t;
len : float;
* Distance between the center and the middle of one of the edges
edges : int;
}
val make : Point.t -> Point.t -> int -> t
val next_point : ?nth:int -> t -> Point.t
val fold_stop : (Point.t -> Point.t -> bool) ->
(int -> 'a -> Point.t -> Point.t -> 'a) -> 'a -> t -> 'a
val perimeter : t -> float
val area : t -> float
val to_polygon : t -> polygon
val to_randomized_polygon : ?minp:int -> ?prob:float -> t -> polygon
val translate : float -> float -> t -> t
val transform : Affine.t -> t -> t
val is_square : t -> bool
val contains : t -> Point.t -> bool
val map : (Point.t -> Point.t) -> t -> t
end
end
|
42abfc9304e549461932b7e76aada8532b81a4c9ed8ad14603f55ab646c9edec | gator1/jepsen | rethinkdb_test.clj | (ns jepsen.rethinkdb-test
(:require [clojure.test :refer :all]
[clojure.pprint :refer :all]
[clojure.java.io :as io]
[jepsen.rethinkdb.document-cas :as dc]
[jepsen.core :as jepsen]))
(defn run!
[test]
(let [test (jepsen/run! test)]
(is (:valid? (:results test)))))
version " 2.1.5 + 2~0jessie "
version "2.2.3+1~0jessie"]
(deftest single-single-test
(run! (dc/cas-test version "single" "single")))
(deftest majority-single-test
(run! (dc/cas-test version "majority" "single")))
(deftest single-majority-test
(run! (dc/cas-test version "single" "majority")))
(deftest majority-majority-test
(run! (dc/cas-test version "majority" "majority")))
(deftest reconfigure-test
(run! (dc/cas-reconfigure-test version))))
| null | https://raw.githubusercontent.com/gator1/jepsen/1932cbd72cbc1f6c2a27abe0fe347ea989f0cfbb/rethinkdb/test/jepsen/rethinkdb_test.clj | clojure | (ns jepsen.rethinkdb-test
(:require [clojure.test :refer :all]
[clojure.pprint :refer :all]
[clojure.java.io :as io]
[jepsen.rethinkdb.document-cas :as dc]
[jepsen.core :as jepsen]))
(defn run!
[test]
(let [test (jepsen/run! test)]
(is (:valid? (:results test)))))
version " 2.1.5 + 2~0jessie "
version "2.2.3+1~0jessie"]
(deftest single-single-test
(run! (dc/cas-test version "single" "single")))
(deftest majority-single-test
(run! (dc/cas-test version "majority" "single")))
(deftest single-majority-test
(run! (dc/cas-test version "single" "majority")))
(deftest majority-majority-test
(run! (dc/cas-test version "majority" "majority")))
(deftest reconfigure-test
(run! (dc/cas-reconfigure-test version))))
| |
d112ceaf75e2af89f5dbb031e8ea036b7e91c2fa344f57a73befeb259200f3f6 | piranha/piu.clj | main.clj | (ns piu.main
(:gen-class)
(:require [mount.core :as mount]
[org.httpkit.server :as httpkit]
[piu.config :as config]
[piu.log :as log]
[piu.app :as app]))
(set! *warn-on-reflection* true)
(alter-var-root #'log/*logger (fn [_] (log/->Stdout)))
(mount/defstate server
:start (let [p (config/PORT)]
(println "Opening port" p)
(httpkit/run-server app/app {:port p}))
:stop (server))
(defn -main [& args]
(mount/start))
| null | https://raw.githubusercontent.com/piranha/piu.clj/6dbf397dd315a520b1c3c2522f7855767a4f0e78/src/piu/main.clj | clojure | (ns piu.main
(:gen-class)
(:require [mount.core :as mount]
[org.httpkit.server :as httpkit]
[piu.config :as config]
[piu.log :as log]
[piu.app :as app]))
(set! *warn-on-reflection* true)
(alter-var-root #'log/*logger (fn [_] (log/->Stdout)))
(mount/defstate server
:start (let [p (config/PORT)]
(println "Opening port" p)
(httpkit/run-server app/app {:port p}))
:stop (server))
(defn -main [& args]
(mount/start))
| |
9b21e45f07ec8788f75fd99a0cdc7cd91d26949cf1d99c69b2b4db6918906bbc | lehins/massiv | NumericSpec.hs | # LANGUAGE TypeApplications #
module Test.Massiv.Array.NumericSpec (
spec,
) where
import Data.Massiv.Array as A
import Test.Massiv.Array.Numeric
import Test.Massiv.Core
spec :: Spec
spec = do
mutableNumericSpec @P @Int
mutableNumericFloatSpec @P
mutableNumericSpec @S @Int
mutableNumericFloatSpec @S
| null | https://raw.githubusercontent.com/lehins/massiv/67a920d4403f210d0bfdad1acc4bec208d80a588/massiv-test/tests/Test/Massiv/Array/NumericSpec.hs | haskell | # LANGUAGE TypeApplications #
module Test.Massiv.Array.NumericSpec (
spec,
) where
import Data.Massiv.Array as A
import Test.Massiv.Array.Numeric
import Test.Massiv.Core
spec :: Spec
spec = do
mutableNumericSpec @P @Int
mutableNumericFloatSpec @P
mutableNumericSpec @S @Int
mutableNumericFloatSpec @S
| |
674a120e60edf57ca8586f7090ad84aac19beffe606421e6c2550dc42dce9975 | bmsherman/haskell-matlab | Engine.hs | {-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
module Test.Engine where
import Control.Exception (SomeException, assert, try)
import Data.Either (isLeft, isRight, lefts)
import Foreign.Matlab
import Foreign.Matlab.Engine
import Foreign.Matlab.Engine.Wrappers
import Language.Haskell.TH (Q, runIO)
import Language.Haskell.TH.Syntax (lift)
import Path
import Test.Util
engineTests = runEngineTests ""
runEngineTests :: String -> IO ()
runEngineTests host = do
putStrLn "-- Starting engine --"
eng <- newEngine host
putStrLn "-- Engine created --"
let testPath = repoDir </> testRel
addpath eng testPath
runLocalMatFun eng
cosOfPi eng
testIsMNull eng
testGetFirstLast eng
testAbstractValueUse eng
testTypedAbstractValueUse eng
testGetByteStreamFromArray eng
testGetArrayFromByteStream eng
testCellGet eng
testClearVar eng
cosOfPi :: Engine -> IO ()
cosOfPi eng = do
putStrLn "\n-- cos pi --"
x <- createMXScalar (pi :: MDouble)
cosBody eng "cos" x
runLocalMatFun :: Engine -> IO ()
runLocalMatFun eng = do
putStrLn "\n-- mtest: cos pi --"
x <- createMXScalar (pi :: MDouble)
cosBody eng "mtest" x
cosBody :: Engine -> String -> MXArray MDouble -> IO ()
cosBody eng cosFun x = do
[y] <- engineEvalFun eng cosFun [EvalArray x] 1
mxArrayClass y >>= print
Just y <- castMXArray y
y <- mxScalarGet y
print (y :: MDouble)
testIsMNull :: Engine -> IO ()
testIsMNull eng = do
putStrLn $ "\n-- testIsMNull --"
xa <- createMXScalar (1.0 :: MDouble)
let xaRes = assert (isMNull xa == False) xa
xaResEi <- mxArrayGetFirst xaRes
putStrLn $ " xaResEi is Right: " <> (show xaResEi)
xae :: MXArray MChar <- createMXArray []
freeMXArray xae
mxLen <- mxArrayLength xae
mxDims <- mxArraySize xae
putStrLn $ "length is " <> (show mxLen) <> " dims are " <> (show $ mxDims)
let xaeRes = assert (isMNull xae == False) xae
xaeResEi <- mxArrayGetFirst xaeRes
putStrLn $ " xaeResEi is Left: " <> (show xaeResEi)
testGetFirstLast :: Engine -> IO ()
testGetFirstLast eng = do
putStrLn $ "\n-- testGetFirstLast --"
let testVal :: MDouble = 1.0
xa <- createMXScalar testVal
xfEi <- mxArrayGetFirst xa
xlEi <- mxArrayGetLast xa
let xRes = assert (xlEi == Right 1.0 && xfEi == xlEi) xfEi
putStrLn $ " xRes is : " <> (show xRes)
threeArray :: MXArray MDouble <- fromListIO [5.0, 6.0, 7.0]
txfEi <- mxArrayGetFirst threeArray
txlEi <- mxArrayGetLast threeArray
let txfRes = assert (txfEi == Right 5.0) txfEi
putStrLn $ " txfRes is : " <> (show txfRes)
let txlRes = assert (txlEi == Right 7.0) txlEi
putStrLn $ " txlRes is : " <> (show txlRes)
testAbstractValueUse :: Engine -> IO ()
testAbstractValueUse eng = do
putStrLn $ "\n-- testAbstractValueUse --"
sOut <- makeTestStruct eng
sSum <- useTestStruct eng sOut
let sSumRes = assert (sSum == 7.0) sSum
putStrLn $ " struct sum is: " <> (show sSumRes)
makeTestStruct :: Engine -> IO MAnyArray
makeTestStruct eng = do
[res] <- engineEvalFun eng "makeTestStruct" [] 1
pure res
useTestStruct :: Engine -> MAnyArray -> IO MDouble
useTestStruct eng sIn = do
[res] <- engineEvalFun eng "useTestStruct" [EvalArray sIn] 1
mxArrMay <- castMXArray res
case mxArrMay of
Just mxArr -> mxScalarGet mxArr
Nothing -> pure 0.0
newtype MyAbsType = MyAbsType { unMyAbsType :: MAnyArray }
-- |Similar to testAbstractValueUse, but instead of using
|MAnyArray , we use newtypes for better type safety
testTypedAbstractValueUse :: Engine -> IO ()
testTypedAbstractValueUse eng = do
putStrLn $ "\n-- testTypedAbstractValueUse --"
sOut <- makeTestStructTyped eng
sSum <- useTestStructTyped eng sOut
let sSumRes = assert (sSum == 7.0) sSum
putStrLn $ " struct sum is: " <> (show sSumRes)
makeTestStructTyped :: Engine -> IO MyAbsType
makeTestStructTyped eng = MyAbsType <$> (makeTestStruct eng)
useTestStructTyped :: Engine -> MyAbsType -> IO MDouble
useTestStructTyped eng (MyAbsType sIn) = useTestStruct eng sIn
testGetByteStreamFromArray :: Engine -> IO ()
testGetByteStreamFromArray eng = do
putStrLn $ "\n-- testGetByteStreamFromArray --"
sOutBSMatlab <- makeTestStructByteStream eng
sOut <- makeTestStruct eng
Right sOutBSHaskell <- getByteStreamFromArray eng sOut
let bsSum = sum $ fromIntegral <$> (assert (sOutBSMatlab == sOutBSHaskell) sOutBSHaskell)
putStrLn $ " bytestream sum is: " <> (show bsSum)
testGetArrayFromByteStream :: Engine -> IO ()
testGetArrayFromByteStream eng = do
putStrLn $ "\n-- testGetArrayFromByteStream --"
sOutBS <- makeTestStructByteStream eng
sOutFromBS <- getArrayFromByteStream eng sOutBS
sOut <- makeTestStruct eng
sSumFromBS <- useTestStruct eng sOutFromBS
sSum <- useTestStruct eng sOut
let sSumRes = assert (sSumFromBS == sSum) sSumFromBS
putStrLn $ " deserialized struct sum is: " <> (show sSumRes)
makeTestStructByteStream :: Engine -> IO [MUint8]
makeTestStructByteStream eng = do
[res] <- engineEvalFun eng "makeTestStructByteStream" [] 1
mxArrMay <- castMXArray res
case mxArrMay of
Just mxArr -> mxArrayGetAll mxArr
Nothing -> pure []
-- TODO: display cell array and extracted values in test
testCellGet :: Engine -> IO ()
testCellGet eng = do
putStrLn "\n-- testCellGet --"
[ca] <- engineEvalFun eng "mcellTest" [] 1
Just (ca :: MXArray MCell) <- castMXArray ca
caLen <- mxArrayLength ca
let caLenMsg = assert (caLen == 6) "cell array has length 6"
putStrLn caLenMsg
dCells :: [MXArray MDouble] <- mxCellGetArraysOfType ca
let dCellsMsg = assert (length dCells == 4) "cell array has 4 double arrays"
putStrLn dCellsMsg
dVals :: [MDouble] <- mxCellGetAllOfType ca
let dValsMsg = assert (length dVals == 4) "cell array has 4 double values"
putStrLn dValsMsg
testClearVar :: Engine -> IO ()
testClearVar eng = do
putStrLn $ "\n-- testClearVar --"
let foopi = "foopi"
x <- createMXScalar (pi :: MDouble)
engineSetVar eng foopi x
ei1 :: Either SomeException MAnyArray <- try $ engineGetVar eng foopi
putStrLn $ assert (isRight ei1) " Can clearVar once"
clearVar eng foopi
ei2 :: Either SomeException MAnyArray <- try $ engineGetVar eng foopi
putStrLn $ assert (isLeft ei2) $
" Can't clearVar twice: " <> (show $ lefts [ei2])
putStrLn " Finished testClearVar"
testRel :: Path Rel Dir
testRel = $(mkRelDir "test")
repoDir :: Path Abs Dir
repoDir = $(mkAbsDir getRepoDirStatic)
| null | https://raw.githubusercontent.com/bmsherman/haskell-matlab/21cdb98a2bcf23c90eb31026063f4c3a2cf5da15/test/Test/Engine.hs | haskell | # LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
|Similar to testAbstractValueUse, but instead of using
TODO: display cell array and extracted values in test |
module Test.Engine where
import Control.Exception (SomeException, assert, try)
import Data.Either (isLeft, isRight, lefts)
import Foreign.Matlab
import Foreign.Matlab.Engine
import Foreign.Matlab.Engine.Wrappers
import Language.Haskell.TH (Q, runIO)
import Language.Haskell.TH.Syntax (lift)
import Path
import Test.Util
engineTests = runEngineTests ""
runEngineTests :: String -> IO ()
runEngineTests host = do
putStrLn "-- Starting engine --"
eng <- newEngine host
putStrLn "-- Engine created --"
let testPath = repoDir </> testRel
addpath eng testPath
runLocalMatFun eng
cosOfPi eng
testIsMNull eng
testGetFirstLast eng
testAbstractValueUse eng
testTypedAbstractValueUse eng
testGetByteStreamFromArray eng
testGetArrayFromByteStream eng
testCellGet eng
testClearVar eng
cosOfPi :: Engine -> IO ()
cosOfPi eng = do
putStrLn "\n-- cos pi --"
x <- createMXScalar (pi :: MDouble)
cosBody eng "cos" x
runLocalMatFun :: Engine -> IO ()
runLocalMatFun eng = do
putStrLn "\n-- mtest: cos pi --"
x <- createMXScalar (pi :: MDouble)
cosBody eng "mtest" x
cosBody :: Engine -> String -> MXArray MDouble -> IO ()
cosBody eng cosFun x = do
[y] <- engineEvalFun eng cosFun [EvalArray x] 1
mxArrayClass y >>= print
Just y <- castMXArray y
y <- mxScalarGet y
print (y :: MDouble)
testIsMNull :: Engine -> IO ()
testIsMNull eng = do
putStrLn $ "\n-- testIsMNull --"
xa <- createMXScalar (1.0 :: MDouble)
let xaRes = assert (isMNull xa == False) xa
xaResEi <- mxArrayGetFirst xaRes
putStrLn $ " xaResEi is Right: " <> (show xaResEi)
xae :: MXArray MChar <- createMXArray []
freeMXArray xae
mxLen <- mxArrayLength xae
mxDims <- mxArraySize xae
putStrLn $ "length is " <> (show mxLen) <> " dims are " <> (show $ mxDims)
let xaeRes = assert (isMNull xae == False) xae
xaeResEi <- mxArrayGetFirst xaeRes
putStrLn $ " xaeResEi is Left: " <> (show xaeResEi)
testGetFirstLast :: Engine -> IO ()
testGetFirstLast eng = do
putStrLn $ "\n-- testGetFirstLast --"
let testVal :: MDouble = 1.0
xa <- createMXScalar testVal
xfEi <- mxArrayGetFirst xa
xlEi <- mxArrayGetLast xa
let xRes = assert (xlEi == Right 1.0 && xfEi == xlEi) xfEi
putStrLn $ " xRes is : " <> (show xRes)
threeArray :: MXArray MDouble <- fromListIO [5.0, 6.0, 7.0]
txfEi <- mxArrayGetFirst threeArray
txlEi <- mxArrayGetLast threeArray
let txfRes = assert (txfEi == Right 5.0) txfEi
putStrLn $ " txfRes is : " <> (show txfRes)
let txlRes = assert (txlEi == Right 7.0) txlEi
putStrLn $ " txlRes is : " <> (show txlRes)
testAbstractValueUse :: Engine -> IO ()
testAbstractValueUse eng = do
putStrLn $ "\n-- testAbstractValueUse --"
sOut <- makeTestStruct eng
sSum <- useTestStruct eng sOut
let sSumRes = assert (sSum == 7.0) sSum
putStrLn $ " struct sum is: " <> (show sSumRes)
makeTestStruct :: Engine -> IO MAnyArray
makeTestStruct eng = do
[res] <- engineEvalFun eng "makeTestStruct" [] 1
pure res
useTestStruct :: Engine -> MAnyArray -> IO MDouble
useTestStruct eng sIn = do
[res] <- engineEvalFun eng "useTestStruct" [EvalArray sIn] 1
mxArrMay <- castMXArray res
case mxArrMay of
Just mxArr -> mxScalarGet mxArr
Nothing -> pure 0.0
newtype MyAbsType = MyAbsType { unMyAbsType :: MAnyArray }
|MAnyArray , we use newtypes for better type safety
testTypedAbstractValueUse :: Engine -> IO ()
testTypedAbstractValueUse eng = do
putStrLn $ "\n-- testTypedAbstractValueUse --"
sOut <- makeTestStructTyped eng
sSum <- useTestStructTyped eng sOut
let sSumRes = assert (sSum == 7.0) sSum
putStrLn $ " struct sum is: " <> (show sSumRes)
makeTestStructTyped :: Engine -> IO MyAbsType
makeTestStructTyped eng = MyAbsType <$> (makeTestStruct eng)
useTestStructTyped :: Engine -> MyAbsType -> IO MDouble
useTestStructTyped eng (MyAbsType sIn) = useTestStruct eng sIn
testGetByteStreamFromArray :: Engine -> IO ()
testGetByteStreamFromArray eng = do
putStrLn $ "\n-- testGetByteStreamFromArray --"
sOutBSMatlab <- makeTestStructByteStream eng
sOut <- makeTestStruct eng
Right sOutBSHaskell <- getByteStreamFromArray eng sOut
let bsSum = sum $ fromIntegral <$> (assert (sOutBSMatlab == sOutBSHaskell) sOutBSHaskell)
putStrLn $ " bytestream sum is: " <> (show bsSum)
testGetArrayFromByteStream :: Engine -> IO ()
testGetArrayFromByteStream eng = do
putStrLn $ "\n-- testGetArrayFromByteStream --"
sOutBS <- makeTestStructByteStream eng
sOutFromBS <- getArrayFromByteStream eng sOutBS
sOut <- makeTestStruct eng
sSumFromBS <- useTestStruct eng sOutFromBS
sSum <- useTestStruct eng sOut
let sSumRes = assert (sSumFromBS == sSum) sSumFromBS
putStrLn $ " deserialized struct sum is: " <> (show sSumRes)
makeTestStructByteStream :: Engine -> IO [MUint8]
makeTestStructByteStream eng = do
[res] <- engineEvalFun eng "makeTestStructByteStream" [] 1
mxArrMay <- castMXArray res
case mxArrMay of
Just mxArr -> mxArrayGetAll mxArr
Nothing -> pure []
testCellGet :: Engine -> IO ()
testCellGet eng = do
putStrLn "\n-- testCellGet --"
[ca] <- engineEvalFun eng "mcellTest" [] 1
Just (ca :: MXArray MCell) <- castMXArray ca
caLen <- mxArrayLength ca
let caLenMsg = assert (caLen == 6) "cell array has length 6"
putStrLn caLenMsg
dCells :: [MXArray MDouble] <- mxCellGetArraysOfType ca
let dCellsMsg = assert (length dCells == 4) "cell array has 4 double arrays"
putStrLn dCellsMsg
dVals :: [MDouble] <- mxCellGetAllOfType ca
let dValsMsg = assert (length dVals == 4) "cell array has 4 double values"
putStrLn dValsMsg
testClearVar :: Engine -> IO ()
testClearVar eng = do
putStrLn $ "\n-- testClearVar --"
let foopi = "foopi"
x <- createMXScalar (pi :: MDouble)
engineSetVar eng foopi x
ei1 :: Either SomeException MAnyArray <- try $ engineGetVar eng foopi
putStrLn $ assert (isRight ei1) " Can clearVar once"
clearVar eng foopi
ei2 :: Either SomeException MAnyArray <- try $ engineGetVar eng foopi
putStrLn $ assert (isLeft ei2) $
" Can't clearVar twice: " <> (show $ lefts [ei2])
putStrLn " Finished testClearVar"
testRel :: Path Rel Dir
testRel = $(mkRelDir "test")
repoDir :: Path Abs Dir
repoDir = $(mkAbsDir getRepoDirStatic)
|
b1d45f7987ac67cf738d61ac303ccc364813f7c5e47b6cc6ea08c500f00eab5c | nomeata/ghc-proofs | Simple.hs | {-# OPTIONS_GHC -O -fplugin GHC.Proof.Plugin #-}
module Simple where
import GHC.Proof
import Data.Maybe
my_proof1 :: (a -> b) -> Maybe a -> Proof
my_proof1 f x = isNothing (fmap f x)
=== isNothing x
my_proof2 :: a -> Maybe a -> Proof
my_proof2 d x = fromMaybe d x
=== maybe d id x
| null | https://raw.githubusercontent.com/nomeata/ghc-proofs/9d013d36e1cac7b6e9322cd0b6295479cc7429eb/examples/Simple.hs | haskell | # OPTIONS_GHC -O -fplugin GHC.Proof.Plugin # | module Simple where
import GHC.Proof
import Data.Maybe
my_proof1 :: (a -> b) -> Maybe a -> Proof
my_proof1 f x = isNothing (fmap f x)
=== isNothing x
my_proof2 :: a -> Maybe a -> Proof
my_proof2 d x = fromMaybe d x
=== maybe d id x
|
4dc3e780539ad20159e8b5788986301fe0748ec29fadbcdc15b251d4ba4d5100 | mwand/5010-examples | 11-6-after-review.rkt | #lang racket
11-6-after-review.rkt
;; Clean up and review.
11-5-generalize-methods-in-superclass.rkt
;; If there are methods that are similar but not identical, generalize
;; them and put the generalization in the superclass. They can pick
;; up the differences using a hook method.
;; Here we'll do that with add-to-scene.
11-4-turn-differences-into-methods.rkt
;; local functions in the subclasses weren't accessible from the
;; superclass.
;; So turn them into methods, and call them with 'this'
;; We'll clean up a bit as we go, so we can see what we're doing.
(require rackunit)
(require 2htdp/universe)
(require 2htdp/image)
(require "extras.rkt")
start with ( run framerate ) . Typically : ( run 0.25 )
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; CONSTANTS
(define CANVAS-WIDTH 400)
(define CANVAS-HEIGHT 300)
(define EMPTY-CANVAS (empty-scene CANVAS-WIDTH CANVAS-HEIGHT))
(define INIT-WIDGET-X (/ CANVAS-HEIGHT 2))
(define INIT-WIDGET-Y (/ CANVAS-WIDTH 3))
(define INIT-WIDGET-SPEED 25)
(define INITIAL-WALL-POSITION 300)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Data Definitions
;; A Widget is an object whose class implements Widget<%>
;; An SWidget is an object whose class implements SWidget<%>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; INTERFACES
The World implements the > interface
(define StatefulWorld<%>
(interface ()
; -> Void
; GIVEN: no arguments
; EFFECT: updates this world to its state after a tick
after-tick
; Integer Integer MouseEvent-> Void
; GIVEN: an (x,y) location
; EFFECT: updates this world to the state that should follow the
; given mouse event at the given location.
after-mouse-event
KeyEvent : KeyEvent - > Void
; GIVEN: a key event
; EFFECT: updates this world to the state that should follow the
; given key event
after-key-event
; -> Scene
; GIVEN: a scene
; RETURNS: a scene that depicts this World
to-scene
; Widget -> Void
; GIVEN: A widget
; EFFECT: add the given widget to the world
add-widget
; SWidget -> Void
; GIVEN: A stateful widget
; EFFECT: add the given widget to the world
add-stateful-widget
))
;; Every functional object that lives in the world must implement the
;; Widget<%> interface.
(define Widget<%>
(interface ()
; -> Widget
; GIVEN: no arguments
; RETURNS: the state of this object that should follow at time t+1.
after-tick
Integer Integer - > Widget
; GIVEN: an (x,y) location
; RETURNS: the state of this object that should follow the
; specified mouse event at the given location.
after-button-down
after-button-up
after-drag
KeyEvent : KeyEvent - > Widget
; GIVEN: a key event and a time
; RETURNS: the state of this object that should follow the
; given key event
after-key-event
; Scene -> Scene
; GIVEN: a scene
; RETURNS: a scene like the given one, but with this object
; painted on it.
add-to-scene
))
;; Every stable (stateful) object that lives in the world must implement the
;; SWidget<%> interface.
(define SWidget<%>
(interface ()
; -> Void
; GIVEN: no arguments
; EFFECT: updates this widget to the state it should have
; following a tick.
after-tick
Integer Integer - > Void
; GIVEN: a location
; EFFECT: updates this widget to the state it should have
; following the specified mouse event at the given location.
after-button-down
after-button-up
after-drag
KeyEvent : KeyEvent - > Void
; GIVEN: a key event
; EFFECT: updates this widget to the state it should have
; following the given key event
after-key-event
; Scene -> Scene
; GIVEN: a scene
; RETURNS: a scene like the given one, but with this object
; painted on it.
add-to-scene
))
;; while we're at it, we'll rename the interfaces to reflect their
;; generic nature.
;; Interface for Ball and other classes that receive messages
;; from the wall:
(define SWidgetListener<%>
(interface (SWidget<%>)
; Int -> Void
; EFFECT: updates the ball's cached value of the wall's position
update-wall-pos
))
;; Interface for Wall and any other classes that send message to the
;; listeners:
(define SWidgetPublisher<%>
(interface (SWidget<%>)
; SWidgetListener<%> -> Int
; GIVEN: An SWidgetListener<%>
; EFFECT: registers the listener to receive position updates from this wall.
; RETURNS: the current x-position of the wall
register
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; initial-world : -> WorldState
;; RETURNS: a world with a wall, a ball, and a factory
(define (initial-world)
(local
((define the-wall (new Wall%))
(define the-ball (new Ball% [w the-wall]))
(define the-world
(make-world-state
empty
(list the-wall)))
(define the-factory
(new WidgetFactory% [wall the-wall][world the-world])))
(begin
;; put the factory in the world
(send the-world add-stateful-widget the-factory)
;; tell the factory to start a ball
(send the-factory after-key-event "b")
the-world)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; run : PosReal -> World
; GIVEN: a frame rate, in secs/tick
; EFFECT: runs an initial world at the given frame rate
; RETURNS: the world in its final state of the world
; Note: the (begin (send w ...) w) idiom
(define (run rate)
(big-bang (initial-world)
(on-tick
(lambda (w) (begin (send w after-tick) w))
rate)
(on-draw
(lambda (w) (send w to-scene)))
(on-key
(lambda (w kev)
(begin
(send w after-key-event kev)
w)))
(on-mouse
(lambda (w mx my mev)
(begin
(send w after-mouse-event mx my mev)
w)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The World% class
We 've renamed this class because it is now a real World , not merely
;; a mathematical object representing the state of a world.
ListOf(Widget<% > ) ListOf(SWidget<% > ) - > StatefulWorld<% >
(define (make-world-state objs sobjs)
(new World% [objs objs][sobjs sobjs]))
(define World%
(class* object% (StatefulWorld<%>)
(init-field objs) ; ListOfWidget
(init-field sobjs) ; ListOfSWidget
(super-new)
(define/public (add-widget w)
(set! objs (cons w objs)))
(define/public (add-stateful-widget w)
(set! sobjs (cons w sobjs)))
;; (Widget or SWidget -> Void) -> Void
(define (process-widgets fn)
(begin
(set! objs (map fn objs))
(for-each fn sobjs)))
;; after-tick : -> Void
Use map on the Widgets in this World ; use for - each on the
;; stateful widgets
(define/public (after-tick)
(process-widgets
(lambda (obj) (send obj after-tick))))
;; to-scene : -> Scene
;; Use HOFC foldr on the Widgets and SWidgets in this World
;; Note: the append is inefficient, but clear.
(define/public (to-scene)
(foldr
(lambda (obj scene)
(send obj add-to-scene scene))
EMPTY-CANVAS
(append objs sobjs)))
after - key - event : KeyEvent - > WorldState
STRATEGY : Pass the KeyEvents on to the objects in the world .
(define/public (after-key-event kev)
(process-widgets
(lambda (obj) (send obj after-key-event kev))))
world - after - mouse - event : WorldState
;; STRATGY: Cases on mev
(define/public (after-mouse-event mx my mev)
(cond
[(mouse=? mev "button-down")
(world-after-button-down mx my)]
[(mouse=? mev "drag")
(world-after-drag mx my)]
[(mouse=? mev "button-up")
(world-after-button-up mx my)]
[else this]))
;; the next few functions are local functions, not in the interface.
(define (world-after-button-down mx my)
(process-widgets
(lambda (obj) (send obj after-button-down mx my))))
(define (world-after-button-up mx my)
(process-widgets
(lambda (obj) (send obj after-button-up mx my))))
(define (world-after-drag mx my)
(process-widgets
(lambda (obj) (send obj after-drag mx my))))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The WidgetFactory% class
;; accepts key events and adds SWidgets to the world.
;; gets the world and the wall as init-fields.
We have only one of these . This is called the " singleton pattern "
(define WidgetFactory%
(class* object% (SWidget<%>)
(init-field world) ; the world to which the factory adds balls
(init-field wall) ; the wall that the new balls should bounce
; off of.
(super-new)
KeyEvent - > Void
(define/public (after-key-event kev)
(cond
[(key=? kev "b")
(send world add-stateful-widget (new Ball% [w wall]))]
[(key=? kev "f")
(send world add-stateful-widget (new FlashingBall% [w wall]))]
[(key=? kev "s")
(send world add-stateful-widget (new Square% [w wall]))]
))
the Ball Factory has no other behavior
(define/public (after-tick) this)
(define/public (after-button-down mx my) this)
(define/public (after-button-up mx my) this)
(define/public (after-drag mx my) this)
(define/public (add-to-scene s) s)
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
A DraggableWidget is a ( new DraggableWidget% [ w Wall ] )
(define DraggableWidget%
(class* object%
these guys are all stateful Widget Listeners
(SWidgetListener<%>)
the Wall that the ball should bounce off of
(init-field w)
;; initial values of x, y (center of widget)
(init-field [x INIT-WIDGET-X])
(init-field [y INIT-WIDGET-Y])
(init-field [speed INIT-WIDGET-SPEED])
; is this selected? Default is false.
(init-field [selected? false])
;; if this is selected, the position of
;; the last button-down event inside this, relative to the
;; object's center. Else any value.
(init-field [saved-mx 0] [saved-my 0])
;; register this ball with the wall, and use the result as the
;; initial value of wall-pos
(field [wall-pos (send w register this)])
(super-new)
;; Int -> Void
;; EFFECT: updates the widget's idea of the wall's position to the
;; given integer.
(define/public (update-wall-pos n)
(set! wall-pos n))
;; after-tick : -> Void
;; state of this ball after a tick. A selected widget doesn't move.
(define/public (after-tick)
(if selected?
this
(let ((x1 (send this next-x-pos))
(speed1 (send this next-speed)))
(begin
(set! speed speed1)
(set! x x1)))))
;; to be supplied by each subclass
(abstract next-x-pos)
(abstract next-speed)
(define/public (add-to-scene s)
(place-image
(send this get-image)
x y s))
;; to be supplied by each subclass
(abstract get-image)
after - button - down : Integer Integer - > Void
; GIVEN: the location of a button-down event
; STRATEGY: Cases on whether the event is in this
(define/public (after-button-down mx my)
(if (send this in-this? mx my)
(begin
(set! selected? true)
(set! saved-mx (- mx x))
(set! saved-my (- my y)))
this))
;; to be supplied by the subclass
(abstract in-this?)
after - button - up : Integer Integer - > Void
; GIVEN: the (x,y) location of a button-up event
; STRATEGY: Cases on whether the event is in this
; If this is selected, then unselect it.
(define/public (after-button-up mx my)
(if (send this in-this? mx my)
(set! selected? false)
this))
after - drag : Integer Integer - > Void
; GIVEN: the (x, y) location of a drag event
; STRATEGY: Cases on whether the ball is selected.
; If it is selected, move it so that the vector from the center to
; the drag event is equal to (mx, my)
(define/public (after-drag mx my)
(if selected?
(begin
(set! x (- mx saved-mx))
(set! y (- my saved-my)))
this))
;; the widget ignores key events
(define/public (after-key-event kev) this)
(define/public (for-test:x) x)
(define/public (for-test:speed) speed)
(define/public (for-test:wall-pos) wall-pos)
(define/public (for-test:next-speed) (next-speed))
(define/public (for-test:next-x) (next-x-pos))
))
;; Hooks left over: these methods must be filled in from subclass.
(define DraggableWidgetHooks<%>
(interface ()
;; Int Int -> Boolean
;; is the given location in this widget?
in-this?
;; -> Int
;; RETURNS: the next x position or speed of this widget
next-x-pos
next-speed
;; -> Image
;; RETURNS: the image of this widget for display
get-image
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The class
A Ball is a ( new [ w Wall ] )
(define Ball%
(class*
;; inherit method implementations from DraggableWidget%
DraggableWidget%
;; must implement SBall + the open hooks from the superclass
(SWidgetListener<%> DraggableWidgetHooks<%>)
;; inherit all these fields from the superclass:
the Wall that the ball should bounce off of
(inherit-field w)
;; initial values of x, y (center of ball) and speed:
(inherit-field x y speed)
; is this selected? Default is false.
(inherit-field selected?)
;; position of the wall, updated by update-wall-pos
(inherit-field wall-pos)
this field is local to
(field [radius 20])
(super-new)
;; make this a method instead of a function:
;; -> Integer
;; position of the ball at the next tick
;; STRATEGY: use the ball's cached copy of the wall position to
;; set the upper limit of motion
(define/override (next-x-pos)
(limit-value
radius
(+ x speed)
(- wall-pos radius)))
;; Number^3 -> Number
;; WHERE: lo <= hi
RETURNS : , but limited to the range [ lo , hi ]
(define (limit-value lo val hi)
(max lo (min val hi)))
;; -> Integer
;; RETURNS: the velocity of the ball at the next tick
;; STRATEGY: if the ball will not be at its limit, return it
;; unchanged. Otherwise, negate the velocity.
(define/override (next-speed)
(if
(< radius (next-x-pos) (- wall-pos radius))
speed
(- speed)))
;; the image of the ball. This could be dynamic.
(define/override (get-image)
(circle radius
"outline"
"red"))
in - this ? : Boolean
;; GIVEN: a location on the canvas
;; RETURNS: true iff the location is inside this.
(define/override (in-this? other-x other-y)
(<= (+ (sqr (- x other-x)) (sqr (- y other-y)))
(sqr radius)))
))
;; unit tests for ball:
(begin-for-test
(local
((define wall1 (new Wall% [pos 200]))
(define ball1 (new Ball% [x 110][speed 50][w wall1])))
(check-equal? (send ball1 for-test:speed) 50)
(check-equal? (send ball1 for-test:wall-pos) 200)
(check-equal? (send ball1 for-test:next-speed) 50)
(check-equal? (send ball1 for-test:next-x) 160)
(send ball1 after-tick)
(check-equal? (send ball1 for-test:x) 160)
(check-equal? (send ball1 for-test:speed) 50)
(send ball1 after-tick)
(check-equal? (send ball1 for-test:x) 180)
(check-equal? (send ball1 for-test:speed) -50)
))
(begin-for-test
(local
((define wall1 (new Wall% [pos 200]))
(define ball1 (new Ball% [x 160][speed 50][w wall1])))
(check-equal? (send ball1 for-test:x) 160)
(check-equal? (send ball1 for-test:speed) 50)
(check-equal? (send ball1 for-test:next-x) 180)
(check-equal? (send ball1 for-test:next-speed) -50)
(send ball1 after-tick)
(check-equal? (send ball1 for-test:x) 180)
(check-equal? (send ball1 for-test:speed) -50)
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
FlashingBall% is like a , but it displays differently : it
changes color on every fourth tick .
(define FlashingBall%
(class* Ball% (SWidgetListener<%>)
;; here are fields of the superclass that we need.
;; we should copy the interpretations here so we'll know what they mean.
(inherit-field radius x y selected?)
; how much time between color changes?
(field [color-change-interval 4])
; time left til next color change
(field [time-left color-change-interval])
the list of possible colors , first elt is current color
(field [colors (list "red" "green")])
;; the value for init-field w is sent to the superclass.
(super-new)
FlashingBall% behaves just like , except for add - to - scene .
so we 'll find on - tick , on - key , on - mouse methods in
;; Scene -> Scene
;; RETURNS: a scene like the given one, but with the flashing ball
;; painted on it.
;; EFFECT: decrements time-left and changes colors if necessary
(define/override (add-to-scene s)
(begin
;; is it time to change colors?
(if (zero? time-left)
(change-colors)
(set! time-left (- time-left 1)))
;; call the super. The super calls (get-image) to find the
;; image.
(super add-to-scene s)))
;; RETURNS: the image of this widget.
;; NOTE: this is dynamic-- it depends on color
(define/override (get-image)
(circle radius
(if selected? "solid" "outline")
(first colors)))
;; -> Void
;; EFFECT: rotate the list of colors, and reset time-left
(define (change-colors)
(set! colors (append (rest colors) (list (first colors))))
(set! time-left color-change-interval))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define Square%
(class* DraggableWidget%
;; must implement SWidgetListener + the open hooks from the superclass
(SWidgetListener<%> DraggableWidgetHooks<%>)
the Wall that the square should bounce off of
;; initial values of x, y (center of square)
(inherit-field x y speed)
; is this selected? Default is false.
(inherit-field selected?)
(inherit-field wall-pos)
(field [size 40])
(field [half-size (/ size 2)])
(super-new)
;; -> Integer
;; position of the square at the next tick
;; STRATEGY: use the square's cached copy of the wall position to
;; set the upper limit of motion
(define/override (next-x-pos)
(limit-value
half-size
(+ x speed)
(- wall-pos half-size)))
;; Number^3 -> Number
;; WHERE: lo <= hi
RETURNS : , but limited to the range [ lo , hi ]
(define (limit-value lo val hi)
(max lo (min val hi)))
;; Square-specific: turn into method
;; -> Integer
;; RETURNS: the velocity of the square at the next tick
;; STRATEGY: if the square will not be at its limit, return it
;; unchanged. Otherwise, negate the velocity.
(define/override (next-speed)
(if
(< half-size (next-x-pos) (- wall-pos half-size))
speed
(- speed)))
(define/override (get-image)
(square size
(if selected? "solid" "outline")
"green"))
in - this ? : Boolean
;; GIVEN: a location on the canvas
;; RETURNS: true iff the location is inside this.
(define/override (in-this? other-x other-y)
(and
(<= (- x half-size) other-x (+ x half-size))
(<= (- y half-size) other-y (+ y half-size))))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The Wall% class
(define Wall%
(class* object% (SWidgetPublisher<%>)
(init-field [pos INITIAL-WALL-POSITION]) ; the x position of the wall
; is the wall selected? Default is false.
(init-field [selected? false])
;; if the wall is selected, the x position of
;; the last button-down event near the wall, otherwise can be any
;; value.
(init-field [saved-mx 0])
;; the list of registered listeners
;; ListOf(WidgetListener<%>)
(field [listeners empty])
(super-new)
;; WidgetListener<%> -> Int
;; EFFECT: registers the given listener
;; RETURNS: the current position of the wall
(define/public (register b)
(begin
(set! listeners (cons b listeners))
pos))
;; Mouse responses. How much of this could be shared using
DraggableWidget ?
after - button - down : Integer Integer - > Void
; GIVEN: the (x, y) location of a button-down event
; EFFECT: if the event is near the wall, make the wall selected.
; STRATEGY: Cases on whether the event is near the wall
(define/public (after-button-down mx my)
(if (near-wall? mx)
(begin
(set! selected? true)
(set! saved-mx (- mx pos)))
this))
after - button - up : Integer Integer - > Void
; GIVEN: the (x,y) location of a button-up event
EFFECT : makes the Wall unselected
(define/public (after-button-up mx my)
(set! selected? false))
after - drag : Integer Integer - > Void
; GIVEN: the (x,y) location of a drag event
; STRATEGY: Cases on whether the wall is selected.
; If it is selected, move it so that the vector from its position to
; the drag event is equal to saved-mx. Report the new position to
; the listeners.
(define/public (after-drag mx my)
(if selected?
(begin
(set! pos (- mx saved-mx))
(for-each
(lambda (b) (send b update-wall-pos pos))
listeners))
this))
;; add-to-scene : Scene -> Scene
;; RETURNS: a scene like the given one, but with this wall painted
;; on it.
(define/public (add-to-scene scene)
(scene+line scene pos 0 pos CANVAS-HEIGHT "black"))
;; is mx near the wall? We arbitrarily say it's near if its
within 5 pixels .
(define (near-wall? mx)
(< (abs (- mx pos)) 5))
;; the wall has no other behaviors
(define/public (after-tick) this)
(define/public (after-key-event kev) this)
))
| null | https://raw.githubusercontent.com/mwand/5010-examples/ac24491ec2e533d048e11087ccc30ff1c087c218/11-6-after-review.rkt | racket | Clean up and review.
If there are methods that are similar but not identical, generalize
them and put the generalization in the superclass. They can pick
up the differences using a hook method.
Here we'll do that with add-to-scene.
local functions in the subclasses weren't accessible from the
superclass.
So turn them into methods, and call them with 'this'
We'll clean up a bit as we go, so we can see what we're doing.
CONSTANTS
Data Definitions
A Widget is an object whose class implements Widget<%>
An SWidget is an object whose class implements SWidget<%>
INTERFACES
-> Void
GIVEN: no arguments
EFFECT: updates this world to its state after a tick
Integer Integer MouseEvent-> Void
GIVEN: an (x,y) location
EFFECT: updates this world to the state that should follow the
given mouse event at the given location.
GIVEN: a key event
EFFECT: updates this world to the state that should follow the
given key event
-> Scene
GIVEN: a scene
RETURNS: a scene that depicts this World
Widget -> Void
GIVEN: A widget
EFFECT: add the given widget to the world
SWidget -> Void
GIVEN: A stateful widget
EFFECT: add the given widget to the world
Every functional object that lives in the world must implement the
Widget<%> interface.
-> Widget
GIVEN: no arguments
RETURNS: the state of this object that should follow at time t+1.
GIVEN: an (x,y) location
RETURNS: the state of this object that should follow the
specified mouse event at the given location.
GIVEN: a key event and a time
RETURNS: the state of this object that should follow the
given key event
Scene -> Scene
GIVEN: a scene
RETURNS: a scene like the given one, but with this object
painted on it.
Every stable (stateful) object that lives in the world must implement the
SWidget<%> interface.
-> Void
GIVEN: no arguments
EFFECT: updates this widget to the state it should have
following a tick.
GIVEN: a location
EFFECT: updates this widget to the state it should have
following the specified mouse event at the given location.
GIVEN: a key event
EFFECT: updates this widget to the state it should have
following the given key event
Scene -> Scene
GIVEN: a scene
RETURNS: a scene like the given one, but with this object
painted on it.
while we're at it, we'll rename the interfaces to reflect their
generic nature.
Interface for Ball and other classes that receive messages
from the wall:
Int -> Void
EFFECT: updates the ball's cached value of the wall's position
Interface for Wall and any other classes that send message to the
listeners:
SWidgetListener<%> -> Int
GIVEN: An SWidgetListener<%>
EFFECT: registers the listener to receive position updates from this wall.
RETURNS: the current x-position of the wall
initial-world : -> WorldState
RETURNS: a world with a wall, a ball, and a factory
put the factory in the world
tell the factory to start a ball
run : PosReal -> World
GIVEN: a frame rate, in secs/tick
EFFECT: runs an initial world at the given frame rate
RETURNS: the world in its final state of the world
Note: the (begin (send w ...) w) idiom
The World% class
a mathematical object representing the state of a world.
ListOfWidget
ListOfSWidget
(Widget or SWidget -> Void) -> Void
after-tick : -> Void
use for - each on the
stateful widgets
to-scene : -> Scene
Use HOFC foldr on the Widgets and SWidgets in this World
Note: the append is inefficient, but clear.
STRATGY: Cases on mev
the next few functions are local functions, not in the interface.
accepts key events and adds SWidgets to the world.
gets the world and the wall as init-fields.
the world to which the factory adds balls
the wall that the new balls should bounce
off of.
initial values of x, y (center of widget)
is this selected? Default is false.
if this is selected, the position of
the last button-down event inside this, relative to the
object's center. Else any value.
register this ball with the wall, and use the result as the
initial value of wall-pos
Int -> Void
EFFECT: updates the widget's idea of the wall's position to the
given integer.
after-tick : -> Void
state of this ball after a tick. A selected widget doesn't move.
to be supplied by each subclass
to be supplied by each subclass
GIVEN: the location of a button-down event
STRATEGY: Cases on whether the event is in this
to be supplied by the subclass
GIVEN: the (x,y) location of a button-up event
STRATEGY: Cases on whether the event is in this
If this is selected, then unselect it.
GIVEN: the (x, y) location of a drag event
STRATEGY: Cases on whether the ball is selected.
If it is selected, move it so that the vector from the center to
the drag event is equal to (mx, my)
the widget ignores key events
Hooks left over: these methods must be filled in from subclass.
Int Int -> Boolean
is the given location in this widget?
-> Int
RETURNS: the next x position or speed of this widget
-> Image
RETURNS: the image of this widget for display
inherit method implementations from DraggableWidget%
must implement SBall + the open hooks from the superclass
inherit all these fields from the superclass:
initial values of x, y (center of ball) and speed:
is this selected? Default is false.
position of the wall, updated by update-wall-pos
make this a method instead of a function:
-> Integer
position of the ball at the next tick
STRATEGY: use the ball's cached copy of the wall position to
set the upper limit of motion
Number^3 -> Number
WHERE: lo <= hi
-> Integer
RETURNS: the velocity of the ball at the next tick
STRATEGY: if the ball will not be at its limit, return it
unchanged. Otherwise, negate the velocity.
the image of the ball. This could be dynamic.
GIVEN: a location on the canvas
RETURNS: true iff the location is inside this.
unit tests for ball:
here are fields of the superclass that we need.
we should copy the interpretations here so we'll know what they mean.
how much time between color changes?
time left til next color change
the value for init-field w is sent to the superclass.
Scene -> Scene
RETURNS: a scene like the given one, but with the flashing ball
painted on it.
EFFECT: decrements time-left and changes colors if necessary
is it time to change colors?
call the super. The super calls (get-image) to find the
image.
RETURNS: the image of this widget.
NOTE: this is dynamic-- it depends on color
-> Void
EFFECT: rotate the list of colors, and reset time-left
must implement SWidgetListener + the open hooks from the superclass
initial values of x, y (center of square)
is this selected? Default is false.
-> Integer
position of the square at the next tick
STRATEGY: use the square's cached copy of the wall position to
set the upper limit of motion
Number^3 -> Number
WHERE: lo <= hi
Square-specific: turn into method
-> Integer
RETURNS: the velocity of the square at the next tick
STRATEGY: if the square will not be at its limit, return it
unchanged. Otherwise, negate the velocity.
GIVEN: a location on the canvas
RETURNS: true iff the location is inside this.
the x position of the wall
is the wall selected? Default is false.
if the wall is selected, the x position of
the last button-down event near the wall, otherwise can be any
value.
the list of registered listeners
ListOf(WidgetListener<%>)
WidgetListener<%> -> Int
EFFECT: registers the given listener
RETURNS: the current position of the wall
Mouse responses. How much of this could be shared using
GIVEN: the (x, y) location of a button-down event
EFFECT: if the event is near the wall, make the wall selected.
STRATEGY: Cases on whether the event is near the wall
GIVEN: the (x,y) location of a button-up event
GIVEN: the (x,y) location of a drag event
STRATEGY: Cases on whether the wall is selected.
If it is selected, move it so that the vector from its position to
the drag event is equal to saved-mx. Report the new position to
the listeners.
add-to-scene : Scene -> Scene
RETURNS: a scene like the given one, but with this wall painted
on it.
is mx near the wall? We arbitrarily say it's near if its
the wall has no other behaviors | #lang racket
11-6-after-review.rkt
11-5-generalize-methods-in-superclass.rkt
11-4-turn-differences-into-methods.rkt
(require rackunit)
(require 2htdp/universe)
(require 2htdp/image)
(require "extras.rkt")
start with ( run framerate ) . Typically : ( run 0.25 )
(define CANVAS-WIDTH 400)
(define CANVAS-HEIGHT 300)
(define EMPTY-CANVAS (empty-scene CANVAS-WIDTH CANVAS-HEIGHT))
(define INIT-WIDGET-X (/ CANVAS-HEIGHT 2))
(define INIT-WIDGET-Y (/ CANVAS-WIDTH 3))
(define INIT-WIDGET-SPEED 25)
(define INITIAL-WALL-POSITION 300)
The World implements the > interface
(define StatefulWorld<%>
(interface ()
after-tick
after-mouse-event
KeyEvent : KeyEvent - > Void
after-key-event
to-scene
add-widget
add-stateful-widget
))
(define Widget<%>
(interface ()
after-tick
Integer Integer - > Widget
after-button-down
after-button-up
after-drag
KeyEvent : KeyEvent - > Widget
after-key-event
add-to-scene
))
(define SWidget<%>
(interface ()
after-tick
Integer Integer - > Void
after-button-down
after-button-up
after-drag
KeyEvent : KeyEvent - > Void
after-key-event
add-to-scene
))
(define SWidgetListener<%>
(interface (SWidget<%>)
update-wall-pos
))
(define SWidgetPublisher<%>
(interface (SWidget<%>)
register
))
(define (initial-world)
(local
((define the-wall (new Wall%))
(define the-ball (new Ball% [w the-wall]))
(define the-world
(make-world-state
empty
(list the-wall)))
(define the-factory
(new WidgetFactory% [wall the-wall][world the-world])))
(begin
(send the-world add-stateful-widget the-factory)
(send the-factory after-key-event "b")
the-world)))
(define (run rate)
(big-bang (initial-world)
(on-tick
(lambda (w) (begin (send w after-tick) w))
rate)
(on-draw
(lambda (w) (send w to-scene)))
(on-key
(lambda (w kev)
(begin
(send w after-key-event kev)
w)))
(on-mouse
(lambda (w mx my mev)
(begin
(send w after-mouse-event mx my mev)
w)))))
We 've renamed this class because it is now a real World , not merely
ListOf(Widget<% > ) ListOf(SWidget<% > ) - > StatefulWorld<% >
(define (make-world-state objs sobjs)
(new World% [objs objs][sobjs sobjs]))
(define World%
(class* object% (StatefulWorld<%>)
(super-new)
(define/public (add-widget w)
(set! objs (cons w objs)))
(define/public (add-stateful-widget w)
(set! sobjs (cons w sobjs)))
(define (process-widgets fn)
(begin
(set! objs (map fn objs))
(for-each fn sobjs)))
(define/public (after-tick)
(process-widgets
(lambda (obj) (send obj after-tick))))
(define/public (to-scene)
(foldr
(lambda (obj scene)
(send obj add-to-scene scene))
EMPTY-CANVAS
(append objs sobjs)))
after - key - event : KeyEvent - > WorldState
STRATEGY : Pass the KeyEvents on to the objects in the world .
(define/public (after-key-event kev)
(process-widgets
(lambda (obj) (send obj after-key-event kev))))
world - after - mouse - event : WorldState
(define/public (after-mouse-event mx my mev)
(cond
[(mouse=? mev "button-down")
(world-after-button-down mx my)]
[(mouse=? mev "drag")
(world-after-drag mx my)]
[(mouse=? mev "button-up")
(world-after-button-up mx my)]
[else this]))
(define (world-after-button-down mx my)
(process-widgets
(lambda (obj) (send obj after-button-down mx my))))
(define (world-after-button-up mx my)
(process-widgets
(lambda (obj) (send obj after-button-up mx my))))
(define (world-after-drag mx my)
(process-widgets
(lambda (obj) (send obj after-drag mx my))))
))
The WidgetFactory% class
We have only one of these . This is called the " singleton pattern "
(define WidgetFactory%
(class* object% (SWidget<%>)
(super-new)
KeyEvent - > Void
(define/public (after-key-event kev)
(cond
[(key=? kev "b")
(send world add-stateful-widget (new Ball% [w wall]))]
[(key=? kev "f")
(send world add-stateful-widget (new FlashingBall% [w wall]))]
[(key=? kev "s")
(send world add-stateful-widget (new Square% [w wall]))]
))
the Ball Factory has no other behavior
(define/public (after-tick) this)
(define/public (after-button-down mx my) this)
(define/public (after-button-up mx my) this)
(define/public (after-drag mx my) this)
(define/public (add-to-scene s) s)
))
A DraggableWidget is a ( new DraggableWidget% [ w Wall ] )
(define DraggableWidget%
(class* object%
these guys are all stateful Widget Listeners
(SWidgetListener<%>)
the Wall that the ball should bounce off of
(init-field w)
(init-field [x INIT-WIDGET-X])
(init-field [y INIT-WIDGET-Y])
(init-field [speed INIT-WIDGET-SPEED])
(init-field [selected? false])
(init-field [saved-mx 0] [saved-my 0])
(field [wall-pos (send w register this)])
(super-new)
(define/public (update-wall-pos n)
(set! wall-pos n))
(define/public (after-tick)
(if selected?
this
(let ((x1 (send this next-x-pos))
(speed1 (send this next-speed)))
(begin
(set! speed speed1)
(set! x x1)))))
(abstract next-x-pos)
(abstract next-speed)
(define/public (add-to-scene s)
(place-image
(send this get-image)
x y s))
(abstract get-image)
after - button - down : Integer Integer - > Void
(define/public (after-button-down mx my)
(if (send this in-this? mx my)
(begin
(set! selected? true)
(set! saved-mx (- mx x))
(set! saved-my (- my y)))
this))
(abstract in-this?)
after - button - up : Integer Integer - > Void
(define/public (after-button-up mx my)
(if (send this in-this? mx my)
(set! selected? false)
this))
after - drag : Integer Integer - > Void
(define/public (after-drag mx my)
(if selected?
(begin
(set! x (- mx saved-mx))
(set! y (- my saved-my)))
this))
(define/public (after-key-event kev) this)
(define/public (for-test:x) x)
(define/public (for-test:speed) speed)
(define/public (for-test:wall-pos) wall-pos)
(define/public (for-test:next-speed) (next-speed))
(define/public (for-test:next-x) (next-x-pos))
))
(define DraggableWidgetHooks<%>
(interface ()
in-this?
next-x-pos
next-speed
get-image
))
The class
A Ball is a ( new [ w Wall ] )
(define Ball%
(class*
DraggableWidget%
(SWidgetListener<%> DraggableWidgetHooks<%>)
the Wall that the ball should bounce off of
(inherit-field w)
(inherit-field x y speed)
(inherit-field selected?)
(inherit-field wall-pos)
this field is local to
(field [radius 20])
(super-new)
(define/override (next-x-pos)
(limit-value
radius
(+ x speed)
(- wall-pos radius)))
RETURNS : , but limited to the range [ lo , hi ]
(define (limit-value lo val hi)
(max lo (min val hi)))
(define/override (next-speed)
(if
(< radius (next-x-pos) (- wall-pos radius))
speed
(- speed)))
(define/override (get-image)
(circle radius
"outline"
"red"))
in - this ? : Boolean
(define/override (in-this? other-x other-y)
(<= (+ (sqr (- x other-x)) (sqr (- y other-y)))
(sqr radius)))
))
(begin-for-test
(local
((define wall1 (new Wall% [pos 200]))
(define ball1 (new Ball% [x 110][speed 50][w wall1])))
(check-equal? (send ball1 for-test:speed) 50)
(check-equal? (send ball1 for-test:wall-pos) 200)
(check-equal? (send ball1 for-test:next-speed) 50)
(check-equal? (send ball1 for-test:next-x) 160)
(send ball1 after-tick)
(check-equal? (send ball1 for-test:x) 160)
(check-equal? (send ball1 for-test:speed) 50)
(send ball1 after-tick)
(check-equal? (send ball1 for-test:x) 180)
(check-equal? (send ball1 for-test:speed) -50)
))
(begin-for-test
(local
((define wall1 (new Wall% [pos 200]))
(define ball1 (new Ball% [x 160][speed 50][w wall1])))
(check-equal? (send ball1 for-test:x) 160)
(check-equal? (send ball1 for-test:speed) 50)
(check-equal? (send ball1 for-test:next-x) 180)
(check-equal? (send ball1 for-test:next-speed) -50)
(send ball1 after-tick)
(check-equal? (send ball1 for-test:x) 180)
(check-equal? (send ball1 for-test:speed) -50)
))
FlashingBall% is like a , but it displays differently : it
changes color on every fourth tick .
(define FlashingBall%
(class* Ball% (SWidgetListener<%>)
(inherit-field radius x y selected?)
(field [color-change-interval 4])
(field [time-left color-change-interval])
the list of possible colors , first elt is current color
(field [colors (list "red" "green")])
(super-new)
FlashingBall% behaves just like , except for add - to - scene .
so we 'll find on - tick , on - key , on - mouse methods in
(define/override (add-to-scene s)
(begin
(if (zero? time-left)
(change-colors)
(set! time-left (- time-left 1)))
(super add-to-scene s)))
(define/override (get-image)
(circle radius
(if selected? "solid" "outline")
(first colors)))
(define (change-colors)
(set! colors (append (rest colors) (list (first colors))))
(set! time-left color-change-interval))
))
(define Square%
(class* DraggableWidget%
(SWidgetListener<%> DraggableWidgetHooks<%>)
the Wall that the square should bounce off of
(inherit-field x y speed)
(inherit-field selected?)
(inherit-field wall-pos)
(field [size 40])
(field [half-size (/ size 2)])
(super-new)
(define/override (next-x-pos)
(limit-value
half-size
(+ x speed)
(- wall-pos half-size)))
RETURNS : , but limited to the range [ lo , hi ]
(define (limit-value lo val hi)
(max lo (min val hi)))
(define/override (next-speed)
(if
(< half-size (next-x-pos) (- wall-pos half-size))
speed
(- speed)))
(define/override (get-image)
(square size
(if selected? "solid" "outline")
"green"))
in - this ? : Boolean
(define/override (in-this? other-x other-y)
(and
(<= (- x half-size) other-x (+ x half-size))
(<= (- y half-size) other-y (+ y half-size))))
))
The Wall% class
(define Wall%
(class* object% (SWidgetPublisher<%>)
(init-field [selected? false])
(init-field [saved-mx 0])
(field [listeners empty])
(super-new)
(define/public (register b)
(begin
(set! listeners (cons b listeners))
pos))
DraggableWidget ?
after - button - down : Integer Integer - > Void
(define/public (after-button-down mx my)
(if (near-wall? mx)
(begin
(set! selected? true)
(set! saved-mx (- mx pos)))
this))
after - button - up : Integer Integer - > Void
EFFECT : makes the Wall unselected
(define/public (after-button-up mx my)
(set! selected? false))
after - drag : Integer Integer - > Void
(define/public (after-drag mx my)
(if selected?
(begin
(set! pos (- mx saved-mx))
(for-each
(lambda (b) (send b update-wall-pos pos))
listeners))
this))
(define/public (add-to-scene scene)
(scene+line scene pos 0 pos CANVAS-HEIGHT "black"))
within 5 pixels .
(define (near-wall? mx)
(< (abs (- mx pos)) 5))
(define/public (after-tick) this)
(define/public (after-key-event kev) this)
))
|
8d073a5c719027005c359195ef7e1bc3b21308a3a2f96c410c5a7c42ca0ab50a | gafiatulin/codewars | Trim.hs | -- Trim a String
-- /
module Trim where
import Data.Char (isSpace)
trim :: String -> String
trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/6%20kyu/Trim.hs | haskell | Trim a String
/ |
module Trim where
import Data.Char (isSpace)
trim :: String -> String
trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace
|
57f7c91d15a0de0d5bd400f212a9a24489c1275d1a307ab21785da502653b279 | metaocaml/ber-metaocaml | rec_check.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, University of Cambridge
(* *)
Copyright 2017
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
exception Illegal_expr
val is_valid_recursive_expression : Ident.t list -> Typedtree.expression -> bool
val is_valid_class_expr : Ident.t list -> Typedtree.class_expr -> bool
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/typing/rec_check.mli | ocaml | ************************************************************************
OCaml
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************ | , University of Cambridge
Copyright 2017
the GNU Lesser General Public License version 2.1 , with the
exception Illegal_expr
val is_valid_recursive_expression : Ident.t list -> Typedtree.expression -> bool
val is_valid_class_expr : Ident.t list -> Typedtree.class_expr -> bool
|
4f789e64a010e4e25ba34dee1e4b93db52583bde8616288417d1469481242e81 | pixlsus/registry.gimp.org_static | descreen.scm | Descreen v1.0
; Tested on Gimp v2.6.8
(define (script-fu-descreen image drawable sensitivity selectiongrowth despeckle middle-ratio)
This script requires the FFT plug - in which provides FFT forward and FFT inverse filter
(if (not (defined? 'plug-in-fft-dir))
(begin
; Display an error message
(gimp-message "This script requires the FFT plug-in")
; Abort the script
(quit)
)
)
; Start an undo group
(gimp-image-undo-group-start image)
Save the context ( FFT plug - in change the foreground color )
(gimp-context-push)
Ensure the layer has no alpha channel ( FFT plug - in does not work well with them )
(gimp-layer-flatten drawable)
Apply the FFT forward filter
(plug-in-fft-dir RUN-NONINTERACTIVE image drawable)
(let* (
Duplicate the layer containing the image FFTed
(detection (car (gimp-layer-copy drawable FALSE)))
; Add the new layer to the image
(exec (gimp-image-add-layer image detection -1))
; Calculate the low threshold given the sensitivity (low-threshold=256-sensitivity)
(low-threshold (- 256 sensitivity))
; Determine the dimensions of the middle zone that should remain untouched
(middle-width (/ (car (gimp-image-width image)) middle-ratio))
(middle-height (/ (car (gimp-image-height image)) middle-ratio))
; Calculate the middle of the picture
(middle-x (/ (car (gimp-image-width image)) 2))
(middle-y (/ (car (gimp-image-height image)) 2))
; gimp-ellipse-select needs the upper left coordinates of the ellipse
(middle-x (- middle-x (/ middle-width 2)))
(middle-y (- middle-y (/ middle-height 2))))
; Keep only strong frequencies
(gimp-threshold detection low-threshold 255)
; Select the points
(gimp-by-color-select detection '(255 255 255) 0 0 0 FALSE 0 FALSE)
; Grow the selection
(gimp-selection-grow image selectiongrowth)
; Remove the middle of the picture from the selection
(gimp-ellipse-select image middle-x middle-y middle-width middle-height 1 FALSE FALSE 0)
; Fill the picture according to the selection.
Foreground color has been set by the FFT plugin to # 808080
(gimp-edit-fill drawable 0)
; Delete the detection layer
(gimp-image-remove-layer image detection)
; Unselect
(gimp-selection-none image)
)
Do an FFT inverse on the picture
(plug-in-fft-inv RUN-NONINTERACTIVE image drawable)
; Check if despeckle has been selected
(if despeckle
; Do a last despeckle to remove small points
(plug-in-despeckle RUN-NONINTERACTIVE image drawable 1 0 -1 256)
)
; Restore the original context
(gimp-context-pop)
; End the undo group
(gimp-image-undo-group-end image)
)
(script-fu-register "script-fu-descreen"
"<Image>/Filters/Enhance/Descreen"
"Descreen filter"
"Frédéric BISSON"
"Frédéric BISSON"
"01/05/2010"
"RGB*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
; Sensitivity to frequency level :
1 = nearly insensitive , 128 = sensitive to any frequency level
SF-ADJUSTMENT "Sensitivity" '(72 1 128 1 16 0 SF-ROLLBOX)
; After the frequency level detection, the filter will affect
; everything within the range of the growth
SF-VALUE "Selection growth" "16"
; Do a final despeckle before ending the filter
SF-TOGGLE "Despeckle" TRUE
; Consider the middle of the picture to be a ratio of the
; image dimensions.
SF-VALUE "Ratio for middle preservation" "5"
)
| null | https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/descreen.scm | scheme | Tested on Gimp v2.6.8
Display an error message
Abort the script
Start an undo group
Add the new layer to the image
Calculate the low threshold given the sensitivity (low-threshold=256-sensitivity)
Determine the dimensions of the middle zone that should remain untouched
Calculate the middle of the picture
gimp-ellipse-select needs the upper left coordinates of the ellipse
Keep only strong frequencies
Select the points
Grow the selection
Remove the middle of the picture from the selection
Fill the picture according to the selection.
Delete the detection layer
Unselect
Check if despeckle has been selected
Do a last despeckle to remove small points
Restore the original context
End the undo group
Sensitivity to frequency level :
After the frequency level detection, the filter will affect
everything within the range of the growth
Do a final despeckle before ending the filter
Consider the middle of the picture to be a ratio of the
image dimensions.
| Descreen v1.0
(define (script-fu-descreen image drawable sensitivity selectiongrowth despeckle middle-ratio)
This script requires the FFT plug - in which provides FFT forward and FFT inverse filter
(if (not (defined? 'plug-in-fft-dir))
(begin
(gimp-message "This script requires the FFT plug-in")
(quit)
)
)
(gimp-image-undo-group-start image)
Save the context ( FFT plug - in change the foreground color )
(gimp-context-push)
Ensure the layer has no alpha channel ( FFT plug - in does not work well with them )
(gimp-layer-flatten drawable)
Apply the FFT forward filter
(plug-in-fft-dir RUN-NONINTERACTIVE image drawable)
(let* (
Duplicate the layer containing the image FFTed
(detection (car (gimp-layer-copy drawable FALSE)))
(exec (gimp-image-add-layer image detection -1))
(low-threshold (- 256 sensitivity))
(middle-width (/ (car (gimp-image-width image)) middle-ratio))
(middle-height (/ (car (gimp-image-height image)) middle-ratio))
(middle-x (/ (car (gimp-image-width image)) 2))
(middle-y (/ (car (gimp-image-height image)) 2))
(middle-x (- middle-x (/ middle-width 2)))
(middle-y (- middle-y (/ middle-height 2))))
(gimp-threshold detection low-threshold 255)
(gimp-by-color-select detection '(255 255 255) 0 0 0 FALSE 0 FALSE)
(gimp-selection-grow image selectiongrowth)
(gimp-ellipse-select image middle-x middle-y middle-width middle-height 1 FALSE FALSE 0)
Foreground color has been set by the FFT plugin to # 808080
(gimp-edit-fill drawable 0)
(gimp-image-remove-layer image detection)
(gimp-selection-none image)
)
Do an FFT inverse on the picture
(plug-in-fft-inv RUN-NONINTERACTIVE image drawable)
(if despeckle
(plug-in-despeckle RUN-NONINTERACTIVE image drawable 1 0 -1 256)
)
(gimp-context-pop)
(gimp-image-undo-group-end image)
)
(script-fu-register "script-fu-descreen"
"<Image>/Filters/Enhance/Descreen"
"Descreen filter"
"Frédéric BISSON"
"Frédéric BISSON"
"01/05/2010"
"RGB*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
1 = nearly insensitive , 128 = sensitive to any frequency level
SF-ADJUSTMENT "Sensitivity" '(72 1 128 1 16 0 SF-ROLLBOX)
SF-VALUE "Selection growth" "16"
SF-TOGGLE "Despeckle" TRUE
SF-VALUE "Ratio for middle preservation" "5"
)
|
e01d6285fb12e5cd63bafb0c4b269f64459861e52d91bff450cc2989dcb6b587 | ralsei/bingus | parsing-submission.rkt | #lang racket
(require "data-def-parsing.rkt"
"check-signature.rkt")
(provide parse-submission)
; mode controls what is parsed
; - 'a is for all lines
; - 'c is for all comments
; - 'd is for all data definitions
; - 's is for all signatures
(define (parse submitted-string [mode 'a])
(let ([regexp-exp
(match mode
['a #px"(?m:^.*$)"]
['c #px"(?m:^\\s*;.*$)"]
['d #px"(?mi:^\\s*;[\\s;]*an?\\s+(.*\\S)\\s+is\\s+(?:an?\\s+)?(.*\\S)\\s*$)"]
# \\s]+)\\s*:\\s*(.*?)\\s*--*>\\s*(.*?)\\s*$ ) " ]
)])
(regexp-match* regexp-exp submitted-string)))
(define (parse-submission ss)
(let ([signatures (parse ss 's)]
[dd (parse ss 'd)])
(values (add-all-dd dd '())
(map ss->signature signatures))))
| null | https://raw.githubusercontent.com/ralsei/bingus/c08cf67534088a19987c6c35bf7006d9a3a39171/bingus-lib/parser/from-checkers/parsing-submission.rkt | racket | mode controls what is parsed
- 'a is for all lines
- 'c is for all comments
- 'd is for all data definitions
- 's is for all signatures | #lang racket
(require "data-def-parsing.rkt"
"check-signature.rkt")
(provide parse-submission)
(define (parse submitted-string [mode 'a])
(let ([regexp-exp
(match mode
['a #px"(?m:^.*$)"]
['c #px"(?m:^\\s*;.*$)"]
['d #px"(?mi:^\\s*;[\\s;]*an?\\s+(.*\\S)\\s+is\\s+(?:an?\\s+)?(.*\\S)\\s*$)"]
# \\s]+)\\s*:\\s*(.*?)\\s*--*>\\s*(.*?)\\s*$ ) " ]
)])
(regexp-match* regexp-exp submitted-string)))
(define (parse-submission ss)
(let ([signatures (parse ss 's)]
[dd (parse ss 'd)])
(values (add-all-dd dd '())
(map ss->signature signatures))))
|
aab971d4c4054a0d1443434e763f8db001f590902012e6c3db566907974bf83d | UBTECH-Walker/WalkerSimulationFor2020WAIC | _package_EndEffectorProperties.lisp | (cl:in-package ubt_core_msgs-msg)
(cl:export '(ID-VAL
ID
UI_TYPE-VAL
UI_TYPE
MANUFACTURER-VAL
MANUFACTURER
PRODUCT-VAL
PRODUCT
SERIAL_NUMBER-VAL
SERIAL_NUMBER
HARDWARE_REV-VAL
HARDWARE_REV
FIRMWARE_REV-VAL
FIRMWARE_REV
FIRMWARE_DATE-VAL
FIRMWARE_DATE
HAS_CALIBRATION-VAL
HAS_CALIBRATION
CONTROLS_GRIP-VAL
CONTROLS_GRIP
SENSES_GRIP-VAL
SENSES_GRIP
REVERSES_GRIP-VAL
REVERSES_GRIP
CONTROLS_FORCE-VAL
CONTROLS_FORCE
SENSES_FORCE-VAL
SENSES_FORCE
CONTROLS_POSITION-VAL
CONTROLS_POSITION
SENSES_POSITION-VAL
SENSES_POSITION
PROPERTIES-VAL
PROPERTIES
)) | null | https://raw.githubusercontent.com/UBTECH-Walker/WalkerSimulationFor2020WAIC/7cdb21dabb8423994ba3f6021bc7934290d5faa9/walker_WAIC_18.04_v1.2_20200616/walker_install/share/common-lisp/ros/ubt_core_msgs/msg/_package_EndEffectorProperties.lisp | lisp | (cl:in-package ubt_core_msgs-msg)
(cl:export '(ID-VAL
ID
UI_TYPE-VAL
UI_TYPE
MANUFACTURER-VAL
MANUFACTURER
PRODUCT-VAL
PRODUCT
SERIAL_NUMBER-VAL
SERIAL_NUMBER
HARDWARE_REV-VAL
HARDWARE_REV
FIRMWARE_REV-VAL
FIRMWARE_REV
FIRMWARE_DATE-VAL
FIRMWARE_DATE
HAS_CALIBRATION-VAL
HAS_CALIBRATION
CONTROLS_GRIP-VAL
CONTROLS_GRIP
SENSES_GRIP-VAL
SENSES_GRIP
REVERSES_GRIP-VAL
REVERSES_GRIP
CONTROLS_FORCE-VAL
CONTROLS_FORCE
SENSES_FORCE-VAL
SENSES_FORCE
CONTROLS_POSITION-VAL
CONTROLS_POSITION
SENSES_POSITION-VAL
SENSES_POSITION
PROPERTIES-VAL
PROPERTIES
)) | |
22797cba71dd459d323be481fd4b1e1b8e0706f6766a7b0550ae2a18baf505ba | janestreet/memtrace_viewer_with_deps | details_panel.ml | open! Core_kernel
open! Async_kernel
open! Bonsai_web
open Memtrace_viewer_common
let view ~focus ~total_allocations ~direction =
let header_text = Vdom.Node.text "Selection" in
let header = Vdom.Node.h2 [] [ header_text ] in
let body =
let to_percent size = 100. *. Byte_units.(size // total_allocations) in
let location_line =
let loc_name =
match focus with
| Some (locs, _) -> Data.Location.defname (List.last_exn locs)
| None -> "\u{2013}"
(* en dash *)
in
Vdom.Node.p [] [ Vdom.Node.text loc_name ]
in
let allocations_line =
let value_part =
match focus with
| Some (_, entry) ->
Vdom.Node.textf
"%s (%.1f%%) / %s (%.1f%%) excluding children"
(Data.Entry.allocations entry |> Byte_units.Short.to_string)
(Data.Entry.allocations entry |> to_percent)
(Data.Entry.allocations_excluding_children entry |> Byte_units.Short.to_string)
(Data.Entry.allocations_excluding_children entry |> to_percent)
| None -> Vdom.Node.text "\u{2013}"
in
Vdom.Node.p
[]
[ Vdom.Node.span
[ Vdom.Attr.class_ "info-label" ]
[ Vdom.Node.text "Allocations: " ]
; value_part
]
in
let backtrace_view =
match focus with
| None -> Vdom.Node.none
| Some (locs, _) -> Backtrace_view.render ~direction locs
in
Vdom.Node.div
[]
[ location_line
; allocations_line
; Vdom.Node.p [ Vdom.Attr.class_ "info-label" ] [ Vdom.Node.text "Backtrace:" ]
; backtrace_view
]
in
Vdom.Node.section [ Vdom.Attr.id "details-panel" ] [ header; body ]
;;
let component ~focus ~total_allocations ~direction =
let open Bonsai.Let_syntax in
return
(let%map focus = focus
and total_allocations = total_allocations
and direction = direction in
view ~focus ~total_allocations ~direction)
;;
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/client/details_panel.ml | ocaml | en dash | open! Core_kernel
open! Async_kernel
open! Bonsai_web
open Memtrace_viewer_common
let view ~focus ~total_allocations ~direction =
let header_text = Vdom.Node.text "Selection" in
let header = Vdom.Node.h2 [] [ header_text ] in
let body =
let to_percent size = 100. *. Byte_units.(size // total_allocations) in
let location_line =
let loc_name =
match focus with
| Some (locs, _) -> Data.Location.defname (List.last_exn locs)
| None -> "\u{2013}"
in
Vdom.Node.p [] [ Vdom.Node.text loc_name ]
in
let allocations_line =
let value_part =
match focus with
| Some (_, entry) ->
Vdom.Node.textf
"%s (%.1f%%) / %s (%.1f%%) excluding children"
(Data.Entry.allocations entry |> Byte_units.Short.to_string)
(Data.Entry.allocations entry |> to_percent)
(Data.Entry.allocations_excluding_children entry |> Byte_units.Short.to_string)
(Data.Entry.allocations_excluding_children entry |> to_percent)
| None -> Vdom.Node.text "\u{2013}"
in
Vdom.Node.p
[]
[ Vdom.Node.span
[ Vdom.Attr.class_ "info-label" ]
[ Vdom.Node.text "Allocations: " ]
; value_part
]
in
let backtrace_view =
match focus with
| None -> Vdom.Node.none
| Some (locs, _) -> Backtrace_view.render ~direction locs
in
Vdom.Node.div
[]
[ location_line
; allocations_line
; Vdom.Node.p [ Vdom.Attr.class_ "info-label" ] [ Vdom.Node.text "Backtrace:" ]
; backtrace_view
]
in
Vdom.Node.section [ Vdom.Attr.id "details-panel" ] [ header; body ]
;;
let component ~focus ~total_allocations ~direction =
let open Bonsai.Let_syntax in
return
(let%map focus = focus
and total_allocations = total_allocations
and direction = direction in
view ~focus ~total_allocations ~direction)
;;
|
7022729b18768ea3f9568e503356ba39b12eba69dca0a16a5cbd3eb3b68a3a55 | xxyzz/SICP | Exercise_5_30.rkt | #lang racket/base
;; a:
(define (lookup-variable-value var env)
(travsersing-env
(lambda (env) (lookup-variable-value var (enclosing-environment env)))
(lambda (current-pair) (frame-unit-value current-pair))
(lambda (var) (list 'unbound-variable-error var)) ;; ***
env
var))
(define (unbound-error? val) ;; add it to eceval-operations
(tagged-list? val 'unbound-variable-error))
ev-variable
(assign val (op lookup-variable-value) (reg exp) (reg env))
(test (op unbound-error?) (reg val)) ;; ***
(branch (label signal-error))
(goto (reg continue))
;; b:
(define (apply-in-underlying-scheme proc args)
(with-handlers ([exn:fail:contract:divide-by-zero?
(lambda (exn) (list 'primitive-error exn))])
(apply proc args)))
(define (primitive-error? val) ;; add it to eceval-operations
(tagged-list? val 'primitive-error))
primitive-apply
(assign val (op apply-primitive-procedure)
(reg proc)
(reg argl))
(test (op primitive-error?) (reg val)) ;; ***
(branch (label signal-error))
(restore continue)
(goto (reg continue))
| null | https://raw.githubusercontent.com/xxyzz/SICP/e26aea1c58fd896297dbf5406f7fcd32bb4f8f78/5_Computing_with_Register_Machines/5.4_The_Explicit-Control_Evaluator/Exercise_5_30.rkt | racket | a:
***
add it to eceval-operations
***
b:
add it to eceval-operations
*** | #lang racket/base
(define (lookup-variable-value var env)
(travsersing-env
(lambda (env) (lookup-variable-value var (enclosing-environment env)))
(lambda (current-pair) (frame-unit-value current-pair))
env
var))
(tagged-list? val 'unbound-variable-error))
ev-variable
(assign val (op lookup-variable-value) (reg exp) (reg env))
(branch (label signal-error))
(goto (reg continue))
(define (apply-in-underlying-scheme proc args)
(with-handlers ([exn:fail:contract:divide-by-zero?
(lambda (exn) (list 'primitive-error exn))])
(apply proc args)))
(tagged-list? val 'primitive-error))
primitive-apply
(assign val (op apply-primitive-procedure)
(reg proc)
(reg argl))
(branch (label signal-error))
(restore continue)
(goto (reg continue))
|
c27b8ddddf23a01a40f8d8deffefaba7c1921251cd05f8a6053ac06da089c1fe | screenshotbot/screenshotbot-oss | settings.lisp | ;;;; Copyright 2018-Present Modern Interpreters Inc.
;;;;
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(defpackage :screenshotbot/email-tasks/settings
(:use #:cl)
(:import-from #:screenshotbot/settings-api
#:settings-template
#:defsettings)
(:import-from #:screenshotbot/user-api
#:user-companies
#:current-user
#:personalp
#:current-company
#:company-name)
(:import-from #:bknr.datastore
#:store-object)
(:import-from #:bknr.indices
#:hash-index)
(:import-from #:bknr.datastore
#:persistent-class)
(:import-from #:bknr.datastore
#:with-transaction)
(:import-from #:nibble
#:nibble)
(:import-from #:util/object-id
#:find-by-oid)
(:import-from #:screenshotbot/model/company
#:company)
(:local-nicknames (#:a #:alexandria)))
(in-package :screenshotbot/email-tasks/settings)
(markup:enable-reader)
(defclass email-setting (store-object)
((%user :initarg :user
:index-type hash-index
:index-reader email-settings-for-user)
(%company :initarg :company
:reader company)
(enabledp :initarg :enabledp
:accessor emails-enabledp
:initform t))
(:metaclass persistent-class))
(defvar *lock* (bt:make-lock))
(defun email-setting (&key user company)
(flet ((old ()
(loop for setting in (email-settings-for-user user)
if (eql company (company setting))
return setting)))
(or
(old)
(bt:with-lock-held (*lock*)
(or
(old)
(make-instance 'email-setting
:user user
:company company))))))
(defun save-settings (settings enabledp)
;; there's not much in terms of validation to do here.
(with-transaction ()
(setf (emails-enabledp settings)
(if enabledp t)))
(hex:safe-redirect "/settings/email-tasks"))
(defun get-email-settings (&key (user (current-user))
(company (current-company)))
(let ((company-oid (hunchentoot:parameter "company")))
(when company-oid
(let ((company (find-by-oid company-oid)))
(check-type company company)
(assert (member company (user-companies user)))
;; If we're here, we're probably clicking the email control
;; link in an email. Since we need to change the setting for
;; specific organization, let's change the organization, and
;; then redirect back to the settings page.
(setf (current-company) company)
(hex:safe-redirect "/settings/email-tasks"))))
(let* ((settings (email-setting :user user
:company company))
(save (nibble (enabledp)
(save-settings settings enabledp))))
<settings-template>
<form action=save method= "POST">
<div class= "card mt-3">
<div class= "card-header">
<h3>Email notifications for tasks</h3>
</div>
<div class= "card-body" >
<p class= "text-muted" >By default, we send notifications to every user on the account. You can control whether your account should receive emails on this page.</p>
<div class= "form-check">
<input type= "checkbox" name= "enabledp"
id= "enabledp"
class= "form-check-input"
checked= (if (emails-enabledp settings) "checked")
/>
<label for= "enabledp" class= "form-check-label">
Email me when reports are generated for
,(cond
((personalp company)
"your organization")
(t
(company-name company)))
</label>
</div>
</div>
<div class= "card-footer">
<input type= "submit" class= "btn btn-primary" value= "Save" />
</div>
</div> <!-- card -->
</form>
</settings-template>))
(defsettings email-tasks
:name "email-tasks"
:title "Email Tasks"
:section :tasks
:handler 'get-email-settings)
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/0dbade94b9a2f898cccc1193dbf8e45694cacaca/src/screenshotbot/email-tasks/settings.lisp | lisp | Copyright 2018-Present Modern Interpreters Inc.
there's not much in terms of validation to do here.
If we're here, we're probably clicking the email control
link in an email. Since we need to change the setting for
specific organization, let's change the organization, and
then redirect back to the settings page. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(defpackage :screenshotbot/email-tasks/settings
(:use #:cl)
(:import-from #:screenshotbot/settings-api
#:settings-template
#:defsettings)
(:import-from #:screenshotbot/user-api
#:user-companies
#:current-user
#:personalp
#:current-company
#:company-name)
(:import-from #:bknr.datastore
#:store-object)
(:import-from #:bknr.indices
#:hash-index)
(:import-from #:bknr.datastore
#:persistent-class)
(:import-from #:bknr.datastore
#:with-transaction)
(:import-from #:nibble
#:nibble)
(:import-from #:util/object-id
#:find-by-oid)
(:import-from #:screenshotbot/model/company
#:company)
(:local-nicknames (#:a #:alexandria)))
(in-package :screenshotbot/email-tasks/settings)
(markup:enable-reader)
(defclass email-setting (store-object)
((%user :initarg :user
:index-type hash-index
:index-reader email-settings-for-user)
(%company :initarg :company
:reader company)
(enabledp :initarg :enabledp
:accessor emails-enabledp
:initform t))
(:metaclass persistent-class))
(defvar *lock* (bt:make-lock))
(defun email-setting (&key user company)
(flet ((old ()
(loop for setting in (email-settings-for-user user)
if (eql company (company setting))
return setting)))
(or
(old)
(bt:with-lock-held (*lock*)
(or
(old)
(make-instance 'email-setting
:user user
:company company))))))
(defun save-settings (settings enabledp)
(with-transaction ()
(setf (emails-enabledp settings)
(if enabledp t)))
(hex:safe-redirect "/settings/email-tasks"))
(defun get-email-settings (&key (user (current-user))
(company (current-company)))
(let ((company-oid (hunchentoot:parameter "company")))
(when company-oid
(let ((company (find-by-oid company-oid)))
(check-type company company)
(assert (member company (user-companies user)))
(setf (current-company) company)
(hex:safe-redirect "/settings/email-tasks"))))
(let* ((settings (email-setting :user user
:company company))
(save (nibble (enabledp)
(save-settings settings enabledp))))
<settings-template>
<form action=save method= "POST">
<div class= "card mt-3">
<div class= "card-header">
<h3>Email notifications for tasks</h3>
</div>
<div class= "card-body" >
<p class= "text-muted" >By default, we send notifications to every user on the account. You can control whether your account should receive emails on this page.</p>
<div class= "form-check">
<input type= "checkbox" name= "enabledp"
id= "enabledp"
class= "form-check-input"
checked= (if (emails-enabledp settings) "checked")
/>
<label for= "enabledp" class= "form-check-label">
Email me when reports are generated for
,(cond
((personalp company)
"your organization")
(t
(company-name company)))
</label>
</div>
</div>
<div class= "card-footer">
<input type= "submit" class= "btn btn-primary" value= "Save" />
</div>
</div> <!-- card -->
</form>
</settings-template>))
(defsettings email-tasks
:name "email-tasks"
:title "Email Tasks"
:section :tasks
:handler 'get-email-settings)
|
963e03d94471d0c763447379ea05b51da79e43e5819f53a69ba1294afea1778b | fpco/ide-backend | TestPkgB.hs | module Testing.TestPkgB where
testPkgB :: String
testPkgB = "This is test package B"
| null | https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/test-packages/testpkg-B/Testing/TestPkgB.hs | haskell | module Testing.TestPkgB where
testPkgB :: String
testPkgB = "This is test package B"
| |
5d71ee42a8e20a733483e851e402cb09161b09515b4f4ba195c9e6ecc7410426 | gsakkas/rite | 20060323-10:36:10-23f563f30054417a24188e71c358a86b.seminal.ml |
exception Unimplemented
exception AlreadyDone
(*** part a ***)
type move = Home | Forward of float
| Turn of float | For of int * (move)list
(*** part b -- return move***)
let makePoly sides len =
# # # # # # # # # # # # # # # # # # # # #
let rec makePolyHelp sidesLeft turn =
match sidesLeft with
0 -> []
| 1 -> Home::makePolyHelp 0 true
| n ->
if turn = true
then
Turn(turnAmount)::makePolyHelp sidesLeft false
else
(
let decSidesLeft = sidesLeft - 1 in
Forward(len)::makePolyHelp decSidesLeft true
)
in
if sides < 3
then
Home
else
For(sides, makePolyHelp sides false)
(*** part c ***)
let interpLarge (movelist : move list) : (float*float) list =
let rec loop movelist x y dir acc =
match movelist with
[] -> acc
| Home::tl -> loop tl 0.0 0.0 dir ((0.0,0.0)::acc)
| Forward f::tl ->
let newX = x +. ( f *. (cos dir) ) in
let newY = y +. ( f *. (sin dir) ) in
loop tl newX newY dir ((newX,newY)::acc)
| Turn f::tl ->
let newDir = f +. dir in
loop tl x y newDir acc
| For (il, ml)::tl ->
if il > 0
then
let ild = il - 1 in
let newMlTemp = For(ild, movelist)::tl in
let newMl = List.append ml newMlTemp in
loop newMl x y dir acc
else
loop tl x y dir acc
in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
(*** part d ***)
let interpSmall (movelist : move list) : (float*float) list =
let interpSmallStep movelist x y dir : move list * float * float * float =
match movelist with
[] -> raise AlreadyDone
| Home::tl -> tl, 0.0, 0.0, 0.0
| Forward f::tl ->
let newX = x +. ( f *. (cos dir) ) in
let newY = y +. ( f *. (sin dir) ) in
tl, newX, newY, dir
| Turn f::tl ->
let newDir = f +. dir in
tl, x, y, newDir
| For (il, ml)::tl ->
let ild = il - 1 in
let newMlTemp = For(ild, movelist)::tl in
let newMl = List.append ml newMlTemp in
newMl, x, y, dir
in
let rec loop movelist x y dir acc =
match movelist with
[] -> acc
| _ ->
let ret = interpSmallStep movelist x y dir in
match ret with
newList, retX, retY, retDir ->
if retX <> x || retY <> y
then
loop newList retX retY retDir ((retX, retY)::acc)
else
loop newList x y retDir acc
in
List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
(*** part e ***)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
######################################################################
#############################################################################
##########################################
*)
(*** part f ***)
let interpTrans movelist : float->float->float-> (float * float) list * float=
# # # # # # # # # # # # # # # # # # # # # # # # #
in
match movelist with
[] -> (fun x y dir -> [(x,y)], dir)
| Home::tl -> (fun x y dir -> (x,y)::(0.0,0.0),dir )
| Forward f::tl -> raise Unimplemented
| Turn f::tl -> raise Unimplemented
| For (il, ml)::tl -> raise Unimplemented
(*** possibly helpful testing code ***)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
let example_logo_prog = raise Unimplemented
let ansL = interpLarge example_logo_prog
let ansS = interpSmall example_logo_prog
let ansI = (0.0,0.0)::(fst ((interpTrans example_logo_prog) 0.0 0.0 0.0))
let rec pr lst =
match lst with
[] -> ()
| (x,y)::tl ->
print_string("(" ^ (string_of_float x) ^ "," ^ (string_of_float y) ^ ")");
pr tl
let _ =
pr ansL; print_newline ();
pr ansS; print_newline ();
pr ansI; print_newline ();
| null | https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060323-10%3A36%3A10-23f563f30054417a24188e71c358a86b.seminal.ml | ocaml | ** part a **
** part b -- return move**
** part c **
** part d **
** part e **
** part f **
** possibly helpful testing code ** |
exception Unimplemented
exception AlreadyDone
type move = Home | Forward of float
| Turn of float | For of int * (move)list
let makePoly sides len =
# # # # # # # # # # # # # # # # # # # # #
let rec makePolyHelp sidesLeft turn =
match sidesLeft with
0 -> []
| 1 -> Home::makePolyHelp 0 true
| n ->
if turn = true
then
Turn(turnAmount)::makePolyHelp sidesLeft false
else
(
let decSidesLeft = sidesLeft - 1 in
Forward(len)::makePolyHelp decSidesLeft true
)
in
if sides < 3
then
Home
else
For(sides, makePolyHelp sides false)
let interpLarge (movelist : move list) : (float*float) list =
let rec loop movelist x y dir acc =
match movelist with
[] -> acc
| Home::tl -> loop tl 0.0 0.0 dir ((0.0,0.0)::acc)
| Forward f::tl ->
let newX = x +. ( f *. (cos dir) ) in
let newY = y +. ( f *. (sin dir) ) in
loop tl newX newY dir ((newX,newY)::acc)
| Turn f::tl ->
let newDir = f +. dir in
loop tl x y newDir acc
| For (il, ml)::tl ->
if il > 0
then
let ild = il - 1 in
let newMlTemp = For(ild, movelist)::tl in
let newMl = List.append ml newMlTemp in
loop newMl x y dir acc
else
loop tl x y dir acc
in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
let interpSmall (movelist : move list) : (float*float) list =
let interpSmallStep movelist x y dir : move list * float * float * float =
match movelist with
[] -> raise AlreadyDone
| Home::tl -> tl, 0.0, 0.0, 0.0
| Forward f::tl ->
let newX = x +. ( f *. (cos dir) ) in
let newY = y +. ( f *. (sin dir) ) in
tl, newX, newY, dir
| Turn f::tl ->
let newDir = f +. dir in
tl, x, y, newDir
| For (il, ml)::tl ->
let ild = il - 1 in
let newMlTemp = For(ild, movelist)::tl in
let newMl = List.append ml newMlTemp in
newMl, x, y, dir
in
let rec loop movelist x y dir acc =
match movelist with
[] -> acc
| _ ->
let ret = interpSmallStep movelist x y dir in
match ret with
newList, retX, retY, retDir ->
if retX <> x || retY <> y
then
loop newList retX retY retDir ((retX, retY)::acc)
else
loop newList x y retDir acc
in
List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
######################################################################
#############################################################################
##########################################
*)
let interpTrans movelist : float->float->float-> (float * float) list * float=
# # # # # # # # # # # # # # # # # # # # # # # # #
in
match movelist with
[] -> (fun x y dir -> [(x,y)], dir)
| Home::tl -> (fun x y dir -> (x,y)::(0.0,0.0),dir )
| Forward f::tl -> raise Unimplemented
| Turn f::tl -> raise Unimplemented
| For (il, ml)::tl -> raise Unimplemented
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
let example_logo_prog = raise Unimplemented
let ansL = interpLarge example_logo_prog
let ansS = interpSmall example_logo_prog
let ansI = (0.0,0.0)::(fst ((interpTrans example_logo_prog) 0.0 0.0 0.0))
let rec pr lst =
match lst with
[] -> ()
| (x,y)::tl ->
print_string("(" ^ (string_of_float x) ^ "," ^ (string_of_float y) ^ ")");
pr tl
let _ =
pr ansL; print_newline ();
pr ansS; print_newline ();
pr ansI; print_newline ();
|
ab3f21a7de20700840f72f4cbbb2286d18bb0ab7ab98f4a7538b1a9d8e408b71 | egonSchiele/actionkid | Internal.hs | module ActionKid.Internal where
import ActionKid.Types
import ActionKid.Utils
import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Text.Printf
import Graphics.Gloss hiding (display)
import Data.Monoid ((<>), mconcat)
import Graphics.Gloss.Interface.IO.Game
import Data.Ord
import ActionKid.Globals
import Data.StateVar
import Control.Lens
import qualified Debug.Trace as D
-- bounding box for a series of points
pathBox points =
let minx = minimum $ map fst points
miny = minimum $ map snd points
maxx = maximum $ map fst points
maxy = maximum $ map snd points
in ((minx, miny), (maxx, maxy))
catPoints :: (Point, Point) -> [Point]
catPoints (p1, p2) = [p1, p2]
-- | Code borrowed from -game-0.3.0.0/docs/src/Graphics-Gloss-Game.html
-- Calculate bounding boxes for various `Picture` types.
type Rect = (Point, Point) -- ^origin & extent, where the origin is at the centre
boundingBox :: Picture -> Rect
boundingBox Blank = ((0, 0), (0, 0))
boundingBox (Polygon path) = pathBox path
boundingBox (Line path) = pathBox path
boundingBox (Circle r) = ((0, 0), (2 * r, 2 * r))
boundingBox (ThickCircle t r) = ((0, 0), (2 * r + t, 2 * r + t))
boundingBox (Arc _ _ _) = error "ActionKid.Core.boundingbox: Arc not implemented yet"
boundingBox (ThickArc _ _ _ _) = error "ActionKid.Core.boundingbox: ThickArc not implemented yet"
boundingBox (Text _) = error "ActionKid.Core.boundingbox: Text not implemented yet"
boundingBox (Bitmap w h _ _) = ((0, 0), (fromIntegral w, fromIntegral h))
boundingBox (Color _ p) = boundingBox p
boundingBox (Translate dx dy p) = ((x1 + dx, y1 + dy), (x2 + dx, y2 + dy))
where ((x1, y1), (x2, y2)) = boundingBox p
boundingBox (Rotate _ang _p) = error "Graphics.Gloss.Game.boundingbox: Rotate not implemented yet"
TODO fix scale , this implementation is incorrect ( only works if scale
= 1 ) . Commented out version is incorrect too
boundingBox (Scale xf yf p) = boundingBox p
-- let ((x1, y1), (x2, y2)) = boundingBox p
-- w = x2 - x1
-- h = y2 - y1
-- scaledW = w * xf
-- scaledH = h * yf
-- in ((x1, x2), (x1 + scaledW, y1 + scaledH))
boundingBox (Pictures ps) = pathBox points
where points = concatMap (catPoints . boundingBox) ps
| Check if one rect is touching another .
intersects :: Rect -> Rect -> Bool
intersects ((min_ax, min_ay), (max_ax, max_ay)) ((min_bx, min_by), (max_bx, max_by))
| max_ax < min_bx = False
| min_ax > max_bx = False
| min_ay > max_by = False
| max_ay < min_by = False
| otherwise = True
-- | For future, if I want to inject something into the step function,
-- I'll do it here. Right now I just call the step function.
onEnterFrame :: MovieClip a => (Float -> a -> IO a) -> Float -> a -> IO a
onEnterFrame stepFunc num state = stepFunc num state
-- | Called to draw the game. Translates the coordinate system.
draw :: Renderable a => a -> IO Picture
draw gs = do
w <- get boardWidth
h <- get boardHeight
return $ translate (-(fromIntegral $ w // 2)) (-(fromIntegral $ h // 2)) $
display gs
| null | https://raw.githubusercontent.com/egonSchiele/actionkid/a1f1ca4efafb5a692dfd12b6c3a2fd74e8888fb0/src/ActionKid/Internal.hs | haskell | bounding box for a series of points
| Code borrowed from -game-0.3.0.0/docs/src/Graphics-Gloss-Game.html
Calculate bounding boxes for various `Picture` types.
^origin & extent, where the origin is at the centre
let ((x1, y1), (x2, y2)) = boundingBox p
w = x2 - x1
h = y2 - y1
scaledW = w * xf
scaledH = h * yf
in ((x1, x2), (x1 + scaledW, y1 + scaledH))
| For future, if I want to inject something into the step function,
I'll do it here. Right now I just call the step function.
| Called to draw the game. Translates the coordinate system. | module ActionKid.Internal where
import ActionKid.Types
import ActionKid.Utils
import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Text.Printf
import Graphics.Gloss hiding (display)
import Data.Monoid ((<>), mconcat)
import Graphics.Gloss.Interface.IO.Game
import Data.Ord
import ActionKid.Globals
import Data.StateVar
import Control.Lens
import qualified Debug.Trace as D
pathBox points =
let minx = minimum $ map fst points
miny = minimum $ map snd points
maxx = maximum $ map fst points
maxy = maximum $ map snd points
in ((minx, miny), (maxx, maxy))
catPoints :: (Point, Point) -> [Point]
catPoints (p1, p2) = [p1, p2]
boundingBox :: Picture -> Rect
boundingBox Blank = ((0, 0), (0, 0))
boundingBox (Polygon path) = pathBox path
boundingBox (Line path) = pathBox path
boundingBox (Circle r) = ((0, 0), (2 * r, 2 * r))
boundingBox (ThickCircle t r) = ((0, 0), (2 * r + t, 2 * r + t))
boundingBox (Arc _ _ _) = error "ActionKid.Core.boundingbox: Arc not implemented yet"
boundingBox (ThickArc _ _ _ _) = error "ActionKid.Core.boundingbox: ThickArc not implemented yet"
boundingBox (Text _) = error "ActionKid.Core.boundingbox: Text not implemented yet"
boundingBox (Bitmap w h _ _) = ((0, 0), (fromIntegral w, fromIntegral h))
boundingBox (Color _ p) = boundingBox p
boundingBox (Translate dx dy p) = ((x1 + dx, y1 + dy), (x2 + dx, y2 + dy))
where ((x1, y1), (x2, y2)) = boundingBox p
boundingBox (Rotate _ang _p) = error "Graphics.Gloss.Game.boundingbox: Rotate not implemented yet"
TODO fix scale , this implementation is incorrect ( only works if scale
= 1 ) . Commented out version is incorrect too
boundingBox (Scale xf yf p) = boundingBox p
boundingBox (Pictures ps) = pathBox points
where points = concatMap (catPoints . boundingBox) ps
| Check if one rect is touching another .
intersects :: Rect -> Rect -> Bool
intersects ((min_ax, min_ay), (max_ax, max_ay)) ((min_bx, min_by), (max_bx, max_by))
| max_ax < min_bx = False
| min_ax > max_bx = False
| min_ay > max_by = False
| max_ay < min_by = False
| otherwise = True
onEnterFrame :: MovieClip a => (Float -> a -> IO a) -> Float -> a -> IO a
onEnterFrame stepFunc num state = stepFunc num state
draw :: Renderable a => a -> IO Picture
draw gs = do
w <- get boardWidth
h <- get boardHeight
return $ translate (-(fromIntegral $ w // 2)) (-(fromIntegral $ h // 2)) $
display gs
|
2ceea9f9d68fc1549527a72ce803a3591e2b2f4f6c056c97131797192a0b8b42 | stan-dev/stanc3 | Parse.mli | * Some complicated stuff to get the custom syntax errors out of Menhir 's Incremental
API
API *)
open Core_kernel
val parse_file :
(Lexing.position -> Ast.untyped_program Parser.MenhirInterpreter.checkpoint)
-> string
-> (Ast.untyped_program, Errors.t) result * Warnings.t list
* A helper function to take a parser , a filename and produce an AST . Under the
hood , it takes care of Menhir 's custom syntax error messages .
hood, it takes care of Menhir's custom syntax error messages. *)
val parse_string :
(Lexing.position -> Ast.untyped_program Parser.MenhirInterpreter.checkpoint)
-> string
-> (Ast.untyped_program, Errors.t) result * Warnings.t list
| null | https://raw.githubusercontent.com/stan-dev/stanc3/2e5562c16c7567ddf7fedc988902f9e38e390136/src/frontend/Parse.mli | ocaml | * Some complicated stuff to get the custom syntax errors out of Menhir 's Incremental
API
API *)
open Core_kernel
val parse_file :
(Lexing.position -> Ast.untyped_program Parser.MenhirInterpreter.checkpoint)
-> string
-> (Ast.untyped_program, Errors.t) result * Warnings.t list
* A helper function to take a parser , a filename and produce an AST . Under the
hood , it takes care of Menhir 's custom syntax error messages .
hood, it takes care of Menhir's custom syntax error messages. *)
val parse_string :
(Lexing.position -> Ast.untyped_program Parser.MenhirInterpreter.checkpoint)
-> string
-> (Ast.untyped_program, Errors.t) result * Warnings.t list
| |
cf3cacb18bf9e2714a96b10e2128ab67b5a0f94612fc98c3cb376b1b32fc9cf8 | google/rysim | num_gen_SUITE.erl | %%%-------------------------------------------------------------------
Copyright 2014 The RySim Authors . 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(num_gen_SUITE).
-include_lib("common_test/include/ct.hrl").
-export([all/0]).
-export([init_per_testcase/2, end_per_testcase/2]).
%% Tests
-export([test_simple_generation/1, test_multiple_dists/1]).
all() ->
[test_simple_generation,
test_multiple_dists].
init_per_testcase(_, Config) ->
{ok, State} = num_gen:initialize_generator(1),
[{mod_state, State}|Config].
end_per_testcase(_, _) ->
ok.
%% ===================================================================
%% Tests
%% ===================================================================
test_simple_generation(Config) ->
State = ?config(mod_state, Config),
Label = "Bob",
Scale = 1.0,
DistType = gaussian_tail,
Params = [1.0, 2.0],
{ok, NewState} = num_gen:register_distribution(Label, DistType, Scale, Params, State),
{ok, _} = num_gen:call_distribution(Label, NewState),
ok = unique([State, NewState]).
test_multiple_dists(Config) ->
State = ?config(mod_state, Config),
Scale = 1.0,
DistType = gaussian_tail,
Params = [1.0, 2.0],
{ok, NewState0} = num_gen:register_distribution("Bob", DistType, Scale, Params, State),
{ok, _} = num_gen:call_distribution("Bob", NewState0),
{ok, NewState1} = num_gen:register_distribution("Bill", DistType, Scale, Params, NewState0),
{ok, _} = num_gen:call_distribution("Bill", NewState1),
{ok, _} = num_gen:call_distribution("Bob", NewState1),
{ok, NewState2} = num_gen:register_distribution("Ben", DistType, Scale, Params, NewState1),
{ok, _} = num_gen:call_distribution("Ben", NewState2),
{ok, _} = num_gen:call_distribution("Bill", NewState2),
{ok, _} = num_gen:call_distribution("Bob", NewState2),
ok = unique([State, NewState0, NewState1, NewState2]).
%% ===================================================================
Utilities
%% ===================================================================
unique([]) ->
ok;
unique([Head|Tail]) ->
case lists:any(fun(Item) ->
(Item == Head)
end,
Tail) of
true ->
error;
_ ->
unique(Tail)
end.
| null | https://raw.githubusercontent.com/google/rysim/afe19cea6415eb9d17e97f2f67280cf0b92eaa6e/erlang/rysim_des_actor_smp/test/num_gen_SUITE.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.
-------------------------------------------------------------------
Tests
===================================================================
Tests
===================================================================
===================================================================
=================================================================== | Copyright 2014 The RySim Authors . 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(num_gen_SUITE).
-include_lib("common_test/include/ct.hrl").
-export([all/0]).
-export([init_per_testcase/2, end_per_testcase/2]).
-export([test_simple_generation/1, test_multiple_dists/1]).
all() ->
[test_simple_generation,
test_multiple_dists].
init_per_testcase(_, Config) ->
{ok, State} = num_gen:initialize_generator(1),
[{mod_state, State}|Config].
end_per_testcase(_, _) ->
ok.
test_simple_generation(Config) ->
State = ?config(mod_state, Config),
Label = "Bob",
Scale = 1.0,
DistType = gaussian_tail,
Params = [1.0, 2.0],
{ok, NewState} = num_gen:register_distribution(Label, DistType, Scale, Params, State),
{ok, _} = num_gen:call_distribution(Label, NewState),
ok = unique([State, NewState]).
test_multiple_dists(Config) ->
State = ?config(mod_state, Config),
Scale = 1.0,
DistType = gaussian_tail,
Params = [1.0, 2.0],
{ok, NewState0} = num_gen:register_distribution("Bob", DistType, Scale, Params, State),
{ok, _} = num_gen:call_distribution("Bob", NewState0),
{ok, NewState1} = num_gen:register_distribution("Bill", DistType, Scale, Params, NewState0),
{ok, _} = num_gen:call_distribution("Bill", NewState1),
{ok, _} = num_gen:call_distribution("Bob", NewState1),
{ok, NewState2} = num_gen:register_distribution("Ben", DistType, Scale, Params, NewState1),
{ok, _} = num_gen:call_distribution("Ben", NewState2),
{ok, _} = num_gen:call_distribution("Bill", NewState2),
{ok, _} = num_gen:call_distribution("Bob", NewState2),
ok = unique([State, NewState0, NewState1, NewState2]).
Utilities
unique([]) ->
ok;
unique([Head|Tail]) ->
case lists:any(fun(Item) ->
(Item == Head)
end,
Tail) of
true ->
error;
_ ->
unique(Tail)
end.
|
9238a1e1b408cdbba0864fbb5826629debb34a30dfd38f621cae3264503025f2 | schnef/pm | pm_sup.erl | %%%-------------------------------------------------------------------
%% @doc pm top level supervisor.
%% @end
%%%-------------------------------------------------------------------
-module(pm_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%====================================================================
%% API functions
%%====================================================================
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%====================================================================
%% Supervisor callbacks
%%====================================================================
Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules }
init([]) ->
Sup_flags = #{},
{ok, { Sup_flags, [#{id => pap, start => {pm_pap, start_link, []}},
#{id => pdp, start => {pm_pdp, start_link, []}},
#{id => epp, start => {pm_epp, start_link, []}},
#{id => rap, start => {pm_rap, start_link, []}},
#{id => pep_sup,
start => {pm_pep_sup, start_link, []},
shutdown => infinity,
type => supervisor}
]}}.
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/schnef/pm/8691c9688c51dfb0aaa4d089ef59c0af54c27e63/src/pm_sup.erl | erlang | -------------------------------------------------------------------
@doc pm top level supervisor.
@end
-------------------------------------------------------------------
API
Supervisor callbacks
====================================================================
API functions
====================================================================
====================================================================
Supervisor callbacks
====================================================================
====================================================================
==================================================================== |
-module(pm_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules }
init([]) ->
Sup_flags = #{},
{ok, { Sup_flags, [#{id => pap, start => {pm_pap, start_link, []}},
#{id => pdp, start => {pm_pdp, start_link, []}},
#{id => epp, start => {pm_epp, start_link, []}},
#{id => rap, start => {pm_rap, start_link, []}},
#{id => pep_sup,
start => {pm_pep_sup, start_link, []},
shutdown => infinity,
type => supervisor}
]}}.
Internal functions
|
d1c402b815b61511676d395fdf810443d59b251474eed5a2462f38eb51058bd3 | simonmar/monad-par | Direct.hs | # LANGUAGE RankNTypes , NamedFieldPuns , BangPatterns ,
ExistentialQuantification , CPP , ScopedTypeVariables ,
TypeSynonymInstances , MultiParamTypeClasses ,
, ,
ParallelListComp #
ExistentialQuantification, CPP, ScopedTypeVariables,
TypeSynonymInstances, MultiParamTypeClasses,
GeneralizedNewtypeDeriving, PackageImports,
ParallelListComp #-}
{- OPTIONS_GHC -Wall -fno-warn-name-shadowing -fno-warn-unused-do-bind -}
-- {- LANGUAGE Trustworthy -}
TODO : Before declaring this module TRUSTWORTHY / SAFE , we need to
make the IVar type abstract .
# LANGUAGE TypeFamilies #
| A scheduler for the Par monad based on directly performing IO
actions when Par methods are called ( i.e. without using a lazy
-- trace data structure).
module Control.Monad.Par.Scheds.Direct (
Sched(..),
Par, -- abstract: Constructor not exported.
IVar(..), IVarContents(..),
-- sched,
runPar, runParIO,
new, get, put_, fork,
newFull, newFull_, put,
spawn, spawn_, spawnP,
spawn1_, fixPar, FixParException (..)
-- runParAsync, runParAsyncHelper,
-- yield,
) where
import Control.Applicative
import Control.Concurrent hiding (yield)
import Data.IORef (IORef,newIORef,readIORef,writeIORef,atomicModifyIORef)
import Text.Printf (printf)
import GHC.Conc (numCapabilities,yield)
import "mtl" Control.Monad.Cont as C
import qualified "mtl" Control.Monad.Reader as RD
import qualified System.Random.MWC as Random
import System.IO.Unsafe (unsafePerformIO)
import System.Mem.StableName (makeStableName, hashStableName)
import qualified Control.Monad.Par.Class as PC
import qualified Control.Monad.Par.Unsafe as UN
import Control.Monad.Par.Scheds.DirectInternal
(Par(..), Sched(..), HotVar, SessionID, Session(Session),
newHotVar, readHotVar, modifyHotVar, modifyHotVar_,
writeHotVarRaw, fixPar, FixParException (..))
#ifdef NEW_GENERIC
import qualified Control.Par.Class as PN
import qualified Control.Par.Class.Unsafe as PU
#endif
import Control.DeepSeq
#ifdef NESTED_SCHEDS
import qualified Data.Map as M
#endif
import qualified Data.Set as S
import Data.Maybe (catMaybes)
import Data.Word (Word64)
import Data . Concurrent . Deque . Class ( WSDeque )
#ifdef USE_CHASELEV
#warning "Note: using Chase-Lev lockfree workstealing deques..."
import Data.Concurrent.Deque.ChaseLev.DequeInstance
import Data.Concurrent.Deque.ChaseLev as R
#else
import Data.Concurrent.Deque.Reference.DequeInstance
import Data.Concurrent.Deque.Reference as R
#endif
import qualified Control.Exception as E
import Prelude hiding (null)
import qualified Prelude
#if __GLASGOW_HASKELL__ <= 700
import GHC.Conc (forkOnIO)
forkOn = forkOnIO
#endif
--------------------------------------------------------------------------------
-- Configuration Toggles
--------------------------------------------------------------------------------
[ 2012.08.30 ] This shows a 10X improvement on nested parfib :
-- #define NESTED_SCHEDS
#define PARPUTS
#define FORKPARENT
#define IDLING_ON
Next , IF idling is on , should we do wakeups ? :
#define WAKEIDLE
-- #define WAIT_FOR_WORKERS
-------------------------------------------------------------------
-- Ifdefs for the above preprocessor defines. Try to MINIMIZE code
-- that lives in this dangerous region, and instead do normal
-- conditionals and trust dead-code-elimination.
--------------------------------------------------------------------
#ifdef DEBUG_DIRECT
#warning "DEBUG: Activating debugging for Direct.hs"
import Debug.Trace (trace)
import System.Environment (getEnvironment)
theEnv = unsafePerformIO $ getEnvironment
dbg = True
dbglvl = 1
#else
dbg = False
dbglvl = 0
#endif
dbg :: Bool
dbglvl :: Int
_PARPUTS :: Bool
#ifdef PARPUTS
_PARPUTS = True
#else
_PARPUTS = False
#endif
_FORKPARENT :: Bool
#ifdef FORKPARENT
_FORKPARENT = True
#else
#warning "FORKPARENT POLICY NOT USED; THIS IS GENERALLY WORSE"
_FORKPARENT = False
#endif
_IDLING_ON :: Bool
#ifdef IDLING_ON
_IDLING_ON = True
#else
_IDLING_ON = False
#endif
_WAIT_FOR_WORKERS :: Bool
#ifdef WAIT_FOR_WORKERS
_WAIT_FOR_WORKERS = True
#else
_WAIT_FOR_WORKERS = False
#endif
--------------------------------------------------------------------------------
Core type definitions
--------------------------------------------------------------------------------
type ROnly = RD.ReaderT Sched IO
newtype IVar a = IVar (IORef (IVarContents a))
data IVarContents a = Full a | Empty | Blocked [a -> IO ()]
unsafeParIO :: IO a -> Par a
unsafeParIO iom = Par (lift$ lift iom)
io :: IO a -> Par a
io = unsafeParIO -- shorthand used below
--------------------------------------------------------------------------------
Global State
--------------------------------------------------------------------------------
-- This keeps track of ALL worker threads across all unreated
-- `runPar` instantiations. This is used to detect nested invocations
-- of `runPar` and avoid reinitialization.
-- globalWorkerPool :: IORef (Data.IntMap ())
#ifdef NESTED_SCHEDS
globalWorkerPool :: IORef (M.Map ThreadId Sched)
globalWorkerPool = unsafePerformIO $ newIORef M.empty
#endif
-- TODO! Make this semi-local! (not shared between "top-level" runPars)
# INLINE amINested #
# INLINE registerWorker #
{-# INLINE unregisterWorker #-}
amINested :: ThreadId -> IO (Maybe Sched)
registerWorker :: ThreadId -> Sched -> IO ()
unregisterWorker :: ThreadId -> IO ()
#ifdef NESTED_SCHEDS
-- | If the current threadID is ALREADY a worker, return the corresponding Sched structure.
amINested tid = do
-- There is no race here. Each thread inserts itself before it
-- becomes an active worker.
wp <- readIORef globalWorkerPool
return (M.lookup tid wp)
registerWorker tid sched =
atomicModifyIORef globalWorkerPool $
\ mp -> (M.insert tid sched mp, ())
unregisterWorker tid =
atomicModifyIORef globalWorkerPool $
\ mp -> (M.delete tid mp, ())
#else
amINested _ = return Nothing
registerWorker _ _ = return ()
unregisterWorker _tid = return ()
#endif
-----------------------------------------------------------------------------
Helpers # 2 : Pushing and popping work .
-----------------------------------------------------------------------------
{-# INLINE popWork #-}
popWork :: Sched -> IO (Maybe (Par ()))
popWork Sched{ workpool, no } = do
mb <- R.tryPopL workpool
when dbg $ case mb of
Nothing -> return ()
Just _ -> do sn <- makeStableName mb
printf " [%d] -> POP work unit %d\n" no (hashStableName sn)
return mb
# INLINE pushWork #
pushWork :: Sched -> Par () -> IO ()
pushWork Sched { workpool, idle, no } task = do
R.pushL workpool task
when dbg $ do sn <- makeStableName task
printf " [%d] -> PUSH work unit %d\n" no (hashStableName sn)
#if defined(IDLING_ON) && defined(WAKEIDLE)
--when isMain$ -- Experimenting with reducing contention by doing this only from a single thread.
-- TODO: We need to have a proper binary wakeup-tree.
tryWakeIdle idle
#endif
return ()
tryWakeIdle :: HotVar [MVar Bool] -> IO ()
tryWakeIdle idle = do
-- NOTE: I worry about having the idle var hammered by all threads on their spawn-path:
-- If any worker is idle, wake one up and give it work to do.
Optimistically do a normal read first .
when (not (Prelude.null idles)) $ do
when dbg$ printf "Waking %d idle thread(s).\n" (length idles)
r <- modifyHotVar idle (\is -> case is of
[] -> ([], return ())
(i:ils) -> (ils, putMVar i False))
wake an idle worker up by putting an MVar .
rand :: HotVar Random.GenIO -> IO Int
rand ref = Random.uniformR (0, numCapabilities-1) =<< readHotVar ref
--------------------------------------------------------------------------------
Running computations in the Par monad
--------------------------------------------------------------------------------
instance NFData (IVar a) where
rnf !_ = ()
# NOINLINE runPar #
runPar = unsafePerformIO . runParIO
-- | This procedure creates a new worker on the current thread (with a
-- new session ID) and plugs it into the work-stealing environment.
-- This new worker extracts itself from the work stealing pool when
-- `userComp` has completed, thus freeing the current thread (this
-- procedure) to return normally.
runNewSessionAndWait :: String -> Sched -> Par b -> IO b
runNewSessionAndWait name sched userComp = do
tid <- myThreadId -- TODO: remove when done debugging
sid <- modifyHotVar (sessionCounter sched) (\ x -> (x+1,x))
_ <- modifyHotVar (activeSessions sched) (\ set -> (S.insert sid set, ()))
-- Here we have an extra IORef... ugly.
ref <- newIORef (error$ "Empty session-result ref ("++name++") should never be touched (sid "++ show sid++", "++show tid ++")")
newFlag <- newHotVar False
-- Push the new session:
_ <- modifyHotVar (sessions sched) (\ ls -> ((Session sid newFlag) : ls, ()))
let userComp' = do when dbg$ io$ do
tid2 <- myThreadId
printf " [%d %s] Starting Par computation on %s.\n" (no sched) (show tid2) name
ans <- userComp
-- This add-on to userComp will run only after userComp has completed successfully,
-- but that does NOT guarantee that userComp-forked computations have terminated:
io$ do when (dbglvl>=1) $ do
tid3 <- myThreadId
printf " [%d %s] Continuation for %s called, finishing it up (%d)...\n" (no sched) (show tid3) name sid
writeIORef ref ans
writeHotVarRaw newFlag True
modifyHotVar (activeSessions sched) (\ set -> (S.delete sid set, ()))
kont :: Word64 -> a -> ROnly ()
kont n = trivialCont$ "("++name++", sid "++show sid++", round "++show n++")"
loop :: Word64 -> ROnly ()
loop n = do flg <- liftIO$ readIORef newFlag
unless flg $ do
when dbg $ liftIO$ do
tid4 <- myThreadId
printf " [%d %s] BOUNCE %d... going into reschedule until finished.\n" (no sched) (show tid4) n
rescheduleR 0 $ trivialCont$ "("++name++", sid "++show sid++")"
loop (n+1)
-- THIS IS RETURNING TOO EARLY!!:
runReaderWith sched (C.runContT (unPar userComp') (kont 0)) -- Does this ASSUME child stealing?
runReaderWith sched (loop 1)
-- TODO: Ideally we would wait for ALL outstanding (stolen) work on this "team" to complete.
when (dbglvl>=1)$ do
active <- readHotVar (activeSessions sched)
ASSERT !
printf " [%d %s] RETURN from %s (sessFin %s) runContT (%d) active set %s\n"
(no sched) (show tid) name (show sess) sid (show active)
-- Here we pop off the frame we added to the session stack:
modifyHotVar_ (sessions sched) $ \ (Session sid2 _ : tl) ->
if sid == sid2
then tl
else error$ "Tried to pop the session stack and found we ("++show sid
++") were not on the top! (instead "++show sid2++")"
-- By returning here we ARE implicitly reengaging the scheduler, since we
-- are already inside the rescheduleR loop on this thread
-- (before runParIO was called in a nested fashion).
readIORef ref
# NOINLINE runParIO #
runParIO userComp = do
tid <- myThreadId
#if __GLASGOW_HASKELL__ >= 701 /* 20110301 */
--
-- We create a thread on each CPU with forkOn. The CPU on which
-- the current thread is running will host the main thread; the
-- other CPUs will host worker threads.
--
Note : GHC 7.1.20110301 is required for this to work , because that
-- is when threadCapability was added.
--
(main_cpu, _) <- threadCapability tid
#else
--
Lacking threadCapability , we always pick CPU # 0 to run the main
thread . If the current thread is not running on CPU # 0 , this
-- will require some data to be shipped over the memory bus, and
-- hence will be slightly slower than the version above.
--
let main_cpu = 0
#endif
maybSched <- amINested tid
tidorig <- myThreadId -- TODO: remove when done debugging
case maybSched of
Just (sched) -> do
-- Here the current thread is ALREADY a worker. All we need to
-- do is plug the users new computation in.
sid0 <- readHotVar (sessionCounter sched)
when (dbglvl>=1)$ printf " [%d %s] runPar called from existing worker thread, new session (%d)....\n" (no sched) (show tid) (sid0 + 1)
runNewSessionAndWait "nested runPar" sched userComp
------------------------------------------------------------
-- Non-nested case, make a new set of worker threads:
------------------------------------------------------------
Nothing -> do
allscheds <- makeScheds main_cpu
[Session _ topSessFlag] <- readHotVar$ sessions$ head allscheds
mfin <- newEmptyMVar
doneFlags <- forM (zip [0..] allscheds) $ \(cpu,sched) -> do
workerDone <- newEmptyMVar
----------------------------------------
let wname = ("(worker "++show cpu++" of originator "++show tidorig++")")
-- forkOn cpu $ do
_ <- forkWithExceptions (forkOn cpu) wname $ do
------------------------------------------------------------STRT WORKER THREAD
tid2 <- myThreadId
registerWorker tid2 sched
if (cpu /= main_cpu)
then do when dbg$ printf " [%d %s] Anonymous worker entering scheduling loop.\n" cpu (show tid2)
runReaderWith sched $ rescheduleR 0 (trivialCont (wname++show tid2))
when dbg$ printf " [%d] Anonymous worker exited scheduling loop. FINISHED.\n" cpu
putMVar workerDone cpu
return ()
else do x <- runNewSessionAndWait "top-lvl main worker" sched userComp
-- When the main worker finishes we can tell the anonymous "system" workers:
writeIORef topSessFlag True
when dbg$ do printf " *** Out of entire runContT user computation on main thread %s.\n" (show tid2)
sanityCheck allscheds
putMVar mfin x
unregisterWorker tid
------------------------------------------------------------END WORKER THREAD
return (if cpu == main_cpu then Nothing else Just workerDone)
when _WAIT_FOR_WORKERS $ do
when dbg$ printf " *** [%s] Originator thread: waiting for workers to complete." (show tidorig)
forM_ (catMaybes doneFlags) $ \ mv -> do
n <- readMVar mv
-- n <- A.wait mv
when dbg$ printf " * [%s] Worker %s completed\n" (show tidorig) (show n)
when dbg$ do printf " *** [%s] Reading final MVar on originator thread.\n" (show tidorig)
-- We don't directly use the thread we come in on. Rather, that thread waits
waits . One reason for this is that the main / progenitor thread in
GHC is expensive like a forkOS thread .
----------------------------------------
-- DEBUGGING --
#ifdef DEBUG_DIRECT
busyTakeMVar (" The global wait "++ show tidorig) mfin -- Final value.
-- dbgTakeMVar "global waiting thread" mfin -- Final value.
#else
takeMVar mfin -- Final value.
#endif
----------------------------------------
-- Create the default scheduler(s) state:
makeScheds :: Int -> IO [Sched]
makeScheds main = do
when dbg$ do tid <- myThreadId
printf "[initialization] Creating %d worker threads, currently on %s\n" numCapabilities (show tid)
workpools <- replicateM numCapabilities $ R.newQ
rngs <- replicateM numCapabilities $ Random.create >>= newHotVar
idle <- newHotVar []
-- The STACKs are per-worker.. but the root finished flag is shared between all anonymous system workers:
sessionFinished <- newHotVar False
sessionStacks <- mapM newHotVar (replicate numCapabilities [Session baseSessionID sessionFinished])
activeSessions <- newHotVar S.empty
sessionCounter <- newHotVar (baseSessionID + 1)
let allscheds = [ Sched { no=x, idle, isMain= (x==main),
workpool=wp, scheds=allscheds, rng=rng,
sessions = stck,
activeSessions=activeSessions,
sessionCounter=sessionCounter
}
| ( x , wp , rng , ) < - zip4 [ 0 .. ] workpools rngs sessionStacks
| x <- [0 .. numCapabilities-1]
| wp <- workpools
| rng <- rngs
| stck <- sessionStacks
]
return allscheds
-- The ID of top-level runPar sessions.
baseSessionID :: SessionID
baseSessionID = 1000
--------------------------------------------------------------------------------
IVar operations
--------------------------------------------------------------------------------
{-# INLINE new #-}
-- | Creates a new @IVar@
new :: Par (IVar a)
new = io$ do r <- newIORef Empty
return (IVar r)
{-# INLINE get #-}
-- | Read the value in an @IVar@. The 'get' operation can only return when the
value has been written by a prior or parallel @put@ to the same
-- @IVar@.
get (IVar vr) = do
callCC $ \kont ->
do
e <- io$ readIORef vr
case e of
Full a -> return a
_ -> do
sch <- RD.ask
# ifdef DEBUG_DIRECT
Should probably do the MutVar inside ...
let resched = trace (" ["++ show (no sch) ++ "] - Rescheduling on unavailable ivar "++show (hashStableName sn)++"!")
#else
let resched =
# endif
longjmpSched -- Invariant: kont must not be lost.
-- Because we continue on the same processor the Sched stays the same:
TODO : Try NOT using monadic values as first class . Check for performance effect :
r <- io$ atomicModifyIORef vr $ \x -> case x of
Empty -> (Blocked [pushWork sch . kont], resched)
Full a -> (Full a, return a) -- kont is implicit here.
Blocked ks -> (Blocked (pushWork sch . kont:ks), resched)
r
| NOTE unsafePeek is NOT exposed directly through this module . ( So
-- this module remains SAFE in the Safe Haskell sense.) It can only
be accessed by importing Control . . Par . Unsafe .
# INLINE unsafePeek #
unsafePeek :: IVar a -> Par (Maybe a)
unsafePeek (IVar v) = do
e <- io$ readIORef v
case e of
Full a -> return (Just a)
_ -> return Nothing
------------------------------------------------------------
{-# INLINE put_ #-}
| @put_@ is a version of @put@ that is head - strict rather than fully - strict .
-- In this scheduler, puts immediately execute woken work in the current thread.
put_ (IVar vr) !content = do
sched <- RD.ask
ks <- io$ do
ks <- atomicModifyIORef vr $ \e -> case e of
Empty -> (Full content, [])
Full _ -> error "multiple put"
Blocked ks -> (Full content, ks)
#ifdef DEBUG_DIRECT
when (dbglvl >= 3) $ do
sn <- makeStableName vr
printf " [%d] Put value %s into IVar %d. Waking up %d continuations.\n"
(no sched) (show content) (hashStableName sn) (length ks)
return ()
#endif
return ks
wakeUp sched ks content
| NOTE is NOT exposed directly through this module . ( So
-- this module remains SAFE in the Safe Haskell sense.) It can only
be accessed by importing Control . . Par . Unsafe .
# INLINE unsafeTryPut #
unsafeTryPut (IVar vr) !content = do
-- Head strict rather than fully strict.
sched <- RD.ask
(ks,res) <- io$ do
pr <- atomicModifyIORef vr $ \e -> case e of
Empty -> (Full content, ([], content))
Full x -> (Full x, ([], x))
Blocked ks -> (Full content, (ks, content))
#ifdef DEBUG_DIRECT
sn <- makeStableName vr
printf " [%d] unsafeTryPut: value %s in IVar %d. Waking up %d continuations.\n"
(no sched) (show content) (hashStableName sn) (length (fst pr))
#endif
return pr
wakeUp sched ks content
return res
| When an IVar is filled in , continuations wake up .
# INLINE wakeUp #
wakeUp :: Sched -> [a -> IO ()]-> a -> Par ()
wakeUp _sched ks arg = loop ks
where
loop [] = return ()
loop (kont:rest) = do
-- FIXME -- without strict firewalls keeping ivars from moving
-- between runPar sessions, if we allow nested scheduler use
-- we could potentially wake up work belonging to a different
-- runPar and thus bring it into our worker and delay our own
-- continuation until its completion.
if _PARPUTS then
-- We do NOT force the putting thread to postpone its continuation.
do _ <- spawn_$ pMap kont rest
return ()
-- case rest of
-- [] -> spawn_$ io$ kont arg
-- _ -> spawn_$ do spawn_$ io$ kont arg
-- io$ parchain rest
-- error$"FINISHME - wake "++show (length ks)++" conts"
else
-- This version sacrifices a parallelism opportunity and
-- imposes additional serialization.
--
[ 2012.08.31 ] WARNING -- this serialzation CAN cause deadlock .
-- This "optimization" should not be on the table.
-- mapM_ ($arg) ks
do io$ kont arg
loop rest
return ()
pMap kont [] = io$ kont arg
pMap kont (more:rest) =
do _ <- spawn_$ io$ kont arg
pMap more rest
parchain [ kont ] = kont arg
-- parchain (kont:rest) = do spawn$ io$ kont arg
-- parchain rest
------------------------------------------------------------
# INLINE fork #
fork :: Par () -> Par ()
fork task =
-- Forking the "parent" means offering up the continuation of the
-- fork rather than the task argument for stealing:
case _FORKPARENT of
True -> do
sched <- RD.ask
callCC$ \parent -> do
let wrapped = parent ()
io$ pushWork sched wrapped
-- Then execute the child task and return to the scheduler when it is complete:
task
-- If we get to this point we have finished the child task:
_ <- longjmpSched -- We reschedule to pop the cont we pushed.
-- TODO... OPTIMIZATION: we could also try the pop directly, and if it succeeds return normally....
io$ printf " !!! ERROR: Should never reach this point #1\n"
when dbg$ do
sched2 <- RD.ask
io$ printf " - called parent continuation... was on worker [%d] now on worker [%d]\n" (no sched) (no sched2)
return ()
False -> do
sch <- RD.ask
when dbg$ io$ printf " [%d] forking task...\n" (no sch)
io$ pushWork sch task
-- This routine "longjmp"s to the scheduler, throwing out its own continuation.
longjmpSched :: Par a
-- longjmpSched = Par $ C.ContT rescheduleR
longjmpSched = Par $ C.ContT (\ _k -> rescheduleR 0 (trivialCont "longjmpSched"))
-- Reschedule the scheduler loop until it observes sessionFinished==True, and
-- then it finally invokes its continuation.
rescheduleR :: Word64 -> (a -> ROnly ()) -> ROnly ()
rescheduleR cnt kont = do
mysched <- RD.ask
when dbg$ liftIO$ do tid <- myThreadId
sess <- readSessions mysched
null <- R.nullQ (workpool mysched)
printf " [%d %s] - Reschedule #%d... sessions %s, pool empty %s\n"
(no mysched) (show tid) cnt (show sess) (show null)
mtask <- liftIO$ popWork mysched
case mtask of
Nothing -> do
(Session _ finRef):_ <- liftIO$ readIORef $ sessions mysched
fin <- liftIO$ readIORef finRef
if fin
then do when (dbglvl >= 1) $ liftIO $ do
tid <- myThreadId
sess <- readSessions mysched
printf " [%d %s] - DROP out of reschedule loop, sessionFinished=%s, all sessions %s\n"
(no mysched) (show tid) (show fin) (show sess)
empt <- R.nullQ$ workpool mysched
when (not empt) $ do
printf " [%d %s] - WARNING - leaving rescheduleR while local workpoll is nonempty\n"
(no mysched) (show tid)
kont (error "Direct.hs: The result value from rescheduleR should not be used.")
else do
when ( dbglvl > = 1 ) $ liftIO $ do
-- tid <- myThreadId
-- sess <- readSessions mysched
-- printf " [%d %s] - Apparently NOT finished with head session... trying to steal, all sessions %s\n"
-- (no mysched) (show tid) (show sess)
liftIO$ steal mysched
#ifdef WAKEIDLE
-- io$ tryWakeIdle (idle mysched)
#endif
liftIO yield
rescheduleR (cnt+1) kont
Just task -> do
-- When popping work from our own queue the Sched (Reader value) stays the same:
when dbg $ do sn <- liftIO$ makeStableName task
liftIO$ printf " [%d] popped work %d from own queue\n" (no mysched) (hashStableName sn)
let C.ContT fn = unPar task
-- Run the stolen task with a continuation that returns to the scheduler if the task exits normally:
fn (\ _ -> do
sch <- RD.ask
when dbg$ liftIO$ printf " + task finished successfully on cpu %d, calling reschedule continuation..\n" (no sch)
rescheduleR 0 kont)
-- | Attempt to steal work or, failing that, give up and go idle.
--
-- The current policy is to do a burst of of N tries without
-- yielding or pausing in between.
steal :: Sched -> IO ()
steal mysched@Sched{ idle, scheds, rng, no=my_no } = do
when (dbglvl>=2)$ do tid <- myThreadId
printf " [%d %s] + stealing\n" my_no (show tid)
i <- getnext (-1 :: Int)
go maxtries i
where
-- maxtries = numCapabilities -- How many times should we attempt theft before going idle?
maxtries = 20 * numCapabilities -- How many times should we attempt theft before going idle?
getnext _ = rand rng
----------------------------------------
-- IDLING behavior:
go 0 _ | _IDLING_ON =
do m <- newEmptyMVar
r <- modifyHotVar idle $ \is -> (m:is, is)
if length r == numCapabilities - 1
then do
when dbg$ printf " [%d] | waking up all threads\n" my_no
writeHotVarRaw idle []
mapM_ (\vr -> putMVar vr True) r
else do
(Session _ finRef):_ <- readIORef $ sessions mysched
fin <- readIORef finRef
done <- if fin then pure True else takeMVar m
if done
then do
when dbg$ printf " [%d] | shutting down\n" my_no
return ()
else do
when dbg$ printf " [%d] | woken up\n" my_no
i <- getnext (-1::Int)
go maxtries i
-- We need to return from this loop to check sessionFinished and exit the scheduler if necessary.
go 0 _i | _IDLING_ON == False = yield
----------------------------------------
go tries i
| i == my_no = do i' <- getnext i
go (tries-1) i'
| otherwise = do
-- We ONLY go through the global sched array to access victims:
let schd = scheds!!i
when (dbglvl>=2)$ printf " [%d] | trying steal from %d\n" my_no (no schd)
-- let dq = workpool schd :: WSDeque (Par ())
let dq = workpool schd
r <- R.tryPopR dq
case r of
Just task -> do
when dbg$ do sn <- makeStableName task
printf " [%d] | stole work (unit %d) from cpu %d\n" my_no (hashStableName sn) (no schd)
runReaderWith mysched $
C.runContT (unPar task)
(\_ -> do
when dbg$ do sn <- liftIO$ makeStableName task
liftIO$ printf " [%d] | DONE running stolen work (unit %d) from %d\n" my_no (hashStableName sn) (no schd)
return ())
Nothing -> do i' <- getnext i
go (tries-1) i'
-- | The continuation which should not be called.
_errK :: t
_errK = error "Error cont: this closure shouldn't be used"
trivialCont :: String -> a -> ROnly ()
#ifdef DEBUG_DIRECT
trivialCont str _ = do
-- trace (str ++" trivialCont evaluated!")
liftIO$ printf " !! trivialCont evaluated, msg: %s\n" str
#else
trivialCont _str _ = do
#endif
return ()
----------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- <boilerplate>
-- TEMP: TODO: Factor out this boilerplate somehow.
{-# INLINE spawn1_ #-}
Spawn a one argument function instead of a thunk . This is good for debugging if the value supports " Show " .
spawn1_ f x =
#ifdef DEBUG_DIRECT
do sn <- io$ makeStableName f
sch <- RD.ask; when dbg$ io$ printf " [%d] spawning fn %d with arg %s\n" (no sch) (hashStableName sn) (show x)
#endif
spawn_ (f x)
-- The following is usually inefficient!
newFull_ a = do v <- new
put_ v a
return v
newFull a = deepseq a (newFull_ a)
{-# INLINE put #-}
put v a = deepseq a (put_ v a)
spawn p = do r <- new; fork (p >>= put r); return r
spawn_ p = do r <- new; fork (p >>= put_ r); return r
spawnP a = spawn (return a)
In Debug mode we require that IVar contents be Show - able :
#ifdef DEBUG_DIRECT
put :: (Show a, NFData a) => IVar a -> a -> Par ()
spawn :: (Show a, NFData a) => Par a -> Par (IVar a)
spawn_ :: Show a => Par a -> Par (IVar a)
spawn1_ :: (Show a, Show b) => (a -> Par b) -> a -> Par (IVar b)
spawnP :: (Show a, NFData a) => a -> Par (IVar a)
put_ :: Show a => IVar a -> a -> Par ()
get :: Show a => IVar a -> Par a
runPar :: Show a => Par a -> a
runParIO :: Show a => Par a -> IO a
newFull :: (Show a, NFData a) => a -> Par (IVar a)
newFull_ :: Show a => a -> Par (IVar a)
unsafeTryPut :: Show b => IVar b -> b -> Par b
#else
spawn :: NFData a => Par a -> Par (IVar a)
spawn_ :: Par a -> Par (IVar a)
spawn1_ :: (a -> Par b) -> a -> Par (IVar b)
spawnP :: NFData a => a -> Par (IVar a)
put_ :: IVar a -> a -> Par ()
put :: NFData a => IVar a -> a -> Par ()
get :: IVar a -> Par a
runPar :: Par a -> a
runParIO :: Par a -> IO a
newFull :: NFData a => a -> Par (IVar a)
newFull_ :: a -> Par (IVar a)
unsafeTryPut :: IVar b -> b -> Par b
-- We can't make proper instances with the extra Show constraints:
instance PC.ParFuture IVar Par where
get = get
spawn = spawn
spawn_ = spawn_
spawnP = spawnP
instance PC.ParIVar IVar Par where
fork = fork
new = new
put_ = put_
newFull = newFull
newFull_ = newFull_
instance UN.ParUnsafe IVar Par where
unsafePeek = unsafePeek
unsafeTryPut = unsafeTryPut
unsafeParIO = unsafeParIO
#endif
#ifdef NEW_GENERIC
instance PU.ParMonad Par where
fork = fork
internalLiftIO io = Par (lift $ lift io)
instance PU.ParThreadSafe Par where
unsafeParIO io = Par (lift $ lift io)
instance PN.ParFuture Par where
type Future Par = IVar
type FutContents Par a = ()
get = get
spawn = spawn
spawn_ = spawn_
spawnP = spawnP
instance PN.ParIVar Par where
new = new
put_ = put_
newFull = newFull
newFull_ = newFull_
#endif
-- </boilerplate>
--------------------------------------------------------------------------------
# INLINE runReaderWith #
-- | Arguments flipped for convenience.
runReaderWith :: r -> RD.ReaderT r m a -> m a
runReaderWith state m = RD.runReaderT m state
--------------------------------------------------------------------------------
-- DEBUGGING TOOLs
--------------------------------------------------------------------------------
-- Make sure there is no work left in any deque after exiting.
_sanityCheck :: [Sched] -> IO ()
_sanityCheck allscheds = do
forM_ allscheds $ \ Sched{no, workpool} -> do
b <- R.nullQ workpool
when (not b) $ do
() <- printf "WARNING: After main thread exited non-empty queue remains for worker %d\n" no
return ()
printf "Sanity check complete.\n"
-- | This tries to localize the blocked-indefinitely exception:
_dbgTakeMVar :: String -> MVar a -> IO a
_dbgTakeMVar msg mv =
-- catch (takeMVar mv) ((\_ -> doDebugStuff) :: BlockedIndefinitelyOnMVar -> IO a)
E.catch (takeMVar mv) (\(_::IOError) -> doDebugStuff)
where
doDebugStuff = do printf "This takeMVar blocked indefinitely!: %s\n" msg
error "failed"
-- | For debugging purposes. This can help us figure out (by an ugly
process of elimination ) which MVar reads are leading to a " Thread
-- blocked indefinitely" exception.
busyTakeMVar : : String - > MVar a - > IO a
busyTakeMVar msg mv = try ( 10 * 1000 * 1000 )
where
try 0 = do
when dbg $ do
tid < - myThreadId
-- After we 've failed enough times , start complaining :
printf " % s not getting anywhere , msg : % s\n " ( show tid ) msg
try ( 100 * 1000 )
try n = do
x < - tryTakeMVar mv
case x of
Just y - > return y
Nothing - > do yield ; try ( n-1 )
busyTakeMVar :: String -> MVar a -> IO a
busyTakeMVar msg mv = try (10 * 1000 * 1000)
where
try 0 = do
when dbg $ do
tid <- myThreadId
-- After we've failed enough times, start complaining:
printf "%s not getting anywhere, msg: %s\n" (show tid) msg
try (100 * 1000)
try n = do
x <- tryTakeMVar mv
case x of
Just y -> return y
Nothing -> do yield; try (n-1)
-}
-- | Fork a thread but ALSO set up an error handler that suppresses
MVar exceptions .
_forkIO_Suppress :: Int -> IO () -> IO ThreadId
_forkIO_Suppress whre action =
forkOn whre $
E.handle (\e ->
case (e :: E.BlockedIndefinitelyOnMVar) of
_ -> do
putStrLn$"CAUGHT child thread exception: "++show e
return ()
)
action
-- | Exceptions that walk up the fork tree of threads:
forkWithExceptions :: (IO () -> IO ThreadId) -> String -> IO () -> IO ThreadId
forkWithExceptions forkit descr action = do
parent <- myThreadId
forkit $ do
tid <- myThreadId
E.catch action
(\ e ->
case E.fromException e of
Just E.ThreadKilled -> printf
"\nThreadKilled exception inside child thread, %s (not propagating!): %s\n" (show tid) (show descr)
_ -> do printf
"\nException inside child thread %s, %s: %s\n" (show descr) (show tid) (show e)
E.throwTo parent (e :: E.SomeException)
)
-- Do all the memory reads to snapshot the current session stack:
readSessions :: Sched -> IO [(SessionID, Bool)]
readSessions sched = do
ls <- readIORef (sessions sched)
bools <- mapM (\ (Session _ r) -> readIORef r) ls
return (zip (map (\ (Session sid _) -> sid) ls) bools)
| null | https://raw.githubusercontent.com/simonmar/monad-par/9a25911e2004c66c1eb14dc200d1f5b0c2d83f0e/monad-par/Control/Monad/Par/Scheds/Direct.hs | haskell | OPTIONS_GHC -Wall -fno-warn-name-shadowing -fno-warn-unused-do-bind
{- LANGUAGE Trustworthy -}
trace data structure).
abstract: Constructor not exported.
sched,
runParAsync, runParAsyncHelper,
yield,
------------------------------------------------------------------------------
Configuration Toggles
------------------------------------------------------------------------------
#define NESTED_SCHEDS
#define WAIT_FOR_WORKERS
-----------------------------------------------------------------
Ifdefs for the above preprocessor defines. Try to MINIMIZE code
that lives in this dangerous region, and instead do normal
conditionals and trust dead-code-elimination.
------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
shorthand used below
------------------------------------------------------------------------------
------------------------------------------------------------------------------
This keeps track of ALL worker threads across all unreated
`runPar` instantiations. This is used to detect nested invocations
of `runPar` and avoid reinitialization.
globalWorkerPool :: IORef (Data.IntMap ())
TODO! Make this semi-local! (not shared between "top-level" runPars)
# INLINE unregisterWorker #
| If the current threadID is ALREADY a worker, return the corresponding Sched structure.
There is no race here. Each thread inserts itself before it
becomes an active worker.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
# INLINE popWork #
when isMain$ -- Experimenting with reducing contention by doing this only from a single thread.
TODO: We need to have a proper binary wakeup-tree.
NOTE: I worry about having the idle var hammered by all threads on their spawn-path:
If any worker is idle, wake one up and give it work to do.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| This procedure creates a new worker on the current thread (with a
new session ID) and plugs it into the work-stealing environment.
This new worker extracts itself from the work stealing pool when
`userComp` has completed, thus freeing the current thread (this
procedure) to return normally.
TODO: remove when done debugging
Here we have an extra IORef... ugly.
Push the new session:
This add-on to userComp will run only after userComp has completed successfully,
but that does NOT guarantee that userComp-forked computations have terminated:
THIS IS RETURNING TOO EARLY!!:
Does this ASSUME child stealing?
TODO: Ideally we would wait for ALL outstanding (stolen) work on this "team" to complete.
Here we pop off the frame we added to the session stack:
By returning here we ARE implicitly reengaging the scheduler, since we
are already inside the rescheduleR loop on this thread
(before runParIO was called in a nested fashion).
We create a thread on each CPU with forkOn. The CPU on which
the current thread is running will host the main thread; the
other CPUs will host worker threads.
is when threadCapability was added.
will require some data to be shipped over the memory bus, and
hence will be slightly slower than the version above.
TODO: remove when done debugging
Here the current thread is ALREADY a worker. All we need to
do is plug the users new computation in.
----------------------------------------------------------
Non-nested case, make a new set of worker threads:
----------------------------------------------------------
--------------------------------------
forkOn cpu $ do
----------------------------------------------------------STRT WORKER THREAD
When the main worker finishes we can tell the anonymous "system" workers:
----------------------------------------------------------END WORKER THREAD
n <- A.wait mv
We don't directly use the thread we come in on. Rather, that thread waits
--------------------------------------
DEBUGGING --
Final value.
dbgTakeMVar "global waiting thread" mfin -- Final value.
Final value.
--------------------------------------
Create the default scheduler(s) state:
The STACKs are per-worker.. but the root finished flag is shared between all anonymous system workers:
The ID of top-level runPar sessions.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
# INLINE new #
| Creates a new @IVar@
# INLINE get #
| Read the value in an @IVar@. The 'get' operation can only return when the
@IVar@.
Invariant: kont must not be lost.
Because we continue on the same processor the Sched stays the same:
kont is implicit here.
this module remains SAFE in the Safe Haskell sense.) It can only
----------------------------------------------------------
# INLINE put_ #
In this scheduler, puts immediately execute woken work in the current thread.
this module remains SAFE in the Safe Haskell sense.) It can only
Head strict rather than fully strict.
FIXME -- without strict firewalls keeping ivars from moving
between runPar sessions, if we allow nested scheduler use
we could potentially wake up work belonging to a different
runPar and thus bring it into our worker and delay our own
continuation until its completion.
We do NOT force the putting thread to postpone its continuation.
case rest of
[] -> spawn_$ io$ kont arg
_ -> spawn_$ do spawn_$ io$ kont arg
io$ parchain rest
error$"FINISHME - wake "++show (length ks)++" conts"
This version sacrifices a parallelism opportunity and
imposes additional serialization.
this serialzation CAN cause deadlock .
This "optimization" should not be on the table.
mapM_ ($arg) ks
parchain (kont:rest) = do spawn$ io$ kont arg
parchain rest
----------------------------------------------------------
Forking the "parent" means offering up the continuation of the
fork rather than the task argument for stealing:
Then execute the child task and return to the scheduler when it is complete:
If we get to this point we have finished the child task:
We reschedule to pop the cont we pushed.
TODO... OPTIMIZATION: we could also try the pop directly, and if it succeeds return normally....
This routine "longjmp"s to the scheduler, throwing out its own continuation.
longjmpSched = Par $ C.ContT rescheduleR
Reschedule the scheduler loop until it observes sessionFinished==True, and
then it finally invokes its continuation.
tid <- myThreadId
sess <- readSessions mysched
printf " [%d %s] - Apparently NOT finished with head session... trying to steal, all sessions %s\n"
(no mysched) (show tid) (show sess)
io$ tryWakeIdle (idle mysched)
When popping work from our own queue the Sched (Reader value) stays the same:
Run the stolen task with a continuation that returns to the scheduler if the task exits normally:
| Attempt to steal work or, failing that, give up and go idle.
The current policy is to do a burst of of N tries without
yielding or pausing in between.
maxtries = numCapabilities -- How many times should we attempt theft before going idle?
How many times should we attempt theft before going idle?
--------------------------------------
IDLING behavior:
We need to return from this loop to check sessionFinished and exit the scheduler if necessary.
--------------------------------------
We ONLY go through the global sched array to access victims:
let dq = workpool schd :: WSDeque (Par ())
| The continuation which should not be called.
trace (str ++" trivialCont evaluated!")
--------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
<boilerplate>
TEMP: TODO: Factor out this boilerplate somehow.
# INLINE spawn1_ #
The following is usually inefficient!
# INLINE put #
We can't make proper instances with the extra Show constraints:
</boilerplate>
------------------------------------------------------------------------------
| Arguments flipped for convenience.
------------------------------------------------------------------------------
DEBUGGING TOOLs
------------------------------------------------------------------------------
Make sure there is no work left in any deque after exiting.
| This tries to localize the blocked-indefinitely exception:
catch (takeMVar mv) ((\_ -> doDebugStuff) :: BlockedIndefinitelyOnMVar -> IO a)
| For debugging purposes. This can help us figure out (by an ugly
blocked indefinitely" exception.
After we 've failed enough times , start complaining :
After we've failed enough times, start complaining:
| Fork a thread but ALSO set up an error handler that suppresses
| Exceptions that walk up the fork tree of threads:
Do all the memory reads to snapshot the current session stack: | # LANGUAGE RankNTypes , NamedFieldPuns , BangPatterns ,
ExistentialQuantification , CPP , ScopedTypeVariables ,
TypeSynonymInstances , MultiParamTypeClasses ,
, ,
ParallelListComp #
ExistentialQuantification, CPP, ScopedTypeVariables,
TypeSynonymInstances, MultiParamTypeClasses,
GeneralizedNewtypeDeriving, PackageImports,
ParallelListComp #-}
TODO : Before declaring this module TRUSTWORTHY / SAFE , we need to
make the IVar type abstract .
# LANGUAGE TypeFamilies #
| A scheduler for the Par monad based on directly performing IO
actions when Par methods are called ( i.e. without using a lazy
module Control.Monad.Par.Scheds.Direct (
Sched(..),
IVar(..), IVarContents(..),
runPar, runParIO,
new, get, put_, fork,
newFull, newFull_, put,
spawn, spawn_, spawnP,
spawn1_, fixPar, FixParException (..)
) where
import Control.Applicative
import Control.Concurrent hiding (yield)
import Data.IORef (IORef,newIORef,readIORef,writeIORef,atomicModifyIORef)
import Text.Printf (printf)
import GHC.Conc (numCapabilities,yield)
import "mtl" Control.Monad.Cont as C
import qualified "mtl" Control.Monad.Reader as RD
import qualified System.Random.MWC as Random
import System.IO.Unsafe (unsafePerformIO)
import System.Mem.StableName (makeStableName, hashStableName)
import qualified Control.Monad.Par.Class as PC
import qualified Control.Monad.Par.Unsafe as UN
import Control.Monad.Par.Scheds.DirectInternal
(Par(..), Sched(..), HotVar, SessionID, Session(Session),
newHotVar, readHotVar, modifyHotVar, modifyHotVar_,
writeHotVarRaw, fixPar, FixParException (..))
#ifdef NEW_GENERIC
import qualified Control.Par.Class as PN
import qualified Control.Par.Class.Unsafe as PU
#endif
import Control.DeepSeq
#ifdef NESTED_SCHEDS
import qualified Data.Map as M
#endif
import qualified Data.Set as S
import Data.Maybe (catMaybes)
import Data.Word (Word64)
import Data . Concurrent . Deque . Class ( WSDeque )
#ifdef USE_CHASELEV
#warning "Note: using Chase-Lev lockfree workstealing deques..."
import Data.Concurrent.Deque.ChaseLev.DequeInstance
import Data.Concurrent.Deque.ChaseLev as R
#else
import Data.Concurrent.Deque.Reference.DequeInstance
import Data.Concurrent.Deque.Reference as R
#endif
import qualified Control.Exception as E
import Prelude hiding (null)
import qualified Prelude
#if __GLASGOW_HASKELL__ <= 700
import GHC.Conc (forkOnIO)
forkOn = forkOnIO
#endif
[ 2012.08.30 ] This shows a 10X improvement on nested parfib :
#define PARPUTS
#define FORKPARENT
#define IDLING_ON
Next , IF idling is on , should we do wakeups ? :
#define WAKEIDLE
#ifdef DEBUG_DIRECT
#warning "DEBUG: Activating debugging for Direct.hs"
import Debug.Trace (trace)
import System.Environment (getEnvironment)
theEnv = unsafePerformIO $ getEnvironment
dbg = True
dbglvl = 1
#else
dbg = False
dbglvl = 0
#endif
dbg :: Bool
dbglvl :: Int
_PARPUTS :: Bool
#ifdef PARPUTS
_PARPUTS = True
#else
_PARPUTS = False
#endif
_FORKPARENT :: Bool
#ifdef FORKPARENT
_FORKPARENT = True
#else
#warning "FORKPARENT POLICY NOT USED; THIS IS GENERALLY WORSE"
_FORKPARENT = False
#endif
_IDLING_ON :: Bool
#ifdef IDLING_ON
_IDLING_ON = True
#else
_IDLING_ON = False
#endif
_WAIT_FOR_WORKERS :: Bool
#ifdef WAIT_FOR_WORKERS
_WAIT_FOR_WORKERS = True
#else
_WAIT_FOR_WORKERS = False
#endif
Core type definitions
type ROnly = RD.ReaderT Sched IO
newtype IVar a = IVar (IORef (IVarContents a))
data IVarContents a = Full a | Empty | Blocked [a -> IO ()]
unsafeParIO :: IO a -> Par a
unsafeParIO iom = Par (lift$ lift iom)
io :: IO a -> Par a
Global State
#ifdef NESTED_SCHEDS
globalWorkerPool :: IORef (M.Map ThreadId Sched)
globalWorkerPool = unsafePerformIO $ newIORef M.empty
#endif
# INLINE amINested #
# INLINE registerWorker #
amINested :: ThreadId -> IO (Maybe Sched)
registerWorker :: ThreadId -> Sched -> IO ()
unregisterWorker :: ThreadId -> IO ()
#ifdef NESTED_SCHEDS
amINested tid = do
wp <- readIORef globalWorkerPool
return (M.lookup tid wp)
registerWorker tid sched =
atomicModifyIORef globalWorkerPool $
\ mp -> (M.insert tid sched mp, ())
unregisterWorker tid =
atomicModifyIORef globalWorkerPool $
\ mp -> (M.delete tid mp, ())
#else
amINested _ = return Nothing
registerWorker _ _ = return ()
unregisterWorker _tid = return ()
#endif
Helpers # 2 : Pushing and popping work .
popWork :: Sched -> IO (Maybe (Par ()))
popWork Sched{ workpool, no } = do
mb <- R.tryPopL workpool
when dbg $ case mb of
Nothing -> return ()
Just _ -> do sn <- makeStableName mb
printf " [%d] -> POP work unit %d\n" no (hashStableName sn)
return mb
# INLINE pushWork #
pushWork :: Sched -> Par () -> IO ()
pushWork Sched { workpool, idle, no } task = do
R.pushL workpool task
when dbg $ do sn <- makeStableName task
printf " [%d] -> PUSH work unit %d\n" no (hashStableName sn)
#if defined(IDLING_ON) && defined(WAKEIDLE)
tryWakeIdle idle
#endif
return ()
tryWakeIdle :: HotVar [MVar Bool] -> IO ()
tryWakeIdle idle = do
Optimistically do a normal read first .
when (not (Prelude.null idles)) $ do
when dbg$ printf "Waking %d idle thread(s).\n" (length idles)
r <- modifyHotVar idle (\is -> case is of
[] -> ([], return ())
(i:ils) -> (ils, putMVar i False))
wake an idle worker up by putting an MVar .
rand :: HotVar Random.GenIO -> IO Int
rand ref = Random.uniformR (0, numCapabilities-1) =<< readHotVar ref
Running computations in the Par monad
instance NFData (IVar a) where
rnf !_ = ()
# NOINLINE runPar #
runPar = unsafePerformIO . runParIO
runNewSessionAndWait :: String -> Sched -> Par b -> IO b
runNewSessionAndWait name sched userComp = do
sid <- modifyHotVar (sessionCounter sched) (\ x -> (x+1,x))
_ <- modifyHotVar (activeSessions sched) (\ set -> (S.insert sid set, ()))
ref <- newIORef (error$ "Empty session-result ref ("++name++") should never be touched (sid "++ show sid++", "++show tid ++")")
newFlag <- newHotVar False
_ <- modifyHotVar (sessions sched) (\ ls -> ((Session sid newFlag) : ls, ()))
let userComp' = do when dbg$ io$ do
tid2 <- myThreadId
printf " [%d %s] Starting Par computation on %s.\n" (no sched) (show tid2) name
ans <- userComp
io$ do when (dbglvl>=1) $ do
tid3 <- myThreadId
printf " [%d %s] Continuation for %s called, finishing it up (%d)...\n" (no sched) (show tid3) name sid
writeIORef ref ans
writeHotVarRaw newFlag True
modifyHotVar (activeSessions sched) (\ set -> (S.delete sid set, ()))
kont :: Word64 -> a -> ROnly ()
kont n = trivialCont$ "("++name++", sid "++show sid++", round "++show n++")"
loop :: Word64 -> ROnly ()
loop n = do flg <- liftIO$ readIORef newFlag
unless flg $ do
when dbg $ liftIO$ do
tid4 <- myThreadId
printf " [%d %s] BOUNCE %d... going into reschedule until finished.\n" (no sched) (show tid4) n
rescheduleR 0 $ trivialCont$ "("++name++", sid "++show sid++")"
loop (n+1)
runReaderWith sched (loop 1)
when (dbglvl>=1)$ do
active <- readHotVar (activeSessions sched)
ASSERT !
printf " [%d %s] RETURN from %s (sessFin %s) runContT (%d) active set %s\n"
(no sched) (show tid) name (show sess) sid (show active)
modifyHotVar_ (sessions sched) $ \ (Session sid2 _ : tl) ->
if sid == sid2
then tl
else error$ "Tried to pop the session stack and found we ("++show sid
++") were not on the top! (instead "++show sid2++")"
readIORef ref
# NOINLINE runParIO #
runParIO userComp = do
tid <- myThreadId
#if __GLASGOW_HASKELL__ >= 701 /* 20110301 */
Note : GHC 7.1.20110301 is required for this to work , because that
(main_cpu, _) <- threadCapability tid
#else
Lacking threadCapability , we always pick CPU # 0 to run the main
thread . If the current thread is not running on CPU # 0 , this
let main_cpu = 0
#endif
maybSched <- amINested tid
case maybSched of
Just (sched) -> do
sid0 <- readHotVar (sessionCounter sched)
when (dbglvl>=1)$ printf " [%d %s] runPar called from existing worker thread, new session (%d)....\n" (no sched) (show tid) (sid0 + 1)
runNewSessionAndWait "nested runPar" sched userComp
Nothing -> do
allscheds <- makeScheds main_cpu
[Session _ topSessFlag] <- readHotVar$ sessions$ head allscheds
mfin <- newEmptyMVar
doneFlags <- forM (zip [0..] allscheds) $ \(cpu,sched) -> do
workerDone <- newEmptyMVar
let wname = ("(worker "++show cpu++" of originator "++show tidorig++")")
_ <- forkWithExceptions (forkOn cpu) wname $ do
tid2 <- myThreadId
registerWorker tid2 sched
if (cpu /= main_cpu)
then do when dbg$ printf " [%d %s] Anonymous worker entering scheduling loop.\n" cpu (show tid2)
runReaderWith sched $ rescheduleR 0 (trivialCont (wname++show tid2))
when dbg$ printf " [%d] Anonymous worker exited scheduling loop. FINISHED.\n" cpu
putMVar workerDone cpu
return ()
else do x <- runNewSessionAndWait "top-lvl main worker" sched userComp
writeIORef topSessFlag True
when dbg$ do printf " *** Out of entire runContT user computation on main thread %s.\n" (show tid2)
sanityCheck allscheds
putMVar mfin x
unregisterWorker tid
return (if cpu == main_cpu then Nothing else Just workerDone)
when _WAIT_FOR_WORKERS $ do
when dbg$ printf " *** [%s] Originator thread: waiting for workers to complete." (show tidorig)
forM_ (catMaybes doneFlags) $ \ mv -> do
n <- readMVar mv
when dbg$ printf " * [%s] Worker %s completed\n" (show tidorig) (show n)
when dbg$ do printf " *** [%s] Reading final MVar on originator thread.\n" (show tidorig)
waits . One reason for this is that the main / progenitor thread in
GHC is expensive like a forkOS thread .
#ifdef DEBUG_DIRECT
#else
#endif
makeScheds :: Int -> IO [Sched]
makeScheds main = do
when dbg$ do tid <- myThreadId
printf "[initialization] Creating %d worker threads, currently on %s\n" numCapabilities (show tid)
workpools <- replicateM numCapabilities $ R.newQ
rngs <- replicateM numCapabilities $ Random.create >>= newHotVar
idle <- newHotVar []
sessionFinished <- newHotVar False
sessionStacks <- mapM newHotVar (replicate numCapabilities [Session baseSessionID sessionFinished])
activeSessions <- newHotVar S.empty
sessionCounter <- newHotVar (baseSessionID + 1)
let allscheds = [ Sched { no=x, idle, isMain= (x==main),
workpool=wp, scheds=allscheds, rng=rng,
sessions = stck,
activeSessions=activeSessions,
sessionCounter=sessionCounter
}
| ( x , wp , rng , ) < - zip4 [ 0 .. ] workpools rngs sessionStacks
| x <- [0 .. numCapabilities-1]
| wp <- workpools
| rng <- rngs
| stck <- sessionStacks
]
return allscheds
baseSessionID :: SessionID
baseSessionID = 1000
IVar operations
new :: Par (IVar a)
new = io$ do r <- newIORef Empty
return (IVar r)
value has been written by a prior or parallel @put@ to the same
get (IVar vr) = do
callCC $ \kont ->
do
e <- io$ readIORef vr
case e of
Full a -> return a
_ -> do
sch <- RD.ask
# ifdef DEBUG_DIRECT
Should probably do the MutVar inside ...
let resched = trace (" ["++ show (no sch) ++ "] - Rescheduling on unavailable ivar "++show (hashStableName sn)++"!")
#else
let resched =
# endif
TODO : Try NOT using monadic values as first class . Check for performance effect :
r <- io$ atomicModifyIORef vr $ \x -> case x of
Empty -> (Blocked [pushWork sch . kont], resched)
Blocked ks -> (Blocked (pushWork sch . kont:ks), resched)
r
| NOTE unsafePeek is NOT exposed directly through this module . ( So
be accessed by importing Control . . Par . Unsafe .
# INLINE unsafePeek #
unsafePeek :: IVar a -> Par (Maybe a)
unsafePeek (IVar v) = do
e <- io$ readIORef v
case e of
Full a -> return (Just a)
_ -> return Nothing
| @put_@ is a version of @put@ that is head - strict rather than fully - strict .
put_ (IVar vr) !content = do
sched <- RD.ask
ks <- io$ do
ks <- atomicModifyIORef vr $ \e -> case e of
Empty -> (Full content, [])
Full _ -> error "multiple put"
Blocked ks -> (Full content, ks)
#ifdef DEBUG_DIRECT
when (dbglvl >= 3) $ do
sn <- makeStableName vr
printf " [%d] Put value %s into IVar %d. Waking up %d continuations.\n"
(no sched) (show content) (hashStableName sn) (length ks)
return ()
#endif
return ks
wakeUp sched ks content
| NOTE is NOT exposed directly through this module . ( So
be accessed by importing Control . . Par . Unsafe .
# INLINE unsafeTryPut #
unsafeTryPut (IVar vr) !content = do
sched <- RD.ask
(ks,res) <- io$ do
pr <- atomicModifyIORef vr $ \e -> case e of
Empty -> (Full content, ([], content))
Full x -> (Full x, ([], x))
Blocked ks -> (Full content, (ks, content))
#ifdef DEBUG_DIRECT
sn <- makeStableName vr
printf " [%d] unsafeTryPut: value %s in IVar %d. Waking up %d continuations.\n"
(no sched) (show content) (hashStableName sn) (length (fst pr))
#endif
return pr
wakeUp sched ks content
return res
| When an IVar is filled in , continuations wake up .
# INLINE wakeUp #
wakeUp :: Sched -> [a -> IO ()]-> a -> Par ()
wakeUp _sched ks arg = loop ks
where
loop [] = return ()
loop (kont:rest) = do
if _PARPUTS then
do _ <- spawn_$ pMap kont rest
return ()
else
do io$ kont arg
loop rest
return ()
pMap kont [] = io$ kont arg
pMap kont (more:rest) =
do _ <- spawn_$ io$ kont arg
pMap more rest
parchain [ kont ] = kont arg
# INLINE fork #
fork :: Par () -> Par ()
fork task =
case _FORKPARENT of
True -> do
sched <- RD.ask
callCC$ \parent -> do
let wrapped = parent ()
io$ pushWork sched wrapped
task
io$ printf " !!! ERROR: Should never reach this point #1\n"
when dbg$ do
sched2 <- RD.ask
io$ printf " - called parent continuation... was on worker [%d] now on worker [%d]\n" (no sched) (no sched2)
return ()
False -> do
sch <- RD.ask
when dbg$ io$ printf " [%d] forking task...\n" (no sch)
io$ pushWork sch task
longjmpSched :: Par a
longjmpSched = Par $ C.ContT (\ _k -> rescheduleR 0 (trivialCont "longjmpSched"))
rescheduleR :: Word64 -> (a -> ROnly ()) -> ROnly ()
rescheduleR cnt kont = do
mysched <- RD.ask
when dbg$ liftIO$ do tid <- myThreadId
sess <- readSessions mysched
null <- R.nullQ (workpool mysched)
printf " [%d %s] - Reschedule #%d... sessions %s, pool empty %s\n"
(no mysched) (show tid) cnt (show sess) (show null)
mtask <- liftIO$ popWork mysched
case mtask of
Nothing -> do
(Session _ finRef):_ <- liftIO$ readIORef $ sessions mysched
fin <- liftIO$ readIORef finRef
if fin
then do when (dbglvl >= 1) $ liftIO $ do
tid <- myThreadId
sess <- readSessions mysched
printf " [%d %s] - DROP out of reschedule loop, sessionFinished=%s, all sessions %s\n"
(no mysched) (show tid) (show fin) (show sess)
empt <- R.nullQ$ workpool mysched
when (not empt) $ do
printf " [%d %s] - WARNING - leaving rescheduleR while local workpoll is nonempty\n"
(no mysched) (show tid)
kont (error "Direct.hs: The result value from rescheduleR should not be used.")
else do
when ( dbglvl > = 1 ) $ liftIO $ do
liftIO$ steal mysched
#ifdef WAKEIDLE
#endif
liftIO yield
rescheduleR (cnt+1) kont
Just task -> do
when dbg $ do sn <- liftIO$ makeStableName task
liftIO$ printf " [%d] popped work %d from own queue\n" (no mysched) (hashStableName sn)
let C.ContT fn = unPar task
fn (\ _ -> do
sch <- RD.ask
when dbg$ liftIO$ printf " + task finished successfully on cpu %d, calling reschedule continuation..\n" (no sch)
rescheduleR 0 kont)
steal :: Sched -> IO ()
steal mysched@Sched{ idle, scheds, rng, no=my_no } = do
when (dbglvl>=2)$ do tid <- myThreadId
printf " [%d %s] + stealing\n" my_no (show tid)
i <- getnext (-1 :: Int)
go maxtries i
where
getnext _ = rand rng
go 0 _ | _IDLING_ON =
do m <- newEmptyMVar
r <- modifyHotVar idle $ \is -> (m:is, is)
if length r == numCapabilities - 1
then do
when dbg$ printf " [%d] | waking up all threads\n" my_no
writeHotVarRaw idle []
mapM_ (\vr -> putMVar vr True) r
else do
(Session _ finRef):_ <- readIORef $ sessions mysched
fin <- readIORef finRef
done <- if fin then pure True else takeMVar m
if done
then do
when dbg$ printf " [%d] | shutting down\n" my_no
return ()
else do
when dbg$ printf " [%d] | woken up\n" my_no
i <- getnext (-1::Int)
go maxtries i
go 0 _i | _IDLING_ON == False = yield
go tries i
| i == my_no = do i' <- getnext i
go (tries-1) i'
| otherwise = do
let schd = scheds!!i
when (dbglvl>=2)$ printf " [%d] | trying steal from %d\n" my_no (no schd)
let dq = workpool schd
r <- R.tryPopR dq
case r of
Just task -> do
when dbg$ do sn <- makeStableName task
printf " [%d] | stole work (unit %d) from cpu %d\n" my_no (hashStableName sn) (no schd)
runReaderWith mysched $
C.runContT (unPar task)
(\_ -> do
when dbg$ do sn <- liftIO$ makeStableName task
liftIO$ printf " [%d] | DONE running stolen work (unit %d) from %d\n" my_no (hashStableName sn) (no schd)
return ())
Nothing -> do i' <- getnext i
go (tries-1) i'
_errK :: t
_errK = error "Error cont: this closure shouldn't be used"
trivialCont :: String -> a -> ROnly ()
#ifdef DEBUG_DIRECT
trivialCont str _ = do
liftIO$ printf " !! trivialCont evaluated, msg: %s\n" str
#else
trivialCont _str _ = do
#endif
return ()
Spawn a one argument function instead of a thunk . This is good for debugging if the value supports " Show " .
spawn1_ f x =
#ifdef DEBUG_DIRECT
do sn <- io$ makeStableName f
sch <- RD.ask; when dbg$ io$ printf " [%d] spawning fn %d with arg %s\n" (no sch) (hashStableName sn) (show x)
#endif
spawn_ (f x)
newFull_ a = do v <- new
put_ v a
return v
newFull a = deepseq a (newFull_ a)
put v a = deepseq a (put_ v a)
spawn p = do r <- new; fork (p >>= put r); return r
spawn_ p = do r <- new; fork (p >>= put_ r); return r
spawnP a = spawn (return a)
In Debug mode we require that IVar contents be Show - able :
#ifdef DEBUG_DIRECT
put :: (Show a, NFData a) => IVar a -> a -> Par ()
spawn :: (Show a, NFData a) => Par a -> Par (IVar a)
spawn_ :: Show a => Par a -> Par (IVar a)
spawn1_ :: (Show a, Show b) => (a -> Par b) -> a -> Par (IVar b)
spawnP :: (Show a, NFData a) => a -> Par (IVar a)
put_ :: Show a => IVar a -> a -> Par ()
get :: Show a => IVar a -> Par a
runPar :: Show a => Par a -> a
runParIO :: Show a => Par a -> IO a
newFull :: (Show a, NFData a) => a -> Par (IVar a)
newFull_ :: Show a => a -> Par (IVar a)
unsafeTryPut :: Show b => IVar b -> b -> Par b
#else
spawn :: NFData a => Par a -> Par (IVar a)
spawn_ :: Par a -> Par (IVar a)
spawn1_ :: (a -> Par b) -> a -> Par (IVar b)
spawnP :: NFData a => a -> Par (IVar a)
put_ :: IVar a -> a -> Par ()
put :: NFData a => IVar a -> a -> Par ()
get :: IVar a -> Par a
runPar :: Par a -> a
runParIO :: Par a -> IO a
newFull :: NFData a => a -> Par (IVar a)
newFull_ :: a -> Par (IVar a)
unsafeTryPut :: IVar b -> b -> Par b
instance PC.ParFuture IVar Par where
get = get
spawn = spawn
spawn_ = spawn_
spawnP = spawnP
instance PC.ParIVar IVar Par where
fork = fork
new = new
put_ = put_
newFull = newFull
newFull_ = newFull_
instance UN.ParUnsafe IVar Par where
unsafePeek = unsafePeek
unsafeTryPut = unsafeTryPut
unsafeParIO = unsafeParIO
#endif
#ifdef NEW_GENERIC
instance PU.ParMonad Par where
fork = fork
internalLiftIO io = Par (lift $ lift io)
instance PU.ParThreadSafe Par where
unsafeParIO io = Par (lift $ lift io)
instance PN.ParFuture Par where
type Future Par = IVar
type FutContents Par a = ()
get = get
spawn = spawn
spawn_ = spawn_
spawnP = spawnP
instance PN.ParIVar Par where
new = new
put_ = put_
newFull = newFull
newFull_ = newFull_
#endif
# INLINE runReaderWith #
runReaderWith :: r -> RD.ReaderT r m a -> m a
runReaderWith state m = RD.runReaderT m state
_sanityCheck :: [Sched] -> IO ()
_sanityCheck allscheds = do
forM_ allscheds $ \ Sched{no, workpool} -> do
b <- R.nullQ workpool
when (not b) $ do
() <- printf "WARNING: After main thread exited non-empty queue remains for worker %d\n" no
return ()
printf "Sanity check complete.\n"
_dbgTakeMVar :: String -> MVar a -> IO a
_dbgTakeMVar msg mv =
E.catch (takeMVar mv) (\(_::IOError) -> doDebugStuff)
where
doDebugStuff = do printf "This takeMVar blocked indefinitely!: %s\n" msg
error "failed"
process of elimination ) which MVar reads are leading to a " Thread
busyTakeMVar : : String - > MVar a - > IO a
busyTakeMVar msg mv = try ( 10 * 1000 * 1000 )
where
try 0 = do
when dbg $ do
tid < - myThreadId
printf " % s not getting anywhere , msg : % s\n " ( show tid ) msg
try ( 100 * 1000 )
try n = do
x < - tryTakeMVar mv
case x of
Just y - > return y
Nothing - > do yield ; try ( n-1 )
busyTakeMVar :: String -> MVar a -> IO a
busyTakeMVar msg mv = try (10 * 1000 * 1000)
where
try 0 = do
when dbg $ do
tid <- myThreadId
printf "%s not getting anywhere, msg: %s\n" (show tid) msg
try (100 * 1000)
try n = do
x <- tryTakeMVar mv
case x of
Just y -> return y
Nothing -> do yield; try (n-1)
-}
MVar exceptions .
_forkIO_Suppress :: Int -> IO () -> IO ThreadId
_forkIO_Suppress whre action =
forkOn whre $
E.handle (\e ->
case (e :: E.BlockedIndefinitelyOnMVar) of
_ -> do
putStrLn$"CAUGHT child thread exception: "++show e
return ()
)
action
forkWithExceptions :: (IO () -> IO ThreadId) -> String -> IO () -> IO ThreadId
forkWithExceptions forkit descr action = do
parent <- myThreadId
forkit $ do
tid <- myThreadId
E.catch action
(\ e ->
case E.fromException e of
Just E.ThreadKilled -> printf
"\nThreadKilled exception inside child thread, %s (not propagating!): %s\n" (show tid) (show descr)
_ -> do printf
"\nException inside child thread %s, %s: %s\n" (show descr) (show tid) (show e)
E.throwTo parent (e :: E.SomeException)
)
readSessions :: Sched -> IO [(SessionID, Bool)]
readSessions sched = do
ls <- readIORef (sessions sched)
bools <- mapM (\ (Session _ r) -> readIORef r) ls
return (zip (map (\ (Session sid _) -> sid) ls) bools)
|
f91c93d8d4235c9adb984990fc16a8b40decfc54c5dfaf9d004709a175762508 | emmabastas/elm-embed | Effects.hs | # OPTIONS_GHC -Wall #
{-# LANGUAGE OverloadedStrings #-}
module Canonicalize.Effects
( canonicalize
, checkPayload
)
where
import qualified Data.Foldable as F
import qualified Data.Map as Map
import qualified Data.Name as Name
import qualified AST.Canonical as Can
import qualified AST.Source as Src
import qualified AST.Utils.Type as Type
import qualified Canonicalize.Environment as Env
import qualified Canonicalize.Type as Type
import qualified Elm.ModuleName as ModuleName
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Canonicalize as Error
import qualified Reporting.Result as Result
-- RESULT
type Result i w a =
Result.Result i w Error.Error a
-- CANONICALIZE
canonicalize
:: Env.Env
-> [A.Located Src.Value]
-> Map.Map Name.Name union
-> Src.Effects
-> Result i w Can.Effects
canonicalize env values unions effects =
case effects of
Src.NoEffects ->
Result.ok Can.NoEffects
Src.Ports ports ->
do pairs <- traverse (canonicalizePort env) ports
return $ Can.Ports (Map.fromList pairs)
Src.Manager region manager ->
let dict = Map.fromList (map toNameRegion values) in
Can.Manager
<$> verifyManager region dict "init"
<*> verifyManager region dict "onEffects"
<*> verifyManager region dict "onSelfMsg"
<*>
case manager of
Src.Cmd cmdType ->
Can.Cmd
<$> verifyEffectType cmdType unions
<* verifyManager region dict "cmdMap"
Src.Sub subType ->
Can.Sub
<$> verifyEffectType subType unions
<* verifyManager region dict "subMap"
Src.Fx cmdType subType ->
Can.Fx
<$> verifyEffectType cmdType unions
<*> verifyEffectType subType unions
<* verifyManager region dict "cmdMap"
<* verifyManager region dict "subMap"
-- CANONICALIZE PORT
canonicalizePort :: Env.Env -> Src.Port -> Result i w (Name.Name, Can.Port)
canonicalizePort env (Src.Port (A.At region portName) tipe) =
do (Can.Forall freeVars ctipe) <- Type.toAnnotation env tipe
case reverse (Type.delambda (Type.deepDealias ctipe)) of
Can.TType _ home name [msg] : revArgs
| home == ModuleName.cmd && name == Name.cmd ->
case revArgs of
[] ->
Result.throw (Error.PortTypeInvalid region portName Error.CmdNoArg)
[outgoingType] ->
case msg of
Can.TVar _ ->
case checkPayload outgoingType of
Right () ->
Result.ok (portName, Can.Outgoing freeVars outgoingType ctipe)
Left (badType, err) ->
Result.throw (Error.PortPayloadInvalid region portName badType err)
_ ->
Result.throw (Error.PortTypeInvalid region portName Error.CmdBadMsg)
_ ->
Result.throw (Error.PortTypeInvalid region portName (Error.CmdExtraArgs (length revArgs)))
| home == ModuleName.sub && name == Name.sub ->
case revArgs of
[Can.TLambda incomingType (Can.TVar msg1)] ->
case msg of
Can.TVar msg2 | msg1 == msg2 ->
case checkPayload incomingType of
Right () ->
Result.ok (portName, Can.Incoming freeVars incomingType ctipe)
Left (badType, err) ->
Result.throw (Error.PortPayloadInvalid region portName badType err)
_ ->
Result.throw (Error.PortTypeInvalid region portName Error.SubBad)
_ ->
Result.throw (Error.PortTypeInvalid region portName Error.SubBad)
_ ->
Result.throw (Error.PortTypeInvalid region portName Error.NotCmdOrSub)
-- VERIFY MANAGER
verifyEffectType :: A.Located Name.Name -> Map.Map Name.Name a -> Result i w Name.Name
verifyEffectType (A.At region name) unions =
if Map.member name unions then
Result.ok name
else
Result.throw (Error.EffectNotFound region name)
toNameRegion :: A.Located Src.Value -> (Name.Name, A.Region)
toNameRegion (A.At _ (Src.Value (A.At region name) _ _ _ _)) =
(name, region)
verifyManager :: A.Region -> Map.Map Name.Name A.Region -> Name.Name -> Result i w A.Region
verifyManager tagRegion values name =
case Map.lookup name values of
Just region ->
Result.ok region
Nothing ->
Result.throw (Error.EffectFunctionNotFound tagRegion name)
-- CHECK PAYLOAD TYPES
checkPayload :: Can.Type -> Either (Can.Type, Error.InvalidPayload) ()
checkPayload tipe =
case tipe of
Can.TAlias _ _ _ args aliasedType ->
checkPayload (Type.dealias args aliasedType)
Can.TType _ home name args ->
case args of
[]
| isJson home name -> Right ()
| isString home name -> Right ()
| isIntFloatBool home name -> Right ()
[arg]
| isList home name -> checkPayload arg
| isMaybe home name -> checkPayload arg
| isArray home name -> checkPayload arg
_ ->
Left (tipe, Error.UnsupportedType name)
Can.TUnit ->
Right ()
Can.TTuple a b maybeC ->
do checkPayload a
checkPayload b
case maybeC of
Nothing ->
Right ()
Just c ->
checkPayload c
Can.TVar name ->
Left (tipe, Error.TypeVariable name)
Can.TLambda _ _ ->
Left (tipe, Error.Function)
Can.TRecord _ (Just _) ->
Left (tipe, Error.ExtendedRecord)
Can.TRecord fields Nothing ->
F.traverse_ checkFieldPayload fields
checkFieldPayload :: Can.FieldType -> Either (Can.Type, Error.InvalidPayload) ()
checkFieldPayload (Can.FieldType _ tipe) =
checkPayload tipe
isIntFloatBool :: ModuleName.Canonical -> Name.Name -> Bool
isIntFloatBool home name =
home == ModuleName.basics
&&
(name == Name.int || name == Name.float || name == Name.bool)
isString :: ModuleName.Canonical -> Name.Name -> Bool
isString home name =
home == ModuleName.string
&&
name == Name.string
isJson :: ModuleName.Canonical -> Name.Name -> Bool
isJson home name =
home == ModuleName.jsonEncode
&&
name == Name.value
isList :: ModuleName.Canonical -> Name.Name -> Bool
isList home name =
home == ModuleName.list
&&
name == Name.list
isMaybe :: ModuleName.Canonical -> Name.Name -> Bool
isMaybe home name =
home == ModuleName.maybe
&&
name == Name.maybe
isArray :: ModuleName.Canonical -> Name.Name -> Bool
isArray home name =
home == ModuleName.array
&&
name == Name.array
| null | https://raw.githubusercontent.com/emmabastas/elm-embed/c2c4f9dcc5c4f47480f728247ff7b4d0700d7476/compiler/src/Canonicalize/Effects.hs | haskell | # LANGUAGE OverloadedStrings #
RESULT
CANONICALIZE
CANONICALIZE PORT
VERIFY MANAGER
CHECK PAYLOAD TYPES | # OPTIONS_GHC -Wall #
module Canonicalize.Effects
( canonicalize
, checkPayload
)
where
import qualified Data.Foldable as F
import qualified Data.Map as Map
import qualified Data.Name as Name
import qualified AST.Canonical as Can
import qualified AST.Source as Src
import qualified AST.Utils.Type as Type
import qualified Canonicalize.Environment as Env
import qualified Canonicalize.Type as Type
import qualified Elm.ModuleName as ModuleName
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Canonicalize as Error
import qualified Reporting.Result as Result
type Result i w a =
Result.Result i w Error.Error a
canonicalize
:: Env.Env
-> [A.Located Src.Value]
-> Map.Map Name.Name union
-> Src.Effects
-> Result i w Can.Effects
canonicalize env values unions effects =
case effects of
Src.NoEffects ->
Result.ok Can.NoEffects
Src.Ports ports ->
do pairs <- traverse (canonicalizePort env) ports
return $ Can.Ports (Map.fromList pairs)
Src.Manager region manager ->
let dict = Map.fromList (map toNameRegion values) in
Can.Manager
<$> verifyManager region dict "init"
<*> verifyManager region dict "onEffects"
<*> verifyManager region dict "onSelfMsg"
<*>
case manager of
Src.Cmd cmdType ->
Can.Cmd
<$> verifyEffectType cmdType unions
<* verifyManager region dict "cmdMap"
Src.Sub subType ->
Can.Sub
<$> verifyEffectType subType unions
<* verifyManager region dict "subMap"
Src.Fx cmdType subType ->
Can.Fx
<$> verifyEffectType cmdType unions
<*> verifyEffectType subType unions
<* verifyManager region dict "cmdMap"
<* verifyManager region dict "subMap"
canonicalizePort :: Env.Env -> Src.Port -> Result i w (Name.Name, Can.Port)
canonicalizePort env (Src.Port (A.At region portName) tipe) =
do (Can.Forall freeVars ctipe) <- Type.toAnnotation env tipe
case reverse (Type.delambda (Type.deepDealias ctipe)) of
Can.TType _ home name [msg] : revArgs
| home == ModuleName.cmd && name == Name.cmd ->
case revArgs of
[] ->
Result.throw (Error.PortTypeInvalid region portName Error.CmdNoArg)
[outgoingType] ->
case msg of
Can.TVar _ ->
case checkPayload outgoingType of
Right () ->
Result.ok (portName, Can.Outgoing freeVars outgoingType ctipe)
Left (badType, err) ->
Result.throw (Error.PortPayloadInvalid region portName badType err)
_ ->
Result.throw (Error.PortTypeInvalid region portName Error.CmdBadMsg)
_ ->
Result.throw (Error.PortTypeInvalid region portName (Error.CmdExtraArgs (length revArgs)))
| home == ModuleName.sub && name == Name.sub ->
case revArgs of
[Can.TLambda incomingType (Can.TVar msg1)] ->
case msg of
Can.TVar msg2 | msg1 == msg2 ->
case checkPayload incomingType of
Right () ->
Result.ok (portName, Can.Incoming freeVars incomingType ctipe)
Left (badType, err) ->
Result.throw (Error.PortPayloadInvalid region portName badType err)
_ ->
Result.throw (Error.PortTypeInvalid region portName Error.SubBad)
_ ->
Result.throw (Error.PortTypeInvalid region portName Error.SubBad)
_ ->
Result.throw (Error.PortTypeInvalid region portName Error.NotCmdOrSub)
verifyEffectType :: A.Located Name.Name -> Map.Map Name.Name a -> Result i w Name.Name
verifyEffectType (A.At region name) unions =
if Map.member name unions then
Result.ok name
else
Result.throw (Error.EffectNotFound region name)
toNameRegion :: A.Located Src.Value -> (Name.Name, A.Region)
toNameRegion (A.At _ (Src.Value (A.At region name) _ _ _ _)) =
(name, region)
verifyManager :: A.Region -> Map.Map Name.Name A.Region -> Name.Name -> Result i w A.Region
verifyManager tagRegion values name =
case Map.lookup name values of
Just region ->
Result.ok region
Nothing ->
Result.throw (Error.EffectFunctionNotFound tagRegion name)
checkPayload :: Can.Type -> Either (Can.Type, Error.InvalidPayload) ()
checkPayload tipe =
case tipe of
Can.TAlias _ _ _ args aliasedType ->
checkPayload (Type.dealias args aliasedType)
Can.TType _ home name args ->
case args of
[]
| isJson home name -> Right ()
| isString home name -> Right ()
| isIntFloatBool home name -> Right ()
[arg]
| isList home name -> checkPayload arg
| isMaybe home name -> checkPayload arg
| isArray home name -> checkPayload arg
_ ->
Left (tipe, Error.UnsupportedType name)
Can.TUnit ->
Right ()
Can.TTuple a b maybeC ->
do checkPayload a
checkPayload b
case maybeC of
Nothing ->
Right ()
Just c ->
checkPayload c
Can.TVar name ->
Left (tipe, Error.TypeVariable name)
Can.TLambda _ _ ->
Left (tipe, Error.Function)
Can.TRecord _ (Just _) ->
Left (tipe, Error.ExtendedRecord)
Can.TRecord fields Nothing ->
F.traverse_ checkFieldPayload fields
checkFieldPayload :: Can.FieldType -> Either (Can.Type, Error.InvalidPayload) ()
checkFieldPayload (Can.FieldType _ tipe) =
checkPayload tipe
isIntFloatBool :: ModuleName.Canonical -> Name.Name -> Bool
isIntFloatBool home name =
home == ModuleName.basics
&&
(name == Name.int || name == Name.float || name == Name.bool)
isString :: ModuleName.Canonical -> Name.Name -> Bool
isString home name =
home == ModuleName.string
&&
name == Name.string
isJson :: ModuleName.Canonical -> Name.Name -> Bool
isJson home name =
home == ModuleName.jsonEncode
&&
name == Name.value
isList :: ModuleName.Canonical -> Name.Name -> Bool
isList home name =
home == ModuleName.list
&&
name == Name.list
isMaybe :: ModuleName.Canonical -> Name.Name -> Bool
isMaybe home name =
home == ModuleName.maybe
&&
name == Name.maybe
isArray :: ModuleName.Canonical -> Name.Name -> Bool
isArray home name =
home == ModuleName.array
&&
name == Name.array
|
e388e732bffe213d412693a16c57c80ed56ce651043498e7b9c81e610267b3cb | MarchLiu/market | matcher.clj | (ns liu.mars.market.matcher
(:require [clojure.java.jdbc :as j]
[liu.mars.market.config :as config]
[cheshire.core :as c]))
(defn save [trade]
(let [data (c/parse-string trade true)]
(j/execute! @config/db {:meta {:category (:category data)
:symbol (:symbol data)
:taker-id (:taker-id data)}
:content data}))) | null | https://raw.githubusercontent.com/MarchLiu/market/7a7daf6c04b41e0f8494be6740da8d54785c5e77/matcher/src/main/clojure/liu/mars/market/matcher.clj | clojure | (ns liu.mars.market.matcher
(:require [clojure.java.jdbc :as j]
[liu.mars.market.config :as config]
[cheshire.core :as c]))
(defn save [trade]
(let [data (c/parse-string trade true)]
(j/execute! @config/db {:meta {:category (:category data)
:symbol (:symbol data)
:taker-id (:taker-id data)}
:content data}))) | |
d329bb3b41ff7e53540264798f09f36d4ce7436d11c1591692bb9dc2f40cc905 | mikera/core.matrix | sequence.cljc | (ns clojure.core.matrix.impl.sequence
"Namepace implementing selected core.matrix protocols for clojure sequences.
Useful if you want to pass Clojure sequences directly to core.matrix functions.
WARNING: because they lack efficient indexed access, sequences will perform badly for most
array operations. In general they should be converted to other implementations before use."
(:require [clojure.core.matrix.protocols :as mp]
[clojure.core.matrix.implementations :as imp]
#?(:clj [clojure.core.matrix.macros :refer [scalar-coerce error]]))
#?(:clj (:import [clojure.lang ISeq])
:cljs (:require-macros [clojure.core.matrix.macros :refer [scalar-coerce error]])))
core.matrix implementation for Clojure ISeq objects
;;
;; Important notes:
1 . Intended mainly for accessing data . Not recommended for computations ...
2 . generally returns a persistent vector where possible
#?(:clj (do
(set! *warn-on-reflection* true)
(set! *unchecked-math* true)
))
(extend-protocol mp/PImplementation
ISeq
(implementation-key [m] :sequence)
(meta-info [m]
{:doc "Core.matrix implementation for Clojure ISeq objects"})
(new-vector [m length]
(mp/new-vector [] length))
(new-matrix [m rows columns]
(mp/new-matrix [] rows columns))
(new-matrix-nd [m dims]
(mp/new-matrix-nd [] dims))
(construct-matrix [m data]
(mp/coerce-param [] data))
(supports-dimensionality? [m dims]
true))
(extend-protocol mp/PIndexedAccess
ISeq
(get-1d [m x]
(scalar-coerce (nth m x)))
(get-2d [m x y]
(let [row (nth m x)]
(mp/get-1d row y)))
(get-nd [m indexes]
(if-let [indexes (seq indexes)]
(if-let [next-indexes (next indexes)]
(let [mv (nth m (first indexes))]
(mp/get-nd mv next-indexes))
(nth m (first indexes)))
m ;; TODO: figure out if this is a good return value? should it be an error?
)))
(extend-protocol mp/PIndexedSetting
ISeq
(set-1d [m row v]
(mp/set-1d (mp/convert-to-nested-vectors m) row v))
(set-2d [m row column v]
(mp/set-2d (mp/convert-to-nested-vectors m) row column v))
(set-nd [m indexes v]
(mp/set-nd (mp/convert-to-nested-vectors m) indexes v))
(is-mutable? [m]
false))
(extend-protocol mp/PBroadcast
ISeq
(broadcast [m new-shape]
(mp/broadcast (mp/convert-to-nested-vectors m) new-shape)))
(extend-protocol mp/PBroadcastLike
ISeq
(broadcast-like [m a]
(mp/broadcast (mp/convert-to-nested-vectors a) (mp/get-shape m))))
(extend-protocol mp/PSliceView
ISeq
(get-major-slice-view [m i]
(nth m i)))
(extend-protocol mp/PSliceSeq
ISeq
(get-major-slice-seq [m] (vec m)))
(extend-protocol mp/PMatrixRows
ISeq
(get-rows [m]
(vec m)))
(extend-protocol mp/PMatrixColumns
ISeq
(get-columns [m]
(let [m (mp/coerce-param [] m)]
(mp/get-columns m))))
(extend-protocol mp/PSliceSeq2
ISeq
(get-slice-seq [m dimension]
(let [ldimension (long dimension)]
(cond
(== ldimension 0) (mp/get-major-slice-seq m)
(< ldimension 0) (error "Can't get slices of a negative dimension: " dimension)
:else (mapv #(mp/get-slice m dimension %) (range (mp/dimension-count m dimension)))))))
(extend-protocol mp/PConversion
ISeq
(convert-to-nested-vectors [m]
(if (> (mp/dimensionality (first m)) 0)
(mapv mp/convert-to-nested-vectors m)
(vec m))))
(extend-protocol mp/PDimensionInfo
ISeq
(dimensionality [m]
(inc (mp/dimensionality (first m))))
(is-vector? [m]
(== 0 (mp/dimensionality (first m))))
(is-scalar? [m]
false)
(get-shape [m]
#?(:cljs (js/console.log (str "shape of seq: " m)))
(cons (count m) (mp/get-shape (first m))))
(dimension-count [m x]
(if (== x 0)
(count m)
(mp/dimension-count (first m) (dec x)))))
(extend-protocol mp/PFunctionalOperations
ISeq
(element-seq [m]
(if (== 0 (long (mp/dimensionality (first m))))
m ;; handle 1D case, just return this sequence unchanged
(mapcat mp/element-seq m)))
(element-map
([m f]
(mapv #(mp/element-map % f) m))
([m f a]
(let [[m a] (mp/broadcast-compatible m a)]
(mapv #(mp/element-map % f %2) m (mp/get-major-slice-seq a))))
([m f a more]
FIXME
(mapv #(mp/element-map % f %2 %3) m (mp/get-major-slice-seq a) (map mp/get-major-slice-seq more)))))
(element-map!
([m f]
(error "Sequence arrays are not mutable!"))
([m f a]
(error "Sequence arrays are not mutable!"))
([m f a more]
(error "Sequence arrays are not mutable!")))
(element-reduce
([m f]
(reduce f (mapcat mp/element-seq m)))
([m f init]
(reduce f init (mapcat mp/element-seq m)))))
(extend-protocol mp/PMapIndexed
ISeq
(element-map-indexed
([ms f]
(mapv (fn [i m] (mp/element-map-indexed m #(apply f (cons i %1) %&)))
(range (count ms)) ms))
([ms f as]
(let [[ms as] (mp/broadcast-compatible ms as)]
(mapv (fn [i m a]
(mp/element-map-indexed m #(apply f (cons i %1) %&) a))
(range (count ms)) ms (mp/get-major-slice-seq as))))
([ms f as more]
FIXME
(mapv (fn [i m a & mr]
(mp/element-map-indexed m #(apply f (cons i %1) %&) a mr))
(range (count ms)) ms
(mp/get-major-slice-seq as)
(map mp/get-major-slice-seq more)))))
(element-map-indexed!
([m f]
(error "Sequence arrays are not mutable!"))
([m f a]
(error "Sequence arrays are not mutable!"))
([m f a more]
(error "Sequence arrays are not mutable!"))))
;; =====================================
;; Register implementation
;(imp/register-implementation '(1 2 3))
| null | https://raw.githubusercontent.com/mikera/core.matrix/0a35f6e3d6d2335cb56f6f3e5744bfa1dd0390aa/src/main/clojure/clojure/core/matrix/impl/sequence.cljc | clojure |
Important notes:
TODO: figure out if this is a good return value? should it be an error?
handle 1D case, just return this sequence unchanged
=====================================
Register implementation
(imp/register-implementation '(1 2 3)) | (ns clojure.core.matrix.impl.sequence
"Namepace implementing selected core.matrix protocols for clojure sequences.
Useful if you want to pass Clojure sequences directly to core.matrix functions.
WARNING: because they lack efficient indexed access, sequences will perform badly for most
array operations. In general they should be converted to other implementations before use."
(:require [clojure.core.matrix.protocols :as mp]
[clojure.core.matrix.implementations :as imp]
#?(:clj [clojure.core.matrix.macros :refer [scalar-coerce error]]))
#?(:clj (:import [clojure.lang ISeq])
:cljs (:require-macros [clojure.core.matrix.macros :refer [scalar-coerce error]])))
core.matrix implementation for Clojure ISeq objects
1 . Intended mainly for accessing data . Not recommended for computations ...
2 . generally returns a persistent vector where possible
#?(:clj (do
(set! *warn-on-reflection* true)
(set! *unchecked-math* true)
))
(extend-protocol mp/PImplementation
ISeq
(implementation-key [m] :sequence)
(meta-info [m]
{:doc "Core.matrix implementation for Clojure ISeq objects"})
(new-vector [m length]
(mp/new-vector [] length))
(new-matrix [m rows columns]
(mp/new-matrix [] rows columns))
(new-matrix-nd [m dims]
(mp/new-matrix-nd [] dims))
(construct-matrix [m data]
(mp/coerce-param [] data))
(supports-dimensionality? [m dims]
true))
(extend-protocol mp/PIndexedAccess
ISeq
(get-1d [m x]
(scalar-coerce (nth m x)))
(get-2d [m x y]
(let [row (nth m x)]
(mp/get-1d row y)))
(get-nd [m indexes]
(if-let [indexes (seq indexes)]
(if-let [next-indexes (next indexes)]
(let [mv (nth m (first indexes))]
(mp/get-nd mv next-indexes))
(nth m (first indexes)))
)))
(extend-protocol mp/PIndexedSetting
ISeq
(set-1d [m row v]
(mp/set-1d (mp/convert-to-nested-vectors m) row v))
(set-2d [m row column v]
(mp/set-2d (mp/convert-to-nested-vectors m) row column v))
(set-nd [m indexes v]
(mp/set-nd (mp/convert-to-nested-vectors m) indexes v))
(is-mutable? [m]
false))
(extend-protocol mp/PBroadcast
ISeq
(broadcast [m new-shape]
(mp/broadcast (mp/convert-to-nested-vectors m) new-shape)))
(extend-protocol mp/PBroadcastLike
ISeq
(broadcast-like [m a]
(mp/broadcast (mp/convert-to-nested-vectors a) (mp/get-shape m))))
(extend-protocol mp/PSliceView
ISeq
(get-major-slice-view [m i]
(nth m i)))
(extend-protocol mp/PSliceSeq
ISeq
(get-major-slice-seq [m] (vec m)))
(extend-protocol mp/PMatrixRows
ISeq
(get-rows [m]
(vec m)))
(extend-protocol mp/PMatrixColumns
ISeq
(get-columns [m]
(let [m (mp/coerce-param [] m)]
(mp/get-columns m))))
(extend-protocol mp/PSliceSeq2
ISeq
(get-slice-seq [m dimension]
(let [ldimension (long dimension)]
(cond
(== ldimension 0) (mp/get-major-slice-seq m)
(< ldimension 0) (error "Can't get slices of a negative dimension: " dimension)
:else (mapv #(mp/get-slice m dimension %) (range (mp/dimension-count m dimension)))))))
(extend-protocol mp/PConversion
ISeq
(convert-to-nested-vectors [m]
(if (> (mp/dimensionality (first m)) 0)
(mapv mp/convert-to-nested-vectors m)
(vec m))))
(extend-protocol mp/PDimensionInfo
ISeq
(dimensionality [m]
(inc (mp/dimensionality (first m))))
(is-vector? [m]
(== 0 (mp/dimensionality (first m))))
(is-scalar? [m]
false)
(get-shape [m]
#?(:cljs (js/console.log (str "shape of seq: " m)))
(cons (count m) (mp/get-shape (first m))))
(dimension-count [m x]
(if (== x 0)
(count m)
(mp/dimension-count (first m) (dec x)))))
(extend-protocol mp/PFunctionalOperations
ISeq
(element-seq [m]
(if (== 0 (long (mp/dimensionality (first m))))
(mapcat mp/element-seq m)))
(element-map
([m f]
(mapv #(mp/element-map % f) m))
([m f a]
(let [[m a] (mp/broadcast-compatible m a)]
(mapv #(mp/element-map % f %2) m (mp/get-major-slice-seq a))))
([m f a more]
FIXME
(mapv #(mp/element-map % f %2 %3) m (mp/get-major-slice-seq a) (map mp/get-major-slice-seq more)))))
(element-map!
([m f]
(error "Sequence arrays are not mutable!"))
([m f a]
(error "Sequence arrays are not mutable!"))
([m f a more]
(error "Sequence arrays are not mutable!")))
(element-reduce
([m f]
(reduce f (mapcat mp/element-seq m)))
([m f init]
(reduce f init (mapcat mp/element-seq m)))))
(extend-protocol mp/PMapIndexed
ISeq
(element-map-indexed
([ms f]
(mapv (fn [i m] (mp/element-map-indexed m #(apply f (cons i %1) %&)))
(range (count ms)) ms))
([ms f as]
(let [[ms as] (mp/broadcast-compatible ms as)]
(mapv (fn [i m a]
(mp/element-map-indexed m #(apply f (cons i %1) %&) a))
(range (count ms)) ms (mp/get-major-slice-seq as))))
([ms f as more]
FIXME
(mapv (fn [i m a & mr]
(mp/element-map-indexed m #(apply f (cons i %1) %&) a mr))
(range (count ms)) ms
(mp/get-major-slice-seq as)
(map mp/get-major-slice-seq more)))))
(element-map-indexed!
([m f]
(error "Sequence arrays are not mutable!"))
([m f a]
(error "Sequence arrays are not mutable!"))
([m f a more]
(error "Sequence arrays are not mutable!"))))
|
e7f8affe772bb413bae0a4ad4bebdfbdcfccd42ce6e52e26fa3894546caac3be | gwathlobal/CotD | init-game-events-demonic-steal.lisp | (in-package :cotd)
;;===========================
WIN EVENTS
;;===========================
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-angels+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, have all angels killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (or (and (= (loyal-faction *player*) +faction-type-angels+)
(> (total-angels (level world)) 0)
(zerop (total-demons (level world))))
(and (/= (loyal-faction *player*) +faction-type-angels+)
(zerop (nth +faction-type-satanists+ (total-faction-list (level world))))
(> (total-angels (level world)) 0)
(zerop (total-demons (level world)))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-angels-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-demons+
:descr-func #'(lambda ()
"To win, capture the relic in the church and throw it into a demonic portal (use your ability for that). To lose, have all demons killed.")
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-demons (level world)) 0)
(get-demon-steal-check-relic-captured world))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Relic captured by demons."
:score (calculate-player-score 1300)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-demons-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-military+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, have all military killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-humans (level world)) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (= (loyal-faction *player*) +faction-type-military+)
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1450 (* 7 (total-humans (level world)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-military-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-church+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, get all priests and angels killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-church+)
(> (nth +faction-type-church+ (total-faction-list (level world))) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-church-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-satanists+
:descr-func #'(lambda ()
"To win, capture the relic in the church and throw it into a demonic portal (use your ability for that). To lose, get all satanists and demons killed.")
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-satanists+)
(> (nth +faction-type-satanists+ (total-faction-list (level world))) 0)
(get-demon-steal-check-relic-captured world))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Relic sucessfully captured."
:score (calculate-player-score 1450)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-satanists-won))
)))
| null | https://raw.githubusercontent.com/gwathlobal/CotD/d01ef486cc1d3b21d2ad670ebdb443e957290aa2/src/game-events/init-game-events-demonic-steal.lisp | lisp | ===========================
=========================== | (in-package :cotd)
WIN EVENTS
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-angels+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, have all angels killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (or (and (= (loyal-faction *player*) +faction-type-angels+)
(> (total-angels (level world)) 0)
(zerop (total-demons (level world))))
(and (/= (loyal-faction *player*) +faction-type-angels+)
(zerop (nth +faction-type-satanists+ (total-faction-list (level world))))
(> (total-angels (level world)) 0)
(zerop (total-demons (level world)))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-angels-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-demons+
:descr-func #'(lambda ()
"To win, capture the relic in the church and throw it into a demonic portal (use your ability for that). To lose, have all demons killed.")
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-demons (level world)) 0)
(get-demon-steal-check-relic-captured world))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Relic captured by demons."
:score (calculate-player-score 1300)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-demons-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-military+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, have all military killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (and (> (total-humans (level world)) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (= (loyal-faction *player*) +faction-type-military+)
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1450 (* 7 (total-humans (level world)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-military-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-church+
:descr-func #'(lambda ()
"To win, destroy all demons in the district. To lose, get all priests and angels killed or let the demons capture the relic.")
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-church+)
(> (nth +faction-type-church+ (total-faction-list (level world))) 0)
(zerop (total-demons (level world))))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-angels+)
(= (loyal-faction *player*) +faction-type-church+))
t
nil)))
(trigger-game-over world
:final-str "Demonic theivery attempt prevented."
:score (calculate-player-score (+ 1400 (if (not (mimic-id-list *player*))
0
(loop for mimic-id in (mimic-id-list *player*)
for mimic = (get-mob-by-id mimic-id)
with cur-score = 0
when (not (eq mimic *player*))
do
(incf cur-score (cur-score mimic))
finally (return cur-score)))))
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-church-won))
)))
(set-game-event (make-instance 'game-event :id +game-event-demon-steal-win-for-satanists+
:descr-func #'(lambda ()
"To win, capture the relic in the church and throw it into a demonic portal (use your ability for that). To lose, get all satanists and demons killed.")
:disabled nil
:on-check #'(lambda (world)
(if (and (= (loyal-faction *player*) +faction-type-satanists+)
(> (nth +faction-type-satanists+ (total-faction-list (level world))) 0)
(get-demon-steal-check-relic-captured world))
t
nil))
:on-trigger #'(lambda (world)
(let ((if-player-won (if (or (= (loyal-faction *player*) +faction-type-demons+)
(= (loyal-faction *player*) +faction-type-satanists+))
t
nil)))
(trigger-game-over world
:final-str "Relic sucessfully captured."
:score (calculate-player-score 1450)
:if-player-won if-player-won
:player-msg (if if-player-won
(format nil "Congratulations! Your faction has won!~%")
(format nil "Curses! Your faction has lost!~%"))
:game-over-type :game-over-satanists-won))
)))
|
9703c16960b790e81eed47dd8501239bdcc5c6838c8f2294da26b001e7d6e0f0 | dolotech/erlang_server | data_produce_num.erl | -module(data_produce_num).
-export([get/1]).
get(ids) -> [1,2,3,4,5];
get(1) -> [{rand_top, 50}, {range, [{1,1,50}]}];
get(2) -> [{rand_top, 75}, {range, [{1,1,50},{2,51,75}]}];
get(3) -> [{rand_top, 87}, {range, [{1,1,50},{2,51,75},{3,76,87}]}];
get(4) -> [{rand_top, 95}, {range, [{1,1,50},{2,51,75},{3,76,87},{4,88,95}]}];
get(5) -> [{rand_top, 100}, {range, [{1,1,50},{2,51,75},{3,76,87},{4,88,95},{5,96,100}]}];
get(_) -> undefined. | null | https://raw.githubusercontent.com/dolotech/erlang_server/44ea3693317f60e18b19c9ddfa179307cbd646d7/src/data/data_produce_num.erl | erlang | -module(data_produce_num).
-export([get/1]).
get(ids) -> [1,2,3,4,5];
get(1) -> [{rand_top, 50}, {range, [{1,1,50}]}];
get(2) -> [{rand_top, 75}, {range, [{1,1,50},{2,51,75}]}];
get(3) -> [{rand_top, 87}, {range, [{1,1,50},{2,51,75},{3,76,87}]}];
get(4) -> [{rand_top, 95}, {range, [{1,1,50},{2,51,75},{3,76,87},{4,88,95}]}];
get(5) -> [{rand_top, 100}, {range, [{1,1,50},{2,51,75},{3,76,87},{4,88,95},{5,96,100}]}];
get(_) -> undefined. | |
1d148662cceb833ee2a55156ab23ad35af1e9a6c7a342a58c7f9406a5a26b2a7 | tek/ribosome | MenuFilter.hs | module Ribosome.Menu.Interpreter.MenuFilter where
import Text.Regex.PCRE.Light.Char8 (caseless, compileM, utf8)
import Ribosome.Menu.Data.Entry (Entry (Entry))
import Ribosome.Menu.Data.Filter (Filter (Fuzzy, Prefix, Regex, Substring))
import Ribosome.Menu.Data.FilterMode (FilterMode (FilterMode))
import Ribosome.Menu.Data.State (MenuQuery (MenuQuery))
import Ribosome.Menu.Data.MenuItem (MenuItem)
import Ribosome.Menu.Effect.MenuFilter (
FilterJob (Initial, Match, Refine),
MenuFilter (MenuFilter),
)
import Ribosome.Menu.Filters (
Matcher,
initPar,
matchAll,
matchFuzzy,
matchPrefix,
matchRegex,
matchSubstring,
refinePar,
)
execute ::
(MenuItem i -> Maybe Text) ->
Matcher i ->
FilterJob i a ->
IO a
execute extract m = \case
Match index item ->
pure (m extract (Entry item index False))
Initial items ->
initPar extract m items
Refine entries ->
refinePar extract m entries
TODO this probably needs an error type that is displayed in the status window or echoed
matcher :: MenuQuery -> Filter -> Matcher i
matcher "" =
const matchAll
matcher (MenuQuery query) = \case
Substring ->
matchSubstring query
Fuzzy ->
matchFuzzy True (toString query)
Prefix ->
matchPrefix query
Regex ->
either (const matchAll) matchRegex (compileM (toString query) [caseless, utf8])
defaultFilter ::
Member (Embed IO) r =>
InterpreterFor (MenuFilter (FilterMode Filter)) r
defaultFilter =
interpret \case
MenuFilter (FilterMode f ex) query job ->
embed (execute ex (matcher query f) job)
| null | https://raw.githubusercontent.com/tek/ribosome/ec3dd63ad47322e7fec66043dd7e6ade2f547ac1/packages/menu/lib/Ribosome/Menu/Interpreter/MenuFilter.hs | haskell | module Ribosome.Menu.Interpreter.MenuFilter where
import Text.Regex.PCRE.Light.Char8 (caseless, compileM, utf8)
import Ribosome.Menu.Data.Entry (Entry (Entry))
import Ribosome.Menu.Data.Filter (Filter (Fuzzy, Prefix, Regex, Substring))
import Ribosome.Menu.Data.FilterMode (FilterMode (FilterMode))
import Ribosome.Menu.Data.State (MenuQuery (MenuQuery))
import Ribosome.Menu.Data.MenuItem (MenuItem)
import Ribosome.Menu.Effect.MenuFilter (
FilterJob (Initial, Match, Refine),
MenuFilter (MenuFilter),
)
import Ribosome.Menu.Filters (
Matcher,
initPar,
matchAll,
matchFuzzy,
matchPrefix,
matchRegex,
matchSubstring,
refinePar,
)
execute ::
(MenuItem i -> Maybe Text) ->
Matcher i ->
FilterJob i a ->
IO a
execute extract m = \case
Match index item ->
pure (m extract (Entry item index False))
Initial items ->
initPar extract m items
Refine entries ->
refinePar extract m entries
TODO this probably needs an error type that is displayed in the status window or echoed
matcher :: MenuQuery -> Filter -> Matcher i
matcher "" =
const matchAll
matcher (MenuQuery query) = \case
Substring ->
matchSubstring query
Fuzzy ->
matchFuzzy True (toString query)
Prefix ->
matchPrefix query
Regex ->
either (const matchAll) matchRegex (compileM (toString query) [caseless, utf8])
defaultFilter ::
Member (Embed IO) r =>
InterpreterFor (MenuFilter (FilterMode Filter)) r
defaultFilter =
interpret \case
MenuFilter (FilterMode f ex) query job ->
embed (execute ex (matcher query f) job)
| |
0c8136d8757dc9da2b957366ecbe32b6eb3c41119aac1895698a44a3a1e558f8 | arttuka/reagent-material-ui | stacked_bar_chart_outlined.cljs | (ns reagent-mui.icons.stacked-bar-chart-outlined
"Imports @mui/icons-material/StackedBarChartOutlined as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def stacked-bar-chart-outlined (create-svg-icon (e "path" #js {"d" "M4 9h4v11H4zm0-5h4v4H4zm6 3h4v4h-4zm6 3h4v4h-4zm0 5h4v5h-4zm-6-3h4v8h-4z"})
"StackedBarChartOutlined"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/stacked_bar_chart_outlined.cljs | clojure | (ns reagent-mui.icons.stacked-bar-chart-outlined
"Imports @mui/icons-material/StackedBarChartOutlined as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def stacked-bar-chart-outlined (create-svg-icon (e "path" #js {"d" "M4 9h4v11H4zm0-5h4v4H4zm6 3h4v4h-4zm6 3h4v4h-4zm0 5h4v5h-4zm-6-3h4v8h-4z"})
"StackedBarChartOutlined"))
| |
7dac567e23e9e4ab19b6c1f93b38c725e00013dec421015254f98732e10b9973 | OlivierSohn/hamazed | Drawable.hs | {-# OPTIONS_HADDOCK hide #-}
# LANGUAGE NoImplicitPrelude #
module Imj.Graphics.Class.Drawable
( Drawable(..)
*
, Draw, MonadReader
) where
import Imj.Prelude
import Imj.Graphics.Class.Draw
import Control.Monad.Reader.Class(MonadReader)
-- | A 'Drawable' is a graphical element that knows how to draw itself
-- (it knows its color and position).
class Drawable a where
| Draw the ' Drawable '
draw :: (Draw e, MonadReader e m, MonadIO m)
=> a -> m ()
| null | https://raw.githubusercontent.com/OlivierSohn/hamazed/c0df1bb60a8538ac75e413d2f5bf0bf050e5bc37/imj-base/src/Imj/Graphics/Class/Drawable.hs | haskell | # OPTIONS_HADDOCK hide #
| A 'Drawable' is a graphical element that knows how to draw itself
(it knows its color and position). |
# LANGUAGE NoImplicitPrelude #
module Imj.Graphics.Class.Drawable
( Drawable(..)
*
, Draw, MonadReader
) where
import Imj.Prelude
import Imj.Graphics.Class.Draw
import Control.Monad.Reader.Class(MonadReader)
class Drawable a where
| Draw the ' Drawable '
draw :: (Draw e, MonadReader e m, MonadIO m)
=> a -> m ()
|
5292241c9b97320f03a16217f32bed69310faf9961f7e20234b25ed6c00ae561 | cse-bristol/110-thermos-ui | network_model.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.spreadsheet.network-model
"Functions to output network model data into a spreadsheet"
(:require [thermos-backend.spreadsheet.common :as sheet]
[thermos-specs.document :as document]
[thermos-specs.candidate :as candidate]
[thermos-specs.demand :as demand]
[thermos-specs.tariff :as tariff]
[thermos-specs.solution :as solution]
[thermos-specs.path :as path]
[thermos-specs.supply :as supply]
[thermos-util.pipes :as pipes]
[thermos-specs.measure :as measure]
[clojure.set :as set]
[thermos-backend.spreadsheet.common :as common]
[thermos-util.solution-summary :as solution-summary]))
(def *100 (partial * 100.0))
(defn or-zero [f] (fn [x] (or (f x) 0.0)))
(defn cost-columns [type prefix key]
(case type
:capex
[{:name (str prefix " (principal, ¤)") :key (comp :principal key)}
{:name (str prefix " (NPV, ¤)") :key (comp :present key)}
{:name (str prefix " (total, ¤)") :key (comp :total key)}]
:opex
[{:name (str prefix " (¤/yr)") :key (comp :annual key)}
{:name (str prefix " (NPV, ¤)") :key (comp :present key)}
{:name (str prefix " (total, ¤)") :key (comp :total key)}]
:emission
[{:name (str prefix " (kg/yr)") :key (comp :kg key)}
{:name (str prefix " (¤/yr)") :key (comp :annual key)}
{:name (str prefix " (NPV ¤)") :key (comp :present key)}
{:name (str prefix " (total ¤)") :key (comp :total key)}]
)
)
(defn candidate-columns [doc]
(into [{ :name "ID" :key ::candidate/id}
{ :name "Constraint" :key (comp name ::candidate/inclusion) }]
(for [user-field
(sort (set (mapcat (comp keys ::candidate/user-fields)
(vals (::document/candidates doc)))))]
{:name user-field
:key (fn [x] (get (::candidate/user-fields x) user-field))})))
(defn building-columns [doc]
(let [mode (document/mode doc)
peak-demand #(candidate/solved-peak-demand % mode)
annual-demand #(candidate/solved-annual-demand % mode)
]
(concat
(candidate-columns doc)
[{ :name "Annual demand (kWh)" :key annual-demand :format :double}
{ :name "Peak demand (kW)" :key peak-demand :format :double}
{ :name "Demand model" :key ::demand/source}
{ :name "Tariff name"
:key #(let [name (document/tariff-name doc (::tariff/id %))
is-market (= :market (::tariff/id %))
has-market-value (::solution/market-rate %)]
(if (and is-market has-market-value)
(str name " (" (*100 has-market-value) " c/kWh)")
name))}
{ :name "Connection cost name"
:key #(document/connection-cost-name doc (::tariff/cc-id %))}
])))
(defn output-buildings [ss doc]
(let [buildings (filter candidate/is-building? (vals (::document/candidates doc)))
base-cols (building-columns doc)]
(if (document/has-solution? doc)
(let [networked-buildings (filter candidate/is-connected? buildings)
non-networked-buildings (remove candidate/is-connected? buildings)
supply-buildings (filter candidate/has-supply? buildings)
]
(-> ss
(sheet/add-tab
"Networked buildings"
(concat
base-cols
(cost-columns :opex "Revenue" ::solution/heat-revenue)
(cost-columns :capex "Connection cost" ::solution/connection-capex))
networked-buildings)
(sheet/add-tab
"Other buildings"
(concat
base-cols
[{:name "Heating system" :key candidate/solution-description}]
(cost-columns :capex "System capex" (comp :capex ::solution/alternative))
(cost-columns :opex "System opex" (comp :opex ::solution/alternative))
(cost-columns :opex "System fuel" (comp :heat-cost ::solution/alternative))
(apply concat
(for [e candidate/emissions-types]
(cost-columns
:emission
(candidate/text-emissions-labels e)
(comp e :emissions ::solution/alternative)))))
non-networked-buildings
)
(sheet/add-tab
"Supply points"
(concat
base-cols
[{:name "Maximum capacity (kW)" :key ::supply/capacity-kwp}
{:name "Heat price (c/kWh)" :key (comp *100 ::supply/cost-per-kwh)}
{:name "Fixed capital cost (¤)" :key ::supply/fixed-cost}
{:name "Capital cost (¤/kWp)" :key ::supply/capex-per-kwp}
{:name "Operating cost (¤/kWp)" :key ::supply/opex-per-kwp}
{:name "Installed capacity (kW)" :key ::solution/capacity-kw}
{:name "Coincidence" :key ::solution/diversity}
{:name "Annual output (kWh/yr)" :key ::solution/output-kwh}
]
(cost-columns :capex "Plant capex" ::solution/supply-capex)
(cost-columns :opex "Heat cost" ::solution/heat-cost)
(apply concat
(for [e candidate/emissions-types]
(cost-columns
:emission
(str "Plant " (candidate/text-emissions-labels e))
(comp e ::solution/supply-emissions))))
[{:name "Pumping kWh" :key ::solution/pumping-kwh}]
(cost-columns :opex "Pumping cost" ::solution/pumping-cost)
(apply concat
(for [e candidate/emissions-types]
(cost-columns
:emission
(str "Pumping " (candidate/text-emissions-labels e))
(comp e ::solution/pumping-emissions))))
)
supply-buildings)
))
(sheet/add-tab
ss "Buildings"
base-cols
buildings)
)))
(defn output-pipe-costs [ss doc]
(let [pipe-costs (::document/pipe-costs doc)
civils (:civils pipe-costs)
curve-rows (pipes/curve-rows (pipes/curves doc))
]
(sheet/add-tab
ss
"Pipe costs"
(into
[{:name "NB (mm)" :key (comp (partial * 1000.0) :diameter)}
{:name "Capacity (kW)" :key :capacity-kw}
{:name "Losses (kWh/m.yr)" :key :losses-kwh}
{:name "Pipe cost (¤/m)" :key :pipe}]
(for [[id n] civils]
{:name (str n " (¤/m)") :key #(get % id)}))
curve-rows
)))
(def capital-cost-names
"Used to output keys from ::document/capital-costs"
{:alternative "Other heating"
:connection "Connections"
:insulation "Insulation"
:supply "Supply"
:pipework "Pipework"})
(defn output-network-parameters [ss doc]
(-> ss
(sheet/add-tab
"Tariffs"
[{:name "Tariff name" :key ::tariff/name}
{:name "Unit rate (c/¤)" :key (comp *100 (or-zero ::tariff/unit-charge))}
{:name "Capacity charge (¤/kWp)" :key (or-zero ::tariff/capacity-charge)}
{:name "Standing charge (¤)" :key (or-zero ::tariff/standing-charge)}]
(vals (::document/tariffs doc)))
(sheet/add-tab
"Connection costs"
[{:name "Cost name" :key ::tariff/name}
{:name "Fixed cost (¤)" :key (or-zero ::tariff/fixed-connection-cost)}
{:name "Capacity cost (¤/kWp)" :key (or-zero ::tariff/variable-connection-cost)}]
(vals (::document/connection-costs doc)))
(sheet/add-tab
"Individual systems"
(into
[{:name "Name" :key ::supply/name}
{:name "Fixed cost (¤)" :key (or-zero ::supply/fixed-cost)}
{:name "Capacity cost (¤/kWp)" :key (or-zero ::supply/capex-per-kwp)}
{:name "Operating cost (¤/kWp.yr)" :key (or-zero ::supply/opex-per-kwp)}
{:name "Heat price (c/kWh)" :key (comp *100 (or-zero ::supply/cost-per-kwh))}
{:name "Tank factor" :key ::supply/kwp-per-mean-kw}
]
(for [e candidate/emissions-types]
{:name (str (candidate/text-emissions-labels e)
" ("
(candidate/emissions-factor-units e)
")")
:key (comp (partial * (candidate/emissions-factor-scales e))
#(e % 0) ::supply/emissions)}
))
(vals (::document/alternatives doc)))
(sheet/add-tab
"Insulation"
[{:name "Name" :key ::measure/name}
{:name "Fixed cost" :key (or-zero ::measure/fixed-cost)}
{:name "Cost / m2" :key (or-zero ::measure/cost-per-m2)}
{:name "Maximum reduction %" :key (comp *100 (or-zero ::measure/maximum-effect))}
{:name "Maximum area %" :key (comp *100 (or-zero ::measure/maximum-area))}
{:name "Surface" :key (comp name ::measure/surface)}]
(vals (::document/insulation doc)))
(output-pipe-costs doc)
(sheet/add-tab
"Capital costs"
[{:name "Name" :key (comp capital-cost-names first)}
{:name "Annualize" :key (comp boolean :annualize second)}
{:name "Recur" :key (comp boolean :recur second)}
{:name "Period (years)" :key #(int (:period (second %) 0))}
{:name "Rate (%)" :key #(* 100 (:rate (second %) 0))}]
(::document/capital-costs doc))
(sheet/add-tab
"Other parameters"
[{:name "Parameter" :key first}
{:name "Value" :key second}]
`[~["Medium" (name (document/medium doc))]
~@(if (= :hot-water (document/medium doc))
[["Flow temperature" (::document/flow-temperature doc)]
["Return temperature" (::document/return-temperature doc)]
["Ground temperature" (::document/ground-temperature doc)]]
[["Steam pressure (MPa)" (document/steam-pressure doc)]
["Steam velocity (m/s)" (document/steam-velocity doc)]])
~["Pumping overhead" (*100 (::document/pumping-overhead doc 0))]
~["Pumping cost/kWh" (::document/pumping-cost-per-kwh doc 0)]
~["Default civil cost" (let [pc (-> doc ::document/pipe-costs)
id (:default-civils pc)]
(get (:civils pc) id "none"))]
~@(for [[e f] (::document/pumping-emissions doc)]
[(str "Pumping "
(candidate/text-emissions-labels e)
" ("
(candidate/emissions-factor-units e)
")")
(* (or f 0) (candidate/emissions-factor-scales e))])
~@(let [prices (::document/emissions-cost doc)]
(for [e candidate/emissions-types
:let [cost (get prices e)]
:when cost]
[(str (candidate/text-emissions-labels e) " cost") cost]))
~@(let [limits (::document/emissions-limit doc)]
(for [e candidate/emissions-types
:let [{:keys [value enabled]} (get limits e )]]
[(str (candidate/text-emissions-labels e) " limit")
(if enabled value "none")]))
~["Objective" (name (::document/objective doc))]
~["Consider alternative systems" (::document/consider-alternatives doc)]
~["Consider insulation" (::document/consider-insulation doc)]
~["NPV Term" (::document/npv-term doc)]
~["NPV Rate" (*100 (::document/npv-rate doc))]
~["Loan Term" (::document/loan-term doc)]
~["Loan Rate" (*100 (::document/loan-rate doc))]
~["MIP Gap" (::document/mip-gap doc)]
~["Param Gap" (::document/param-gap doc)]
~["Max runtime" (::document/maximum-runtime doc)]
~["Max supplies" (::document/maximum-supply-sites
doc
"unlimited")]
]
)
)
)
(defn output-paths [ss doc]
(sheet/add-tab
ss "Paths & pipes"
(concat
(candidate-columns doc)
[{ :name "Length" :key ::path/length}
{ :name "Civils" :key #(document/civil-cost-name doc (::path/civil-cost-id %)) }
{ :name "Exists" :key ::path/exists }]
(when (document/has-solution? doc)
(concat
[{:name "In solution" :key ::solution/included}
{:name "Diameter (mm)" :key ::solution/diameter-mm}
{:name "Capacity (kW)" :key ::solution/capacity-kw}
{:name "Losses (kWh/yr)" :key ::solution/losses-kwh}
{:name "Coincidence" :key ::solution/diversity}
]
(cost-columns :capex "Capital cost" ::solution/pipe-capex)
)))
(filter candidate/is-path? (vals (::document/candidates doc)))))
(defn output-solution-summary [ss doc]
(if (document/has-solution? doc)
(let [{:keys [rows grand-total]} (solution-summary/data-table doc :total :total)]
(sheet/add-tab
ss
"Network solution summary"
[{:name "Item" :key :name}
{:name "Capital cost (¤)" :key :capex}
{:name "Operating cost (¤)" :key :opex}
{:name "Operating revenue (¤)" :key :revenue}
{:name "EC (c/kWh)" :key :equivalized-cost}
{:name "NPV (¤)" :key :present}]
(flatten
(concat
(for [{:keys [name subcategories total]} rows]
(concat
(for [{sub-name :name value :value} subcategories]
(assoc value :name sub-name))
[(assoc total :name name)]
[{}])) ; Add an empty row between categories
[{:name "Whole system"
:capex (:capex grand-total)
:opex (:opex grand-total)
:present (:present grand-total)}]))))
ss))
(defn output-to-spreadsheet [ss doc]
(-> ss
(output-buildings doc)
(output-paths doc)
(output-network-parameters doc)
(output-solution-summary doc)
))
(defn input-from-spreadsheet
"Inverse function - takes a spreadsheet, as loaded by `common/read-to-tables`.
So far this ignores everything to do with candidates.
Assumes validation has happened already."
[ss]
(let [{:keys [tariffs
connection-costs
individual-systems
pipe-costs
insulation
other-parameters
capital-costs]} ss
parameters
(reduce
(fn [a {:keys [parameter value]}]
(assoc a (common/to-keyword parameter) value))
{} (:rows other-parameters))
copy-parameter
(fn [out-key in-key & {:keys [type convert]
:or {type number? convert identity}}]
(when-let [v (get parameters out-key)] (when (type v) {in-key (convert v)})))
bool-or-num?
(fn [x] (or (number? x) (boolean? x)))
bool-or-num-to-bool
(fn [x] (or (and (boolean? x) x)
(boolean (not (zero? x)))))
]
(merge
(copy-parameter :medium ::document/medium :type #{"hot-water" "saturated-steam"}
:convert keyword)
(copy-parameter :flow-temperature ::document/flow-temperature)
(copy-parameter :return-temperature ::document/return-temperature)
(copy-parameter :ground-temperature ::document/ground-temperature)
(copy-parameter :steam-pressure ::document/steam-pressure)
(copy-parameter :steam-velocity ::document/steam-velocity)
(copy-parameter :pumping-overhead ::document/pumping-overhead)
(copy-parameter :pumping-cost-per-kwh ::document/pumping-cost-per-kwh)
(copy-parameter :objective ::document/objective
:type #{"network" "system"}
:convert keyword)
(copy-parameter :consider-alternative-systems
::document/consider-alternatives
:type bool-or-num?
:convert bool-or-num-to-bool
)
(copy-parameter :consider-insulation
::document/consider-insulation
:type bool-or-num?
:convert bool-or-num-to-bool
)
(copy-parameter :npv-term ::document/npv-term)
(copy-parameter :npv-rate ::document/npv-rate
:type number? :convert #(/ % 100.0))
(copy-parameter :loan-term ::document/loan-term)
(copy-parameter :loan-rate ::document/loan-rate
:type number? :convert #(/ % 100.0))
(copy-parameter :mip-gap ::document/mip-gap)
(copy-parameter :param-gap ::document/param-gap)
(copy-parameter :max-runtime ::document/maximum-runtime)
(copy-parameter :max-supplies ::document/maximum-supply-sites
:type number?
:convert int)
{::document/capital-costs
(let [capital-cost-names (set/map-invert capital-cost-names)]
(->> (for [{:keys [name annualize recur period rate]
:or {recur false annualize false period 0 rate 0}}
(:rows capital-costs)
:let [name (get capital-cost-names name)]
:when name]
[name
{:annualize (boolean annualize)
:recur (boolean recur)
:period (int (or period 0))
:rate (/ (or rate 0) 100)}])
(into {})))}
{::document/pumping-emissions
(->>
(for [e candidate/emissions-types
:let [v (get parameters (common/to-keyword (str "pumping-" (name e))))]]
[e (if (number? v) (/ v (candidate/emissions-factor-scales e)) 0)])
(into {}))}
{::document/emissions-cost
(->>
(for [e candidate/emissions-types
:let [c (get parameters (common/to-keyword (str (name e) "-cost")))]]
[e (if (number? c) c 0)])
(into {}))}
{::document/emissions-limit
(->>
(for [e candidate/emissions-types
:let [c (get parameters (common/to-keyword (str (name e) "-limit")))]]
[e (if (number? c) {:enabled true :value c} {:enabled false :value nil})])
(into {}))
}
{::document/tariffs
(-> (for [{:keys [tariff-name unit-rate capacity-charge standing-charge]}
(:rows tariffs)]
#::tariff
{:name tariff-name
:standing-charge standing-charge
:unit-charge (/ unit-rate 100)
:capacity-charge capacity-charge})
(common/index ::tariff/id))
::document/connection-costs
(-> (for [{:keys [cost-name fixed-cost capacity-cost]}
(:rows connection-costs)]
#::tariff
{:name cost-name
:fixed-connection-cost fixed-cost
:variable-connection-cost capacity-cost})
(common/index ::tariff/cc-id))
::document/alternatives
(-> (for [{:keys [name fixed-cost capacity-cost operating-cost heat-price
co2 pm25 nox tank-factor]
}
(:rows individual-systems)]
#::supply
{:name name
:cost-per-kwh (/ heat-price 100.0)
:capex-per-kwp capacity-cost
:opex-per-kwp operating-cost
:fixed-cost fixed-cost
:kwp-per-mean-kw tank-factor
:emissions
{:co2 (/ (or co2 0.0) (candidate/emissions-factor-scales :co2))
:pm25 (/ (or pm25 0.0) (candidate/emissions-factor-scales :pm25))
:nox (/ (or nox 0.0) (candidate/emissions-factor-scales :nox))}})
(common/index ::supply/id))
::document/insulation
(-> (for [{:keys [name fixed-cost cost-per-m2
maximum-reduction-% maximum-area-%
surface]}
(:rows insulation)]
#::measure
{:name name
:fixed-cost fixed-cost
:cost-per-m2 cost-per-m2
:maximum-effect (/ maximum-reduction-% 100.0)
:maximum-area (/ maximum-area-% 100.0)
:surface (keyword surface)})
(common/index ::measure/id))
::document/pipe-costs
(let [civils-keys (-> (:header pipe-costs)
(dissoc :nb :capacity :losses :pipe-cost))
civils-ids (common/index (set (vals civils-keys)))
inverse (set/map-invert civils-ids)
civils-keys* (->> (for [[kwd s] civils-keys] [kwd (inverse s)])
(into {}))
default-civils (get inverse
(get parameters :default-civil-cost))
]
{:civils civils-ids
:default-civils default-civils
:rows
(->>
(for [row (:rows pipe-costs)]
[(:nb row)
(let [basics
(cond-> {:pipe (:pipe-cost row 0)}
(:capacity row) (assoc :capacity-kw (:capacity row))
(:losses row) (assoc :losses-kwh (:losses row)))]
(reduce-kv
(fn [a civ-key civ-id]
(let [cost (get row civ-key 0)]
(cond-> a
cost (assoc civ-id cost))))
basics
civils-keys*))])
(into {}))})})))
| null | https://raw.githubusercontent.com/cse-bristol/110-thermos-ui/729c0a279dba40b6d1a49bc485c968569741e915/src/thermos_backend/spreadsheet/network_model.clj | clojure | Add an empty row between categories | 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.spreadsheet.network-model
"Functions to output network model data into a spreadsheet"
(:require [thermos-backend.spreadsheet.common :as sheet]
[thermos-specs.document :as document]
[thermos-specs.candidate :as candidate]
[thermos-specs.demand :as demand]
[thermos-specs.tariff :as tariff]
[thermos-specs.solution :as solution]
[thermos-specs.path :as path]
[thermos-specs.supply :as supply]
[thermos-util.pipes :as pipes]
[thermos-specs.measure :as measure]
[clojure.set :as set]
[thermos-backend.spreadsheet.common :as common]
[thermos-util.solution-summary :as solution-summary]))
(def *100 (partial * 100.0))
(defn or-zero [f] (fn [x] (or (f x) 0.0)))
(defn cost-columns [type prefix key]
(case type
:capex
[{:name (str prefix " (principal, ¤)") :key (comp :principal key)}
{:name (str prefix " (NPV, ¤)") :key (comp :present key)}
{:name (str prefix " (total, ¤)") :key (comp :total key)}]
:opex
[{:name (str prefix " (¤/yr)") :key (comp :annual key)}
{:name (str prefix " (NPV, ¤)") :key (comp :present key)}
{:name (str prefix " (total, ¤)") :key (comp :total key)}]
:emission
[{:name (str prefix " (kg/yr)") :key (comp :kg key)}
{:name (str prefix " (¤/yr)") :key (comp :annual key)}
{:name (str prefix " (NPV ¤)") :key (comp :present key)}
{:name (str prefix " (total ¤)") :key (comp :total key)}]
)
)
(defn candidate-columns [doc]
(into [{ :name "ID" :key ::candidate/id}
{ :name "Constraint" :key (comp name ::candidate/inclusion) }]
(for [user-field
(sort (set (mapcat (comp keys ::candidate/user-fields)
(vals (::document/candidates doc)))))]
{:name user-field
:key (fn [x] (get (::candidate/user-fields x) user-field))})))
(defn building-columns [doc]
(let [mode (document/mode doc)
peak-demand #(candidate/solved-peak-demand % mode)
annual-demand #(candidate/solved-annual-demand % mode)
]
(concat
(candidate-columns doc)
[{ :name "Annual demand (kWh)" :key annual-demand :format :double}
{ :name "Peak demand (kW)" :key peak-demand :format :double}
{ :name "Demand model" :key ::demand/source}
{ :name "Tariff name"
:key #(let [name (document/tariff-name doc (::tariff/id %))
is-market (= :market (::tariff/id %))
has-market-value (::solution/market-rate %)]
(if (and is-market has-market-value)
(str name " (" (*100 has-market-value) " c/kWh)")
name))}
{ :name "Connection cost name"
:key #(document/connection-cost-name doc (::tariff/cc-id %))}
])))
(defn output-buildings [ss doc]
(let [buildings (filter candidate/is-building? (vals (::document/candidates doc)))
base-cols (building-columns doc)]
(if (document/has-solution? doc)
(let [networked-buildings (filter candidate/is-connected? buildings)
non-networked-buildings (remove candidate/is-connected? buildings)
supply-buildings (filter candidate/has-supply? buildings)
]
(-> ss
(sheet/add-tab
"Networked buildings"
(concat
base-cols
(cost-columns :opex "Revenue" ::solution/heat-revenue)
(cost-columns :capex "Connection cost" ::solution/connection-capex))
networked-buildings)
(sheet/add-tab
"Other buildings"
(concat
base-cols
[{:name "Heating system" :key candidate/solution-description}]
(cost-columns :capex "System capex" (comp :capex ::solution/alternative))
(cost-columns :opex "System opex" (comp :opex ::solution/alternative))
(cost-columns :opex "System fuel" (comp :heat-cost ::solution/alternative))
(apply concat
(for [e candidate/emissions-types]
(cost-columns
:emission
(candidate/text-emissions-labels e)
(comp e :emissions ::solution/alternative)))))
non-networked-buildings
)
(sheet/add-tab
"Supply points"
(concat
base-cols
[{:name "Maximum capacity (kW)" :key ::supply/capacity-kwp}
{:name "Heat price (c/kWh)" :key (comp *100 ::supply/cost-per-kwh)}
{:name "Fixed capital cost (¤)" :key ::supply/fixed-cost}
{:name "Capital cost (¤/kWp)" :key ::supply/capex-per-kwp}
{:name "Operating cost (¤/kWp)" :key ::supply/opex-per-kwp}
{:name "Installed capacity (kW)" :key ::solution/capacity-kw}
{:name "Coincidence" :key ::solution/diversity}
{:name "Annual output (kWh/yr)" :key ::solution/output-kwh}
]
(cost-columns :capex "Plant capex" ::solution/supply-capex)
(cost-columns :opex "Heat cost" ::solution/heat-cost)
(apply concat
(for [e candidate/emissions-types]
(cost-columns
:emission
(str "Plant " (candidate/text-emissions-labels e))
(comp e ::solution/supply-emissions))))
[{:name "Pumping kWh" :key ::solution/pumping-kwh}]
(cost-columns :opex "Pumping cost" ::solution/pumping-cost)
(apply concat
(for [e candidate/emissions-types]
(cost-columns
:emission
(str "Pumping " (candidate/text-emissions-labels e))
(comp e ::solution/pumping-emissions))))
)
supply-buildings)
))
(sheet/add-tab
ss "Buildings"
base-cols
buildings)
)))
(defn output-pipe-costs [ss doc]
(let [pipe-costs (::document/pipe-costs doc)
civils (:civils pipe-costs)
curve-rows (pipes/curve-rows (pipes/curves doc))
]
(sheet/add-tab
ss
"Pipe costs"
(into
[{:name "NB (mm)" :key (comp (partial * 1000.0) :diameter)}
{:name "Capacity (kW)" :key :capacity-kw}
{:name "Losses (kWh/m.yr)" :key :losses-kwh}
{:name "Pipe cost (¤/m)" :key :pipe}]
(for [[id n] civils]
{:name (str n " (¤/m)") :key #(get % id)}))
curve-rows
)))
(def capital-cost-names
"Used to output keys from ::document/capital-costs"
{:alternative "Other heating"
:connection "Connections"
:insulation "Insulation"
:supply "Supply"
:pipework "Pipework"})
(defn output-network-parameters [ss doc]
(-> ss
(sheet/add-tab
"Tariffs"
[{:name "Tariff name" :key ::tariff/name}
{:name "Unit rate (c/¤)" :key (comp *100 (or-zero ::tariff/unit-charge))}
{:name "Capacity charge (¤/kWp)" :key (or-zero ::tariff/capacity-charge)}
{:name "Standing charge (¤)" :key (or-zero ::tariff/standing-charge)}]
(vals (::document/tariffs doc)))
(sheet/add-tab
"Connection costs"
[{:name "Cost name" :key ::tariff/name}
{:name "Fixed cost (¤)" :key (or-zero ::tariff/fixed-connection-cost)}
{:name "Capacity cost (¤/kWp)" :key (or-zero ::tariff/variable-connection-cost)}]
(vals (::document/connection-costs doc)))
(sheet/add-tab
"Individual systems"
(into
[{:name "Name" :key ::supply/name}
{:name "Fixed cost (¤)" :key (or-zero ::supply/fixed-cost)}
{:name "Capacity cost (¤/kWp)" :key (or-zero ::supply/capex-per-kwp)}
{:name "Operating cost (¤/kWp.yr)" :key (or-zero ::supply/opex-per-kwp)}
{:name "Heat price (c/kWh)" :key (comp *100 (or-zero ::supply/cost-per-kwh))}
{:name "Tank factor" :key ::supply/kwp-per-mean-kw}
]
(for [e candidate/emissions-types]
{:name (str (candidate/text-emissions-labels e)
" ("
(candidate/emissions-factor-units e)
")")
:key (comp (partial * (candidate/emissions-factor-scales e))
#(e % 0) ::supply/emissions)}
))
(vals (::document/alternatives doc)))
(sheet/add-tab
"Insulation"
[{:name "Name" :key ::measure/name}
{:name "Fixed cost" :key (or-zero ::measure/fixed-cost)}
{:name "Cost / m2" :key (or-zero ::measure/cost-per-m2)}
{:name "Maximum reduction %" :key (comp *100 (or-zero ::measure/maximum-effect))}
{:name "Maximum area %" :key (comp *100 (or-zero ::measure/maximum-area))}
{:name "Surface" :key (comp name ::measure/surface)}]
(vals (::document/insulation doc)))
(output-pipe-costs doc)
(sheet/add-tab
"Capital costs"
[{:name "Name" :key (comp capital-cost-names first)}
{:name "Annualize" :key (comp boolean :annualize second)}
{:name "Recur" :key (comp boolean :recur second)}
{:name "Period (years)" :key #(int (:period (second %) 0))}
{:name "Rate (%)" :key #(* 100 (:rate (second %) 0))}]
(::document/capital-costs doc))
(sheet/add-tab
"Other parameters"
[{:name "Parameter" :key first}
{:name "Value" :key second}]
`[~["Medium" (name (document/medium doc))]
~@(if (= :hot-water (document/medium doc))
[["Flow temperature" (::document/flow-temperature doc)]
["Return temperature" (::document/return-temperature doc)]
["Ground temperature" (::document/ground-temperature doc)]]
[["Steam pressure (MPa)" (document/steam-pressure doc)]
["Steam velocity (m/s)" (document/steam-velocity doc)]])
~["Pumping overhead" (*100 (::document/pumping-overhead doc 0))]
~["Pumping cost/kWh" (::document/pumping-cost-per-kwh doc 0)]
~["Default civil cost" (let [pc (-> doc ::document/pipe-costs)
id (:default-civils pc)]
(get (:civils pc) id "none"))]
~@(for [[e f] (::document/pumping-emissions doc)]
[(str "Pumping "
(candidate/text-emissions-labels e)
" ("
(candidate/emissions-factor-units e)
")")
(* (or f 0) (candidate/emissions-factor-scales e))])
~@(let [prices (::document/emissions-cost doc)]
(for [e candidate/emissions-types
:let [cost (get prices e)]
:when cost]
[(str (candidate/text-emissions-labels e) " cost") cost]))
~@(let [limits (::document/emissions-limit doc)]
(for [e candidate/emissions-types
:let [{:keys [value enabled]} (get limits e )]]
[(str (candidate/text-emissions-labels e) " limit")
(if enabled value "none")]))
~["Objective" (name (::document/objective doc))]
~["Consider alternative systems" (::document/consider-alternatives doc)]
~["Consider insulation" (::document/consider-insulation doc)]
~["NPV Term" (::document/npv-term doc)]
~["NPV Rate" (*100 (::document/npv-rate doc))]
~["Loan Term" (::document/loan-term doc)]
~["Loan Rate" (*100 (::document/loan-rate doc))]
~["MIP Gap" (::document/mip-gap doc)]
~["Param Gap" (::document/param-gap doc)]
~["Max runtime" (::document/maximum-runtime doc)]
~["Max supplies" (::document/maximum-supply-sites
doc
"unlimited")]
]
)
)
)
(defn output-paths [ss doc]
(sheet/add-tab
ss "Paths & pipes"
(concat
(candidate-columns doc)
[{ :name "Length" :key ::path/length}
{ :name "Civils" :key #(document/civil-cost-name doc (::path/civil-cost-id %)) }
{ :name "Exists" :key ::path/exists }]
(when (document/has-solution? doc)
(concat
[{:name "In solution" :key ::solution/included}
{:name "Diameter (mm)" :key ::solution/diameter-mm}
{:name "Capacity (kW)" :key ::solution/capacity-kw}
{:name "Losses (kWh/yr)" :key ::solution/losses-kwh}
{:name "Coincidence" :key ::solution/diversity}
]
(cost-columns :capex "Capital cost" ::solution/pipe-capex)
)))
(filter candidate/is-path? (vals (::document/candidates doc)))))
(defn output-solution-summary [ss doc]
(if (document/has-solution? doc)
(let [{:keys [rows grand-total]} (solution-summary/data-table doc :total :total)]
(sheet/add-tab
ss
"Network solution summary"
[{:name "Item" :key :name}
{:name "Capital cost (¤)" :key :capex}
{:name "Operating cost (¤)" :key :opex}
{:name "Operating revenue (¤)" :key :revenue}
{:name "EC (c/kWh)" :key :equivalized-cost}
{:name "NPV (¤)" :key :present}]
(flatten
(concat
(for [{:keys [name subcategories total]} rows]
(concat
(for [{sub-name :name value :value} subcategories]
(assoc value :name sub-name))
[(assoc total :name name)]
[{:name "Whole system"
:capex (:capex grand-total)
:opex (:opex grand-total)
:present (:present grand-total)}]))))
ss))
(defn output-to-spreadsheet [ss doc]
(-> ss
(output-buildings doc)
(output-paths doc)
(output-network-parameters doc)
(output-solution-summary doc)
))
(defn input-from-spreadsheet
"Inverse function - takes a spreadsheet, as loaded by `common/read-to-tables`.
So far this ignores everything to do with candidates.
Assumes validation has happened already."
[ss]
(let [{:keys [tariffs
connection-costs
individual-systems
pipe-costs
insulation
other-parameters
capital-costs]} ss
parameters
(reduce
(fn [a {:keys [parameter value]}]
(assoc a (common/to-keyword parameter) value))
{} (:rows other-parameters))
copy-parameter
(fn [out-key in-key & {:keys [type convert]
:or {type number? convert identity}}]
(when-let [v (get parameters out-key)] (when (type v) {in-key (convert v)})))
bool-or-num?
(fn [x] (or (number? x) (boolean? x)))
bool-or-num-to-bool
(fn [x] (or (and (boolean? x) x)
(boolean (not (zero? x)))))
]
(merge
(copy-parameter :medium ::document/medium :type #{"hot-water" "saturated-steam"}
:convert keyword)
(copy-parameter :flow-temperature ::document/flow-temperature)
(copy-parameter :return-temperature ::document/return-temperature)
(copy-parameter :ground-temperature ::document/ground-temperature)
(copy-parameter :steam-pressure ::document/steam-pressure)
(copy-parameter :steam-velocity ::document/steam-velocity)
(copy-parameter :pumping-overhead ::document/pumping-overhead)
(copy-parameter :pumping-cost-per-kwh ::document/pumping-cost-per-kwh)
(copy-parameter :objective ::document/objective
:type #{"network" "system"}
:convert keyword)
(copy-parameter :consider-alternative-systems
::document/consider-alternatives
:type bool-or-num?
:convert bool-or-num-to-bool
)
(copy-parameter :consider-insulation
::document/consider-insulation
:type bool-or-num?
:convert bool-or-num-to-bool
)
(copy-parameter :npv-term ::document/npv-term)
(copy-parameter :npv-rate ::document/npv-rate
:type number? :convert #(/ % 100.0))
(copy-parameter :loan-term ::document/loan-term)
(copy-parameter :loan-rate ::document/loan-rate
:type number? :convert #(/ % 100.0))
(copy-parameter :mip-gap ::document/mip-gap)
(copy-parameter :param-gap ::document/param-gap)
(copy-parameter :max-runtime ::document/maximum-runtime)
(copy-parameter :max-supplies ::document/maximum-supply-sites
:type number?
:convert int)
{::document/capital-costs
(let [capital-cost-names (set/map-invert capital-cost-names)]
(->> (for [{:keys [name annualize recur period rate]
:or {recur false annualize false period 0 rate 0}}
(:rows capital-costs)
:let [name (get capital-cost-names name)]
:when name]
[name
{:annualize (boolean annualize)
:recur (boolean recur)
:period (int (or period 0))
:rate (/ (or rate 0) 100)}])
(into {})))}
{::document/pumping-emissions
(->>
(for [e candidate/emissions-types
:let [v (get parameters (common/to-keyword (str "pumping-" (name e))))]]
[e (if (number? v) (/ v (candidate/emissions-factor-scales e)) 0)])
(into {}))}
{::document/emissions-cost
(->>
(for [e candidate/emissions-types
:let [c (get parameters (common/to-keyword (str (name e) "-cost")))]]
[e (if (number? c) c 0)])
(into {}))}
{::document/emissions-limit
(->>
(for [e candidate/emissions-types
:let [c (get parameters (common/to-keyword (str (name e) "-limit")))]]
[e (if (number? c) {:enabled true :value c} {:enabled false :value nil})])
(into {}))
}
{::document/tariffs
(-> (for [{:keys [tariff-name unit-rate capacity-charge standing-charge]}
(:rows tariffs)]
#::tariff
{:name tariff-name
:standing-charge standing-charge
:unit-charge (/ unit-rate 100)
:capacity-charge capacity-charge})
(common/index ::tariff/id))
::document/connection-costs
(-> (for [{:keys [cost-name fixed-cost capacity-cost]}
(:rows connection-costs)]
#::tariff
{:name cost-name
:fixed-connection-cost fixed-cost
:variable-connection-cost capacity-cost})
(common/index ::tariff/cc-id))
::document/alternatives
(-> (for [{:keys [name fixed-cost capacity-cost operating-cost heat-price
co2 pm25 nox tank-factor]
}
(:rows individual-systems)]
#::supply
{:name name
:cost-per-kwh (/ heat-price 100.0)
:capex-per-kwp capacity-cost
:opex-per-kwp operating-cost
:fixed-cost fixed-cost
:kwp-per-mean-kw tank-factor
:emissions
{:co2 (/ (or co2 0.0) (candidate/emissions-factor-scales :co2))
:pm25 (/ (or pm25 0.0) (candidate/emissions-factor-scales :pm25))
:nox (/ (or nox 0.0) (candidate/emissions-factor-scales :nox))}})
(common/index ::supply/id))
::document/insulation
(-> (for [{:keys [name fixed-cost cost-per-m2
maximum-reduction-% maximum-area-%
surface]}
(:rows insulation)]
#::measure
{:name name
:fixed-cost fixed-cost
:cost-per-m2 cost-per-m2
:maximum-effect (/ maximum-reduction-% 100.0)
:maximum-area (/ maximum-area-% 100.0)
:surface (keyword surface)})
(common/index ::measure/id))
::document/pipe-costs
(let [civils-keys (-> (:header pipe-costs)
(dissoc :nb :capacity :losses :pipe-cost))
civils-ids (common/index (set (vals civils-keys)))
inverse (set/map-invert civils-ids)
civils-keys* (->> (for [[kwd s] civils-keys] [kwd (inverse s)])
(into {}))
default-civils (get inverse
(get parameters :default-civil-cost))
]
{:civils civils-ids
:default-civils default-civils
:rows
(->>
(for [row (:rows pipe-costs)]
[(:nb row)
(let [basics
(cond-> {:pipe (:pipe-cost row 0)}
(:capacity row) (assoc :capacity-kw (:capacity row))
(:losses row) (assoc :losses-kwh (:losses row)))]
(reduce-kv
(fn [a civ-key civ-id]
(let [cost (get row civ-key 0)]
(cond-> a
cost (assoc civ-id cost))))
basics
civils-keys*))])
(into {}))})})))
|
1426df613d6400e80eb35535387915b5cff4dbf9787590ea1db31324c5fe274c | dgtized/shimmers | space_colonization.cljc | (ns shimmers.algorithm.space-colonization
(:require
[clojure.set :as set]
[shimmers.math.deterministic-random :as dr]
[shimmers.math.vector :as v]
[thi.ng.geom.core :as g]
[thi.ng.geom.spatialtree :as spatialtree]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
;; Ideas:
;; * attractors could have influence PER attractor instead of global, or a weight on their influence?
* some implementations have a branching likelyhood , or can just experiment with only creating one leaf per branch per cycle ?
- using distinct on closest branch kinda does this , but looks odd , maybe ( take 2 ) of each unique branch or only N per iteration ?
;; - need kd-tree, or voronoi for faster "closest" lookups
;; * build up an initial trunk if no attractors are in range?
;; * add more weight to roots of the tree
;; * improve rules for detecting steady state completion
;; * grow to fit shapes or other distributions of attractors
(defrecord Branch [parent position])
(defn grow-branch [{:keys [position]} parent-idx direction length]
(->Branch parent-idx (tm/+ position (tm/normalize direction length))))
(defn branch-distance [attractor branch]
(g/dist attractor (:position branch)))
(defn influenced-branches [quadtree radius position]
(spatialtree/select-with-circle quadtree position radius))
(defn close-to-branch? [quadtree radius position]
(spatialtree/points-in-circle? quadtree position radius))
(defn closest-branch [attractor branches]
(apply min-key (partial branch-distance attractor) branches))
(defn average-attraction
[{:keys [position]} attractors snap-theta jitter]
(-> (reduce (fn [acc attractor]
(tm/+ acc (tm/normalize (tm/- attractor position))))
jitter attractors)
tm/normalize
(v/snap-to snap-theta)))
;; Approach borrowed from
;; -space-colonization-experiments/blob/master/core/Network.js#L108-L114
(defn propagate-branch-weight [weights branches branch]
(if-let [parent-idx (:parent branch)]
(let [parent (nth branches parent-idx)
current-weight (get weights branch)]
(recur (update weights parent
(fn [parent-weight]
(if (< parent-weight (+ current-weight 0.1))
(+ parent-weight 0.01)
parent-weight)))
branches
parent))
weights))
(defn update-weights [weights branches growth]
(reduce-kv
(fn [weights _ bud]
(propagate-branch-weight (assoc weights bud 0.05) branches bud))
weights growth))
(defn add-branch-positions [quadtree branches]
;; CAUTION: if add-point fails the return value is nil. I believe
this happens if point is out of bounds of the quadtree but we
;; can recover as those branches should never be within an
;; attractors range.q
(reduce (fn [tree branch]
(if-let [tree' (g/add-point tree (:position branch) branch)]
tree' tree))
quadtree
branches))
(defn influencing-attractors [{:keys [quadtree influence-distance attractors]}]
(apply merge-with set/union
(for [attractor attractors
:let [influences (influenced-branches quadtree influence-distance attractor)]
:when (seq influences)]
{(closest-branch attractor influences) #{attractor}})))
(defn grow-branches
[{:keys [segment-distance snap-theta jitter branches]} influencers]
(let [branch-index (->> branches
(map-indexed (fn [idx branch] {branch idx}))
(into {}))]
(for [[branch attractors] influencers]
(grow-branch branch (get branch-index branch)
(average-attraction branch attractors snap-theta (jitter))
segment-distance))))
(defn grow-closest
"Generate a branch growing towards the closest attractor.
This is the fallback case if no attractor is close enough to influence a
branch. It grows faster as a slight optimization as this case costs
branches*attractors comparisons per call."
[{:keys [segment-distance snap-theta branches attractors]}]
(let [branch-index (->> branches
(map-indexed (fn [idx branch] {branch idx}))
(into {}))
[branch attractor]
(apply min-key (fn [[branch bud]] (branch-distance bud branch))
(for [bud attractors
branch branches]
[branch bud]))]
(grow-branch branch (get branch-index branch)
(average-attraction branch [attractor] snap-theta (gv/vec2))
(max segment-distance
(/ (branch-distance attractor branch) 2)))))
(defn pruning-set
[quadtree prune-distance influencers]
(->> influencers
vals
(apply set/union)
(filter (partial close-to-branch? quadtree prune-distance))
set))
(defn grow
[{:keys [prune-distance attractors branches quadtree weights]
:as state}]
(if (empty? attractors)
(assoc state :steady-state true)
(let [influencers (influencing-attractors state)]
(if (empty? influencers)
(let [new-branch (grow-closest state)
branches' (conj branches new-branch)]
(assoc state
:weights (update-weights weights branches' [new-branch])
:branches branches'
:quadtree (add-branch-positions quadtree [new-branch])))
(let [growth (vec (grow-branches state influencers))
quadtree' (add-branch-positions quadtree growth)
pruned (pruning-set quadtree' prune-distance influencers)
branches' (vec (concat branches growth))]
(assoc state
:weights (update-weights weights branches' growth)
:branches branches'
:attractors (remove pruned attractors)
:quadtree quadtree'))))))
(defn grow-tree [state]
(some (fn [{:keys [steady-state] :as s}] (when steady-state s))
(iterate grow state)))
(defn make-root [position]
(->Branch nil position))
(defn create-tree
[{:keys [bounds attractors branches
influence-distance prune-distance segment-distance snap-theta]}]
{:influence-distance influence-distance
:prune-distance prune-distance
:segment-distance segment-distance
:snap-theta snap-theta
:jitter (partial dr/jitter 0.33)
:attractors attractors
:branches branches
:weights (update-weights {} branches branches)
:quadtree (add-branch-positions (spatialtree/quadtree bounds) branches)})
| null | https://raw.githubusercontent.com/dgtized/shimmers/65df950817dfd06f86dc418413a0285fdf1fcc37/src/shimmers/algorithm/space_colonization.cljc | clojure | Ideas:
* attractors could have influence PER attractor instead of global, or a weight on their influence?
- need kd-tree, or voronoi for faster "closest" lookups
* build up an initial trunk if no attractors are in range?
* add more weight to roots of the tree
* improve rules for detecting steady state completion
* grow to fit shapes or other distributions of attractors
Approach borrowed from
-space-colonization-experiments/blob/master/core/Network.js#L108-L114
CAUTION: if add-point fails the return value is nil. I believe
can recover as those branches should never be within an
attractors range.q | (ns shimmers.algorithm.space-colonization
(:require
[clojure.set :as set]
[shimmers.math.deterministic-random :as dr]
[shimmers.math.vector :as v]
[thi.ng.geom.core :as g]
[thi.ng.geom.spatialtree :as spatialtree]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
* some implementations have a branching likelyhood , or can just experiment with only creating one leaf per branch per cycle ?
- using distinct on closest branch kinda does this , but looks odd , maybe ( take 2 ) of each unique branch or only N per iteration ?
(defrecord Branch [parent position])
(defn grow-branch [{:keys [position]} parent-idx direction length]
(->Branch parent-idx (tm/+ position (tm/normalize direction length))))
(defn branch-distance [attractor branch]
(g/dist attractor (:position branch)))
(defn influenced-branches [quadtree radius position]
(spatialtree/select-with-circle quadtree position radius))
(defn close-to-branch? [quadtree radius position]
(spatialtree/points-in-circle? quadtree position radius))
(defn closest-branch [attractor branches]
(apply min-key (partial branch-distance attractor) branches))
(defn average-attraction
[{:keys [position]} attractors snap-theta jitter]
(-> (reduce (fn [acc attractor]
(tm/+ acc (tm/normalize (tm/- attractor position))))
jitter attractors)
tm/normalize
(v/snap-to snap-theta)))
(defn propagate-branch-weight [weights branches branch]
(if-let [parent-idx (:parent branch)]
(let [parent (nth branches parent-idx)
current-weight (get weights branch)]
(recur (update weights parent
(fn [parent-weight]
(if (< parent-weight (+ current-weight 0.1))
(+ parent-weight 0.01)
parent-weight)))
branches
parent))
weights))
(defn update-weights [weights branches growth]
(reduce-kv
(fn [weights _ bud]
(propagate-branch-weight (assoc weights bud 0.05) branches bud))
weights growth))
(defn add-branch-positions [quadtree branches]
this happens if point is out of bounds of the quadtree but we
(reduce (fn [tree branch]
(if-let [tree' (g/add-point tree (:position branch) branch)]
tree' tree))
quadtree
branches))
(defn influencing-attractors [{:keys [quadtree influence-distance attractors]}]
(apply merge-with set/union
(for [attractor attractors
:let [influences (influenced-branches quadtree influence-distance attractor)]
:when (seq influences)]
{(closest-branch attractor influences) #{attractor}})))
(defn grow-branches
[{:keys [segment-distance snap-theta jitter branches]} influencers]
(let [branch-index (->> branches
(map-indexed (fn [idx branch] {branch idx}))
(into {}))]
(for [[branch attractors] influencers]
(grow-branch branch (get branch-index branch)
(average-attraction branch attractors snap-theta (jitter))
segment-distance))))
(defn grow-closest
"Generate a branch growing towards the closest attractor.
This is the fallback case if no attractor is close enough to influence a
branch. It grows faster as a slight optimization as this case costs
branches*attractors comparisons per call."
[{:keys [segment-distance snap-theta branches attractors]}]
(let [branch-index (->> branches
(map-indexed (fn [idx branch] {branch idx}))
(into {}))
[branch attractor]
(apply min-key (fn [[branch bud]] (branch-distance bud branch))
(for [bud attractors
branch branches]
[branch bud]))]
(grow-branch branch (get branch-index branch)
(average-attraction branch [attractor] snap-theta (gv/vec2))
(max segment-distance
(/ (branch-distance attractor branch) 2)))))
(defn pruning-set
[quadtree prune-distance influencers]
(->> influencers
vals
(apply set/union)
(filter (partial close-to-branch? quadtree prune-distance))
set))
(defn grow
[{:keys [prune-distance attractors branches quadtree weights]
:as state}]
(if (empty? attractors)
(assoc state :steady-state true)
(let [influencers (influencing-attractors state)]
(if (empty? influencers)
(let [new-branch (grow-closest state)
branches' (conj branches new-branch)]
(assoc state
:weights (update-weights weights branches' [new-branch])
:branches branches'
:quadtree (add-branch-positions quadtree [new-branch])))
(let [growth (vec (grow-branches state influencers))
quadtree' (add-branch-positions quadtree growth)
pruned (pruning-set quadtree' prune-distance influencers)
branches' (vec (concat branches growth))]
(assoc state
:weights (update-weights weights branches' growth)
:branches branches'
:attractors (remove pruned attractors)
:quadtree quadtree'))))))
(defn grow-tree [state]
(some (fn [{:keys [steady-state] :as s}] (when steady-state s))
(iterate grow state)))
(defn make-root [position]
(->Branch nil position))
(defn create-tree
[{:keys [bounds attractors branches
influence-distance prune-distance segment-distance snap-theta]}]
{:influence-distance influence-distance
:prune-distance prune-distance
:segment-distance segment-distance
:snap-theta snap-theta
:jitter (partial dr/jitter 0.33)
:attractors attractors
:branches branches
:weights (update-weights {} branches branches)
:quadtree (add-branch-positions (spatialtree/quadtree bounds) branches)})
|
766d92a5313a11523f4c81ad2abd081c2470e675ebfab9ef0cd8496fb0e83020 | altsun/My-Lisps | (CLD) Ve bong may revcloud.lsp | ;; free lisp from cadviet.com
;;; this lisp was downloaded from
(defun C:CLD (/ aleng p1 p2 )
(setq p1 (getpoint "\nCh\U+1ECDn \U+0111i\U+1EC3m \U+0111\U+1EA7u HCN :")
p2 (getcorner p1 "\n\U+0110i\U+1EC3m cu\U+1ED1i :")
aleng (getdist "\nB\U+00E1n k\U+00EDnh cong :"))
(command "_.rectangle" p1 p2)
(command "_.revcloud" "_A" aleng "" "_O" (entlast) "")
(princ)
)
| null | https://raw.githubusercontent.com/altsun/My-Lisps/85476bb09b79ef5e966402cc5158978d1cebd7eb/Common/Revcloud/(CLD)%20Ve%20bong%20may%20revcloud.lsp | lisp | free lisp from cadviet.com
this lisp was downloaded from | (defun C:CLD (/ aleng p1 p2 )
(setq p1 (getpoint "\nCh\U+1ECDn \U+0111i\U+1EC3m \U+0111\U+1EA7u HCN :")
p2 (getcorner p1 "\n\U+0110i\U+1EC3m cu\U+1ED1i :")
aleng (getdist "\nB\U+00E1n k\U+00EDnh cong :"))
(command "_.rectangle" p1 p2)
(command "_.revcloud" "_A" aleng "" "_O" (entlast) "")
(princ)
)
|
eee4b97342a3a8195df1f7f2d8bf3b73b20a1cfaf9815b9cf82e4f0d5853bd40 | elm/package.elm-lang.org | Router.hs | # OPTIONS_GHC -Wall #
# LANGUAGE BangPatterns , GADTs , OverloadedStrings , UnboxedTuples #
module Server.Router
( Route, top, s, int, bytes, custom
, (</>), map, oneOf
, (==>)
, serve
)
where
import Prelude hiding (length, map)
import Control.Applicative ((<|>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.ByteString.Unsafe (unsafeIndex)
import qualified Data.ByteString.Validate as BSV
import qualified Data.Char as Char
import qualified Data.List as List
import Data.Word (Word8)
import qualified Snap.Core as Snap
import Snap.Core (Snap)
-- ROUTES
data Route a b where
Top :: Route a a
Exact :: ByteString -> Route a a
Integer :: Route (Int -> a) a
Custom :: (BS.ByteString -> Maybe a) -> Route (a -> b) b
Slash :: Route a b -> Route b c -> Route a c
Map :: a -> Route a b -> Route (b -> c) c
OneOf :: [Route a b] -> Route a b
top :: Route a a
top =
Top
s :: ByteString -> Route a a
s =
Exact
int :: Route (Int -> a) a
int =
Integer
bytes :: Route (BS.ByteString -> a) a
bytes =
Custom Just
custom :: (BS.ByteString -> Maybe a) -> Route (a -> b) b
custom =
Custom
(</>) :: Route a b -> Route b c -> Route a c
(</>) =
Slash
infixr 7 </>
map :: a -> Route a b -> Route (b -> c) c
map =
Map
oneOf :: [Route a b] -> Route a b
oneOf =
OneOf
(==>) :: Route a b -> a -> Route (b -> c) c
(==>) route arg =
Map arg route
infixl 5 ==>
-- SERVE
serve :: Route (Snap a -> Snap a) (Snap a) -> Snap a
serve route =
do request <- Snap.getRequest
let path = Snap.rqPathInfo request
case parse route path of
Nothing ->
Snap.pass
Just snap ->
do Snap.putRequest (finishPath request)
snap
<|>
do Snap.putRequest request
Snap.pass
finishPath :: Snap.Request -> Snap.Request
finishPath req =
let
path =
BS.concat [ Snap.rqContextPath req, Snap.rqPathInfo req, "/" ]
in
req { Snap.rqContextPath = path, Snap.rqPathInfo = "" }
PARSE
parse :: Route (a -> a) a -> ByteString -> Maybe a
parse route bs =
parseHelp $
try route (State bs 0 (BS.length bs) id)
parseHelp :: [State a] -> Maybe a
parseHelp states =
case states of
[] ->
Nothing
State _ _ length value : otherStates ->
if length == 0 then
Just value
else
parseHelp otherStates
data State a =
State
{ _url :: !ByteString
, _offset :: !Int
, _length :: !Int
, _value :: a
}
try :: Route a b -> State a -> [State b]
try route state@(State url offset length value) =
case route of
Top ->
if length == 0 then [state] else []
Exact byteString ->
let
(# newOffset, newLength #) =
chompExact byteString url offset length
in
if newOffset == -1 then
[]
else
[State url newOffset newLength value]
Integer ->
let
(# newOffset, newLength, number #) =
chompInt url offset length
in
if newOffset <= offset then
[]
else
[State url newOffset newLength (value number)]
Custom check ->
let
(# endOffset, newOffset, newLength #) =
chompSegment url offset length
in
if endOffset == offset then
[]
else
let
!subByteString =
BS.take (endOffset - offset) (BS.drop offset url)
in
if BSV.isUtf8 subByteString
then
case check subByteString of
Just nextValue -> [State url newOffset newLength (value nextValue)]
Nothing -> []
else
[]
Slash before after ->
concatMap (try after) (try before state)
Map subValue subParser ->
List.map (mapHelp value) $
try subParser (State url offset length subValue)
OneOf routes ->
concatMap (\p -> try p state) routes
mapHelp :: (a -> b) -> State a -> State b
mapHelp func (State url offset length value) =
State url offset length (func value)
slash :: Word8
slash =
fromIntegral (Char.ord '/')
CHOMP EXACT
chompExact :: ByteString -> ByteString -> Int -> Int -> (# Int, Int #)
chompExact small big offset length =
let
smallLen =
BS.length small
in
if length < smallLen || smallLen == 0 then
(# -1, length #)
else
if not (isSubString small big offset 0 smallLen) then
(# -1, length #)
else
let
!newOffset = offset + smallLen
!newLength = length - smallLen
in
if newLength == 0 then
(# newOffset, newLength #)
else if unsafeIndex big newOffset == slash then
(# newOffset + 1, newLength - 1 #)
else
(# -1, length #)
isSubString :: ByteString -> ByteString -> Int -> Int -> Int -> Bool
isSubString small big offset i smallLen =
if i == smallLen then
True
else if unsafeIndex small i == unsafeIndex big (offset + i) then
isSubString small big offset (i + 1) smallLen
else
False
CHOMP INT
chompInt :: ByteString -> Int -> Int -> (# Int, Int, Int #)
chompInt url offset length =
if length == 0 then
(# offset, length, 0 #)
else
let
!word = unsafeIndex url offset
in
if 0x30 <= word && word <= 0x39 then
chompIntHelp url (offset + 1) (length - 1) (fromIntegral word - 0x30)
else
(# offset, length, 0 #)
chompIntHelp :: ByteString -> Int -> Int -> Int -> (# Int, Int, Int #)
chompIntHelp url offset length n =
if length == 0 then
(# offset, length, n #)
else
let
!word = unsafeIndex url offset
in
if 0x30 <= word && word <= 0x39 then
chompIntHelp url (offset + 1) (length - 1) (n * 10 + (fromIntegral word - 0x30))
else if word == slash then
(# offset + 1, length - 1, n #)
else
(# offset, length, n #)
-- GET SEGMENT
chompSegment :: ByteString -> Int -> Int -> (# Int, Int, Int #)
chompSegment url offset length =
if length == 0 then
(# offset, offset, length #)
else if unsafeIndex url offset == slash then
(# offset, offset + 1, length - 1 #)
else
chompSegment url (offset + 1) (length - 1)
| null | https://raw.githubusercontent.com/elm/package.elm-lang.org/d4d5a997a5d9d6622694c488e6a3ae9f537da761/src/backend/Server/Router.hs | haskell | ROUTES
SERVE
GET SEGMENT | # OPTIONS_GHC -Wall #
# LANGUAGE BangPatterns , GADTs , OverloadedStrings , UnboxedTuples #
module Server.Router
( Route, top, s, int, bytes, custom
, (</>), map, oneOf
, (==>)
, serve
)
where
import Prelude hiding (length, map)
import Control.Applicative ((<|>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.ByteString.Unsafe (unsafeIndex)
import qualified Data.ByteString.Validate as BSV
import qualified Data.Char as Char
import qualified Data.List as List
import Data.Word (Word8)
import qualified Snap.Core as Snap
import Snap.Core (Snap)
data Route a b where
Top :: Route a a
Exact :: ByteString -> Route a a
Integer :: Route (Int -> a) a
Custom :: (BS.ByteString -> Maybe a) -> Route (a -> b) b
Slash :: Route a b -> Route b c -> Route a c
Map :: a -> Route a b -> Route (b -> c) c
OneOf :: [Route a b] -> Route a b
top :: Route a a
top =
Top
s :: ByteString -> Route a a
s =
Exact
int :: Route (Int -> a) a
int =
Integer
bytes :: Route (BS.ByteString -> a) a
bytes =
Custom Just
custom :: (BS.ByteString -> Maybe a) -> Route (a -> b) b
custom =
Custom
(</>) :: Route a b -> Route b c -> Route a c
(</>) =
Slash
infixr 7 </>
map :: a -> Route a b -> Route (b -> c) c
map =
Map
oneOf :: [Route a b] -> Route a b
oneOf =
OneOf
(==>) :: Route a b -> a -> Route (b -> c) c
(==>) route arg =
Map arg route
infixl 5 ==>
serve :: Route (Snap a -> Snap a) (Snap a) -> Snap a
serve route =
do request <- Snap.getRequest
let path = Snap.rqPathInfo request
case parse route path of
Nothing ->
Snap.pass
Just snap ->
do Snap.putRequest (finishPath request)
snap
<|>
do Snap.putRequest request
Snap.pass
finishPath :: Snap.Request -> Snap.Request
finishPath req =
let
path =
BS.concat [ Snap.rqContextPath req, Snap.rqPathInfo req, "/" ]
in
req { Snap.rqContextPath = path, Snap.rqPathInfo = "" }
PARSE
parse :: Route (a -> a) a -> ByteString -> Maybe a
parse route bs =
parseHelp $
try route (State bs 0 (BS.length bs) id)
parseHelp :: [State a] -> Maybe a
parseHelp states =
case states of
[] ->
Nothing
State _ _ length value : otherStates ->
if length == 0 then
Just value
else
parseHelp otherStates
data State a =
State
{ _url :: !ByteString
, _offset :: !Int
, _length :: !Int
, _value :: a
}
try :: Route a b -> State a -> [State b]
try route state@(State url offset length value) =
case route of
Top ->
if length == 0 then [state] else []
Exact byteString ->
let
(# newOffset, newLength #) =
chompExact byteString url offset length
in
if newOffset == -1 then
[]
else
[State url newOffset newLength value]
Integer ->
let
(# newOffset, newLength, number #) =
chompInt url offset length
in
if newOffset <= offset then
[]
else
[State url newOffset newLength (value number)]
Custom check ->
let
(# endOffset, newOffset, newLength #) =
chompSegment url offset length
in
if endOffset == offset then
[]
else
let
!subByteString =
BS.take (endOffset - offset) (BS.drop offset url)
in
if BSV.isUtf8 subByteString
then
case check subByteString of
Just nextValue -> [State url newOffset newLength (value nextValue)]
Nothing -> []
else
[]
Slash before after ->
concatMap (try after) (try before state)
Map subValue subParser ->
List.map (mapHelp value) $
try subParser (State url offset length subValue)
OneOf routes ->
concatMap (\p -> try p state) routes
mapHelp :: (a -> b) -> State a -> State b
mapHelp func (State url offset length value) =
State url offset length (func value)
slash :: Word8
slash =
fromIntegral (Char.ord '/')
CHOMP EXACT
chompExact :: ByteString -> ByteString -> Int -> Int -> (# Int, Int #)
chompExact small big offset length =
let
smallLen =
BS.length small
in
if length < smallLen || smallLen == 0 then
(# -1, length #)
else
if not (isSubString small big offset 0 smallLen) then
(# -1, length #)
else
let
!newOffset = offset + smallLen
!newLength = length - smallLen
in
if newLength == 0 then
(# newOffset, newLength #)
else if unsafeIndex big newOffset == slash then
(# newOffset + 1, newLength - 1 #)
else
(# -1, length #)
isSubString :: ByteString -> ByteString -> Int -> Int -> Int -> Bool
isSubString small big offset i smallLen =
if i == smallLen then
True
else if unsafeIndex small i == unsafeIndex big (offset + i) then
isSubString small big offset (i + 1) smallLen
else
False
CHOMP INT
chompInt :: ByteString -> Int -> Int -> (# Int, Int, Int #)
chompInt url offset length =
if length == 0 then
(# offset, length, 0 #)
else
let
!word = unsafeIndex url offset
in
if 0x30 <= word && word <= 0x39 then
chompIntHelp url (offset + 1) (length - 1) (fromIntegral word - 0x30)
else
(# offset, length, 0 #)
chompIntHelp :: ByteString -> Int -> Int -> Int -> (# Int, Int, Int #)
chompIntHelp url offset length n =
if length == 0 then
(# offset, length, n #)
else
let
!word = unsafeIndex url offset
in
if 0x30 <= word && word <= 0x39 then
chompIntHelp url (offset + 1) (length - 1) (n * 10 + (fromIntegral word - 0x30))
else if word == slash then
(# offset + 1, length - 1, n #)
else
(# offset, length, n #)
chompSegment :: ByteString -> Int -> Int -> (# Int, Int, Int #)
chompSegment url offset length =
if length == 0 then
(# offset, offset, length #)
else if unsafeIndex url offset == slash then
(# offset, offset + 1, length - 1 #)
else
chompSegment url (offset + 1) (length - 1)
|
c125916f380c1322d1a534dad84c758f17f98aafec754ec481a0eac1f7811574 | donaldsonjw/bigloo | alphatize.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / comptime / Ast / alphatize.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Fri Jan 6 11:09:14 1995 * /
* Last change : Mon Nov 11 09:41:12 2013 ( serrano ) * /
;* ------------------------------------------------------------- */
;* The substitution tools module */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module ast_alphatize
(include "Ast/node.sch"
"Tools/location.sch")
(import tools_error
tools_shape
tools_error
type_cache
ast_sexp
ast_local
ast_apply
ast_app)
(export (alphatize::node what* by* loc ::node)
(alphatize-sans-closure::node what* by* loc ::node ::variable)))
;*---------------------------------------------------------------------*/
;* alphatize ... */
;* ------------------------------------------------------------- */
;* This function differs from SUBSTITUTE, because: */
;* - it operates only on variables */
;* - it allocates new nodes (i.e. it does not operate on place). */
;* ------------------------------------------------------------- */
* Alphatize can replace a variable by a variable * /
;* construction but nothing else. */
;*---------------------------------------------------------------------*/
(define (alphatize what* by* loc node)
;; we set alpha-fnode slot and the type of the new variable
(for-each (lambda (what by)
(variable-fast-alpha-set! what by))
what*
by*)
(let ((res (do-alphatize node loc)))
;; we remove alpha-fast slots
(for-each (lambda (what)
(variable-fast-alpha-set! what #unspecified))
what*)
res))
;*---------------------------------------------------------------------*/
;* *no-alphatize-closure* ... */
;*---------------------------------------------------------------------*/
(define *no-alphatize-closure* #f)
;*---------------------------------------------------------------------*/
;* alphatize-sans-closure ... */
;*---------------------------------------------------------------------*/
(define (alphatize-sans-closure what* by* loc node closure)
(set! *no-alphatize-closure* closure)
(unwind-protect
(alphatize what* by* loc node)
(set! *no-alphatize-closure* #f)))
;*---------------------------------------------------------------------*/
;* get-location ... */
;* ------------------------------------------------------------- */
* This function selects which location to use , four different * /
;* cases: */
;* */
* 1- if there is no current loc , use the one of the node * /
* 2- if the node contains no location , use the current one * /
;* 3- if the location of the node refers to another file, */
;* use the default one. */
;* 4- otherwise, use the location of the node. */
;*---------------------------------------------------------------------*/
(define (get-location node loc)
(cond
((not (location? (node-loc node)))
loc)
((not (location? loc))
(node-loc node))
((not (string=? (location-fname (node-loc node)) (location-fname loc)))
loc)
(else
(node-loc node))))
;*---------------------------------------------------------------------*/
;* do-alphatize* ... */
;*---------------------------------------------------------------------*/
(define (do-alphatize* nodes::pair-nil loc)
(map (lambda (node) (do-alphatize node loc)) nodes))
;*---------------------------------------------------------------------*/
;* do-alphatize ... */
;*---------------------------------------------------------------------*/
(define-generic (do-alphatize::node node::node loc))
;*---------------------------------------------------------------------*/
;* do-alphatize ::atom ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::atom loc)
(duplicate::atom node
(loc (get-location node loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::var ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::var loc)
(let* ((var (var-variable node))
(alpha (variable-fast-alpha var)))
(cond
((eq? alpha #unspecified)
(use-variable! var (node-loc node) 'value)
(duplicate::var node (loc (get-location node loc))))
((variable? alpha)
(use-variable! alpha (node-loc node) 'value)
(if (fun? (variable-value alpha))
(instantiate::closure
(loc (get-location node loc))
(type (strict-node-type *procedure* (variable-type alpha)))
(variable alpha))
(duplicate::var node
(loc (get-location node loc))
(variable alpha))))
((atom? alpha)
(duplicate::atom alpha))
((kwote? alpha)
(duplicate::kwote alpha))
(else
(internal-error "alphatize"
"Illegal alphatization (var)"
(cons (shape node) (shape alpha)))))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::closure ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::closure loc)
(let ((var (var-variable node)))
(if (eq? var *no-alphatize-closure*)
node
(let ((alpha (variable-fast-alpha var)))
(cond
((eq? alpha #unspecified)
(use-variable! var (node-loc node) 'value)
(duplicate::closure node (loc (get-location node loc))))
((variable? alpha)
(use-variable! alpha (node-loc node) 'value)
(duplicate::closure node
(loc (get-location node loc))
(variable alpha)))
(else
(internal-error "alphatize"
"Illegal alphatization (closure)"
(shape node))))))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::kwote ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::kwote loc)
(duplicate::kwote node (loc (get-location node loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::sequence ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::sequence loc)
(duplicate::sequence node
(loc (get-location node loc))
(nodes (do-alphatize* (sequence-nodes node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::sync ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::sync loc)
(duplicate::sync node
(loc (get-location node loc))
(mutex (do-alphatize (sync-mutex node) loc))
(prelock (do-alphatize (sync-prelock node) loc))
(body (do-alphatize (sync-body node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::app ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::app loc)
;; we have to enforce here a variable and not a closure (that
;; why the duplicate::var of the fun field).
(duplicate::app node
(loc (get-location node loc))
(fun (let ((var (do-alphatize (app-fun node) loc)))
(if (closure? var)
(duplicate::var var)
var)))
(args (do-alphatize* (app-args node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::app-ly ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::app-ly loc)
(let ((fun (do-alphatize (app-ly-fun node) loc))
(arg (do-alphatize (app-ly-arg node) loc)))
(if (and (closure? fun)
(not (global-optional? (var-variable fun)))
(not (global-key? (var-variable fun))))
(known-app-ly->node '()
(get-location node loc)
(duplicate::var fun)
arg
'value)
(duplicate::app-ly node
(loc (get-location node loc))
(fun fun)
(arg arg)))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::funcall ... */
;* ------------------------------------------------------------- */
;* When transforming a funcall into an app node we have to remove */
;* the extra argument which hold the closure. */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::funcall loc)
(let ((fun (do-alphatize (funcall-fun node) loc))
(args (do-alphatize* (funcall-args node) loc)))
(if (closure? fun)
(sexp->node `(,(duplicate::var fun) ,@(cdr args))
'() (node-loc node) 'app)
(duplicate::funcall node
(loc (get-location node loc))
(fun fun)
(args args)))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::pragma ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::pragma loc)
(duplicate::pragma node
(loc (get-location node loc))
(expr* (do-alphatize* (pragma-expr* node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::cast-null ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::cast-null loc)
(duplicate::cast-null node
(loc (get-location node loc))
(expr* (do-alphatize* (cast-null-expr* node) loc))))
;*---------------------------------------------------------------------*/
* do - alphatize : : ... * /
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::getfield loc)
(duplicate::getfield node
(loc (get-location node loc))
(expr* (do-alphatize* (getfield-expr* node) loc))))
;*---------------------------------------------------------------------*/
* do - alphatize : : ... * /
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::setfield loc)
(duplicate::setfield node
(loc (get-location node loc))
(expr* (do-alphatize* (setfield-expr* node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::new ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::new loc)
(duplicate::new node
(loc (get-location node loc))
(expr* (do-alphatize* (new-expr* node) loc)) ))
;*---------------------------------------------------------------------*/
* do - alphatize : : ... * /
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::vlength loc)
(duplicate::vlength node
(loc (get-location node loc))
(expr* (do-alphatize* (vlength-expr* node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::vref ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::vref loc)
(duplicate::vref node
(loc (get-location node loc))
(expr* (do-alphatize* (vref-expr* node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::vset! ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::vset! loc)
(duplicate::vset! node
(loc (get-location node loc))
(expr* (do-alphatize* (vset!-expr* node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::valloc ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::valloc loc)
(duplicate::valloc node
(loc (get-location node loc))
(expr* (do-alphatize* (valloc-expr* node) loc))))
;*---------------------------------------------------------------------*/
* do - alphatize : : ... * /
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::instanceof loc)
(duplicate::instanceof node
(expr* (list (do-alphatize (car (instanceof-expr* node)) loc)))
(loc (get-location node loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::cast ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::cast loc)
(duplicate::cast node
(loc (get-location node loc))
(arg (do-alphatize (cast-arg node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::setq ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::setq loc)
(let* ((v (setq-var node))
(var (var-variable v))
(alpha (variable-fast-alpha var)))
(cond
((eq? alpha #unspecified)
(use-variable! var (node-loc node) 'set!)
(duplicate::setq node
(loc (get-location node loc))
(var (duplicate::var v (loc (get-location node loc))))
(value (do-alphatize (setq-value node) loc))))
((variable? alpha)
(use-variable! alpha (node-loc node) 'set!)
(duplicate::setq node
(loc (get-location node loc))
(var (duplicate::var v
(loc (get-location node loc))
(variable alpha)))
(value (do-alphatize (setq-value node) loc))))
(else
(internal-error "alphatize"
"Illegal alphatization (setq)"
(shape node))))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::conditional ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::conditional loc)
(duplicate::conditional node
(loc (get-location node loc))
(test (do-alphatize (conditional-test node) loc))
(true (do-alphatize (conditional-true node) loc))
(false (do-alphatize (conditional-false node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::fail ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::fail loc)
(duplicate::fail node
(loc (get-location node loc))
(proc (do-alphatize (fail-proc node) loc))
(msg (do-alphatize (fail-msg node) loc))
(obj (do-alphatize (fail-obj node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::select ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::select loc)
(duplicate::select node
(loc (get-location node loc))
(test (do-alphatize (select-test node) loc))
(clauses (map (lambda (clause)
(cons (car clause)
(do-alphatize (cdr clause) loc)))
(select-clauses node)))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::make-box ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::make-box loc)
(duplicate::make-box node
(loc (get-location node loc))
(value (do-alphatize (make-box-value node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::box-ref ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::box-ref loc)
(duplicate::box-ref node
(loc (get-location node loc))
(var (do-alphatize (box-ref-var node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::box-set! ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::box-set! loc)
(duplicate::box-set! node
(loc (get-location node loc))
(var (do-alphatize (box-set!-var node) loc))
(value (do-alphatize (box-set!-value node) loc))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::let-fun ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::let-fun loc)
(let* ((old-locals (let-fun-locals node))
(new-locals (map (lambda (l)
(make-local-sfun (local-id l)
(local-type l)
(local-value l)))
old-locals)))
(for-each (lambda (old new)
(let* ((old-sfun (local-value old))
(old-args (sfun-args old-sfun))
(new-args (map (lambda (l)
(make-local-svar (local-id l)
(local-type l)))
old-args))
(old-body (sfun-body old-sfun))
(new-body (alphatize (append old-locals old-args)
(append new-locals new-args)
(get-location node loc)
old-body))
(new-sfun (duplicate::sfun old-sfun
(args new-args)
(body new-body))))
(local-user?-set! new (local-user? old))
(local-value-set! new new-sfun)))
old-locals
new-locals)
(duplicate::let-fun node
(loc (get-location node loc))
(locals new-locals)
(body (alphatize old-locals
new-locals
(get-location node loc)
(let-fun-body node))))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::let-var ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::let-var loc)
(let* ((old-locals (map car (let-var-bindings node)))
(new-locals (map (lambda (l)
;; we can't use duplicate for locals because
;; all local variables must be allocated
;; using the `make-local-svar' form
;; (for the key attribution).
(let ((var (make-local-svar (local-id l)
(local-type l))))
(local-user?-set! var (local-user? l))
(local-access-set! var (local-access l))
var))
old-locals))
(new-bindings (map (lambda (binding new-local)
(cons new-local (do-alphatize (cdr binding) loc)))
(let-var-bindings node)
new-locals)))
(duplicate::let-var node
(loc (get-location node loc))
(bindings new-bindings)
(body (alphatize old-locals
new-locals
(get-location node loc)
(let-var-body node))))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::set-ex-it ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::set-ex-it loc)
(let* ((old-var (var-variable (set-ex-it-var node)))
(old-exit (local-value old-var))
(old-hdlg (sexit-handler old-exit))
(alpha-hdlg (variable-fast-alpha old-hdlg))
(new-var (make-local-sexit (local-id old-var)
(local-type old-var)
(duplicate::sexit old-exit
(handler alpha-hdlg))))
(old-body (set-ex-it-body node)))
(local-user?-set! new-var (local-user? old-var))
(duplicate::set-ex-it node
(loc (get-location node loc))
(var (duplicate::var (set-ex-it-var node)
(loc (get-location node loc))
(variable new-var)))
(body (alphatize (list old-var)
(list new-var)
(get-location node loc)
old-body)))))
;*---------------------------------------------------------------------*/
;* do-alphatize ::jump-ex-it ... */
;*---------------------------------------------------------------------*/
(define-method (do-alphatize node::jump-ex-it loc)
(duplicate::jump-ex-it node
(loc (get-location node loc))
(exit (do-alphatize (jump-ex-it-exit node) loc))
(value (do-alphatize (jump-ex-it-value node) loc))))
| null | https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/comptime/Ast/alphatize.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* The substitution tools module */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alphatize ... */
* ------------------------------------------------------------- */
* This function differs from SUBSTITUTE, because: */
* - it operates only on variables */
* - it allocates new nodes (i.e. it does not operate on place). */
* ------------------------------------------------------------- */
* construction but nothing else. */
*---------------------------------------------------------------------*/
we set alpha-fnode slot and the type of the new variable
we remove alpha-fast slots
*---------------------------------------------------------------------*/
* *no-alphatize-closure* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alphatize-sans-closure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-location ... */
* ------------------------------------------------------------- */
* cases: */
* */
* 3- if the location of the node refers to another file, */
* use the default one. */
* 4- otherwise, use the location of the node. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::atom ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::var ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::closure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::kwote ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::sequence ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::sync ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::app ... */
*---------------------------------------------------------------------*/
we have to enforce here a variable and not a closure (that
why the duplicate::var of the fun field).
*---------------------------------------------------------------------*/
* do-alphatize ::app-ly ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::funcall ... */
* ------------------------------------------------------------- */
* When transforming a funcall into an app node we have to remove */
* the extra argument which hold the closure. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::pragma ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::cast-null ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::new ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::vref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::vset! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::valloc ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::cast ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::setq ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::conditional ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::fail ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::select ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::make-box ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::box-ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::box-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::let-fun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::let-var ... */
*---------------------------------------------------------------------*/
we can't use duplicate for locals because
all local variables must be allocated
using the `make-local-svar' form
(for the key attribution).
*---------------------------------------------------------------------*/
* do-alphatize ::set-ex-it ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-alphatize ::jump-ex-it ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / comptime / Ast / alphatize.scm * /
* Author : * /
* Creation : Fri Jan 6 11:09:14 1995 * /
* Last change : Mon Nov 11 09:41:12 2013 ( serrano ) * /
(module ast_alphatize
(include "Ast/node.sch"
"Tools/location.sch")
(import tools_error
tools_shape
tools_error
type_cache
ast_sexp
ast_local
ast_apply
ast_app)
(export (alphatize::node what* by* loc ::node)
(alphatize-sans-closure::node what* by* loc ::node ::variable)))
* Alphatize can replace a variable by a variable * /
(define (alphatize what* by* loc node)
(for-each (lambda (what by)
(variable-fast-alpha-set! what by))
what*
by*)
(let ((res (do-alphatize node loc)))
(for-each (lambda (what)
(variable-fast-alpha-set! what #unspecified))
what*)
res))
(define *no-alphatize-closure* #f)
(define (alphatize-sans-closure what* by* loc node closure)
(set! *no-alphatize-closure* closure)
(unwind-protect
(alphatize what* by* loc node)
(set! *no-alphatize-closure* #f)))
* This function selects which location to use , four different * /
* 1- if there is no current loc , use the one of the node * /
* 2- if the node contains no location , use the current one * /
(define (get-location node loc)
(cond
((not (location? (node-loc node)))
loc)
((not (location? loc))
(node-loc node))
((not (string=? (location-fname (node-loc node)) (location-fname loc)))
loc)
(else
(node-loc node))))
(define (do-alphatize* nodes::pair-nil loc)
(map (lambda (node) (do-alphatize node loc)) nodes))
(define-generic (do-alphatize::node node::node loc))
(define-method (do-alphatize node::atom loc)
(duplicate::atom node
(loc (get-location node loc))))
(define-method (do-alphatize node::var loc)
(let* ((var (var-variable node))
(alpha (variable-fast-alpha var)))
(cond
((eq? alpha #unspecified)
(use-variable! var (node-loc node) 'value)
(duplicate::var node (loc (get-location node loc))))
((variable? alpha)
(use-variable! alpha (node-loc node) 'value)
(if (fun? (variable-value alpha))
(instantiate::closure
(loc (get-location node loc))
(type (strict-node-type *procedure* (variable-type alpha)))
(variable alpha))
(duplicate::var node
(loc (get-location node loc))
(variable alpha))))
((atom? alpha)
(duplicate::atom alpha))
((kwote? alpha)
(duplicate::kwote alpha))
(else
(internal-error "alphatize"
"Illegal alphatization (var)"
(cons (shape node) (shape alpha)))))))
(define-method (do-alphatize node::closure loc)
(let ((var (var-variable node)))
(if (eq? var *no-alphatize-closure*)
node
(let ((alpha (variable-fast-alpha var)))
(cond
((eq? alpha #unspecified)
(use-variable! var (node-loc node) 'value)
(duplicate::closure node (loc (get-location node loc))))
((variable? alpha)
(use-variable! alpha (node-loc node) 'value)
(duplicate::closure node
(loc (get-location node loc))
(variable alpha)))
(else
(internal-error "alphatize"
"Illegal alphatization (closure)"
(shape node))))))))
(define-method (do-alphatize node::kwote loc)
(duplicate::kwote node (loc (get-location node loc))))
(define-method (do-alphatize node::sequence loc)
(duplicate::sequence node
(loc (get-location node loc))
(nodes (do-alphatize* (sequence-nodes node) loc))))
(define-method (do-alphatize node::sync loc)
(duplicate::sync node
(loc (get-location node loc))
(mutex (do-alphatize (sync-mutex node) loc))
(prelock (do-alphatize (sync-prelock node) loc))
(body (do-alphatize (sync-body node) loc))))
(define-method (do-alphatize node::app loc)
(duplicate::app node
(loc (get-location node loc))
(fun (let ((var (do-alphatize (app-fun node) loc)))
(if (closure? var)
(duplicate::var var)
var)))
(args (do-alphatize* (app-args node) loc))))
(define-method (do-alphatize node::app-ly loc)
(let ((fun (do-alphatize (app-ly-fun node) loc))
(arg (do-alphatize (app-ly-arg node) loc)))
(if (and (closure? fun)
(not (global-optional? (var-variable fun)))
(not (global-key? (var-variable fun))))
(known-app-ly->node '()
(get-location node loc)
(duplicate::var fun)
arg
'value)
(duplicate::app-ly node
(loc (get-location node loc))
(fun fun)
(arg arg)))))
(define-method (do-alphatize node::funcall loc)
(let ((fun (do-alphatize (funcall-fun node) loc))
(args (do-alphatize* (funcall-args node) loc)))
(if (closure? fun)
(sexp->node `(,(duplicate::var fun) ,@(cdr args))
'() (node-loc node) 'app)
(duplicate::funcall node
(loc (get-location node loc))
(fun fun)
(args args)))))
(define-method (do-alphatize node::pragma loc)
(duplicate::pragma node
(loc (get-location node loc))
(expr* (do-alphatize* (pragma-expr* node) loc))))
(define-method (do-alphatize node::cast-null loc)
(duplicate::cast-null node
(loc (get-location node loc))
(expr* (do-alphatize* (cast-null-expr* node) loc))))
* do - alphatize : : ... * /
(define-method (do-alphatize node::getfield loc)
(duplicate::getfield node
(loc (get-location node loc))
(expr* (do-alphatize* (getfield-expr* node) loc))))
* do - alphatize : : ... * /
(define-method (do-alphatize node::setfield loc)
(duplicate::setfield node
(loc (get-location node loc))
(expr* (do-alphatize* (setfield-expr* node) loc))))
(define-method (do-alphatize node::new loc)
(duplicate::new node
(loc (get-location node loc))
(expr* (do-alphatize* (new-expr* node) loc)) ))
* do - alphatize : : ... * /
(define-method (do-alphatize node::vlength loc)
(duplicate::vlength node
(loc (get-location node loc))
(expr* (do-alphatize* (vlength-expr* node) loc))))
(define-method (do-alphatize node::vref loc)
(duplicate::vref node
(loc (get-location node loc))
(expr* (do-alphatize* (vref-expr* node) loc))))
(define-method (do-alphatize node::vset! loc)
(duplicate::vset! node
(loc (get-location node loc))
(expr* (do-alphatize* (vset!-expr* node) loc))))
(define-method (do-alphatize node::valloc loc)
(duplicate::valloc node
(loc (get-location node loc))
(expr* (do-alphatize* (valloc-expr* node) loc))))
* do - alphatize : : ... * /
(define-method (do-alphatize node::instanceof loc)
(duplicate::instanceof node
(expr* (list (do-alphatize (car (instanceof-expr* node)) loc)))
(loc (get-location node loc))))
(define-method (do-alphatize node::cast loc)
(duplicate::cast node
(loc (get-location node loc))
(arg (do-alphatize (cast-arg node) loc))))
(define-method (do-alphatize node::setq loc)
(let* ((v (setq-var node))
(var (var-variable v))
(alpha (variable-fast-alpha var)))
(cond
((eq? alpha #unspecified)
(use-variable! var (node-loc node) 'set!)
(duplicate::setq node
(loc (get-location node loc))
(var (duplicate::var v (loc (get-location node loc))))
(value (do-alphatize (setq-value node) loc))))
((variable? alpha)
(use-variable! alpha (node-loc node) 'set!)
(duplicate::setq node
(loc (get-location node loc))
(var (duplicate::var v
(loc (get-location node loc))
(variable alpha)))
(value (do-alphatize (setq-value node) loc))))
(else
(internal-error "alphatize"
"Illegal alphatization (setq)"
(shape node))))))
(define-method (do-alphatize node::conditional loc)
(duplicate::conditional node
(loc (get-location node loc))
(test (do-alphatize (conditional-test node) loc))
(true (do-alphatize (conditional-true node) loc))
(false (do-alphatize (conditional-false node) loc))))
(define-method (do-alphatize node::fail loc)
(duplicate::fail node
(loc (get-location node loc))
(proc (do-alphatize (fail-proc node) loc))
(msg (do-alphatize (fail-msg node) loc))
(obj (do-alphatize (fail-obj node) loc))))
(define-method (do-alphatize node::select loc)
(duplicate::select node
(loc (get-location node loc))
(test (do-alphatize (select-test node) loc))
(clauses (map (lambda (clause)
(cons (car clause)
(do-alphatize (cdr clause) loc)))
(select-clauses node)))))
(define-method (do-alphatize node::make-box loc)
(duplicate::make-box node
(loc (get-location node loc))
(value (do-alphatize (make-box-value node) loc))))
(define-method (do-alphatize node::box-ref loc)
(duplicate::box-ref node
(loc (get-location node loc))
(var (do-alphatize (box-ref-var node) loc))))
(define-method (do-alphatize node::box-set! loc)
(duplicate::box-set! node
(loc (get-location node loc))
(var (do-alphatize (box-set!-var node) loc))
(value (do-alphatize (box-set!-value node) loc))))
(define-method (do-alphatize node::let-fun loc)
(let* ((old-locals (let-fun-locals node))
(new-locals (map (lambda (l)
(make-local-sfun (local-id l)
(local-type l)
(local-value l)))
old-locals)))
(for-each (lambda (old new)
(let* ((old-sfun (local-value old))
(old-args (sfun-args old-sfun))
(new-args (map (lambda (l)
(make-local-svar (local-id l)
(local-type l)))
old-args))
(old-body (sfun-body old-sfun))
(new-body (alphatize (append old-locals old-args)
(append new-locals new-args)
(get-location node loc)
old-body))
(new-sfun (duplicate::sfun old-sfun
(args new-args)
(body new-body))))
(local-user?-set! new (local-user? old))
(local-value-set! new new-sfun)))
old-locals
new-locals)
(duplicate::let-fun node
(loc (get-location node loc))
(locals new-locals)
(body (alphatize old-locals
new-locals
(get-location node loc)
(let-fun-body node))))))
(define-method (do-alphatize node::let-var loc)
(let* ((old-locals (map car (let-var-bindings node)))
(new-locals (map (lambda (l)
(let ((var (make-local-svar (local-id l)
(local-type l))))
(local-user?-set! var (local-user? l))
(local-access-set! var (local-access l))
var))
old-locals))
(new-bindings (map (lambda (binding new-local)
(cons new-local (do-alphatize (cdr binding) loc)))
(let-var-bindings node)
new-locals)))
(duplicate::let-var node
(loc (get-location node loc))
(bindings new-bindings)
(body (alphatize old-locals
new-locals
(get-location node loc)
(let-var-body node))))))
(define-method (do-alphatize node::set-ex-it loc)
(let* ((old-var (var-variable (set-ex-it-var node)))
(old-exit (local-value old-var))
(old-hdlg (sexit-handler old-exit))
(alpha-hdlg (variable-fast-alpha old-hdlg))
(new-var (make-local-sexit (local-id old-var)
(local-type old-var)
(duplicate::sexit old-exit
(handler alpha-hdlg))))
(old-body (set-ex-it-body node)))
(local-user?-set! new-var (local-user? old-var))
(duplicate::set-ex-it node
(loc (get-location node loc))
(var (duplicate::var (set-ex-it-var node)
(loc (get-location node loc))
(variable new-var)))
(body (alphatize (list old-var)
(list new-var)
(get-location node loc)
old-body)))))
(define-method (do-alphatize node::jump-ex-it loc)
(duplicate::jump-ex-it node
(loc (get-location node loc))
(exit (do-alphatize (jump-ex-it-exit node) loc))
(value (do-alphatize (jump-ex-it-value node) loc))))
|
e93d86e00564fd4c1aa725841c00c049fac6e9fdb4f1d068c87a6558208a9168 | SamirTalwar/advent-of-code | AOC_22_2.hs | {-# OPTIONS -Wall #-}
import Data.Functor
import qualified Data.List as List
import Data.Text (Text)
import Helpers.Parse
import Text.Parsec
data Instruction = Instruction Switch Cube
deriving (Show)
data Switch = Off | On
deriving (Show)
data Cube = Cube Range Range Range
deriving (Eq)
instance Show Cube where
show (Cube x y z) = "(x=" ++ show x ++ ",y=" ++ show y ++ ",z=" ++ show z ++ ")"
data Range = Range Int Int
deriving (Eq)
instance Show Range where
show (Range start end) = show start ++ ".." ++ show end
main :: IO ()
main = do
instructions <- parseLinesIO parser
let cubes = List.foldl' apply [] instructions
print $ sum $ map size cubes
apply :: [Cube] -> Instruction -> [Cube]
apply onCubes (Instruction Off cube) =
concatMap (`without` cube) onCubes
apply onCubes (Instruction On cube) =
cube : concatMap (`without` cube) onCubes
without :: Cube -> Cube -> [Cube]
a@(Cube aX aY aZ) `without` b@(Cube bX bY bZ) =
let xs = if aX `overlapsWith` bX then splitX bX a else [a]
ys = if aY `overlapsWith` bY then concatMap (splitY bY) xs else xs
zs = if aZ `overlapsWith` bZ then concatMap (splitZ bZ) ys else ys
in mergeCubes $ List.delete (constrainCubeTo a b) zs
where
splitX range (Cube x y z) = map (\x' -> Cube x' y z) (splitRange range x)
splitY range (Cube x y z) = map (\y' -> Cube x y' z) (splitRange range y)
splitZ range (Cube x y z) = map (Cube x y) (splitRange range z)
mergeCubes :: [Cube] -> [Cube]
mergeCubes cubes =
case List.find (\((_, a), (_, b)) -> mergeable a b) pairs of
Nothing -> cubes
Just ((aI, a), (bI, b)) -> mergeCubes $ (merge a b :) $ deleteAt aI $ deleteAt bI cubes
where
pairs = [((aI, cubes !! aI), (bI, cubes !! bI)) | aI <- [0 .. length cubes - 1], bI <- [aI + 1 .. length cubes - 1]]
mergeable (Cube aX aY aZ) (Cube bX bY bZ) =
aX == bX && aY == bY && contiguous aZ bZ
|| aX == bX && aZ == bZ && contiguous aY bY
|| aY == bY && aZ == bZ && contiguous aX bX
contiguous (Range aStart aEnd) (Range bStart bEnd) =
aEnd + 1 == bStart || bEnd + 1 == aStart
merge (Cube aX aY aZ) (Cube bX bY bZ) =
Cube (connect aX bX) (connect aY bY) (connect aZ bZ)
connect (Range aStart aEnd) (Range bStart bEnd) =
if aStart < bStart
then Range aStart bEnd
else Range bStart aEnd
deleteAt _ [] = error "deleteAt: Out of range."
deleteAt 0 (_ : xs) = xs
deleteAt n (x : xs) = x : deleteAt (n - 1) xs
constrainCubeTo :: Cube -> Cube -> Cube
constrainCubeTo (Cube aX aY aZ) (Cube bX bY bZ) =
Cube (constrainRangeTo aX bX) (constrainRangeTo aY bY) (constrainRangeTo aZ bZ)
constrainRangeTo :: Range -> Range -> Range
constrainRangeTo (Range aStart aEnd) (Range bStart bEnd) =
Range (max aStart bStart) (min aEnd bEnd)
splitRange :: Range -> Range -> [Range]
splitRange a@(Range aStart aEnd) b@(Range bStart bEnd) =
case (aStart <= bStart, aEnd >= bEnd) of
(True, True) -> [b]
(True, False) -> [Range bStart aEnd, Range (aEnd + 1) bEnd]
(False, True) -> [Range bStart (aStart - 1), Range aStart bEnd]
(False, False) -> [Range bStart (aStart - 1), a, Range (aEnd + 1) bEnd]
overlapsWith :: Range -> Range -> Bool
Range aStart aEnd `overlapsWith` Range bStart bEnd =
aStart <= bStart && aEnd >= bStart
|| aStart <= bEnd && aEnd >= bEnd
size :: Cube -> Int
size (Cube xRange yRange zRange) = rangeLength xRange * rangeLength yRange * rangeLength zRange
where
rangeLength (Range start end) = end - start + 1
parser :: Parsec Text () Instruction
parser = do
s <- switch
x <- string " x=" *> range
y <- string ",y=" *> range
z <- string ",z=" *> range
return $ Instruction s $ Cube x y z
where
switch = choice [try (string "off") $> Off, try (string "on") $> On]
range = do
start <- int
end <- string ".." *> int
return $ Range start end
| null | https://raw.githubusercontent.com/SamirTalwar/advent-of-code/5f73557b8d62353e43062148e37ef0d03adab50b/2021/AOC_22_2.hs | haskell | # OPTIONS -Wall # |
import Data.Functor
import qualified Data.List as List
import Data.Text (Text)
import Helpers.Parse
import Text.Parsec
data Instruction = Instruction Switch Cube
deriving (Show)
data Switch = Off | On
deriving (Show)
data Cube = Cube Range Range Range
deriving (Eq)
instance Show Cube where
show (Cube x y z) = "(x=" ++ show x ++ ",y=" ++ show y ++ ",z=" ++ show z ++ ")"
data Range = Range Int Int
deriving (Eq)
instance Show Range where
show (Range start end) = show start ++ ".." ++ show end
main :: IO ()
main = do
instructions <- parseLinesIO parser
let cubes = List.foldl' apply [] instructions
print $ sum $ map size cubes
apply :: [Cube] -> Instruction -> [Cube]
apply onCubes (Instruction Off cube) =
concatMap (`without` cube) onCubes
apply onCubes (Instruction On cube) =
cube : concatMap (`without` cube) onCubes
without :: Cube -> Cube -> [Cube]
a@(Cube aX aY aZ) `without` b@(Cube bX bY bZ) =
let xs = if aX `overlapsWith` bX then splitX bX a else [a]
ys = if aY `overlapsWith` bY then concatMap (splitY bY) xs else xs
zs = if aZ `overlapsWith` bZ then concatMap (splitZ bZ) ys else ys
in mergeCubes $ List.delete (constrainCubeTo a b) zs
where
splitX range (Cube x y z) = map (\x' -> Cube x' y z) (splitRange range x)
splitY range (Cube x y z) = map (\y' -> Cube x y' z) (splitRange range y)
splitZ range (Cube x y z) = map (Cube x y) (splitRange range z)
mergeCubes :: [Cube] -> [Cube]
mergeCubes cubes =
case List.find (\((_, a), (_, b)) -> mergeable a b) pairs of
Nothing -> cubes
Just ((aI, a), (bI, b)) -> mergeCubes $ (merge a b :) $ deleteAt aI $ deleteAt bI cubes
where
pairs = [((aI, cubes !! aI), (bI, cubes !! bI)) | aI <- [0 .. length cubes - 1], bI <- [aI + 1 .. length cubes - 1]]
mergeable (Cube aX aY aZ) (Cube bX bY bZ) =
aX == bX && aY == bY && contiguous aZ bZ
|| aX == bX && aZ == bZ && contiguous aY bY
|| aY == bY && aZ == bZ && contiguous aX bX
contiguous (Range aStart aEnd) (Range bStart bEnd) =
aEnd + 1 == bStart || bEnd + 1 == aStart
merge (Cube aX aY aZ) (Cube bX bY bZ) =
Cube (connect aX bX) (connect aY bY) (connect aZ bZ)
connect (Range aStart aEnd) (Range bStart bEnd) =
if aStart < bStart
then Range aStart bEnd
else Range bStart aEnd
deleteAt _ [] = error "deleteAt: Out of range."
deleteAt 0 (_ : xs) = xs
deleteAt n (x : xs) = x : deleteAt (n - 1) xs
constrainCubeTo :: Cube -> Cube -> Cube
constrainCubeTo (Cube aX aY aZ) (Cube bX bY bZ) =
Cube (constrainRangeTo aX bX) (constrainRangeTo aY bY) (constrainRangeTo aZ bZ)
constrainRangeTo :: Range -> Range -> Range
constrainRangeTo (Range aStart aEnd) (Range bStart bEnd) =
Range (max aStart bStart) (min aEnd bEnd)
splitRange :: Range -> Range -> [Range]
splitRange a@(Range aStart aEnd) b@(Range bStart bEnd) =
case (aStart <= bStart, aEnd >= bEnd) of
(True, True) -> [b]
(True, False) -> [Range bStart aEnd, Range (aEnd + 1) bEnd]
(False, True) -> [Range bStart (aStart - 1), Range aStart bEnd]
(False, False) -> [Range bStart (aStart - 1), a, Range (aEnd + 1) bEnd]
overlapsWith :: Range -> Range -> Bool
Range aStart aEnd `overlapsWith` Range bStart bEnd =
aStart <= bStart && aEnd >= bStart
|| aStart <= bEnd && aEnd >= bEnd
size :: Cube -> Int
size (Cube xRange yRange zRange) = rangeLength xRange * rangeLength yRange * rangeLength zRange
where
rangeLength (Range start end) = end - start + 1
parser :: Parsec Text () Instruction
parser = do
s <- switch
x <- string " x=" *> range
y <- string ",y=" *> range
z <- string ",z=" *> range
return $ Instruction s $ Cube x y z
where
switch = choice [try (string "off") $> Off, try (string "on") $> On]
range = do
start <- int
end <- string ".." *> int
return $ Range start end
|
8e5f9cf392773313f6259945a8de630603160cae04f345782308364b48685c1e | larcenists/larceny | numbers.scm | numbers.scm - Sassy 's number predicates
Copyright ( C ) 2005
; This library 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 ; either
version 2.1 of the License , or ( at your option ) any later version .
; This library is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
; Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
; License along with this library; if not, write to the Free Software
Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
; Contact:
; 4130 43 ST #C2
Sunnyside , NY 11104
;
see file COPYING in the top of Sassy 's distribution directory
; module numbers
import srfi-60
; export all
; also loads "other/srfi-56-pieces.scm"
(define s-byte #f)
(define s-word #f)
(define s-dword #f)
(define s-qword #f)
(define u-byte #f)
(define u-word #f)
(define u-dword #f)
(define u-qword #f)
(let ((signed-x (lambda (bitfield)
(lambda (number)
(and (integer? number)
(exact? number)
(let ((tester (logand number bitfield)))
(or (zero? tester) (= tester bitfield)))))))
(unsigned-x (lambda (bitfield)
(lambda (number)
(and (integer? number)
(exact? number)
(= bitfield (logior number bitfield)))))))
(define s-byte-x (signed-x (- (expt 2 7))))
(define s-word-x (signed-x (- (expt 2 15))))
(define s-dword-x (signed-x (- (expt 2 31))))
(define s-qword-x (signed-x (- (expt 2 63))))
(define u-byte-x (unsigned-x (- (expt 2 8) 1)))
(define u-word-x (unsigned-x (- (expt 2 16) 1)))
(define u-dword-x (unsigned-x (- (expt 2 32) 1)))
(define u-qword-x (unsigned-x (- (expt 2 64) 1)))
(let ((num-x (lambda (pred key)
(lambda (x)
(or (and (pred x) x)
(and (pair? x) (equal? key (car x))
(not (null? (cdr x)))
(pred (cadr x))
(null? (cddr x))
(cadr x)))))))
(set! s-byte (memoize (num-x s-byte-x 'byte)))
(set! s-word (memoize (num-x s-word-x 'word)))
(set! s-dword (memoize (num-x s-dword-x 'dword)))
(set! s-qword (memoize (num-x s-qword-x 'qword)))
(set! u-byte (memoize (num-x u-byte-x 'byte)))
(set! u-word (memoize (num-x u-word-x 'word)))
(set! u-dword (memoize (num-x u-dword-x 'dword)))
(set! u-qword (memoize (num-x u-qword-x 'qword)))))
(define (u/s-byte x) (or (s-byte x) (u-byte x)))
(define (u/s-word x) (or (s-word x) (u-word x)))
(define (u/s-dword x) (or (s-dword x) (u-dword x) (real? x)))
(define (u/s-qword x) (or (s-qword x) (u-qword x) (real? x)))
; The byte-list returned is little-endian
(define (number->byte-list number size)
(cond ((integer? number) (integer->byte-list number size))
((real? number)
(cond ((= 4 size) (float32->byte-list number))
((= 8 size) (float64->byte-list number))
(else (error "bad size for float" number size))))
(else (error "not a number sassy can assemble" number))))
; The following all return little-endian byte-lists
; Very few scheme implementations provide something like
; integer->bytes or float->bytes. Those that do (including slib)
; return a string, so I would have write:
; (map char->integer (string->list (integer/float->bytes ...)))
; which is less efficient for sassy. So I'm using these instead...
(define (integer->byte-list orig-int orig-size)
(let iter ((int orig-int) (size orig-size))
(if (zero? size)
(if (or (zero? orig-int)
(and (positive? orig-int) (zero? int))
(and (negative? orig-int) (= -1 int)))
'()
(error "integer too big for field width" orig-int orig-size))
(cons (logand int 255) (iter (ash int -8) (- size 1))))))
; (load "other/srfi-56-pieces.scm")
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/src/Lib/Sassy/numbers.scm | scheme | This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this library; if not, write to the Free Software
Contact:
4130 43 ST #C2
module numbers
export all
also loads "other/srfi-56-pieces.scm"
The byte-list returned is little-endian
The following all return little-endian byte-lists
Very few scheme implementations provide something like
integer->bytes or float->bytes. Those that do (including slib)
return a string, so I would have write:
(map char->integer (string->list (integer/float->bytes ...)))
which is less efficient for sassy. So I'm using these instead...
(load "other/srfi-56-pieces.scm") | numbers.scm - Sassy 's number predicates
Copyright ( C ) 2005
version 2.1 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
Sunnyside , NY 11104
see file COPYING in the top of Sassy 's distribution directory
import srfi-60
(define s-byte #f)
(define s-word #f)
(define s-dword #f)
(define s-qword #f)
(define u-byte #f)
(define u-word #f)
(define u-dword #f)
(define u-qword #f)
(let ((signed-x (lambda (bitfield)
(lambda (number)
(and (integer? number)
(exact? number)
(let ((tester (logand number bitfield)))
(or (zero? tester) (= tester bitfield)))))))
(unsigned-x (lambda (bitfield)
(lambda (number)
(and (integer? number)
(exact? number)
(= bitfield (logior number bitfield)))))))
(define s-byte-x (signed-x (- (expt 2 7))))
(define s-word-x (signed-x (- (expt 2 15))))
(define s-dword-x (signed-x (- (expt 2 31))))
(define s-qword-x (signed-x (- (expt 2 63))))
(define u-byte-x (unsigned-x (- (expt 2 8) 1)))
(define u-word-x (unsigned-x (- (expt 2 16) 1)))
(define u-dword-x (unsigned-x (- (expt 2 32) 1)))
(define u-qword-x (unsigned-x (- (expt 2 64) 1)))
(let ((num-x (lambda (pred key)
(lambda (x)
(or (and (pred x) x)
(and (pair? x) (equal? key (car x))
(not (null? (cdr x)))
(pred (cadr x))
(null? (cddr x))
(cadr x)))))))
(set! s-byte (memoize (num-x s-byte-x 'byte)))
(set! s-word (memoize (num-x s-word-x 'word)))
(set! s-dword (memoize (num-x s-dword-x 'dword)))
(set! s-qword (memoize (num-x s-qword-x 'qword)))
(set! u-byte (memoize (num-x u-byte-x 'byte)))
(set! u-word (memoize (num-x u-word-x 'word)))
(set! u-dword (memoize (num-x u-dword-x 'dword)))
(set! u-qword (memoize (num-x u-qword-x 'qword)))))
(define (u/s-byte x) (or (s-byte x) (u-byte x)))
(define (u/s-word x) (or (s-word x) (u-word x)))
(define (u/s-dword x) (or (s-dword x) (u-dword x) (real? x)))
(define (u/s-qword x) (or (s-qword x) (u-qword x) (real? x)))
(define (number->byte-list number size)
(cond ((integer? number) (integer->byte-list number size))
((real? number)
(cond ((= 4 size) (float32->byte-list number))
((= 8 size) (float64->byte-list number))
(else (error "bad size for float" number size))))
(else (error "not a number sassy can assemble" number))))
(define (integer->byte-list orig-int orig-size)
(let iter ((int orig-int) (size orig-size))
(if (zero? size)
(if (or (zero? orig-int)
(and (positive? orig-int) (zero? int))
(and (negative? orig-int) (= -1 int)))
'()
(error "integer too big for field width" orig-int orig-size))
(cons (logand int 255) (iter (ash int -8) (- size 1))))))
|
def8c141fae60de303b1cc666251fa662dc100182c62b1a421e2c5aa34ab8db5 | zhongwencool/observer_cli | observer_cli_inet.erl | %%% @author zhongwen <>
-module(observer_cli_inet).
-include("observer_cli.hrl").
%% API
-export([start/1]).
-export([clean/1]).
-define(LAST_LINE,
"q(quit) ic(inet_count) iw(inet_window) rc(recv_cnt) ro(recv_oct)"
" sc(send_cnt) so(send_oct) cnt oct 9(port 9 info) pd/pu(page:down/up)"
).
-spec start(view_opts()) -> no_return.
start(#view_opts{inet = InetOpt, auto_row = AutoRow} = ViewOpts) ->
StorePid = observer_cli_store:start(),
RenderPid = spawn_link(
fun() ->
?output(?CLEAR),
{{input, In}, {output, Out}} = erlang:statistics(io),
render_worker(StorePid, InetOpt, ?INIT_TIME_REF, 0, {In, Out}, AutoRow)
end
),
manager(StorePid, RenderPid, ViewOpts).
-spec clean(list()) -> ok.
clean(Pids) -> observer_cli_lib:exit_processes(Pids).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Private
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
manager(StorePid, RenderPid, ViewOpts = #view_opts{inet = InetOpts}) ->
#inet{cur_page = CurPage, pages = Pages} = InetOpts,
case observer_cli_lib:parse_cmd(ViewOpts, ?MODULE, [RenderPid, StorePid]) of
quit ->
observer_cli_lib:exit_processes([StorePid]),
erlang:send(RenderPid, quit);
{new_interval, NewInterval} ->
erlang:send(RenderPid, {new_interval, NewInterval}),
NewInet = InetOpts#inet{interval = NewInterval},
manager(StorePid, RenderPid, ViewOpts#view_opts{inet = NewInet});
Func when Func =:= inet_count; Func =:= inet_window ->
clean([StorePid, RenderPid]),
start(ViewOpts#view_opts{inet = InetOpts#inet{func = Func}});
Type when
Type =:= recv_cnt;
Type =:= recv_oct;
Type =:= send_cnt;
Type =:= send_oct;
Type =:= cnt;
Type =:= oct
->
clean([StorePid, RenderPid]),
start(ViewOpts#view_opts{inet = InetOpts#inet{type = Type}});
{jump, NewPos} ->
NewPages = observer_cli_lib:update_page_pos(CurPage, NewPos, Pages),
NewInetOpts = InetOpts#inet{pages = NewPages},
start_port_view(StorePid, RenderPid, ViewOpts#view_opts{inet = NewInetOpts}, false);
jump ->
start_port_view(StorePid, RenderPid, ViewOpts, true);
page_down_top_n ->
NewPage = max(CurPage + 1, 1),
NewPages = observer_cli_lib:update_page_pos(StorePid, NewPage, Pages),
clean([StorePid, RenderPid]),
start(ViewOpts#view_opts{inet = InetOpts#inet{cur_page = NewPage, pages = NewPages}});
page_up_top_n ->
NewPage = max(CurPage - 1, 1),
NewPages = observer_cli_lib:update_page_pos(StorePid, NewPage, Pages),
clean([StorePid, RenderPid]),
start(ViewOpts#view_opts{inet = InetOpts#inet{cur_page = NewPage, pages = NewPages}});
_ ->
manager(StorePid, RenderPid, ViewOpts)
end.
render_worker(StorePid, InetOpt, LastTimeRef, Count, LastIO, AutoRow) ->
#inet{func = Function, type = Type, interval = Interval, cur_page = CurPage} = InetOpt,
TerminalRow = observer_cli_lib:get_terminal_rows(AutoRow),
Row = erlang:max(TerminalRow - 5, 0),
Text = get_menu_str(Function, Type, Interval, Row),
Menu = observer_cli_lib:render_menu(inet, Text),
TopLen = Row * CurPage,
InetList = inet_info(Function, Type, TopLen, Interval, Count),
{IORows, NewIO} = render_io_rows(LastIO),
{PortList, InetRows} = render_inet_rows(InetList, TopLen, InetOpt),
LastLine = observer_cli_lib:render_last_line(?LAST_LINE),
?output([?CURSOR_TOP, Menu, IORows, InetRows, LastLine]),
observer_cli_store:update(StorePid, Row, PortList),
NewInterval =
case Function of
inet_count -> Interval;
inet_window -> 10
end,
TimeRef = observer_cli_lib:next_redraw(LastTimeRef, NewInterval),
receive
{new_interval, NewInterval} ->
?output(?CLEAR),
render_worker(
StorePid,
InetOpt#inet{interval = NewInterval},
TimeRef,
Count + 1,
NewIO,
AutoRow
);
quit ->
quit;
_ ->
render_worker(StorePid, InetOpt, TimeRef, Count + 1, NewIO, AutoRow)
end.
render_io_rows({LastIn, LastOut}) ->
{{input, In}, {output, Out}} = erlang:statistics(io),
{
?render([
?YELLOW,
?W("Byte Input", 14),
?W({byte, In - LastIn}, 12),
?W("Byte Output", 13),
?W({byte, Out - LastOut}, 12),
?W("Total Input", 15),
?W({byte, In}, 17),
?W("Total Output", 15),
?W({byte, Out}, 17)
]),
{In, Out}
}.
render_inet_rows([], Rows, #inet{func = inet_count, type = Type}) ->
{[], io_lib:format("\e[32;1mGet nothing for recon:inet_count(~p, ~p)\e[0m~n", [Type, Rows])};
render_inet_rows([], Rows, #inet{func = inet_window, type = Type, interval = Interval}) ->
{[],
io_lib:format("\e[32;1mGet nothing for recon:inet_window(~p, ~p, ~p)\e[0m~n", [
Type,
Rows,
Interval
])};
render_inet_rows(InetList, Num, #inet{
type = Type,
pages = Pages,
cur_page = Page
}) when Type =:= cnt orelse Type =:= oct ->
{Unit, RecvType, SendType} = trans_type(Type),
Title = title(Type, RecvType, SendType),
{Start, ChoosePos} = observer_cli_lib:get_pos(Page, Num, Pages, erlang:length(InetList)),
FormatFunc = fun(Item, {Acc, Acc1, Pos}) ->
{Port, Value, [{_, Recv}, {_, Send}]} = Item,
{memory_used, MemoryUsed} = recon:port_info(Port, memory_used),
{io, IO} = recon:port_info(Port, io),
Input = proplists:get_value(input, IO),
Output = proplists:get_value(output, IO),
QueueSize = proplists:get_value(queue_size, MemoryUsed),
Memory = proplists:get_value(memory, MemoryUsed),
IP = get_remote_ip(Port),
{ValueFormat, RecvFormat, SendFormat} = trans_format(Unit, Value, Recv, Send),
R = [
?W(Pos, 2),
?W(Port, 16),
ValueFormat,
RecvFormat,
SendFormat,
?W({byte, Output}, 12),
?W({byte, Input}, 12),
?W(QueueSize, 6),
?W({byte, Memory}, 12),
?W(IP, 19)
],
Rows = add_choose_color(ChoosePos, Pos, R),
{[?render(Rows) | Acc], [{Pos, Port} | Acc1], Pos + 1}
end,
{Rows, PortList, _} = lists:foldl(
FormatFunc,
{[], [], Start},
lists:sublist(InetList, Start, Num)
),
{PortList, [Title | lists:reverse(Rows)]};
render_inet_rows(InetList, Num, #inet{type = Type, pages = Pages, cur_page = Page}) ->
{Unit, Type1, Type2} = trans_type(Type),
Title = title(Type, Type1, Type2),
{Start, ChoosePos} = observer_cli_lib:get_pos(Page, Num, Pages, erlang:length(InetList)),
FormatFunc = fun(Item, {Acc, Acc1, Pos}) ->
{Port, Value, _} = Item,
{memory_used, MemoryUsed} = recon:port_info(Port, memory_used),
{io, IO} = recon:port_info(Port, io),
Input = proplists:get_value(input, IO),
Output = proplists:get_value(output, IO),
QueueSize = proplists:get_value(queue_size, MemoryUsed),
Memory = proplists:get_value(memory, MemoryUsed),
IP = get_remote_ip(Port),
Packet1 = getstat(Port, erlang:list_to_existing_atom(Type1)),
AllPacket =
case is_integer(Packet1) of
true -> Value + Packet1;
false -> Value
end,
{ValueFormat, Packet1Format, AllFormat} = trans_format(Unit, Value, Packet1, AllPacket),
R = [
?W(Pos, 2),
?W(Port, 16),
ValueFormat,
Packet1Format,
AllFormat,
?W({byte, Input}, 12),
?W({byte, Output}, 12),
?W(QueueSize, 6),
?W({byte, Memory}, 12),
?W(IP, 19)
],
Rows = add_choose_color(ChoosePos, Pos, R),
{[?render(Rows) | Acc], [{Pos, Port} | Acc1], Pos + 1}
end,
{Rows, PortList, _} = lists:foldl(
FormatFunc,
{[], [], Start},
lists:sublist(InetList, Start, Num)
),
{PortList, [Title | lists:reverse(Rows)]}.
get_menu_str(inet_count, Type, Interval, Rows) ->
io_lib:format("recon:inet_count(~p, ~w) Interval:~wms", [Type, Rows, Interval]);
get_menu_str(inet_window, Type, Interval, Rows) ->
io_lib:format("recon:inet_window(~p, ~w, ~w) Interval:~wms", [Type, Rows, Interval, Interval]).
inet_info(inet_count, Type, Num, _, _) -> recon:inet_count(Type, Num);
inet_info(inet_window, Type, Num, _, 0) -> recon:inet_count(Type, Num);
inet_info(inet_window, Type, Num, Ms, _) -> recon:inet_window(Type, Num, Ms).
getstat(Port, Attr) ->
case inet:getstat(Port, [Attr]) of
{ok, [{_, Value}]} -> Value;
{error, Err} -> inet:format_error(Err)
end.
start_port_view(StorePid, RenderPid, Opts = #view_opts{inet = InetOpt}, AutoJump) ->
#inet{cur_page = CurPage, pages = Pages} = InetOpt,
{_, CurPos} = lists:keyfind(CurPage, 1, Pages),
case observer_cli_store:lookup_pos(StorePid, CurPos) of
{CurPos, ChoosePort} ->
clean([StorePid, RenderPid]),
observer_cli_port:start(ChoosePort, Opts);
{_, ChoosePort} when AutoJump ->
clean([StorePid, RenderPid]),
observer_cli_port:start(ChoosePort, Opts);
_ ->
manager(StorePid, RenderPid, Opts)
end.
trans_type(cnt) ->
{number, "recv_cnt", "send_cnt"};
trans_type(oct) ->
{byte, "recv_oct", "send_oct"};
trans_type(send_cnt) ->
{number, "recv_cnt", "cnt"};
trans_type(recv_cnt) ->
{number, "send_cnt", "cnt"};
trans_type(send_oct) ->
{byte, "recv_oct", "oct"};
trans_type(recv_oct) ->
{byte, "send_oct", "oct"}.
trans_format(byte, Val, Val1, Val2) ->
{
?W({byte, Val}, 10),
?W({byte, Val1}, 10),
?W({byte, Val2}, 10)
};
trans_format(number, Val, Val1, Val2) ->
{
?W(Val, 10),
?W(Val1, 10),
?W(Val2, 10)
}.
title(Type, Type1, Type2) ->
?render([
?UNDERLINE,
?GRAY_BG,
?W("NO", 2),
?W("Port", 16),
?W(erlang:atom_to_list(Type), 10),
?W(Type1, 10),
?W(Type2, 10),
?W("output", 12),
?W("input", 12),
?W("queuesize", 6),
?W("memory", 12),
?W("Peername(ip:port)", 19)
]).
get_remote_ip(P) ->
case inet:peername(P) of
{ok, {Addr, Port}} ->
AddrList = [
begin
erlang:integer_to_list(A)
end
|| A <- erlang:tuple_to_list(Addr)
],
string:join(AddrList, ".") ++ ":" ++ erlang:integer_to_list(Port);
{error, Err} ->
inet:format_error(Err)
end.
add_choose_color(ChoosePos, ChoosePos, R) -> [?CHOOSE_BG | R];
add_choose_color(_ChoosePos, _CurPos, R) -> R.
| null | https://raw.githubusercontent.com/zhongwencool/observer_cli/baa70569bccc5508e9839e20768540ef3cdca016/src/observer_cli_inet.erl | erlang | @author zhongwen <>
API
Private
| -module(observer_cli_inet).
-include("observer_cli.hrl").
-export([start/1]).
-export([clean/1]).
-define(LAST_LINE,
"q(quit) ic(inet_count) iw(inet_window) rc(recv_cnt) ro(recv_oct)"
" sc(send_cnt) so(send_oct) cnt oct 9(port 9 info) pd/pu(page:down/up)"
).
-spec start(view_opts()) -> no_return.
start(#view_opts{inet = InetOpt, auto_row = AutoRow} = ViewOpts) ->
StorePid = observer_cli_store:start(),
RenderPid = spawn_link(
fun() ->
?output(?CLEAR),
{{input, In}, {output, Out}} = erlang:statistics(io),
render_worker(StorePid, InetOpt, ?INIT_TIME_REF, 0, {In, Out}, AutoRow)
end
),
manager(StorePid, RenderPid, ViewOpts).
-spec clean(list()) -> ok.
clean(Pids) -> observer_cli_lib:exit_processes(Pids).
manager(StorePid, RenderPid, ViewOpts = #view_opts{inet = InetOpts}) ->
#inet{cur_page = CurPage, pages = Pages} = InetOpts,
case observer_cli_lib:parse_cmd(ViewOpts, ?MODULE, [RenderPid, StorePid]) of
quit ->
observer_cli_lib:exit_processes([StorePid]),
erlang:send(RenderPid, quit);
{new_interval, NewInterval} ->
erlang:send(RenderPid, {new_interval, NewInterval}),
NewInet = InetOpts#inet{interval = NewInterval},
manager(StorePid, RenderPid, ViewOpts#view_opts{inet = NewInet});
Func when Func =:= inet_count; Func =:= inet_window ->
clean([StorePid, RenderPid]),
start(ViewOpts#view_opts{inet = InetOpts#inet{func = Func}});
Type when
Type =:= recv_cnt;
Type =:= recv_oct;
Type =:= send_cnt;
Type =:= send_oct;
Type =:= cnt;
Type =:= oct
->
clean([StorePid, RenderPid]),
start(ViewOpts#view_opts{inet = InetOpts#inet{type = Type}});
{jump, NewPos} ->
NewPages = observer_cli_lib:update_page_pos(CurPage, NewPos, Pages),
NewInetOpts = InetOpts#inet{pages = NewPages},
start_port_view(StorePid, RenderPid, ViewOpts#view_opts{inet = NewInetOpts}, false);
jump ->
start_port_view(StorePid, RenderPid, ViewOpts, true);
page_down_top_n ->
NewPage = max(CurPage + 1, 1),
NewPages = observer_cli_lib:update_page_pos(StorePid, NewPage, Pages),
clean([StorePid, RenderPid]),
start(ViewOpts#view_opts{inet = InetOpts#inet{cur_page = NewPage, pages = NewPages}});
page_up_top_n ->
NewPage = max(CurPage - 1, 1),
NewPages = observer_cli_lib:update_page_pos(StorePid, NewPage, Pages),
clean([StorePid, RenderPid]),
start(ViewOpts#view_opts{inet = InetOpts#inet{cur_page = NewPage, pages = NewPages}});
_ ->
manager(StorePid, RenderPid, ViewOpts)
end.
render_worker(StorePid, InetOpt, LastTimeRef, Count, LastIO, AutoRow) ->
#inet{func = Function, type = Type, interval = Interval, cur_page = CurPage} = InetOpt,
TerminalRow = observer_cli_lib:get_terminal_rows(AutoRow),
Row = erlang:max(TerminalRow - 5, 0),
Text = get_menu_str(Function, Type, Interval, Row),
Menu = observer_cli_lib:render_menu(inet, Text),
TopLen = Row * CurPage,
InetList = inet_info(Function, Type, TopLen, Interval, Count),
{IORows, NewIO} = render_io_rows(LastIO),
{PortList, InetRows} = render_inet_rows(InetList, TopLen, InetOpt),
LastLine = observer_cli_lib:render_last_line(?LAST_LINE),
?output([?CURSOR_TOP, Menu, IORows, InetRows, LastLine]),
observer_cli_store:update(StorePid, Row, PortList),
NewInterval =
case Function of
inet_count -> Interval;
inet_window -> 10
end,
TimeRef = observer_cli_lib:next_redraw(LastTimeRef, NewInterval),
receive
{new_interval, NewInterval} ->
?output(?CLEAR),
render_worker(
StorePid,
InetOpt#inet{interval = NewInterval},
TimeRef,
Count + 1,
NewIO,
AutoRow
);
quit ->
quit;
_ ->
render_worker(StorePid, InetOpt, TimeRef, Count + 1, NewIO, AutoRow)
end.
render_io_rows({LastIn, LastOut}) ->
{{input, In}, {output, Out}} = erlang:statistics(io),
{
?render([
?YELLOW,
?W("Byte Input", 14),
?W({byte, In - LastIn}, 12),
?W("Byte Output", 13),
?W({byte, Out - LastOut}, 12),
?W("Total Input", 15),
?W({byte, In}, 17),
?W("Total Output", 15),
?W({byte, Out}, 17)
]),
{In, Out}
}.
render_inet_rows([], Rows, #inet{func = inet_count, type = Type}) ->
{[], io_lib:format("\e[32;1mGet nothing for recon:inet_count(~p, ~p)\e[0m~n", [Type, Rows])};
render_inet_rows([], Rows, #inet{func = inet_window, type = Type, interval = Interval}) ->
{[],
io_lib:format("\e[32;1mGet nothing for recon:inet_window(~p, ~p, ~p)\e[0m~n", [
Type,
Rows,
Interval
])};
render_inet_rows(InetList, Num, #inet{
type = Type,
pages = Pages,
cur_page = Page
}) when Type =:= cnt orelse Type =:= oct ->
{Unit, RecvType, SendType} = trans_type(Type),
Title = title(Type, RecvType, SendType),
{Start, ChoosePos} = observer_cli_lib:get_pos(Page, Num, Pages, erlang:length(InetList)),
FormatFunc = fun(Item, {Acc, Acc1, Pos}) ->
{Port, Value, [{_, Recv}, {_, Send}]} = Item,
{memory_used, MemoryUsed} = recon:port_info(Port, memory_used),
{io, IO} = recon:port_info(Port, io),
Input = proplists:get_value(input, IO),
Output = proplists:get_value(output, IO),
QueueSize = proplists:get_value(queue_size, MemoryUsed),
Memory = proplists:get_value(memory, MemoryUsed),
IP = get_remote_ip(Port),
{ValueFormat, RecvFormat, SendFormat} = trans_format(Unit, Value, Recv, Send),
R = [
?W(Pos, 2),
?W(Port, 16),
ValueFormat,
RecvFormat,
SendFormat,
?W({byte, Output}, 12),
?W({byte, Input}, 12),
?W(QueueSize, 6),
?W({byte, Memory}, 12),
?W(IP, 19)
],
Rows = add_choose_color(ChoosePos, Pos, R),
{[?render(Rows) | Acc], [{Pos, Port} | Acc1], Pos + 1}
end,
{Rows, PortList, _} = lists:foldl(
FormatFunc,
{[], [], Start},
lists:sublist(InetList, Start, Num)
),
{PortList, [Title | lists:reverse(Rows)]};
render_inet_rows(InetList, Num, #inet{type = Type, pages = Pages, cur_page = Page}) ->
{Unit, Type1, Type2} = trans_type(Type),
Title = title(Type, Type1, Type2),
{Start, ChoosePos} = observer_cli_lib:get_pos(Page, Num, Pages, erlang:length(InetList)),
FormatFunc = fun(Item, {Acc, Acc1, Pos}) ->
{Port, Value, _} = Item,
{memory_used, MemoryUsed} = recon:port_info(Port, memory_used),
{io, IO} = recon:port_info(Port, io),
Input = proplists:get_value(input, IO),
Output = proplists:get_value(output, IO),
QueueSize = proplists:get_value(queue_size, MemoryUsed),
Memory = proplists:get_value(memory, MemoryUsed),
IP = get_remote_ip(Port),
Packet1 = getstat(Port, erlang:list_to_existing_atom(Type1)),
AllPacket =
case is_integer(Packet1) of
true -> Value + Packet1;
false -> Value
end,
{ValueFormat, Packet1Format, AllFormat} = trans_format(Unit, Value, Packet1, AllPacket),
R = [
?W(Pos, 2),
?W(Port, 16),
ValueFormat,
Packet1Format,
AllFormat,
?W({byte, Input}, 12),
?W({byte, Output}, 12),
?W(QueueSize, 6),
?W({byte, Memory}, 12),
?W(IP, 19)
],
Rows = add_choose_color(ChoosePos, Pos, R),
{[?render(Rows) | Acc], [{Pos, Port} | Acc1], Pos + 1}
end,
{Rows, PortList, _} = lists:foldl(
FormatFunc,
{[], [], Start},
lists:sublist(InetList, Start, Num)
),
{PortList, [Title | lists:reverse(Rows)]}.
get_menu_str(inet_count, Type, Interval, Rows) ->
io_lib:format("recon:inet_count(~p, ~w) Interval:~wms", [Type, Rows, Interval]);
get_menu_str(inet_window, Type, Interval, Rows) ->
io_lib:format("recon:inet_window(~p, ~w, ~w) Interval:~wms", [Type, Rows, Interval, Interval]).
inet_info(inet_count, Type, Num, _, _) -> recon:inet_count(Type, Num);
inet_info(inet_window, Type, Num, _, 0) -> recon:inet_count(Type, Num);
inet_info(inet_window, Type, Num, Ms, _) -> recon:inet_window(Type, Num, Ms).
getstat(Port, Attr) ->
case inet:getstat(Port, [Attr]) of
{ok, [{_, Value}]} -> Value;
{error, Err} -> inet:format_error(Err)
end.
start_port_view(StorePid, RenderPid, Opts = #view_opts{inet = InetOpt}, AutoJump) ->
#inet{cur_page = CurPage, pages = Pages} = InetOpt,
{_, CurPos} = lists:keyfind(CurPage, 1, Pages),
case observer_cli_store:lookup_pos(StorePid, CurPos) of
{CurPos, ChoosePort} ->
clean([StorePid, RenderPid]),
observer_cli_port:start(ChoosePort, Opts);
{_, ChoosePort} when AutoJump ->
clean([StorePid, RenderPid]),
observer_cli_port:start(ChoosePort, Opts);
_ ->
manager(StorePid, RenderPid, Opts)
end.
trans_type(cnt) ->
{number, "recv_cnt", "send_cnt"};
trans_type(oct) ->
{byte, "recv_oct", "send_oct"};
trans_type(send_cnt) ->
{number, "recv_cnt", "cnt"};
trans_type(recv_cnt) ->
{number, "send_cnt", "cnt"};
trans_type(send_oct) ->
{byte, "recv_oct", "oct"};
trans_type(recv_oct) ->
{byte, "send_oct", "oct"}.
trans_format(byte, Val, Val1, Val2) ->
{
?W({byte, Val}, 10),
?W({byte, Val1}, 10),
?W({byte, Val2}, 10)
};
trans_format(number, Val, Val1, Val2) ->
{
?W(Val, 10),
?W(Val1, 10),
?W(Val2, 10)
}.
title(Type, Type1, Type2) ->
?render([
?UNDERLINE,
?GRAY_BG,
?W("NO", 2),
?W("Port", 16),
?W(erlang:atom_to_list(Type), 10),
?W(Type1, 10),
?W(Type2, 10),
?W("output", 12),
?W("input", 12),
?W("queuesize", 6),
?W("memory", 12),
?W("Peername(ip:port)", 19)
]).
get_remote_ip(P) ->
case inet:peername(P) of
{ok, {Addr, Port}} ->
AddrList = [
begin
erlang:integer_to_list(A)
end
|| A <- erlang:tuple_to_list(Addr)
],
string:join(AddrList, ".") ++ ":" ++ erlang:integer_to_list(Port);
{error, Err} ->
inet:format_error(Err)
end.
add_choose_color(ChoosePos, ChoosePos, R) -> [?CHOOSE_BG | R];
add_choose_color(_ChoosePos, _CurPos, R) -> R.
|
3a1f61f46950a35dd9da7572518191a01ad2e795d2629c4d609c0f0f0f1ed2bd | qfpl/sv | bench.hs | module Main (main) where
import Control.Applicative ((*>))
import Control.DeepSeq (NFData)
import Control.Lens
import Criterion.Main
import qualified Data.Attoparsec.ByteString as A
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LBS
import Data.Csv as C
import Data.Csv.Parser as C
import Data.Vector (Vector)
import HaskellWorks.Data.Dsv.Lazy.Cursor (DsvCursor, makeCursor)
import System.Exit (exitFailure)
import Data.Sv (Validation (Failure, Success), DecodeValidation, ParseOptions, defaultParseOptions, headedness, Headedness (Unheaded), comma, parseDecode, parseDecodeFromDsvCursor)
import Data.Sv.Cassava (parseDecodeFromCassava)
import Data.Sv.Random
opts :: ParseOptions
opts = defaultParseOptions & headedness .~ Unheaded
failOnError :: Show e => DecodeValidation e a -> IO a
failOnError v = case v of
Failure e -> do
putStr "Sanity check failed: "
print e
exitFailure
Success s -> pure s
failOnLeft :: Show s => Either s a -> IO a
failOnLeft = either (\s -> print s *> exitFailure) pure
sanitySv :: ByteString -> IO DsvCursor
sanitySv bs = do
_ <- failOnError (parseDec bs)
let s = parse bs
_ <- failOnError (dec s)
s `seq` pure s
sanityCassava :: ByteString -> IO Csv
sanityCassava bs = do
s <- failOnLeft (parseCassava bs)
_ <- failOnLeft (decCassava s)
_ <- failOnLeft (parseDecCassava bs)
s `seq` pure s
parse :: ByteString -> DsvCursor
parse = makeCursor comma . LBS.fromStrict
dec :: DsvCursor -> DecodeValidation ByteString [Row]
dec = parseDecodeFromDsvCursor rowDec opts
decCassava :: C.Csv -> Either String (Vector Row)
decCassava = runParser . traverse parseRecord
parseDec :: ByteString -> DecodeValidation ByteString [Row]
parseDec = parseDecode rowDec opts . LBS.fromStrict
parseCassava :: ByteString -> Either String C.Csv
parseCassava = A.parseOnly (C.csv C.defaultDecodeOptions)
parseDecCassava :: ByteString -> Either String (Vector Row)
parseDecCassava = C.decode C.NoHeader . LBS.fromStrict
parseCassavaDecSv :: ByteString -> DecodeValidation ByteString [Row]
parseCassavaDecSv = parseDecodeFromCassava rowDec Unheaded C.defaultDecodeOptions
mkBench :: NFData b => String -> (a -> b) -> BenchData a -> Benchmark
mkBench nm func bs = bgroup nm [
bench "1" $ nf func (f1 bs)
, bench "10" $ nf func (f10 bs)
, bench "100" $ nf func (f100 bs)
, bench "500" $ nf func (f500 bs)
, bench "1000" $ nf func (f1000 bs)
, bench "5000" $ nf func (f5000 bs)
, bench "10000" $ nf func (f10000 bs)
, bench "50000" $ nf func (f50000 bs)
, bench "100000" $ nf func (f100000 bs)
]
main :: IO ()
main = do
benchData <- loadOrCreateTestFiles
cassavas <- traverse sanityCassava benchData
svs <- traverse sanitySv benchData
defaultMain
[ mkBench "Parse hw-dsv" parse benchData
, mkBench "Parse Cassava" parseCassava benchData
, mkBench "Decode sv" dec svs
, mkBench "Decode Cassava" decCassava cassavas
, mkBench "Parse and decode sv" parseDec benchData
, mkBench "Parse with Cassava, decode with sv" parseCassavaDecSv benchData
, mkBench "Parse and decode Cassava" parseDecCassava benchData
]
| null | https://raw.githubusercontent.com/qfpl/sv/74aa56bcdcc0d7f1d7b5783bf59e3878dfbb64bc/benchmarks/bench/bench.hs | haskell | module Main (main) where
import Control.Applicative ((*>))
import Control.DeepSeq (NFData)
import Control.Lens
import Criterion.Main
import qualified Data.Attoparsec.ByteString as A
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LBS
import Data.Csv as C
import Data.Csv.Parser as C
import Data.Vector (Vector)
import HaskellWorks.Data.Dsv.Lazy.Cursor (DsvCursor, makeCursor)
import System.Exit (exitFailure)
import Data.Sv (Validation (Failure, Success), DecodeValidation, ParseOptions, defaultParseOptions, headedness, Headedness (Unheaded), comma, parseDecode, parseDecodeFromDsvCursor)
import Data.Sv.Cassava (parseDecodeFromCassava)
import Data.Sv.Random
opts :: ParseOptions
opts = defaultParseOptions & headedness .~ Unheaded
failOnError :: Show e => DecodeValidation e a -> IO a
failOnError v = case v of
Failure e -> do
putStr "Sanity check failed: "
print e
exitFailure
Success s -> pure s
failOnLeft :: Show s => Either s a -> IO a
failOnLeft = either (\s -> print s *> exitFailure) pure
sanitySv :: ByteString -> IO DsvCursor
sanitySv bs = do
_ <- failOnError (parseDec bs)
let s = parse bs
_ <- failOnError (dec s)
s `seq` pure s
sanityCassava :: ByteString -> IO Csv
sanityCassava bs = do
s <- failOnLeft (parseCassava bs)
_ <- failOnLeft (decCassava s)
_ <- failOnLeft (parseDecCassava bs)
s `seq` pure s
parse :: ByteString -> DsvCursor
parse = makeCursor comma . LBS.fromStrict
dec :: DsvCursor -> DecodeValidation ByteString [Row]
dec = parseDecodeFromDsvCursor rowDec opts
decCassava :: C.Csv -> Either String (Vector Row)
decCassava = runParser . traverse parseRecord
parseDec :: ByteString -> DecodeValidation ByteString [Row]
parseDec = parseDecode rowDec opts . LBS.fromStrict
parseCassava :: ByteString -> Either String C.Csv
parseCassava = A.parseOnly (C.csv C.defaultDecodeOptions)
parseDecCassava :: ByteString -> Either String (Vector Row)
parseDecCassava = C.decode C.NoHeader . LBS.fromStrict
parseCassavaDecSv :: ByteString -> DecodeValidation ByteString [Row]
parseCassavaDecSv = parseDecodeFromCassava rowDec Unheaded C.defaultDecodeOptions
mkBench :: NFData b => String -> (a -> b) -> BenchData a -> Benchmark
mkBench nm func bs = bgroup nm [
bench "1" $ nf func (f1 bs)
, bench "10" $ nf func (f10 bs)
, bench "100" $ nf func (f100 bs)
, bench "500" $ nf func (f500 bs)
, bench "1000" $ nf func (f1000 bs)
, bench "5000" $ nf func (f5000 bs)
, bench "10000" $ nf func (f10000 bs)
, bench "50000" $ nf func (f50000 bs)
, bench "100000" $ nf func (f100000 bs)
]
main :: IO ()
main = do
benchData <- loadOrCreateTestFiles
cassavas <- traverse sanityCassava benchData
svs <- traverse sanitySv benchData
defaultMain
[ mkBench "Parse hw-dsv" parse benchData
, mkBench "Parse Cassava" parseCassava benchData
, mkBench "Decode sv" dec svs
, mkBench "Decode Cassava" decCassava cassavas
, mkBench "Parse and decode sv" parseDec benchData
, mkBench "Parse with Cassava, decode with sv" parseCassavaDecSv benchData
, mkBench "Parse and decode Cassava" parseDecCassava benchData
]
| |
ebf74a76c6572abe3b3abb5e6a323a613503a173ce3ee80f26e77009db3658ca | htm-community/comportex | tools.cljc | (ns org.nfrac.comportex.layer.tools
(:require [org.nfrac.comportex.core :as cx]
[org.nfrac.comportex.synapses :as syn]
[org.nfrac.comportex.topography :as topo]
[org.nfrac.comportex.layer :as layer]
[org.nfrac.comportex.util :as util]
[clojure.set :as set]
[clojure.spec :as s]
[#?(:clj clojure.spec.gen :cljs clojure.spec.impl.gen) :as gen]))
(defn source-of-distal-bit
"Returns [src-id j] where src-id may be a layer key or sense key, and j is
the index into the output of the source."
[htm lyr-id i]
(let [lyr (get-in htm [:layers lyr-id])
params (cx/params lyr)
[src-type j] (layer/id->source params (:embedding lyr) i)]
(case src-type
:this [lyr-id i]
:lat (cx/source-of-incoming-bit htm lyr-id j :lat-deps))))
(defn source-of-apical-bit
"Returns [src-id j] where src-id is a layer key, and j is the index into the
output of the source layer."
[htm lyr-id i]
(cx/source-of-incoming-bit htm lyr-id i :fb-deps))
(defn- zap-fewer
[n xs]
(if (< (count xs) n) (empty xs) xs))
(defn cell-excitation-breakdowns
"Calculates the various sources contributing to total excitation
level of each of the `cell-ids` in the given layer. Returns a map
keyed by these cell ids. Each cell value is a map with keys
* :total - number.
* :proximal-unstable - a map keyed by source layer/sense id.
* :proximal-stable - a map keyed by source layer/sense id.
* :distal - a map keyed by source layer/sense id.
* :boost - number.
"
[htm prior-htm lyr-id cell-ids]
(let [lyr (get-in htm [:layers lyr-id])
prior-lyr (get-in prior-htm [:layers lyr-id])
params (:params lyr)
ff-stim-thresh (:stimulus-threshold (:proximal params))
d-stim-thresh (:stimulus-threshold (:distal params))
a-stim-thresh (:stimulus-threshold (:apical params))
distal-weight (:distal-vs-proximal-weight params)
active-state (:active-state lyr)
prior-active-state (:active-state prior-lyr)
distal-state (:distal-state prior-lyr)
apical-state (:apical-state prior-lyr)
;; inputs to layer
ff-bits (-> active-state :in-ff-signal :bits set)
ff-s-bits (-> active-state :in-ff-signal ::layer/stable-bits set)
ff-b-bits (set/difference ff-bits ff-s-bits)
distal-bits (:active-bits distal-state)
apical-bits (:active-bits apical-state)
ff-bits-srcs (into {}
(map (fn [i]
(let [[k _] (cx/source-of-incoming-bit
htm lyr-id i :ff-bits)]
[i k])))
ff-bits)
distal-bits-srcs (into {}
(map (fn [i]
(let [[k _] (source-of-distal-bit
htm lyr-id i)]
[i k])))
distal-bits)
apical-bits-srcs (into {}
(map (fn [i]
(let [[k _] (source-of-apical-bit
htm lyr-id i)]
[i k])))
apical-bits)
;; synapse graphs - pre-learning state so from prior time step
psg (:proximal-sg prior-lyr)
dsg (:distal-sg prior-lyr)
asg (:apical-sg prior-lyr)
;; internal sources
boosts (:boosts prior-lyr)]
(into {}
(map (fn [cell-id]
(let [[col ci] cell-id
;; breakdown of proximal excitation by source
[ff-seg-path _] (get (:fully-matching-ff-segs active-state) [col 0])
ff-conn-sources (when ff-seg-path
(syn/sources-connected-to psg ff-seg-path))
active-ff-b (->> (filter ff-b-bits ff-conn-sources)
(zap-fewer ff-stim-thresh))
active-ff-s (->> (filter ff-s-bits ff-conn-sources)
(zap-fewer ff-stim-thresh))
ff-b-by-src (frequencies (map ff-bits-srcs active-ff-b))
ff-s-by-src (frequencies (map ff-bits-srcs active-ff-s))
;; breakdown of distal excitation by source
[d-seg-path _] (get (:fully-matching-segs distal-state) cell-id)
d-conn-sources (when d-seg-path
(syn/sources-connected-to dsg d-seg-path))
active-d (->> (filter distal-bits d-conn-sources)
(zap-fewer d-stim-thresh))
d-by-src (->> (frequencies (map distal-bits-srcs active-d))
(util/remap #(* % distal-weight)))
;; same for apical
[a-seg-path _] (get (:fully-matching-segs apical-state) cell-id)
a-conn-sources (when a-seg-path
(syn/sources-connected-to asg a-seg-path))
active-a (->> (filter apical-bits a-conn-sources)
(zap-fewer a-stim-thresh))
a-by-src (->> (frequencies (map apical-bits-srcs active-a))
(util/remap #(* % distal-weight)))
;; excitation levels
b-overlap (count active-ff-b)
s-overlap (count active-ff-s)
d-a-exc (->> (+ (count active-d) (count active-a))
(* distal-weight))
;; effect of boosting
overlap (+ b-overlap s-overlap)
boost-amt (* overlap (- (get boosts col) 1.0))
;; total excitation
total (+ b-overlap s-overlap boost-amt d-a-exc)]
[cell-id {:total total
:proximal-unstable ff-b-by-src
:proximal-stable ff-s-by-src
:boost boost-amt
:distal (merge d-by-src a-by-src)}])))
cell-ids)))
(defn update-excitation-breakdown
"Takes an excitation breakdown such as returned under one key from
cell-excitation-breakdowns, and updates each numeric component with
the function f. Key :total will be updated accordingly. The default
is to scale the values to a total of 1.0. To aggregate breakdowns,
use `(util/deep-merge-with +)`."
([breakdown]
(let [total (:total breakdown)]
(update-excitation-breakdown breakdown #(/ % total))))
([breakdown f]
(persistent!
(reduce-kv (fn [m k v]
(let [new-v (if (map? v)
(util/remap f v)
(f v))
v-total (if (map? v)
(reduce + (vals new-v))
new-v)]
(assoc! m k new-v
:total (+ (get m :total) v-total))))
(transient {:total 0.0})
(dissoc breakdown :total)))))
| null | https://raw.githubusercontent.com/htm-community/comportex/cd318492cf2e43cb7f25238b116b90b8195ec5aa/src/org/nfrac/comportex/layer/tools.cljc | clojure | inputs to layer
synapse graphs - pre-learning state so from prior time step
internal sources
breakdown of proximal excitation by source
breakdown of distal excitation by source
same for apical
excitation levels
effect of boosting
total excitation | (ns org.nfrac.comportex.layer.tools
(:require [org.nfrac.comportex.core :as cx]
[org.nfrac.comportex.synapses :as syn]
[org.nfrac.comportex.topography :as topo]
[org.nfrac.comportex.layer :as layer]
[org.nfrac.comportex.util :as util]
[clojure.set :as set]
[clojure.spec :as s]
[#?(:clj clojure.spec.gen :cljs clojure.spec.impl.gen) :as gen]))
(defn source-of-distal-bit
"Returns [src-id j] where src-id may be a layer key or sense key, and j is
the index into the output of the source."
[htm lyr-id i]
(let [lyr (get-in htm [:layers lyr-id])
params (cx/params lyr)
[src-type j] (layer/id->source params (:embedding lyr) i)]
(case src-type
:this [lyr-id i]
:lat (cx/source-of-incoming-bit htm lyr-id j :lat-deps))))
(defn source-of-apical-bit
"Returns [src-id j] where src-id is a layer key, and j is the index into the
output of the source layer."
[htm lyr-id i]
(cx/source-of-incoming-bit htm lyr-id i :fb-deps))
(defn- zap-fewer
[n xs]
(if (< (count xs) n) (empty xs) xs))
(defn cell-excitation-breakdowns
"Calculates the various sources contributing to total excitation
level of each of the `cell-ids` in the given layer. Returns a map
keyed by these cell ids. Each cell value is a map with keys
* :total - number.
* :proximal-unstable - a map keyed by source layer/sense id.
* :proximal-stable - a map keyed by source layer/sense id.
* :distal - a map keyed by source layer/sense id.
* :boost - number.
"
[htm prior-htm lyr-id cell-ids]
(let [lyr (get-in htm [:layers lyr-id])
prior-lyr (get-in prior-htm [:layers lyr-id])
params (:params lyr)
ff-stim-thresh (:stimulus-threshold (:proximal params))
d-stim-thresh (:stimulus-threshold (:distal params))
a-stim-thresh (:stimulus-threshold (:apical params))
distal-weight (:distal-vs-proximal-weight params)
active-state (:active-state lyr)
prior-active-state (:active-state prior-lyr)
distal-state (:distal-state prior-lyr)
apical-state (:apical-state prior-lyr)
ff-bits (-> active-state :in-ff-signal :bits set)
ff-s-bits (-> active-state :in-ff-signal ::layer/stable-bits set)
ff-b-bits (set/difference ff-bits ff-s-bits)
distal-bits (:active-bits distal-state)
apical-bits (:active-bits apical-state)
ff-bits-srcs (into {}
(map (fn [i]
(let [[k _] (cx/source-of-incoming-bit
htm lyr-id i :ff-bits)]
[i k])))
ff-bits)
distal-bits-srcs (into {}
(map (fn [i]
(let [[k _] (source-of-distal-bit
htm lyr-id i)]
[i k])))
distal-bits)
apical-bits-srcs (into {}
(map (fn [i]
(let [[k _] (source-of-apical-bit
htm lyr-id i)]
[i k])))
apical-bits)
psg (:proximal-sg prior-lyr)
dsg (:distal-sg prior-lyr)
asg (:apical-sg prior-lyr)
boosts (:boosts prior-lyr)]
(into {}
(map (fn [cell-id]
(let [[col ci] cell-id
[ff-seg-path _] (get (:fully-matching-ff-segs active-state) [col 0])
ff-conn-sources (when ff-seg-path
(syn/sources-connected-to psg ff-seg-path))
active-ff-b (->> (filter ff-b-bits ff-conn-sources)
(zap-fewer ff-stim-thresh))
active-ff-s (->> (filter ff-s-bits ff-conn-sources)
(zap-fewer ff-stim-thresh))
ff-b-by-src (frequencies (map ff-bits-srcs active-ff-b))
ff-s-by-src (frequencies (map ff-bits-srcs active-ff-s))
[d-seg-path _] (get (:fully-matching-segs distal-state) cell-id)
d-conn-sources (when d-seg-path
(syn/sources-connected-to dsg d-seg-path))
active-d (->> (filter distal-bits d-conn-sources)
(zap-fewer d-stim-thresh))
d-by-src (->> (frequencies (map distal-bits-srcs active-d))
(util/remap #(* % distal-weight)))
[a-seg-path _] (get (:fully-matching-segs apical-state) cell-id)
a-conn-sources (when a-seg-path
(syn/sources-connected-to asg a-seg-path))
active-a (->> (filter apical-bits a-conn-sources)
(zap-fewer a-stim-thresh))
a-by-src (->> (frequencies (map apical-bits-srcs active-a))
(util/remap #(* % distal-weight)))
b-overlap (count active-ff-b)
s-overlap (count active-ff-s)
d-a-exc (->> (+ (count active-d) (count active-a))
(* distal-weight))
overlap (+ b-overlap s-overlap)
boost-amt (* overlap (- (get boosts col) 1.0))
total (+ b-overlap s-overlap boost-amt d-a-exc)]
[cell-id {:total total
:proximal-unstable ff-b-by-src
:proximal-stable ff-s-by-src
:boost boost-amt
:distal (merge d-by-src a-by-src)}])))
cell-ids)))
(defn update-excitation-breakdown
"Takes an excitation breakdown such as returned under one key from
cell-excitation-breakdowns, and updates each numeric component with
the function f. Key :total will be updated accordingly. The default
is to scale the values to a total of 1.0. To aggregate breakdowns,
use `(util/deep-merge-with +)`."
([breakdown]
(let [total (:total breakdown)]
(update-excitation-breakdown breakdown #(/ % total))))
([breakdown f]
(persistent!
(reduce-kv (fn [m k v]
(let [new-v (if (map? v)
(util/remap f v)
(f v))
v-total (if (map? v)
(reduce + (vals new-v))
new-v)]
(assoc! m k new-v
:total (+ (get m :total) v-total))))
(transient {:total 0.0})
(dissoc breakdown :total)))))
|
9d90db18bcbc427b70103216f71629ef52a97c98f55a7188eda825b4e36b6f8a | bbc/haskell-workshop | C5Recursion.hs | module C5Recursion where
-- Implement all of these functions using explicit recursion
-- Write a minimum function that takes a list and returns its smallest element
myMin [ 10 , 5 , 15 ] returns 5
myMin :: Ord a => [a] -> a
myMin [] = error "please supply a list"
myMin [x] = x
myMin (y:x:xs)
| y <= x = myMin (y:xs)
| otherwise = myMin (x:xs)
-- Write a function that takes a finite list and turns it into an infinite list which repeats itself
-- Hint: this won't need any base/edge case
longList [ 1,2,3,4,5 ] returns [ 1,2,3,4,5 , ... ]
longList :: [a] -> [a]
longList xs = xs ++ longList xs
Write a function that takes a list of tuples and extracts the first element in each tuple into a new list
tuple2List [ ( " a " , 1 ) , ( " b " , 2 ) ] returns [ " a " , " b " ]
tuple2List :: [(a, b)] -> [a]
tuple2List [] = []
tuple2List ((a,b):xs)= a : tuple2List xs
-- Write the map function,
i.e. JavaScript 's array.map(fn )
-- using recursion
( +2 ) [ 1,2,3 ] returns [ 3,4,5 ]
myMap :: (a -> b) -> [a] -> [b]
myMap _ [] = []
myMap f (x:xs) = f x : myMap f xs
-- Write the filter function,
i.e. JavaScript 's array.filter(fn )
-- using recursion
( > 2 ) [ 1,2,3,4 ] returns [ 3 , 4 ]
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter _ [] = []
myFilter p (x:xs)
| p x = x : myFilter p xs
| otherwise = myFilter p xs
-- Write the reduce function,
i.e. JavaScript 's array.reduce(fn )
-- using recursion
myReduce ( + ) 0 [ 1 .. 100 ] returns 5050
myReduce :: (a -> b -> b) -> b -> [a] -> b
myReduce _ acc [] = acc
myReduce f acc (x:xs) = f x (myReduce f acc xs)
-- Write the map function again, but this time implement it with myReduce
myMapWithReduce ( +2 ) [ 1,2,3 ] returns [ 3,4,5 ]
myMapWithReduce :: (a -> b) -> [a] -> [b]
myMapWithReduce f xs = myReduce (\a -> \acc -> f a : acc) [] xs
| null | https://raw.githubusercontent.com/bbc/haskell-workshop/475b9bac04167665030d7863798ccd27dfd589d0/chrisb/exercises/src/C5Recursion.hs | haskell | Implement all of these functions using explicit recursion
Write a minimum function that takes a list and returns its smallest element
Write a function that takes a finite list and turns it into an infinite list which repeats itself
Hint: this won't need any base/edge case
Write the map function,
using recursion
Write the filter function,
using recursion
Write the reduce function,
using recursion
Write the map function again, but this time implement it with myReduce | module C5Recursion where
myMin [ 10 , 5 , 15 ] returns 5
myMin :: Ord a => [a] -> a
myMin [] = error "please supply a list"
myMin [x] = x
myMin (y:x:xs)
| y <= x = myMin (y:xs)
| otherwise = myMin (x:xs)
longList [ 1,2,3,4,5 ] returns [ 1,2,3,4,5 , ... ]
longList :: [a] -> [a]
longList xs = xs ++ longList xs
Write a function that takes a list of tuples and extracts the first element in each tuple into a new list
tuple2List [ ( " a " , 1 ) , ( " b " , 2 ) ] returns [ " a " , " b " ]
tuple2List :: [(a, b)] -> [a]
tuple2List [] = []
tuple2List ((a,b):xs)= a : tuple2List xs
i.e. JavaScript 's array.map(fn )
( +2 ) [ 1,2,3 ] returns [ 3,4,5 ]
myMap :: (a -> b) -> [a] -> [b]
myMap _ [] = []
myMap f (x:xs) = f x : myMap f xs
i.e. JavaScript 's array.filter(fn )
( > 2 ) [ 1,2,3,4 ] returns [ 3 , 4 ]
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter _ [] = []
myFilter p (x:xs)
| p x = x : myFilter p xs
| otherwise = myFilter p xs
i.e. JavaScript 's array.reduce(fn )
myReduce ( + ) 0 [ 1 .. 100 ] returns 5050
myReduce :: (a -> b -> b) -> b -> [a] -> b
myReduce _ acc [] = acc
myReduce f acc (x:xs) = f x (myReduce f acc xs)
myMapWithReduce ( +2 ) [ 1,2,3 ] returns [ 3,4,5 ]
myMapWithReduce :: (a -> b) -> [a] -> [b]
myMapWithReduce f xs = myReduce (\a -> \acc -> f a : acc) [] xs
|
3776f7a6dd38115e3625584620d7b8d10467ad38d71b75a6262ca58db5347045 | rd--/hsc3 | lfSaw.help.hs | lfSaw ; note SC2 did not have the initial phase argument
lfSaw ar 500 1 * 0.025
lfSaw ; used as both Oscillator and LFO
lfSaw ar (lfSaw kr 4 0 * 400 + 400) 0 * 0.025
-- lfSaw ; output range is bi-polar
let f = mce [linLin (lfSaw kr 0.5 0) (-1) 1 200 1600, 200, 1600]
a = mce [0.1,0.05,0.05]
in mix (sinOsc ar f 0 * a)
-- lfSaw ; saw-tooth wave as sum of sines, for all partials n amplitude is (1 / n) ; phase is always 0
let mk_freq f0 n = f0 * fromInteger n
mk_amp n = 1 / fromInteger n
mk_param f0 n = let m = [1,2 .. n] in zip (map (mk_freq f0) m) (map mk_amp m)
x = midiCps (mouseX kr 20 72 Linear 0.2)
y = mouseY kr 0.01 0.1 Exponential 0.2
cross - fade from sum to
o1 = sum (map (\(fr,am) -> sinOsc ar fr 0 * am) (mk_param x 25)) * (1 - e)
o2 = lfSaw ar x 0 * e
in mce2 o1 o2 * y
-- lfSaw ; as phasor input to sin function
sin (range 0 two_pi (lfSaw ar 440 0)) * 0.1
-- lfSaw ; mixed with sin, then with distortions
let f = xLine kr 220 440 10 DoNothing
o1 = sinOsc ar (f + mce2 0 0.7) 0
o2 = lfSaw ar (f + mce2 0 0.7) 0 * 0.3
o3 = o1 + o2
o4 = cubed (distort (log (distort o3)))
in o4 * 0.05
-- lfSaw
let f = sinOsc kr (mce [0.16,0.33,0.41]) 0 * 10 + mce [1,1.1,1.5,1.78,2.45,6.7,8] * 220
in mix (lfSaw ar f 0) * 0.1
lfSaw ; ln 2021 - 04 - 08 / ; ~= [ 0.1,0.15,0.225,0.3375 ]
let o = lfSaw ar (lfSaw ar (mce (take 4 (iterate (* 1.5) 0.1))) 0 * 5000) 0 * 500
in mix (sinOsc ar (1000 + o) 0) * 1/4 * 0.1
---- ; drawings
UI.ui_baudline 4096 50 "linear" 2
Sound.Sc3.Plot.plot_ugen1 0.1 (lfSaw ar 50 0) -- ascending
Sound.Sc3.Plot.plot_ugen1 0.002 (lfSaw ar 5000 0)
| null | https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Ugen/lfSaw.help.hs | haskell | lfSaw ; output range is bi-polar
lfSaw ; saw-tooth wave as sum of sines, for all partials n amplitude is (1 / n) ; phase is always 0
lfSaw ; as phasor input to sin function
lfSaw ; mixed with sin, then with distortions
lfSaw
-- ; drawings
ascending | lfSaw ; note SC2 did not have the initial phase argument
lfSaw ar 500 1 * 0.025
lfSaw ; used as both Oscillator and LFO
lfSaw ar (lfSaw kr 4 0 * 400 + 400) 0 * 0.025
let f = mce [linLin (lfSaw kr 0.5 0) (-1) 1 200 1600, 200, 1600]
a = mce [0.1,0.05,0.05]
in mix (sinOsc ar f 0 * a)
let mk_freq f0 n = f0 * fromInteger n
mk_amp n = 1 / fromInteger n
mk_param f0 n = let m = [1,2 .. n] in zip (map (mk_freq f0) m) (map mk_amp m)
x = midiCps (mouseX kr 20 72 Linear 0.2)
y = mouseY kr 0.01 0.1 Exponential 0.2
cross - fade from sum to
o1 = sum (map (\(fr,am) -> sinOsc ar fr 0 * am) (mk_param x 25)) * (1 - e)
o2 = lfSaw ar x 0 * e
in mce2 o1 o2 * y
sin (range 0 two_pi (lfSaw ar 440 0)) * 0.1
let f = xLine kr 220 440 10 DoNothing
o1 = sinOsc ar (f + mce2 0 0.7) 0
o2 = lfSaw ar (f + mce2 0 0.7) 0 * 0.3
o3 = o1 + o2
o4 = cubed (distort (log (distort o3)))
in o4 * 0.05
let f = sinOsc kr (mce [0.16,0.33,0.41]) 0 * 10 + mce [1,1.1,1.5,1.78,2.45,6.7,8] * 220
in mix (lfSaw ar f 0) * 0.1
lfSaw ; ln 2021 - 04 - 08 / ; ~= [ 0.1,0.15,0.225,0.3375 ]
let o = lfSaw ar (lfSaw ar (mce (take 4 (iterate (* 1.5) 0.1))) 0 * 5000) 0 * 500
in mix (sinOsc ar (1000 + o) 0) * 1/4 * 0.1
UI.ui_baudline 4096 50 "linear" 2
Sound.Sc3.Plot.plot_ugen1 0.002 (lfSaw ar 5000 0)
|
4283692ce260267e4852e1acfaf82179e5a61cb74a5e75af33a34e48117752d3 | Goheeca/cl-drawille | animations.lisp | (defpackage :cl-drawille/examples-animations
(:use :common-lisp :cl-drawille :cl-charms)
(:export :sine-tracking-example :rotating-cube-example))
(in-package :cl-drawille/examples-animations)
(defun animate (animation)
(cl-charms:with-curses ()
(cl-charms:disable-echoing)
(cl-charms/low-level:timeout 10)
(cl-charms/low-level:curs-set 0)
(cl-charms:clear-window cl-charms:*standard-window*)
(cl-charms:refresh-window cl-charms:*standard-window*)
(loop named curses-loop
for input = (cl-charms:get-char cl-charms:*standard-window* :ignore-error t)
do (when (eq #\q input) (return-from curses-loop))
(multiple-value-bind (frame delay) (funcall animation)
(loop for y from 0 and row in frame
do (ignore-errors (cl-charms:write-string-at-point cl-charms:*standard-window* row 0 y)))
(cl-charms:refresh-window cl-charms:*standard-window*)
(sleep delay)))))
(defun sine-tracking ()
(let ((canvas (cl-drawille:make-canvas))
(i 0)
(height 40))
(lambda ()
(cl-drawille:clear canvas)
(loop for (x y) in (cl-drawille::line 0 height 180 (+ height (* height (sin (/ (* i pi) 180)))))
do (cl-drawille:set-pixel canvas x y))
(loop for x from 0 below 360 by 2
do (cl-drawille:set-pixel canvas (/ x 2) (+ height (* height (sin (/ (* (+ x i) pi) 180))))))
(incf i 2)
(values (cl-drawille:rows canvas) 1/60))))
(defun sine-tracking-example ()
(animate (sine-tracking)))
(defun rotate-x (input angle)
(let ((cos (cos (/ (* angle pi) 180)))
(sin (sin (/ (* angle pi) 180))))
(vector (aref input 0)
(- (* cos (aref input 1)) (* sin (aref input 2)))
(+ (* sin (aref input 1)) (* cos (aref input 2))))))
(defun rotate-y (input angle)
(let ((cos (cos (/ (* angle pi) 180)))
(sin (sin (/ (* angle pi) 180))))
(vector (- (* cos (aref input 2)) (* sin (aref input 0)))
(aref input 1)
(+ (* sin (aref input 2)) (* cos (aref input 0))))))
(defun rotate-z (input angle)
(let ((cos (cos (/ (* angle pi) 180)))
(sin (sin (/ (* angle pi) 180))))
(vector (- (* cos (aref input 0)) (* sin (aref input 1)))
(+ (* sin (aref input 0)) (* cos (aref input 1)))
(aref input 2))))
(defun project (input width height fov distance)
(let ((factor (/ fov (+ distance (aref input 2)))))
(vector (+ (/ width 2) (* factor (aref input 0)))
(+ (/ height 2) (* factor (aref input 1)))
1)))
(defun rotating-cube (&key (projection nil))
(let ((canvas (cl-drawille:make-canvas))
(vertices '(#(-20 20 -20)
#(20 20 -20)
#(20 -20 -20)
#(-20 -20 -20)
#(-20 20 20)
#(20 20 20)
#(20 -20 20)
#(-20 -20 20)))
(faces '((0 1 2 3) (1 5 6 2) (5 4 7 6) (4 0 3 7) (0 4 5 1) (3 2 6 7)))
(angle-x 0)
(angle-y 0)
(angle-z 0))
(lambda ()
(cl-drawille:clear canvas)
(flet ((cond-project (input &rest args) (if projection (apply #'project input args) input)))
(let ((transformed
(loop for vertex in vertices collect (cond-project (rotate-z (rotate-y (rotate-x vertex angle-x) angle-y) angle-z) 50 50 50 50))))
(loop for (a b c d) in faces
do (loop for (x y) in (cl-drawille::line (aref (nth a transformed) 0) (aref (nth a transformed) 1) (aref (nth b transformed) 0) (aref (nth b transformed) 1))
do (cl-drawille:set-pixel canvas x y))
(loop for (x y) in (cl-drawille::line (aref (nth b transformed) 0) (aref (nth b transformed) 1) (aref (nth c transformed) 0) (aref (nth c transformed) 1))
do (cl-drawille:set-pixel canvas x y))
(loop for (x y) in (cl-drawille::line (aref (nth c transformed) 0) (aref (nth c transformed) 1) (aref (nth d transformed) 0) (aref (nth d transformed) 1))
do (cl-drawille:set-pixel canvas x y))
(loop for (x y) in (cl-drawille::line (aref (nth d transformed) 0) (aref (nth d transformed) 1) (aref (nth a transformed) 0) (aref (nth a transformed) 1))
do (cl-drawille:set-pixel canvas x y)))))
(incf angle-x 2)
(incf angle-y 3)
(incf angle-z 5)
(values (cl-drawille:rows canvas :min-x -40 :min-y -40 :max-x 80 :max-y 80) 1/20))))
(defun rotating-cube-example (&key (projection nil))
(animate (rotating-cube :projection projection)))
| null | https://raw.githubusercontent.com/Goheeca/cl-drawille/c5501e71d16fd39f058ed760a0d6034b63e996f5/animations.lisp | lisp | (defpackage :cl-drawille/examples-animations
(:use :common-lisp :cl-drawille :cl-charms)
(:export :sine-tracking-example :rotating-cube-example))
(in-package :cl-drawille/examples-animations)
(defun animate (animation)
(cl-charms:with-curses ()
(cl-charms:disable-echoing)
(cl-charms/low-level:timeout 10)
(cl-charms/low-level:curs-set 0)
(cl-charms:clear-window cl-charms:*standard-window*)
(cl-charms:refresh-window cl-charms:*standard-window*)
(loop named curses-loop
for input = (cl-charms:get-char cl-charms:*standard-window* :ignore-error t)
do (when (eq #\q input) (return-from curses-loop))
(multiple-value-bind (frame delay) (funcall animation)
(loop for y from 0 and row in frame
do (ignore-errors (cl-charms:write-string-at-point cl-charms:*standard-window* row 0 y)))
(cl-charms:refresh-window cl-charms:*standard-window*)
(sleep delay)))))
(defun sine-tracking ()
(let ((canvas (cl-drawille:make-canvas))
(i 0)
(height 40))
(lambda ()
(cl-drawille:clear canvas)
(loop for (x y) in (cl-drawille::line 0 height 180 (+ height (* height (sin (/ (* i pi) 180)))))
do (cl-drawille:set-pixel canvas x y))
(loop for x from 0 below 360 by 2
do (cl-drawille:set-pixel canvas (/ x 2) (+ height (* height (sin (/ (* (+ x i) pi) 180))))))
(incf i 2)
(values (cl-drawille:rows canvas) 1/60))))
(defun sine-tracking-example ()
(animate (sine-tracking)))
(defun rotate-x (input angle)
(let ((cos (cos (/ (* angle pi) 180)))
(sin (sin (/ (* angle pi) 180))))
(vector (aref input 0)
(- (* cos (aref input 1)) (* sin (aref input 2)))
(+ (* sin (aref input 1)) (* cos (aref input 2))))))
(defun rotate-y (input angle)
(let ((cos (cos (/ (* angle pi) 180)))
(sin (sin (/ (* angle pi) 180))))
(vector (- (* cos (aref input 2)) (* sin (aref input 0)))
(aref input 1)
(+ (* sin (aref input 2)) (* cos (aref input 0))))))
(defun rotate-z (input angle)
(let ((cos (cos (/ (* angle pi) 180)))
(sin (sin (/ (* angle pi) 180))))
(vector (- (* cos (aref input 0)) (* sin (aref input 1)))
(+ (* sin (aref input 0)) (* cos (aref input 1)))
(aref input 2))))
(defun project (input width height fov distance)
(let ((factor (/ fov (+ distance (aref input 2)))))
(vector (+ (/ width 2) (* factor (aref input 0)))
(+ (/ height 2) (* factor (aref input 1)))
1)))
(defun rotating-cube (&key (projection nil))
(let ((canvas (cl-drawille:make-canvas))
(vertices '(#(-20 20 -20)
#(20 20 -20)
#(20 -20 -20)
#(-20 -20 -20)
#(-20 20 20)
#(20 20 20)
#(20 -20 20)
#(-20 -20 20)))
(faces '((0 1 2 3) (1 5 6 2) (5 4 7 6) (4 0 3 7) (0 4 5 1) (3 2 6 7)))
(angle-x 0)
(angle-y 0)
(angle-z 0))
(lambda ()
(cl-drawille:clear canvas)
(flet ((cond-project (input &rest args) (if projection (apply #'project input args) input)))
(let ((transformed
(loop for vertex in vertices collect (cond-project (rotate-z (rotate-y (rotate-x vertex angle-x) angle-y) angle-z) 50 50 50 50))))
(loop for (a b c d) in faces
do (loop for (x y) in (cl-drawille::line (aref (nth a transformed) 0) (aref (nth a transformed) 1) (aref (nth b transformed) 0) (aref (nth b transformed) 1))
do (cl-drawille:set-pixel canvas x y))
(loop for (x y) in (cl-drawille::line (aref (nth b transformed) 0) (aref (nth b transformed) 1) (aref (nth c transformed) 0) (aref (nth c transformed) 1))
do (cl-drawille:set-pixel canvas x y))
(loop for (x y) in (cl-drawille::line (aref (nth c transformed) 0) (aref (nth c transformed) 1) (aref (nth d transformed) 0) (aref (nth d transformed) 1))
do (cl-drawille:set-pixel canvas x y))
(loop for (x y) in (cl-drawille::line (aref (nth d transformed) 0) (aref (nth d transformed) 1) (aref (nth a transformed) 0) (aref (nth a transformed) 1))
do (cl-drawille:set-pixel canvas x y)))))
(incf angle-x 2)
(incf angle-y 3)
(incf angle-z 5)
(values (cl-drawille:rows canvas :min-x -40 :min-y -40 :max-x 80 :max-y 80) 1/20))))
(defun rotating-cube-example (&key (projection nil))
(animate (rotating-cube :projection projection)))
| |
1feaada9458c8938376f4fed0812c6ee31d204bff61fb69ec5199baf5eed7b1b | privet-kitty/cl-competitive | 2sat.lisp | (defpackage :cp/test/2sat
(:use :cl :fiveam :cp/2sat)
(:import-from :cp/test/base #:base-suite))
(in-package :cp/test/2sat)
(in-suite base-suite)
(test 2sat
(2sat-solve (make-2sat 0))
(let ((2sat (make-2sat 1)))
(2sat-add-imply 2sat 0 (lognot 0))
(is (equalp #(0) (2sat-solve 2sat))))
(let ((2sat (make-2sat 1)))
(2sat-add-imply 2sat (lognot 0) 0)
(is (equalp #(1) (2sat-solve 2sat))))
(let ((2sat (make-2sat 1)))
(2sat-add-imply 2sat 0 (lognot 0))
(2sat-add-imply 2sat (lognot 0) 0)
(is (null (2sat-solve 2sat))))
(let ((2sat (make-2sat 2)))
(2sat-add-imply 2sat 1 (lognot 1))
(2sat-add-imply 2sat 0 1)
(2sat-add-imply 2sat (lognot 0) 0)
(is (null (2sat-solve 2sat)))))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/f618fa43e1a464c9f088aa367ac1135c0f33cabd/module/test/2sat.lisp | lisp | (defpackage :cp/test/2sat
(:use :cl :fiveam :cp/2sat)
(:import-from :cp/test/base #:base-suite))
(in-package :cp/test/2sat)
(in-suite base-suite)
(test 2sat
(2sat-solve (make-2sat 0))
(let ((2sat (make-2sat 1)))
(2sat-add-imply 2sat 0 (lognot 0))
(is (equalp #(0) (2sat-solve 2sat))))
(let ((2sat (make-2sat 1)))
(2sat-add-imply 2sat (lognot 0) 0)
(is (equalp #(1) (2sat-solve 2sat))))
(let ((2sat (make-2sat 1)))
(2sat-add-imply 2sat 0 (lognot 0))
(2sat-add-imply 2sat (lognot 0) 0)
(is (null (2sat-solve 2sat))))
(let ((2sat (make-2sat 2)))
(2sat-add-imply 2sat 1 (lognot 1))
(2sat-add-imply 2sat 0 1)
(2sat-add-imply 2sat (lognot 0) 0)
(is (null (2sat-solve 2sat)))))
| |
424d7a3463c6a88743890715847681868da23d91140e81bf5dc92cd0c41a92d3 | 3b/3bgl-misc | timing-helper.lisp | (defpackage #:basecode-timing-helper
(:use #:cl #:basecode))
(in-package #:basecode-timing-helper)
;; mixin for handling simple timing graphs
(defclass basecode-timing-helper ()
((max-queries :reader max-queries :initform 16 :initarg :max-timer-queries)
(query-index :accessor query-index :initform 0)
(timestamps :accessor timestamps :initform nil)
(timestamp-masks :accessor timestamp-masks :initform nil)
(timestamp-mode :accessor timestamp-mode :initform nil)
(times :accessor times :initform nil)
(times-x :accessor times-x :initform 0)))
(defmethod run-main-loop :before ((w basecode-timing-helper))
;; todo: adjust max-queries incrementally?
(let ((mq (max-queries w)))
(setf (timestamps w) (list (gl:gen-queries mq)
(gl:gen-queries mq)))
(setf (timestamp-masks w) (list (make-array mq :initial-element nil)
(make-array mq :initial-element nil)))
(setf (timestamp-mode w) (list (make-array mq :initial-element nil)
(make-array mq :initial-element nil)))
(setf (times w)
(coerce (loop repeat mq collect (make-array 512 :initial-element 0))
'vector))))
(defmethod mark (w &key mode)
(declare (ignore w mode))
;; ignore if we don't have the mixin so it can be easily disabled
;; without modifying all the code
nil)
(defmethod mark ((w basecode-timing-helper) &key (mode :delta))
(let ((n (query-index w)))
(assert (< n (max-queries w)))
(%gl:query-counter (nth n (car (timestamps w))) :timestamp)
(setf (aref (car (timestamp-masks w)) n) t)
(setf (aref (car (timestamp-mode w)) n)
mode)
(incf (query-index w))))
(defmethod basecode-draw :around ((w basecode-timing-helper))
(setf (query-index w) 0)
(mark w :mode :start)
(loop for a in (timestamp-mode w) do (fill a :unused))
(call-next-method)
(gl:disable :depth-test)
(rotatef (first (timestamps w)) (second (timestamps w)))
(rotatef (first (timestamp-masks w)) (second (timestamp-masks w)))
update TIMES
(cffi:with-foreign-objects ((done '%gl:int)
(time '%gl:uint64))
(let ((queries (make-array (max-queries w) :initial-element 0)))
;(declare (dynamic-extent queries))
(loop for i below (max-queries w)
for id in (car (timestamps w))
when (aref (car (timestamp-masks w)) i)
do (setf (aref (car (timestamp-masks w)) i) nil)
(%gl:get-query-object-iv id :query-result-available done)
(when (plusp (cffi:mem-ref done '%gl:int))
(%gl:get-query-object-ui64v id :query-result time)
(setf (aref queries i) (cffi:mem-ref time '%gl:uint64))))
(loop with x = (setf (times-x w)
(mod (1+ (times-x w))
(length (aref (times w) 0))))
for i from 0
for mode across (car (timestamp-mode w))
do (case mode
(:delta
(assert (plusp i))
(setf (aref (aref (times w) i) x)
(- (aref queries i)
(aref queries (1- i)))))
(:total
(setf (aref (aref (times w) i) x)
(- (aref queries i)
(aref queries 0))))
(t
(setf (aref (aref (times w) i) x) 0))))))
;; draw graphs
;; fixme: convert this stuff to VBOs or something instead of immediate mode
(basecode::with-pixel-ortho-projection (w :origin :lower-left)
(gl:disable :texture-2d :texture-3d)
(gl:with-pushed-matrix* (:modelview)
(gl:load-identity)
(loop with d = 100
with s = 2
with i = 0
for x1 = (times-x w)
for mode across (car (timestamp-mode w))
for times across (times w)
for color = (1+ i)
for r = (ldb (byte 1 0) color)
for g = (ldb (byte 1 1) color)
for b = (ldb (byte 1 2) color)
for a = (ldb (byte 1 3) color)
when (member mode '(:delta :total))
do (when (= color 4)
;; pure blue is hard to see, lighten it a bit
(setf g 0.4 r 0.4))
(if (plusp a)
(gl:color (* r 0.5) (* g 0.5) (* b 0.5) 1)
(gl:color r g b 1))
(gl:with-primitives :lines
(gl:vertex 0 (* i d))
(gl:vertex 512 (* i d))
(loop for j below 20 by 5
do (gl:vertex 0 (+ (* s j) (* i d)))
(gl:vertex 10 (+ (* s j) (* i d)))))
(gl:with-primitives :line-strip
(loop for j from 1 below 512
for y = (aref times j)
10/1000000.0 = 10px / ms
do (gl:vertex j (+ (* i d) (* s (/ y 1000000.0))))))
(incf i)
finally (gl:with-primitives :lines
(gl:color 1 1 1 1)
(gl:vertex x1 0)
(gl:vertex x1 (* 13 d)))))))
| null | https://raw.githubusercontent.com/3b/3bgl-misc/e3bf2781d603feb6b44e5c4ec20f06225648ffd9/timing/timing-helper.lisp | lisp | mixin for handling simple timing graphs
todo: adjust max-queries incrementally?
ignore if we don't have the mixin so it can be easily disabled
without modifying all the code
(declare (dynamic-extent queries))
draw graphs
fixme: convert this stuff to VBOs or something instead of immediate mode
pure blue is hard to see, lighten it a bit
| (defpackage #:basecode-timing-helper
(:use #:cl #:basecode))
(in-package #:basecode-timing-helper)
(defclass basecode-timing-helper ()
((max-queries :reader max-queries :initform 16 :initarg :max-timer-queries)
(query-index :accessor query-index :initform 0)
(timestamps :accessor timestamps :initform nil)
(timestamp-masks :accessor timestamp-masks :initform nil)
(timestamp-mode :accessor timestamp-mode :initform nil)
(times :accessor times :initform nil)
(times-x :accessor times-x :initform 0)))
(defmethod run-main-loop :before ((w basecode-timing-helper))
(let ((mq (max-queries w)))
(setf (timestamps w) (list (gl:gen-queries mq)
(gl:gen-queries mq)))
(setf (timestamp-masks w) (list (make-array mq :initial-element nil)
(make-array mq :initial-element nil)))
(setf (timestamp-mode w) (list (make-array mq :initial-element nil)
(make-array mq :initial-element nil)))
(setf (times w)
(coerce (loop repeat mq collect (make-array 512 :initial-element 0))
'vector))))
(defmethod mark (w &key mode)
(declare (ignore w mode))
nil)
(defmethod mark ((w basecode-timing-helper) &key (mode :delta))
(let ((n (query-index w)))
(assert (< n (max-queries w)))
(%gl:query-counter (nth n (car (timestamps w))) :timestamp)
(setf (aref (car (timestamp-masks w)) n) t)
(setf (aref (car (timestamp-mode w)) n)
mode)
(incf (query-index w))))
(defmethod basecode-draw :around ((w basecode-timing-helper))
(setf (query-index w) 0)
(mark w :mode :start)
(loop for a in (timestamp-mode w) do (fill a :unused))
(call-next-method)
(gl:disable :depth-test)
(rotatef (first (timestamps w)) (second (timestamps w)))
(rotatef (first (timestamp-masks w)) (second (timestamp-masks w)))
update TIMES
(cffi:with-foreign-objects ((done '%gl:int)
(time '%gl:uint64))
(let ((queries (make-array (max-queries w) :initial-element 0)))
(loop for i below (max-queries w)
for id in (car (timestamps w))
when (aref (car (timestamp-masks w)) i)
do (setf (aref (car (timestamp-masks w)) i) nil)
(%gl:get-query-object-iv id :query-result-available done)
(when (plusp (cffi:mem-ref done '%gl:int))
(%gl:get-query-object-ui64v id :query-result time)
(setf (aref queries i) (cffi:mem-ref time '%gl:uint64))))
(loop with x = (setf (times-x w)
(mod (1+ (times-x w))
(length (aref (times w) 0))))
for i from 0
for mode across (car (timestamp-mode w))
do (case mode
(:delta
(assert (plusp i))
(setf (aref (aref (times w) i) x)
(- (aref queries i)
(aref queries (1- i)))))
(:total
(setf (aref (aref (times w) i) x)
(- (aref queries i)
(aref queries 0))))
(t
(setf (aref (aref (times w) i) x) 0))))))
(basecode::with-pixel-ortho-projection (w :origin :lower-left)
(gl:disable :texture-2d :texture-3d)
(gl:with-pushed-matrix* (:modelview)
(gl:load-identity)
(loop with d = 100
with s = 2
with i = 0
for x1 = (times-x w)
for mode across (car (timestamp-mode w))
for times across (times w)
for color = (1+ i)
for r = (ldb (byte 1 0) color)
for g = (ldb (byte 1 1) color)
for b = (ldb (byte 1 2) color)
for a = (ldb (byte 1 3) color)
when (member mode '(:delta :total))
do (when (= color 4)
(setf g 0.4 r 0.4))
(if (plusp a)
(gl:color (* r 0.5) (* g 0.5) (* b 0.5) 1)
(gl:color r g b 1))
(gl:with-primitives :lines
(gl:vertex 0 (* i d))
(gl:vertex 512 (* i d))
(loop for j below 20 by 5
do (gl:vertex 0 (+ (* s j) (* i d)))
(gl:vertex 10 (+ (* s j) (* i d)))))
(gl:with-primitives :line-strip
(loop for j from 1 below 512
for y = (aref times j)
10/1000000.0 = 10px / ms
do (gl:vertex j (+ (* i d) (* s (/ y 1000000.0))))))
(incf i)
finally (gl:with-primitives :lines
(gl:color 1 1 1 1)
(gl:vertex x1 0)
(gl:vertex x1 (* 13 d)))))))
|
db3e243a4355d53d3cc63c5113b52dcae758a8b851408a47d3a82a2335e0fcbb | NorfairKing/the-notes | BinaryOperation.hs | module Functions.BinaryOperation where
import Notes
import Logic.FirstOrderLogic.Macro
import Sets.Basics.Terms
import Functions.Basics.Macro
import Functions.Basics.Terms
import Functions.BinaryOperation.Macro
import Functions.BinaryOperation.Terms
binaryOperations :: Note
binaryOperations = section "Binary operations" $ do
todo "binary operations x ⨯ y -> z"
binaryOperationDefinition
associativeDefinition
todo "Left identity and right identity"
identityDefinition
identityUniqueTheorem
identityExamples
-- TODO(binary operation can go to other set than dom_
binaryOperationDefinition :: Note
binaryOperationDefinition = de $ do
lab binaryOperationDefinitionLabel
s ["A ", binaryOperation', " is a ", binaryFunction, " as follows"]
ma $ fun fun_ (dom_ ⨯ dom_) dom_
associativeDefinition :: Note
associativeDefinition = de $ do
lab associativeDefinitionLabel
s ["A ", binaryOperation, " ", m binop_ , " is called ", associative', " if ", quoted "placement of parentheses does not matter"]
ma $ fa (cs [a, b, c] ∈ dom_) ((pars $ a ★ b) ★ c) =: (a ★ (pars $ b ★ c))
exneeded
where
a = "a"
b = "b"
c = "c"
identityDefinition :: Note
identityDefinition = de $ do
let x = "X"
s ["Let", m x, "be a", set, and, m binop_, "a", binaryOperation, "on", m x]
s ["If", m x, "contains an", element, m bid_, "with the following property, that element is called an", identity']
let a = "a"
ma $ fa (a ∈ x) $ a ★ bid_ =: bid_ =: bid_ ★ a
identityUniqueTheorem :: Note
identityUniqueTheorem = thm $ do
lab identityUniqueTheoremLabel
let a = "A"
s ["If there exists an", identity, "for a", binaryOperation, m binop_, "in a", set, m a, "then it must be unique"]
proof $ do
let e = "e"
f = "f"
s ["Let", m e, and, m f, "be two", identities, "in", m a]
ma $ e =: e ★ f =: f
s ["Note that the first equation uses that", m f, "is an", identity, "and the second equation that", m e, "is an", identity]
identityExamples :: Note
identityExamples = do
exneeded
| null | https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Functions/BinaryOperation.hs | haskell | TODO(binary operation can go to other set than dom_ | module Functions.BinaryOperation where
import Notes
import Logic.FirstOrderLogic.Macro
import Sets.Basics.Terms
import Functions.Basics.Macro
import Functions.Basics.Terms
import Functions.BinaryOperation.Macro
import Functions.BinaryOperation.Terms
binaryOperations :: Note
binaryOperations = section "Binary operations" $ do
todo "binary operations x ⨯ y -> z"
binaryOperationDefinition
associativeDefinition
todo "Left identity and right identity"
identityDefinition
identityUniqueTheorem
identityExamples
binaryOperationDefinition :: Note
binaryOperationDefinition = de $ do
lab binaryOperationDefinitionLabel
s ["A ", binaryOperation', " is a ", binaryFunction, " as follows"]
ma $ fun fun_ (dom_ ⨯ dom_) dom_
associativeDefinition :: Note
associativeDefinition = de $ do
lab associativeDefinitionLabel
s ["A ", binaryOperation, " ", m binop_ , " is called ", associative', " if ", quoted "placement of parentheses does not matter"]
ma $ fa (cs [a, b, c] ∈ dom_) ((pars $ a ★ b) ★ c) =: (a ★ (pars $ b ★ c))
exneeded
where
a = "a"
b = "b"
c = "c"
identityDefinition :: Note
identityDefinition = de $ do
let x = "X"
s ["Let", m x, "be a", set, and, m binop_, "a", binaryOperation, "on", m x]
s ["If", m x, "contains an", element, m bid_, "with the following property, that element is called an", identity']
let a = "a"
ma $ fa (a ∈ x) $ a ★ bid_ =: bid_ =: bid_ ★ a
identityUniqueTheorem :: Note
identityUniqueTheorem = thm $ do
lab identityUniqueTheoremLabel
let a = "A"
s ["If there exists an", identity, "for a", binaryOperation, m binop_, "in a", set, m a, "then it must be unique"]
proof $ do
let e = "e"
f = "f"
s ["Let", m e, and, m f, "be two", identities, "in", m a]
ma $ e =: e ★ f =: f
s ["Note that the first equation uses that", m f, "is an", identity, "and the second equation that", m e, "is an", identity]
identityExamples :: Note
identityExamples = do
exneeded
|
44be08a35e0b3cb4715f3d34c8449f736644323753aee86df2cb3dbc1dbd9589 | xh4/web-toolkit | test.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : FLEXI - STREAMS - TEST ; Base : 10 -*-
$ Header : /usr / local / cvsrep / flexi - streams / test / test.lisp , v 1.39 2008/05/30 09:10:55 edi Exp $
Copyright ( c ) 2006 - 2008 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :flexi-streams-test)
(defmacro with-test-suite ((test-description &key show-progress-p) &body body)
"Defines a test suite. Three utilities are available inside of the
body of the macro: The function FAIL, and the macros CHECK and
WITH-EXPECTED-ERROR. FAIL, the lowest level utility, marks the test
defined by WITH-TEST-SUITE as failed. CHECK checks whether its argument is
true, otherwise it calls FAIL. If during evaluation of the specified
expression any condition is signalled, this is also considered a
failure. WITH-EXPECTED-ERROR executes its body and considers the test
a success if the specified error was signalled, otherwise it calls
FAIL.
WITH-TEST-SUITE prints a simple progress report if SHOW-PROGRESS-P is true."
(with-unique-names (successp testcount)
(with-rebinding (show-progress-p)
`(let ((,successp t)
(,testcount 1))
(when (and ,show-progress-p (not (numberp ,show-progress-p)))
(setq ,show-progress-p 1))
(flet ((fail (format-str &rest format-args)
(apply #'format t format-str format-args)
(setq ,successp nil))
(maybe-show-progress ()
(when (and ,show-progress-p (zerop (mod ,testcount ,show-progress-p)))
(format t ".")
(when (zerop (mod ,testcount (* 10 ,show-progress-p)))
(terpri))
(force-output))
(incf ,testcount)))
(macrolet ((check (expression)
`(progn
(maybe-show-progress)
(handler-case
(unless ,expression
(fail "~&Test ~S failed.~%" ',expression))
(error (c)
(fail "~&Test ~S failed signalling error of type ~A: ~A.~%"
',expression (type-of c) c)))))
(with-expected-error ((condition-type) &body body)
`(progn
(maybe-show-progress)
(handler-case (progn ,@body)
(,condition-type () t)
(:no-error (&rest args)
(declare (ignore args))
(fail "~&Expected condition ~S not signalled.~%"
',condition-type))))))
(format t "~&Test suite: ~S~%" ,test-description)
,@body))
,successp))))
LW ca n't indent this correctly because it 's in a MACROLET
#+:lispworks
(editor:setup-indent "with-expected-error" 1 2 4)
(defconstant +buffer-size+ 8192
"Size of buffers for COPY-STREAM* below.")
(defvar *copy-function* nil
"Which function to use when copying from one stream to the other -
see for example COPY-FILE below.")
(defvar *this-file* (load-time-value
(or #.*compile-file-pathname* *load-pathname*))
"The pathname of the file \(`test.lisp') where this variable was
defined.")
#+:lispworks
(defun get-env-variable-as-directory (name)
(lw:when-let (string (lw:environment-variable name))
(when (plusp (length string))
(cond ((find (char string (1- (length string))) "\\/" :test #'char=) string)
(t (lw:string-append string "/"))))))
(defvar *tmp-dir*
(load-time-value
(merge-pathnames "odd-streams-test/"
#+:allegro (system:temporary-directory)
#+:lispworks (pathname (or (get-env-variable-as-directory "TEMP")
(get-env-variable-as-directory "TMP")
#+:win32 "C:/"
#-:win32 "/tmp/"))
#-(or :allegro :lispworks) #p"/tmp/"))
"The pathname of a temporary directory used for testing.")
(defvar *test-files*
'(("kafka" (:utf8 :latin1 :cp1252))
("tilton" (:utf8 :ascii))
("hebrew" (:utf8 :latin8))
("russian" (:utf8 :koi8r))
("unicode_demo" (:utf8 :ucs2 :ucs4)))
"A list of test files where each entry consists of the name
prefix and a list of encodings.")
(defun create-file-variants (file-name symbol)
"For a name suffix FILE-NAME and a symbol SYMBOL denoting an
encoding returns a list of pairs where the car is a full file
name and the cdr is the corresponding external format. This list
contains all possible variants w.r.t. to line-end conversion and
endianness."
(let ((args (ecase symbol
(:ascii '(:ascii))
(:latin1 '(:latin-1))
(:latin8 '(:hebrew))
(:cp1252 '(:code-page :id 1252))
(:koi8r '(:koi8-r))
(:utf8 '(:utf-8))
(:ucs2 '(:utf-16))
(:ucs4 '(:utf-32))))
(endianp (member symbol '(:ucs2 :ucs4))))
(loop for little-endian in (if endianp '(t nil) '(t))
for endian-suffix in (if endianp '("_le" "_be") '(""))
nconc (loop for eol-style in '(:lf :cr :crlf)
collect (cons (format nil "~A_~(~A~)_~(~A~)~A.txt"
file-name symbol eol-style endian-suffix)
(apply #'make-external-format
(append args `(:eol-style ,eol-style
:little-endian ,little-endian))))))))
(defun create-test-combinations (file-name symbols &optional simplep)
"For a name suffix FILE-NAME and a list of symbols SYMBOLS denoting
different encodings of the corresponding file returns a list of lists
which can be used as arglists by COMPARE-FILES. If SIMPLEP is true, a
list which can be used for the string and sequence tests below is
returned."
(let ((file-variants (loop for symbol in symbols
nconc (create-file-variants file-name symbol))))
(loop for (name-in . external-format-in) in file-variants
when simplep
collect (list name-in external-format-in)
else
nconc (loop for (name-out . external-format-out) in file-variants
collect (list name-in external-format-in name-out external-format-out)))))
(defun file-equal (file1 file2)
"Returns a true value iff FILE1 and FILE2 have the same
contents \(viewed as binary files)."
(with-open-file (stream1 file1 :element-type 'octet)
(with-open-file (stream2 file2 :element-type 'octet)
(and (= (file-length stream1) (file-length stream2))
(loop for byte1 = (read-byte stream1 nil nil)
for byte2 = (read-byte stream2 nil nil)
while (and byte1 byte2)
always (= byte1 byte2))))))
(defun copy-stream (stream-in external-format-in stream-out external-format-out)
"Copies the contents of the binary stream STREAM-IN to the
binary stream STREAM-OUT using flexi streams - STREAM-IN is read
with the external format EXTERNAL-FORMAT-IN and STREAM-OUT is
written with EXTERNAL-FORMAT-OUT."
(let ((in (make-flexi-stream stream-in :external-format external-format-in))
(out (make-flexi-stream stream-out :external-format external-format-out)))
(loop for line = (read-line in nil nil)
while line
do (write-line line out))))
(defun copy-stream* (stream-in external-format-in stream-out external-format-out)
"Like COPY-STREAM, but uses READ-SEQUENCE and WRITE-SEQUENCE instead
of READ-LINE and WRITE-LINE."
(let ((in (make-flexi-stream stream-in :external-format external-format-in))
(out (make-flexi-stream stream-out :external-format external-format-out))
(buffer (make-array +buffer-size+ :element-type 'char*)))
(loop
(let ((position (read-sequence buffer in)))
(when (zerop position) (return))
(write-sequence buffer out :end position)))))
(defun copy-file (path-in external-format-in path-out external-format-out direction-out direction-in)
"Copies the contents of the file denoted by the pathname
PATH-IN to the file denoted by the pathname PATH-OUT using flexi
streams - STREAM-IN is read with the external format
EXTERNAL-FORMAT-IN and STREAM-OUT is written with
EXTERNAL-FORMAT-OUT. The input file is opened with
the :DIRECTION keyword argument DIRECTION-IN, the output file is
opened with the :DIRECTION keyword argument DIRECTION-OUT."
(with-open-file (in path-in
:element-type 'octet
:direction direction-in
:if-does-not-exist :error
:if-exists :overwrite)
(with-open-file (out path-out
:element-type 'octet
:direction direction-out
:if-does-not-exist :create
:if-exists :supersede)
(funcall *copy-function* in external-format-in out external-format-out))))
#+:lispworks
(defun copy-file-lw (path-in external-format-in path-out external-format-out direction-out direction-in)
"Same as COPY-FILE, but uses character streams instead of
binary streams. Only used to test LispWorks-specific behaviour."
(with-open-file (in path-in
:external-format '(:latin-1 :eol-style :lf)
:element-type 'base-char
:direction direction-in
:if-does-not-exist :error
:if-exists :overwrite)
(with-open-file (out path-out
:external-format '(:latin-1 :eol-style :lf)
:element-type 'base-char
:direction direction-out
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(funcall *copy-function* in external-format-in out external-format-out))))
(defun compare-files (&key verbose)
"Each test in this suite copies the contents of one file \(in the
`test' directory) to another file \(in a temporary directory) using
flexi streams with different external formats. The resulting file is
compared with an existing file in the `test' directory to check if the
outcome is as expected. Uses various variants of the :DIRECTION
keyword when opening the files.
Returns a true value iff all tests succeeded. Prints information
about each individual comparison if VERBOSE is true."
(with-test-suite ("Reading/writing files" :show-progress-p (not verbose))
(flet ((one-comparison (path-in external-format-in path-out external-format-out verbose)
(when verbose
(format t "~&File ~S, using copy function ~S" (file-namestring path-in) *copy-function*)
(format t "~& and external formats ~S --> ~S"
(normalize-external-format external-format-in)
(normalize-external-format external-format-out)))
(let ((full-path-in (merge-pathnames path-in *this-file*))
(full-path-out (ensure-directories-exist
(merge-pathnames path-out *tmp-dir*)))
(full-path-orig (merge-pathnames path-out *this-file*)))
(dolist (direction-out '(:output :io))
(dolist (direction-in '(:input :io))
(when verbose
(format t "~&...directions ~S --> ~S" direction-in direction-out))
(copy-file full-path-in external-format-in
full-path-out external-format-out
direction-out direction-in)
(check (file-equal full-path-out full-path-orig))
#+:lispworks
(progn
(when verbose
(format t "~&...directions ~S --> ~S \(LispWorks)" direction-in direction-out))
(copy-file-lw full-path-in external-format-in
full-path-out external-format-out
direction-out direction-in)
(check (file-equal full-path-out full-path-orig))))))))
(loop with compare-files-args-list = (loop for (file-name symbols) in *test-files*
nconc (create-test-combinations file-name symbols))
for *copy-function* in '(copy-stream copy-stream*)
do (loop for (path-in external-format-in path-out external-format-out) in compare-files-args-list
do (one-comparison path-in external-format-in path-out external-format-out verbose))))))
(defun file-as-octet-vector (pathspec)
"Returns the contents of the file denoted by PATHSPEC as a vector of
octets."
(with-open-file (in pathspec :element-type 'octet)
(let ((vector (make-array (file-length in) :element-type 'octet)))
(read-sequence vector in)
vector)))
(defun file-as-string (pathspec external-format)
"Reads the contents of the file denoted by PATHSPEC using the
external format EXTERNAL-FORMAT and returns the result as a string."
(with-open-file (in pathspec :element-type 'octet)
(let* ((number-of-octets (file-length in))
(in (make-flexi-stream in :external-format external-format))
(string (make-array number-of-octets
:element-type #+:lispworks 'lw:simple-char
#-:lispworks 'character
:fill-pointer t)))
(setf (fill-pointer string) (read-sequence string in))
string)))
(defun old-string-to-octets (string &key
(external-format (make-external-format :latin1))
(start 0) end)
"The old version of STRING-TO-OCTETS. We can use it to test
in-memory streams."
(declare (optimize speed))
(with-output-to-sequence (out)
(let ((flexi (make-flexi-stream out :external-format external-format)))
(write-string string flexi :start start :end end))))
(defun old-octets-to-string (vector &key
(external-format (make-external-format :latin1))
(start 0) (end (length vector)))
"The old version of OCTETS-TO-STRING. We can use it to test
in-memory streams."
(declare (optimize speed))
(with-input-from-sequence (in vector :start start :end end)
(let ((flexi (make-flexi-stream in :external-format external-format))
(result (make-array (- end start)
:element-type #+:lispworks 'lw:simple-char
#-:lispworks 'character
:fill-pointer t)))
(setf (fill-pointer result)
(read-sequence result flexi))
result)))
(defun string-tests (&key verbose)
"Tests whether conversion from strings to octets and vice versa
works as expected. Also tests with the old versions of the conversion
functions in order to test in-memory streams."
(with-test-suite ("String tests" :show-progress-p (and (not verbose) 10))
(flet ((one-string-test (pathspec external-format verbose)
(when verbose
(format t "~&With external format ~S:" (normalize-external-format external-format)))
(let* ((full-path (merge-pathnames pathspec *this-file*))
(octets-vector (file-as-octet-vector full-path))
(octets-list (coerce octets-vector 'list))
(string (file-as-string full-path external-format)))
(when verbose
(format t "~&...testing OCTETS-TO-STRING"))
(check (string= (octets-to-string octets-vector :external-format external-format) string))
(check (string= (octets-to-string octets-list :external-format external-format) string))
(when verbose
(format t "~&...testing STRING-TO-OCTETS"))
(check (equalp (string-to-octets string :external-format external-format) octets-vector))
(when verbose
(format t "~&...testing in-memory streams"))
(check (string= (old-octets-to-string octets-vector :external-format external-format) string))
(check (string= (old-octets-to-string octets-list :external-format external-format) string))
(check (equalp (old-string-to-octets string :external-format external-format) octets-vector)))))
(loop with simple-test-args-list = (loop for (file-name symbols) in *test-files*
nconc (create-test-combinations file-name symbols t))
for (pathspec external-format) in simple-test-args-list
do (one-string-test pathspec external-format verbose)))))
(defun sequence-equal (seq1 seq2)
"Whether the two sequences have the same elements."
(and (= (length seq1) (length seq2))
(loop for i below (length seq1)
always (eql (elt seq1 i) (elt seq2 i)))))
(defun sequence-tests (&key verbose)
"Several tests to confirm that READ-SEQUENCE and WRITE-SEQUENCE
behave as expected."
(with-test-suite ("Sequence tests" :show-progress-p (and (not verbose) 10))
(flet ((one-sequence-test (pathspec external-format verbose)
(when verbose
(format t "~&With external format ~S:" (normalize-external-format external-format)))
(let* ((full-path (merge-pathnames pathspec *this-file*))
(file-string (file-as-string full-path external-format))
(string-length (length file-string))
(octets (file-as-octet-vector full-path))
(octet-length (length octets)))
(when (external-format-equal external-format (make-external-format :utf8))
(when verbose
(format t "~&...reading octets"))
#-:openmcl
;; FLEXI-STREAMS puts integers into the list, but OpenMCL
;; thinks they are characters...
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(list (make-list octet-length)))
(setf (flexi-stream-element-type in) 'octet)
#-:clisp
(read-sequence list in)
#+:clisp
(ext:read-byte-sequence list in)
(check (sequence-equal list octets))))
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(third (floor octet-length 3))
(half (floor octet-length 2))
(vector (make-array half :element-type 'octet)))
(check (sequence-equal (loop repeat third
collect (read-byte in))
(subseq octets 0 third)))
(read-sequence vector in)
(check (sequence-equal vector (subseq octets third (+ third half)))))))
(when verbose
(format t "~&...reading characters"))
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(string (make-string (- string-length 10) :element-type 'char*)))
(setf (flexi-stream-element-type in) 'octet)
(check (sequence-equal (loop repeat 10
collect (read-char in))
(subseq file-string 0 10)))
(read-sequence string in)
(check (sequence-equal string (subseq file-string 10)))))
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(list (make-list (- string-length 100))))
(check (sequence-equal (loop repeat 50
collect (read-char in))
(subseq file-string 0 50)))
#-:clisp
(read-sequence list in)
#+:clisp
(ext:read-char-sequence list in)
(check (sequence-equal list (subseq file-string 50 (- string-length 50))))
(check (sequence-equal (loop repeat 50
collect (read-char in))
(subseq file-string (- string-length 50))))))
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(array (make-array (- string-length 50))))
(check (sequence-equal (loop repeat 25
collect (read-char in))
(subseq file-string 0 25)))
#-:clisp
(read-sequence array in)
#+:clisp
(ext:read-char-sequence array in)
(check (sequence-equal array (subseq file-string 25 (- string-length 25))))
(check (sequence-equal (loop repeat 25
collect (read-char in))
(subseq file-string (- string-length 25))))))
(let ((path-out (ensure-directories-exist (merge-pathnames pathspec *tmp-dir*))))
(when verbose
(format t "~&...writing sequences"))
(with-open-file (out path-out
:direction :output
:if-exists :supersede
:element-type 'octet)
(let ((out (make-flexi-stream out :external-format external-format)))
(write-sequence octets out)))
(check (file-equal full-path path-out))
(with-open-file (out path-out
:direction :output
:if-exists :supersede
:element-type 'octet)
(let ((out (make-flexi-stream out :external-format external-format)))
(write-sequence file-string out)))
(check (file-equal full-path path-out))
(with-open-file (out path-out
:direction :output
:if-exists :supersede
:element-type 'octet)
(let ((out (make-flexi-stream out :external-format external-format)))
(write-sequence file-string out :end 100)
(write-sequence octets out
:start (length (string-to-octets file-string
:external-format external-format
:end 100)))))
(check (file-equal full-path path-out))))))
(loop with simple-test-args-list = (loop for (file-name symbols) in *test-files*
nconc (create-test-combinations file-name symbols t))
for (pathspec external-format) in simple-test-args-list
do (one-sequence-test pathspec external-format verbose)))))
(defmacro using-values ((&rest values) &body body)
"Executes BODY and feeds an element from VALUES to the USE-VALUE
restart each time a EXTERNAL-FORMAT-ENCODING-ERROR is signalled.
Signals an error when there are more or less
EXTERNAL-FORMAT-ENCODING-ERRORs than there are elements in VALUES."
(with-unique-names (value-stack condition-counter)
`(let ((,value-stack ',values)
(,condition-counter 0))
(handler-bind ((external-format-encoding-error
#'(lambda (c)
(declare (ignore c))
(unless ,value-stack
(error "Too many encoding errors signalled, expected only ~A."
,(length values)))
(incf ,condition-counter)
(use-value (pop ,value-stack)))))
(prog1 (progn ,@body)
(when ,value-stack
(error "~A encoding errors signalled, but ~A were expected."
,condition-counter ,(length values))))))))
(defun accept-overlong (octets code-point)
"Converts the `overlong' UTF-8 sequence OCTETS to using
OCTETS-TO-STRINGS, accepts the expected error with the corresponding
restart and checks that the result is CODE-POINT."
(handler-bind ((external-format-encoding-error
(lambda (c)
(declare (ignore c))
(invoke-restart 'accept-overlong-sequence))))
(string= (octets-to-string octets :external-format :utf-8)
(string (code-char code-point)))))
(defun read-flexi-line (sequence external-format)
"Creates and returns a string from the octet sequence SEQUENCE using
the external format EXTERNAL-FORMAT."
(with-input-from-sequence (in sequence)
(setq in (make-flexi-stream in :external-format external-format))
(read-line in)))
(defun read-flexi-line* (sequence external-format)
"Like READ-FLEXI-LINE but uses OCTETS-TO-STRING internally."
(octets-to-string sequence :external-format external-format))
(defun error-handling-tests (&key verbose)
"Tests several possible errors and how they are handled."
(with-test-suite ("Testing error handling" :show-progress-p (not verbose))
(macrolet ((want-encoding-error (input format)
`(with-expected-error (external-format-encoding-error)
(read-flexi-line* ,input ,format))))
(when verbose
(format t "~&\"Overlong\" UTF-8 sequences"))
(want-encoding-error #(#b11000000 #b10000000) :utf-8)
(want-encoding-error #(#b11000001 #b10000000) :utf-8)
(want-encoding-error #(#b11100000 #b10011111 #b10000000) :utf-8)
(want-encoding-error #(#b11110000 #b10001111 #b10000000 #b10000000) :utf-8)
(check (accept-overlong #(#b11000000 #b10000000) #b00000000))
(check (accept-overlong #(#b11000001 #b10000000) #b01000000))
(check (accept-overlong #(#b11100000 #b10011111 #b10000000) #b011111000000))
(check (accept-overlong #(#b11110000 #b10001111 #b10000000 #b10000000)
#b1111000000000000))
(when verbose
(format t "~&Invalid lead octets in UTF-8"))
(want-encoding-error #(#b11111000) :utf-8)
(want-encoding-error #(#b11111001) :utf-8)
(want-encoding-error #(#b11111100) :utf-8)
(want-encoding-error #(#b11111101) :utf-8)
(want-encoding-error #(#b11111110) :utf-8)
(want-encoding-error #(#b11111111) :utf-8)
(when verbose
(format t "~&Illegal code points"))
(want-encoding-error #(#x00 #x00 #x11 #x00) :utf-32le)
(want-encoding-error #(#x00 #xd8) :utf-16le)
(want-encoding-error #(#xff #xdf) :utf-16le))
(macrolet ((want-encoding-error (input format)
`(with-expected-error (external-format-encoding-error)
(read-flexi-line* ,input ,format))))
(when verbose
(format t "~&UTF-8 sequences which are too short"))
(want-encoding-error #(#xe4 #xf6 #xfc) :utf8)
(want-encoding-error #(#xc0) :utf8)
(want-encoding-error #(#xe0 #xff) :utf8)
(want-encoding-error #(#xf0 #xff #xff) :utf8)
(when verbose
(format t "~&UTF-16 sequences with an odd number of octets"))
(want-encoding-error #(#x01) :utf-16le)
(want-encoding-error #(#x01 #x01 #x01) :utf-16le)
(want-encoding-error #(#x01) :utf-16be)
(want-encoding-error #(#x01 #x01 #x01) :utf-16be)
(when verbose
(format t "~&Missing words in UTF-16"))
(want-encoding-error #(#x01 #xd8) :utf-16le)
(want-encoding-error #(#xd8 #x01) :utf-16be)
(when verbose
(format t "~&Missing octets in UTF-32"))
(want-encoding-error #(#x01) :utf-32le)
(want-encoding-error #(#x01 #x01) :utf-32le)
(want-encoding-error #(#x01 #x01 #x01) :utf-32le)
(want-encoding-error #(#x01 #x01 #x01 #x01 #x01) :utf-32le)
(want-encoding-error #(#x01) :utf-32be)
(want-encoding-error #(#x01 #x01) :utf-32be)
(want-encoding-error #(#x01 #x01 #x01) :utf-32be)
(want-encoding-error #(#x01 #x01 #x01 #x01 #x01) :utf-32be))
(when verbose
(format t "~&Handling of EOF in the middle of CRLF"))
(check (string= #.(string #\Return)
(read-flexi-line `(,(char-code #\Return)) '(:ascii :eol-style :crlf))))
(let ((*substitution-char* #\?))
(when verbose
(format t "~&Fixed substitution character #\?")
(format t "~&:ASCII doesn't have characters with char codes > 127"))
(check (string= "a??" (read-flexi-line `(,(char-code #\a) 128 200) :ascii)))
(check (string= "a??" (read-flexi-line* `#(,(char-code #\a) 128 200) :ascii)))
(when verbose
(format t "~&:WINDOWS-1253 doesn't have a characters with codes 170 and 210"))
(check (string= "a??" (read-flexi-line `(,(char-code #\a) 170 210) :windows-1253)))
(check (string= "a??" (read-flexi-line* `#(,(char-code #\a) 170 210) :windows-1253)))
(when verbose
(format t "~&Not a valid UTF-8 sequence"))
(check (string= "??" (read-flexi-line '(#xe4 #xf6 #xfc) :utf8))))
(let ((*substitution-char* nil))
(when verbose
(format t "~&Variable substitution using USE-VALUE restart")
(format t "~&:ASCII doesn't have characters with char codes > 127"))
(check (string= "abc" (using-values (#\b #\c)
(read-flexi-line `(,(char-code #\a) 128 200) :ascii))))
(check (string= "abc" (using-values (#\b #\c)
(read-flexi-line* `#(,(char-code #\a) 128 200) :ascii))))
(when verbose
(format t "~&:WINDOWS-1253 doesn't have a characters with codes 170 and 210"))
(check (string= "axy" (using-values (#\x #\y)
(read-flexi-line `(,(char-code #\a) 170 210) :windows-1253))))
(check (string= "axy" (using-values (#\x #\y)
(read-flexi-line* `#(,(char-code #\a) 170 210) :windows-1253))))
(when verbose
(format t "~&Not a valid UTF-8 sequence"))
(check (string= "QW" (using-values (#\Q #\W) (read-flexi-line '(#xe4 #xf6 #xfc) :utf8))))
(when verbose
(format t "~&UTF-8 can't start neither with #b11111110 nor with #b11111111"))
(check (string= "QW" (using-values (#\Q #\W) (read-flexi-line '(#b11111110 #b11111111) :utf8))))
(when verbose
(format t "~&Only one octet in UTF-16 sequence"))
(check (string= "E" (using-values (#\E) (read-flexi-line '(#x01) :utf-16le))))
(when verbose
(format t "~&Two octets in UTF-16, but value of resulting word suggests that another word follows"))
(check (string= "R" (using-values (#\R) (read-flexi-line '(#x01 #xd8) :utf-16le))))
(when verbose
(format t "~&The second word must fit into the [#xdc00; #xdfff] interval, but it is #xdbff"))
(check (string= "T" (using-values (#\T) (read-flexi-line '(#x01 #xd8 #xff #xdb) :utf-16le))))
(check (string= "T" (using-values (#\T) (read-flexi-line* #(#x01 #xd8 #xff #xdb) :utf-16le))))
(when verbose
(format t "~&The same as for little endian above, but using inverse order of bytes in words"))
(check (string= "E" (using-values (#\E) (read-flexi-line '(#x01) :utf-16be))))
(check (string= "R" (using-values (#\R) (read-flexi-line '(#xd8 #x01) :utf-16be))))
(check (string= "T" (using-values (#\T) (read-flexi-line '(#xd8 #x01 #xdb #xff) :utf-16be))))
(check (string= "T" (using-values (#\T) (read-flexi-line* #(#xd8 #x01 #xdb #xff) :utf-16be))))
(when verbose
(format t "~&EOF in the middle of a 4-octet sequence in UTF-32"))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01) :utf-32le))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01) :utf-32le))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01 #x01) :utf-32le))))
(check (string= "aY" (using-values (#\Y)
(read-flexi-line `(,(char-code #\a) #x00 #x00 #x00 #x01) :utf-32le))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01) :utf-32be))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01) :utf-32be))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01 #x01) :utf-32be))))
(check (string= "aY" (using-values (#\Y)
(read-flexi-line `(#x00 #x00 #x00 ,(char-code #\a) #x01) :utf-32be)))))))
(defun unread-char-tests (&key verbose)
"Tests whether UNREAD-CHAR behaves as expected."
(with-test-suite ("UNREAD-CHAR behaviour." :show-progress-p (and (not verbose) 100))
(flet ((test-one-file (file-name external-format)
(when verbose
(format t "~& ...and external format ~A" (normalize-external-format external-format)))
(with-open-file (in (merge-pathnames file-name *this-file*)
:element-type 'flex:octet)
(let ((in (make-flexi-stream in :external-format external-format)))
(loop repeat 300
for char = (read-char in)
do (unread-char char in)
(check (char= (read-char in) char)))))))
(loop for (file-name symbols) in *test-files*
when verbose
do (format t "~&With file ~S" file-name)
do (loop for symbol in symbols
do (loop for (file-name . external-format) in (create-file-variants file-name symbol)
do (test-one-file file-name external-format)))))))
(defun column-tests (&key verbose)
(with-test-suite ("STREAM-LINE-COLUMN tests" :show-progress-p (not verbose))
(let* ((binary-stream (flexi-streams:make-in-memory-output-stream))
(stream (flexi-streams:make-flexi-stream binary-stream :external-format :iso-8859-1)))
(write-sequence "hello" stream)
(format stream "~12Tworld")
(finish-output stream)
(check (string= "hello world"
(flexi-streams:octets-to-string
(flexi-streams::vector-stream-vector binary-stream)
:external-format :iso-8859-1)))
(terpri stream)
(check (= 0 (flexi-stream-column stream)))
(write-sequence "abc" stream)
(check (= 3 (flexi-stream-column stream)))
(terpri stream)
(check (= 0 (flexi-stream-column stream))))))
(defun make-external-format-tests (&key verbose)
(with-test-suite ("MAKE-EXTERNAL-FORMAT tests" :show-progress-p (not verbose))
(flet ((make-case (real-name &key id name)
(list real-name
:id id
:input-names (list name (string-upcase name) (string-downcase name)))))
(let ((cases (append '((:utf-8 :id nil
:input-names (:utf8 :utf-8 "utf8" "utf-8" "UTF8" "UTF-8")))
(loop for (name . real-name) in +name-map+
unless (member :code-page (list name real-name))
append (list (make-case real-name :name name)
(make-case real-name :name real-name)))
(loop for (name . definition) in +shortcut-map+
for key = (car definition)
for id = (getf (cdr definition) :id)
for expected = (or (cdr (assoc key +name-map+)) key)
collect (make-case expected :id id :name name)))))
(loop for (expected-name . kwargs) in cases
for id = (getf kwargs :id)
for input-names = (getf kwargs :input-names)
do (loop for name in input-names
for ext-format = (make-external-format name)
do (check (eq (flex:external-format-name ext-format) expected-name))
when id
do (check (= (flex:external-format-id ext-format) id))))))
(let ((error-cases '("utf-8 " " utf-8" "utf8 " " utf8" "utf89" :utf89 utf89 :code-page nil)))
(loop for input-name in error-cases
do (with-expected-error (external-format-error)
(make-external-format input-name))))))
(defun peek-byte-tests (&key verbose)
(with-test-suite ("PEEK-BYTE tests" :show-progress-p (not verbose))
(flex:with-input-from-sequence (input #(0 1 2))
(let ((stream (flex:make-flexi-stream input)))
If peek - type was specified as 2 we need to peek the first octect equal to 2
(check (= 2 (flex::peek-byte stream 2 nil 1)))
;; also, the octet should be unread to the stream so that we can peek it again
(check (= 2 (flex::peek-byte stream nil nil nil)))))))
(defun run-all-tests (&key verbose)
"Runs all tests for FLEXI-STREAMS and returns a true value iff all
tests succeeded. VERBOSE is interpreted by the individual test suites
above."
(let ((successp t))
(macrolet ((run-test-suite (&body body)
`(unless (progn ,@body)
(setq successp nil))))
(run-test-suite (compare-files :verbose verbose))
(run-test-suite (string-tests :verbose verbose))
(run-test-suite (sequence-tests :verbose verbose))
(run-test-suite (error-handling-tests :verbose verbose))
(run-test-suite (unread-char-tests :verbose verbose))
(run-test-suite (column-tests :verbose verbose))
(run-test-suite (make-external-format-tests :verbose verbose))
(run-test-suite (peek-byte-tests :verbose verbose))
(format t "~2&~:[Some tests failed~;All tests passed~]." successp)
successp)))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/flexi-streams-20190107-git/test/test.lisp | lisp | Syntax : COMMON - LISP ; Package : FLEXI - STREAMS - TEST ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
FLEXI-STREAMS puts integers into the list, but OpenMCL
thinks they are characters...
also, the octet should be unread to the stream so that we can peek it again | $ Header : /usr / local / cvsrep / flexi - streams / test / test.lisp , v 1.39 2008/05/30 09:10:55 edi Exp $
Copyright ( c ) 2006 - 2008 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :flexi-streams-test)
(defmacro with-test-suite ((test-description &key show-progress-p) &body body)
"Defines a test suite. Three utilities are available inside of the
body of the macro: The function FAIL, and the macros CHECK and
WITH-EXPECTED-ERROR. FAIL, the lowest level utility, marks the test
defined by WITH-TEST-SUITE as failed. CHECK checks whether its argument is
true, otherwise it calls FAIL. If during evaluation of the specified
expression any condition is signalled, this is also considered a
failure. WITH-EXPECTED-ERROR executes its body and considers the test
a success if the specified error was signalled, otherwise it calls
FAIL.
WITH-TEST-SUITE prints a simple progress report if SHOW-PROGRESS-P is true."
(with-unique-names (successp testcount)
(with-rebinding (show-progress-p)
`(let ((,successp t)
(,testcount 1))
(when (and ,show-progress-p (not (numberp ,show-progress-p)))
(setq ,show-progress-p 1))
(flet ((fail (format-str &rest format-args)
(apply #'format t format-str format-args)
(setq ,successp nil))
(maybe-show-progress ()
(when (and ,show-progress-p (zerop (mod ,testcount ,show-progress-p)))
(format t ".")
(when (zerop (mod ,testcount (* 10 ,show-progress-p)))
(terpri))
(force-output))
(incf ,testcount)))
(macrolet ((check (expression)
`(progn
(maybe-show-progress)
(handler-case
(unless ,expression
(fail "~&Test ~S failed.~%" ',expression))
(error (c)
(fail "~&Test ~S failed signalling error of type ~A: ~A.~%"
',expression (type-of c) c)))))
(with-expected-error ((condition-type) &body body)
`(progn
(maybe-show-progress)
(handler-case (progn ,@body)
(,condition-type () t)
(:no-error (&rest args)
(declare (ignore args))
(fail "~&Expected condition ~S not signalled.~%"
',condition-type))))))
(format t "~&Test suite: ~S~%" ,test-description)
,@body))
,successp))))
LW ca n't indent this correctly because it 's in a MACROLET
#+:lispworks
(editor:setup-indent "with-expected-error" 1 2 4)
(defconstant +buffer-size+ 8192
"Size of buffers for COPY-STREAM* below.")
(defvar *copy-function* nil
"Which function to use when copying from one stream to the other -
see for example COPY-FILE below.")
(defvar *this-file* (load-time-value
(or #.*compile-file-pathname* *load-pathname*))
"The pathname of the file \(`test.lisp') where this variable was
defined.")
#+:lispworks
(defun get-env-variable-as-directory (name)
(lw:when-let (string (lw:environment-variable name))
(when (plusp (length string))
(cond ((find (char string (1- (length string))) "\\/" :test #'char=) string)
(t (lw:string-append string "/"))))))
(defvar *tmp-dir*
(load-time-value
(merge-pathnames "odd-streams-test/"
#+:allegro (system:temporary-directory)
#+:lispworks (pathname (or (get-env-variable-as-directory "TEMP")
(get-env-variable-as-directory "TMP")
#+:win32 "C:/"
#-:win32 "/tmp/"))
#-(or :allegro :lispworks) #p"/tmp/"))
"The pathname of a temporary directory used for testing.")
(defvar *test-files*
'(("kafka" (:utf8 :latin1 :cp1252))
("tilton" (:utf8 :ascii))
("hebrew" (:utf8 :latin8))
("russian" (:utf8 :koi8r))
("unicode_demo" (:utf8 :ucs2 :ucs4)))
"A list of test files where each entry consists of the name
prefix and a list of encodings.")
(defun create-file-variants (file-name symbol)
"For a name suffix FILE-NAME and a symbol SYMBOL denoting an
encoding returns a list of pairs where the car is a full file
name and the cdr is the corresponding external format. This list
contains all possible variants w.r.t. to line-end conversion and
endianness."
(let ((args (ecase symbol
(:ascii '(:ascii))
(:latin1 '(:latin-1))
(:latin8 '(:hebrew))
(:cp1252 '(:code-page :id 1252))
(:koi8r '(:koi8-r))
(:utf8 '(:utf-8))
(:ucs2 '(:utf-16))
(:ucs4 '(:utf-32))))
(endianp (member symbol '(:ucs2 :ucs4))))
(loop for little-endian in (if endianp '(t nil) '(t))
for endian-suffix in (if endianp '("_le" "_be") '(""))
nconc (loop for eol-style in '(:lf :cr :crlf)
collect (cons (format nil "~A_~(~A~)_~(~A~)~A.txt"
file-name symbol eol-style endian-suffix)
(apply #'make-external-format
(append args `(:eol-style ,eol-style
:little-endian ,little-endian))))))))
(defun create-test-combinations (file-name symbols &optional simplep)
"For a name suffix FILE-NAME and a list of symbols SYMBOLS denoting
different encodings of the corresponding file returns a list of lists
which can be used as arglists by COMPARE-FILES. If SIMPLEP is true, a
list which can be used for the string and sequence tests below is
returned."
(let ((file-variants (loop for symbol in symbols
nconc (create-file-variants file-name symbol))))
(loop for (name-in . external-format-in) in file-variants
when simplep
collect (list name-in external-format-in)
else
nconc (loop for (name-out . external-format-out) in file-variants
collect (list name-in external-format-in name-out external-format-out)))))
(defun file-equal (file1 file2)
"Returns a true value iff FILE1 and FILE2 have the same
contents \(viewed as binary files)."
(with-open-file (stream1 file1 :element-type 'octet)
(with-open-file (stream2 file2 :element-type 'octet)
(and (= (file-length stream1) (file-length stream2))
(loop for byte1 = (read-byte stream1 nil nil)
for byte2 = (read-byte stream2 nil nil)
while (and byte1 byte2)
always (= byte1 byte2))))))
(defun copy-stream (stream-in external-format-in stream-out external-format-out)
"Copies the contents of the binary stream STREAM-IN to the
binary stream STREAM-OUT using flexi streams - STREAM-IN is read
with the external format EXTERNAL-FORMAT-IN and STREAM-OUT is
written with EXTERNAL-FORMAT-OUT."
(let ((in (make-flexi-stream stream-in :external-format external-format-in))
(out (make-flexi-stream stream-out :external-format external-format-out)))
(loop for line = (read-line in nil nil)
while line
do (write-line line out))))
(defun copy-stream* (stream-in external-format-in stream-out external-format-out)
"Like COPY-STREAM, but uses READ-SEQUENCE and WRITE-SEQUENCE instead
of READ-LINE and WRITE-LINE."
(let ((in (make-flexi-stream stream-in :external-format external-format-in))
(out (make-flexi-stream stream-out :external-format external-format-out))
(buffer (make-array +buffer-size+ :element-type 'char*)))
(loop
(let ((position (read-sequence buffer in)))
(when (zerop position) (return))
(write-sequence buffer out :end position)))))
(defun copy-file (path-in external-format-in path-out external-format-out direction-out direction-in)
"Copies the contents of the file denoted by the pathname
PATH-IN to the file denoted by the pathname PATH-OUT using flexi
streams - STREAM-IN is read with the external format
EXTERNAL-FORMAT-IN and STREAM-OUT is written with
EXTERNAL-FORMAT-OUT. The input file is opened with
the :DIRECTION keyword argument DIRECTION-IN, the output file is
opened with the :DIRECTION keyword argument DIRECTION-OUT."
(with-open-file (in path-in
:element-type 'octet
:direction direction-in
:if-does-not-exist :error
:if-exists :overwrite)
(with-open-file (out path-out
:element-type 'octet
:direction direction-out
:if-does-not-exist :create
:if-exists :supersede)
(funcall *copy-function* in external-format-in out external-format-out))))
#+:lispworks
(defun copy-file-lw (path-in external-format-in path-out external-format-out direction-out direction-in)
"Same as COPY-FILE, but uses character streams instead of
binary streams. Only used to test LispWorks-specific behaviour."
(with-open-file (in path-in
:external-format '(:latin-1 :eol-style :lf)
:element-type 'base-char
:direction direction-in
:if-does-not-exist :error
:if-exists :overwrite)
(with-open-file (out path-out
:external-format '(:latin-1 :eol-style :lf)
:element-type 'base-char
:direction direction-out
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(funcall *copy-function* in external-format-in out external-format-out))))
(defun compare-files (&key verbose)
"Each test in this suite copies the contents of one file \(in the
`test' directory) to another file \(in a temporary directory) using
flexi streams with different external formats. The resulting file is
compared with an existing file in the `test' directory to check if the
outcome is as expected. Uses various variants of the :DIRECTION
keyword when opening the files.
Returns a true value iff all tests succeeded. Prints information
about each individual comparison if VERBOSE is true."
(with-test-suite ("Reading/writing files" :show-progress-p (not verbose))
(flet ((one-comparison (path-in external-format-in path-out external-format-out verbose)
(when verbose
(format t "~&File ~S, using copy function ~S" (file-namestring path-in) *copy-function*)
(format t "~& and external formats ~S --> ~S"
(normalize-external-format external-format-in)
(normalize-external-format external-format-out)))
(let ((full-path-in (merge-pathnames path-in *this-file*))
(full-path-out (ensure-directories-exist
(merge-pathnames path-out *tmp-dir*)))
(full-path-orig (merge-pathnames path-out *this-file*)))
(dolist (direction-out '(:output :io))
(dolist (direction-in '(:input :io))
(when verbose
(format t "~&...directions ~S --> ~S" direction-in direction-out))
(copy-file full-path-in external-format-in
full-path-out external-format-out
direction-out direction-in)
(check (file-equal full-path-out full-path-orig))
#+:lispworks
(progn
(when verbose
(format t "~&...directions ~S --> ~S \(LispWorks)" direction-in direction-out))
(copy-file-lw full-path-in external-format-in
full-path-out external-format-out
direction-out direction-in)
(check (file-equal full-path-out full-path-orig))))))))
(loop with compare-files-args-list = (loop for (file-name symbols) in *test-files*
nconc (create-test-combinations file-name symbols))
for *copy-function* in '(copy-stream copy-stream*)
do (loop for (path-in external-format-in path-out external-format-out) in compare-files-args-list
do (one-comparison path-in external-format-in path-out external-format-out verbose))))))
(defun file-as-octet-vector (pathspec)
"Returns the contents of the file denoted by PATHSPEC as a vector of
octets."
(with-open-file (in pathspec :element-type 'octet)
(let ((vector (make-array (file-length in) :element-type 'octet)))
(read-sequence vector in)
vector)))
(defun file-as-string (pathspec external-format)
"Reads the contents of the file denoted by PATHSPEC using the
external format EXTERNAL-FORMAT and returns the result as a string."
(with-open-file (in pathspec :element-type 'octet)
(let* ((number-of-octets (file-length in))
(in (make-flexi-stream in :external-format external-format))
(string (make-array number-of-octets
:element-type #+:lispworks 'lw:simple-char
#-:lispworks 'character
:fill-pointer t)))
(setf (fill-pointer string) (read-sequence string in))
string)))
(defun old-string-to-octets (string &key
(external-format (make-external-format :latin1))
(start 0) end)
"The old version of STRING-TO-OCTETS. We can use it to test
in-memory streams."
(declare (optimize speed))
(with-output-to-sequence (out)
(let ((flexi (make-flexi-stream out :external-format external-format)))
(write-string string flexi :start start :end end))))
(defun old-octets-to-string (vector &key
(external-format (make-external-format :latin1))
(start 0) (end (length vector)))
"The old version of OCTETS-TO-STRING. We can use it to test
in-memory streams."
(declare (optimize speed))
(with-input-from-sequence (in vector :start start :end end)
(let ((flexi (make-flexi-stream in :external-format external-format))
(result (make-array (- end start)
:element-type #+:lispworks 'lw:simple-char
#-:lispworks 'character
:fill-pointer t)))
(setf (fill-pointer result)
(read-sequence result flexi))
result)))
(defun string-tests (&key verbose)
"Tests whether conversion from strings to octets and vice versa
works as expected. Also tests with the old versions of the conversion
functions in order to test in-memory streams."
(with-test-suite ("String tests" :show-progress-p (and (not verbose) 10))
(flet ((one-string-test (pathspec external-format verbose)
(when verbose
(format t "~&With external format ~S:" (normalize-external-format external-format)))
(let* ((full-path (merge-pathnames pathspec *this-file*))
(octets-vector (file-as-octet-vector full-path))
(octets-list (coerce octets-vector 'list))
(string (file-as-string full-path external-format)))
(when verbose
(format t "~&...testing OCTETS-TO-STRING"))
(check (string= (octets-to-string octets-vector :external-format external-format) string))
(check (string= (octets-to-string octets-list :external-format external-format) string))
(when verbose
(format t "~&...testing STRING-TO-OCTETS"))
(check (equalp (string-to-octets string :external-format external-format) octets-vector))
(when verbose
(format t "~&...testing in-memory streams"))
(check (string= (old-octets-to-string octets-vector :external-format external-format) string))
(check (string= (old-octets-to-string octets-list :external-format external-format) string))
(check (equalp (old-string-to-octets string :external-format external-format) octets-vector)))))
(loop with simple-test-args-list = (loop for (file-name symbols) in *test-files*
nconc (create-test-combinations file-name symbols t))
for (pathspec external-format) in simple-test-args-list
do (one-string-test pathspec external-format verbose)))))
(defun sequence-equal (seq1 seq2)
"Whether the two sequences have the same elements."
(and (= (length seq1) (length seq2))
(loop for i below (length seq1)
always (eql (elt seq1 i) (elt seq2 i)))))
(defun sequence-tests (&key verbose)
"Several tests to confirm that READ-SEQUENCE and WRITE-SEQUENCE
behave as expected."
(with-test-suite ("Sequence tests" :show-progress-p (and (not verbose) 10))
(flet ((one-sequence-test (pathspec external-format verbose)
(when verbose
(format t "~&With external format ~S:" (normalize-external-format external-format)))
(let* ((full-path (merge-pathnames pathspec *this-file*))
(file-string (file-as-string full-path external-format))
(string-length (length file-string))
(octets (file-as-octet-vector full-path))
(octet-length (length octets)))
(when (external-format-equal external-format (make-external-format :utf8))
(when verbose
(format t "~&...reading octets"))
#-:openmcl
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(list (make-list octet-length)))
(setf (flexi-stream-element-type in) 'octet)
#-:clisp
(read-sequence list in)
#+:clisp
(ext:read-byte-sequence list in)
(check (sequence-equal list octets))))
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(third (floor octet-length 3))
(half (floor octet-length 2))
(vector (make-array half :element-type 'octet)))
(check (sequence-equal (loop repeat third
collect (read-byte in))
(subseq octets 0 third)))
(read-sequence vector in)
(check (sequence-equal vector (subseq octets third (+ third half)))))))
(when verbose
(format t "~&...reading characters"))
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(string (make-string (- string-length 10) :element-type 'char*)))
(setf (flexi-stream-element-type in) 'octet)
(check (sequence-equal (loop repeat 10
collect (read-char in))
(subseq file-string 0 10)))
(read-sequence string in)
(check (sequence-equal string (subseq file-string 10)))))
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(list (make-list (- string-length 100))))
(check (sequence-equal (loop repeat 50
collect (read-char in))
(subseq file-string 0 50)))
#-:clisp
(read-sequence list in)
#+:clisp
(ext:read-char-sequence list in)
(check (sequence-equal list (subseq file-string 50 (- string-length 50))))
(check (sequence-equal (loop repeat 50
collect (read-char in))
(subseq file-string (- string-length 50))))))
(with-open-file (in full-path :element-type 'octet)
(let* ((in (make-flexi-stream in :external-format external-format))
(array (make-array (- string-length 50))))
(check (sequence-equal (loop repeat 25
collect (read-char in))
(subseq file-string 0 25)))
#-:clisp
(read-sequence array in)
#+:clisp
(ext:read-char-sequence array in)
(check (sequence-equal array (subseq file-string 25 (- string-length 25))))
(check (sequence-equal (loop repeat 25
collect (read-char in))
(subseq file-string (- string-length 25))))))
(let ((path-out (ensure-directories-exist (merge-pathnames pathspec *tmp-dir*))))
(when verbose
(format t "~&...writing sequences"))
(with-open-file (out path-out
:direction :output
:if-exists :supersede
:element-type 'octet)
(let ((out (make-flexi-stream out :external-format external-format)))
(write-sequence octets out)))
(check (file-equal full-path path-out))
(with-open-file (out path-out
:direction :output
:if-exists :supersede
:element-type 'octet)
(let ((out (make-flexi-stream out :external-format external-format)))
(write-sequence file-string out)))
(check (file-equal full-path path-out))
(with-open-file (out path-out
:direction :output
:if-exists :supersede
:element-type 'octet)
(let ((out (make-flexi-stream out :external-format external-format)))
(write-sequence file-string out :end 100)
(write-sequence octets out
:start (length (string-to-octets file-string
:external-format external-format
:end 100)))))
(check (file-equal full-path path-out))))))
(loop with simple-test-args-list = (loop for (file-name symbols) in *test-files*
nconc (create-test-combinations file-name symbols t))
for (pathspec external-format) in simple-test-args-list
do (one-sequence-test pathspec external-format verbose)))))
(defmacro using-values ((&rest values) &body body)
"Executes BODY and feeds an element from VALUES to the USE-VALUE
restart each time a EXTERNAL-FORMAT-ENCODING-ERROR is signalled.
Signals an error when there are more or less
EXTERNAL-FORMAT-ENCODING-ERRORs than there are elements in VALUES."
(with-unique-names (value-stack condition-counter)
`(let ((,value-stack ',values)
(,condition-counter 0))
(handler-bind ((external-format-encoding-error
#'(lambda (c)
(declare (ignore c))
(unless ,value-stack
(error "Too many encoding errors signalled, expected only ~A."
,(length values)))
(incf ,condition-counter)
(use-value (pop ,value-stack)))))
(prog1 (progn ,@body)
(when ,value-stack
(error "~A encoding errors signalled, but ~A were expected."
,condition-counter ,(length values))))))))
(defun accept-overlong (octets code-point)
"Converts the `overlong' UTF-8 sequence OCTETS to using
OCTETS-TO-STRINGS, accepts the expected error with the corresponding
restart and checks that the result is CODE-POINT."
(handler-bind ((external-format-encoding-error
(lambda (c)
(declare (ignore c))
(invoke-restart 'accept-overlong-sequence))))
(string= (octets-to-string octets :external-format :utf-8)
(string (code-char code-point)))))
(defun read-flexi-line (sequence external-format)
"Creates and returns a string from the octet sequence SEQUENCE using
the external format EXTERNAL-FORMAT."
(with-input-from-sequence (in sequence)
(setq in (make-flexi-stream in :external-format external-format))
(read-line in)))
(defun read-flexi-line* (sequence external-format)
"Like READ-FLEXI-LINE but uses OCTETS-TO-STRING internally."
(octets-to-string sequence :external-format external-format))
(defun error-handling-tests (&key verbose)
"Tests several possible errors and how they are handled."
(with-test-suite ("Testing error handling" :show-progress-p (not verbose))
(macrolet ((want-encoding-error (input format)
`(with-expected-error (external-format-encoding-error)
(read-flexi-line* ,input ,format))))
(when verbose
(format t "~&\"Overlong\" UTF-8 sequences"))
(want-encoding-error #(#b11000000 #b10000000) :utf-8)
(want-encoding-error #(#b11000001 #b10000000) :utf-8)
(want-encoding-error #(#b11100000 #b10011111 #b10000000) :utf-8)
(want-encoding-error #(#b11110000 #b10001111 #b10000000 #b10000000) :utf-8)
(check (accept-overlong #(#b11000000 #b10000000) #b00000000))
(check (accept-overlong #(#b11000001 #b10000000) #b01000000))
(check (accept-overlong #(#b11100000 #b10011111 #b10000000) #b011111000000))
(check (accept-overlong #(#b11110000 #b10001111 #b10000000 #b10000000)
#b1111000000000000))
(when verbose
(format t "~&Invalid lead octets in UTF-8"))
(want-encoding-error #(#b11111000) :utf-8)
(want-encoding-error #(#b11111001) :utf-8)
(want-encoding-error #(#b11111100) :utf-8)
(want-encoding-error #(#b11111101) :utf-8)
(want-encoding-error #(#b11111110) :utf-8)
(want-encoding-error #(#b11111111) :utf-8)
(when verbose
(format t "~&Illegal code points"))
(want-encoding-error #(#x00 #x00 #x11 #x00) :utf-32le)
(want-encoding-error #(#x00 #xd8) :utf-16le)
(want-encoding-error #(#xff #xdf) :utf-16le))
(macrolet ((want-encoding-error (input format)
`(with-expected-error (external-format-encoding-error)
(read-flexi-line* ,input ,format))))
(when verbose
(format t "~&UTF-8 sequences which are too short"))
(want-encoding-error #(#xe4 #xf6 #xfc) :utf8)
(want-encoding-error #(#xc0) :utf8)
(want-encoding-error #(#xe0 #xff) :utf8)
(want-encoding-error #(#xf0 #xff #xff) :utf8)
(when verbose
(format t "~&UTF-16 sequences with an odd number of octets"))
(want-encoding-error #(#x01) :utf-16le)
(want-encoding-error #(#x01 #x01 #x01) :utf-16le)
(want-encoding-error #(#x01) :utf-16be)
(want-encoding-error #(#x01 #x01 #x01) :utf-16be)
(when verbose
(format t "~&Missing words in UTF-16"))
(want-encoding-error #(#x01 #xd8) :utf-16le)
(want-encoding-error #(#xd8 #x01) :utf-16be)
(when verbose
(format t "~&Missing octets in UTF-32"))
(want-encoding-error #(#x01) :utf-32le)
(want-encoding-error #(#x01 #x01) :utf-32le)
(want-encoding-error #(#x01 #x01 #x01) :utf-32le)
(want-encoding-error #(#x01 #x01 #x01 #x01 #x01) :utf-32le)
(want-encoding-error #(#x01) :utf-32be)
(want-encoding-error #(#x01 #x01) :utf-32be)
(want-encoding-error #(#x01 #x01 #x01) :utf-32be)
(want-encoding-error #(#x01 #x01 #x01 #x01 #x01) :utf-32be))
(when verbose
(format t "~&Handling of EOF in the middle of CRLF"))
(check (string= #.(string #\Return)
(read-flexi-line `(,(char-code #\Return)) '(:ascii :eol-style :crlf))))
(let ((*substitution-char* #\?))
(when verbose
(format t "~&Fixed substitution character #\?")
(format t "~&:ASCII doesn't have characters with char codes > 127"))
(check (string= "a??" (read-flexi-line `(,(char-code #\a) 128 200) :ascii)))
(check (string= "a??" (read-flexi-line* `#(,(char-code #\a) 128 200) :ascii)))
(when verbose
(format t "~&:WINDOWS-1253 doesn't have a characters with codes 170 and 210"))
(check (string= "a??" (read-flexi-line `(,(char-code #\a) 170 210) :windows-1253)))
(check (string= "a??" (read-flexi-line* `#(,(char-code #\a) 170 210) :windows-1253)))
(when verbose
(format t "~&Not a valid UTF-8 sequence"))
(check (string= "??" (read-flexi-line '(#xe4 #xf6 #xfc) :utf8))))
(let ((*substitution-char* nil))
(when verbose
(format t "~&Variable substitution using USE-VALUE restart")
(format t "~&:ASCII doesn't have characters with char codes > 127"))
(check (string= "abc" (using-values (#\b #\c)
(read-flexi-line `(,(char-code #\a) 128 200) :ascii))))
(check (string= "abc" (using-values (#\b #\c)
(read-flexi-line* `#(,(char-code #\a) 128 200) :ascii))))
(when verbose
(format t "~&:WINDOWS-1253 doesn't have a characters with codes 170 and 210"))
(check (string= "axy" (using-values (#\x #\y)
(read-flexi-line `(,(char-code #\a) 170 210) :windows-1253))))
(check (string= "axy" (using-values (#\x #\y)
(read-flexi-line* `#(,(char-code #\a) 170 210) :windows-1253))))
(when verbose
(format t "~&Not a valid UTF-8 sequence"))
(check (string= "QW" (using-values (#\Q #\W) (read-flexi-line '(#xe4 #xf6 #xfc) :utf8))))
(when verbose
(format t "~&UTF-8 can't start neither with #b11111110 nor with #b11111111"))
(check (string= "QW" (using-values (#\Q #\W) (read-flexi-line '(#b11111110 #b11111111) :utf8))))
(when verbose
(format t "~&Only one octet in UTF-16 sequence"))
(check (string= "E" (using-values (#\E) (read-flexi-line '(#x01) :utf-16le))))
(when verbose
(format t "~&Two octets in UTF-16, but value of resulting word suggests that another word follows"))
(check (string= "R" (using-values (#\R) (read-flexi-line '(#x01 #xd8) :utf-16le))))
(when verbose
(format t "~&The second word must fit into the [#xdc00; #xdfff] interval, but it is #xdbff"))
(check (string= "T" (using-values (#\T) (read-flexi-line '(#x01 #xd8 #xff #xdb) :utf-16le))))
(check (string= "T" (using-values (#\T) (read-flexi-line* #(#x01 #xd8 #xff #xdb) :utf-16le))))
(when verbose
(format t "~&The same as for little endian above, but using inverse order of bytes in words"))
(check (string= "E" (using-values (#\E) (read-flexi-line '(#x01) :utf-16be))))
(check (string= "R" (using-values (#\R) (read-flexi-line '(#xd8 #x01) :utf-16be))))
(check (string= "T" (using-values (#\T) (read-flexi-line '(#xd8 #x01 #xdb #xff) :utf-16be))))
(check (string= "T" (using-values (#\T) (read-flexi-line* #(#xd8 #x01 #xdb #xff) :utf-16be))))
(when verbose
(format t "~&EOF in the middle of a 4-octet sequence in UTF-32"))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01) :utf-32le))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01) :utf-32le))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01 #x01) :utf-32le))))
(check (string= "aY" (using-values (#\Y)
(read-flexi-line `(,(char-code #\a) #x00 #x00 #x00 #x01) :utf-32le))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01) :utf-32be))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01) :utf-32be))))
(check (string= "Y" (using-values (#\Y) (read-flexi-line '(#x01 #x01 #x01) :utf-32be))))
(check (string= "aY" (using-values (#\Y)
(read-flexi-line `(#x00 #x00 #x00 ,(char-code #\a) #x01) :utf-32be)))))))
(defun unread-char-tests (&key verbose)
"Tests whether UNREAD-CHAR behaves as expected."
(with-test-suite ("UNREAD-CHAR behaviour." :show-progress-p (and (not verbose) 100))
(flet ((test-one-file (file-name external-format)
(when verbose
(format t "~& ...and external format ~A" (normalize-external-format external-format)))
(with-open-file (in (merge-pathnames file-name *this-file*)
:element-type 'flex:octet)
(let ((in (make-flexi-stream in :external-format external-format)))
(loop repeat 300
for char = (read-char in)
do (unread-char char in)
(check (char= (read-char in) char)))))))
(loop for (file-name symbols) in *test-files*
when verbose
do (format t "~&With file ~S" file-name)
do (loop for symbol in symbols
do (loop for (file-name . external-format) in (create-file-variants file-name symbol)
do (test-one-file file-name external-format)))))))
(defun column-tests (&key verbose)
(with-test-suite ("STREAM-LINE-COLUMN tests" :show-progress-p (not verbose))
(let* ((binary-stream (flexi-streams:make-in-memory-output-stream))
(stream (flexi-streams:make-flexi-stream binary-stream :external-format :iso-8859-1)))
(write-sequence "hello" stream)
(format stream "~12Tworld")
(finish-output stream)
(check (string= "hello world"
(flexi-streams:octets-to-string
(flexi-streams::vector-stream-vector binary-stream)
:external-format :iso-8859-1)))
(terpri stream)
(check (= 0 (flexi-stream-column stream)))
(write-sequence "abc" stream)
(check (= 3 (flexi-stream-column stream)))
(terpri stream)
(check (= 0 (flexi-stream-column stream))))))
(defun make-external-format-tests (&key verbose)
(with-test-suite ("MAKE-EXTERNAL-FORMAT tests" :show-progress-p (not verbose))
(flet ((make-case (real-name &key id name)
(list real-name
:id id
:input-names (list name (string-upcase name) (string-downcase name)))))
(let ((cases (append '((:utf-8 :id nil
:input-names (:utf8 :utf-8 "utf8" "utf-8" "UTF8" "UTF-8")))
(loop for (name . real-name) in +name-map+
unless (member :code-page (list name real-name))
append (list (make-case real-name :name name)
(make-case real-name :name real-name)))
(loop for (name . definition) in +shortcut-map+
for key = (car definition)
for id = (getf (cdr definition) :id)
for expected = (or (cdr (assoc key +name-map+)) key)
collect (make-case expected :id id :name name)))))
(loop for (expected-name . kwargs) in cases
for id = (getf kwargs :id)
for input-names = (getf kwargs :input-names)
do (loop for name in input-names
for ext-format = (make-external-format name)
do (check (eq (flex:external-format-name ext-format) expected-name))
when id
do (check (= (flex:external-format-id ext-format) id))))))
(let ((error-cases '("utf-8 " " utf-8" "utf8 " " utf8" "utf89" :utf89 utf89 :code-page nil)))
(loop for input-name in error-cases
do (with-expected-error (external-format-error)
(make-external-format input-name))))))
(defun peek-byte-tests (&key verbose)
(with-test-suite ("PEEK-BYTE tests" :show-progress-p (not verbose))
(flex:with-input-from-sequence (input #(0 1 2))
(let ((stream (flex:make-flexi-stream input)))
If peek - type was specified as 2 we need to peek the first octect equal to 2
(check (= 2 (flex::peek-byte stream 2 nil 1)))
(check (= 2 (flex::peek-byte stream nil nil nil)))))))
(defun run-all-tests (&key verbose)
"Runs all tests for FLEXI-STREAMS and returns a true value iff all
tests succeeded. VERBOSE is interpreted by the individual test suites
above."
(let ((successp t))
(macrolet ((run-test-suite (&body body)
`(unless (progn ,@body)
(setq successp nil))))
(run-test-suite (compare-files :verbose verbose))
(run-test-suite (string-tests :verbose verbose))
(run-test-suite (sequence-tests :verbose verbose))
(run-test-suite (error-handling-tests :verbose verbose))
(run-test-suite (unread-char-tests :verbose verbose))
(run-test-suite (column-tests :verbose verbose))
(run-test-suite (make-external-format-tests :verbose verbose))
(run-test-suite (peek-byte-tests :verbose verbose))
(format t "~2&~:[Some tests failed~;All tests passed~]." successp)
successp)))
|
3e42151cae88a704a41ffc40681837d5df73a38a2c5e726151d772012399727a | whalliburton/academy | pretty-pictures.lisp | (in-package :academy)
(defmacro %create-demo-images (&rest calls)
`(progn
,@(loop for call in calls
collect `(let ((*save-drawing-name*
,(format nil "~{~(~A~)~^-~}" (ensure-list call))))
,(ensure-list call)))))
(defun life-comic (&key (width 32) (height 32) (columns 11) (pattern "dh121") (scale 1))
(let ((*bitmap* (with-comic-strip (:action identity :columns columns :width width :height height)
(life :steps (* columns columns) :size width :pattern pattern)))
(*image-save-scale* scale))
(draw *bitmap*)))
(defun create-demo-images ()
(let ((*image-save-directory* "demo-images")
(*image-save-directory-overwrite* t)
(*image-save-inverse* t))
(%create-demo-images
;; bullseye
(bullseye :size 320)
(bullseye :size 320 :filled t)
;; moiré
(moiré :size 320 :offset 32)
;; sunbeam
(sunbeam :size 320)
(sunbeam :size 320 :step 3)
;; life
(life-comic :width 32 :height 32 :columns 11 :pattern "dh121"))))
| null | https://raw.githubusercontent.com/whalliburton/academy/87a1a13ffbcd60d8553e42e647c59486c761e8cf/pretty-pictures.lisp | lisp | bullseye
moiré
sunbeam
life | (in-package :academy)
(defmacro %create-demo-images (&rest calls)
`(progn
,@(loop for call in calls
collect `(let ((*save-drawing-name*
,(format nil "~{~(~A~)~^-~}" (ensure-list call))))
,(ensure-list call)))))
(defun life-comic (&key (width 32) (height 32) (columns 11) (pattern "dh121") (scale 1))
(let ((*bitmap* (with-comic-strip (:action identity :columns columns :width width :height height)
(life :steps (* columns columns) :size width :pattern pattern)))
(*image-save-scale* scale))
(draw *bitmap*)))
(defun create-demo-images ()
(let ((*image-save-directory* "demo-images")
(*image-save-directory-overwrite* t)
(*image-save-inverse* t))
(%create-demo-images
(bullseye :size 320)
(bullseye :size 320 :filled t)
(moiré :size 320 :offset 32)
(sunbeam :size 320)
(sunbeam :size 320 :step 3)
(life-comic :width 32 :height 32 :columns 11 :pattern "dh121"))))
|
259e27cd79b671be5fd8a07b41f13833b0d3f01fbafbb884de30865bab3078da | earl-ducaine/cl-garnet | global.lisp |
(in-package :garnet-utils)
(defvar black nil)
(defvar white nil)
(defvar *garnet-break-key* :F1)
| null | https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/utils/global.lisp | lisp |
(in-package :garnet-utils)
(defvar black nil)
(defvar white nil)
(defvar *garnet-break-key* :F1)
| |
9dfd7c35c0312a02be2e68215f4820fc307a7b5b44773f50a1c095e8acfe1548 | racket/typed-racket | sealing-contract-4.rkt | #;
(exn-pred exn:fail:contract? #rx"shape-check")
#lang racket/base
(module u racket
(define state #f)
;; don't allow smuggling with mutation either
(define (mixin cls)
(define result
(if (not state)
(class cls
(super-new)
(define/public (n x) x))
;; should subclass from cls, not state since otherwise
;; we lose the `m` method
(class state (super-new))))
(set! state cls)
result)
(provide mixin))
(module t typed/racket/shallow
(require/typed (submod ".." u)
[mixin
(All (r #:row)
(-> (Class #:row-var r)
(Class #:row-var r [n (-> Integer Integer)])))])
(mixin (class object% (super-new)))
(mixin (class object%
(super-new)
(define/public (m x) x))))
(require 't)
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/fail/shallow/sealing-contract-4.rkt | racket |
don't allow smuggling with mutation either
should subclass from cls, not state since otherwise
we lose the `m` method | (exn-pred exn:fail:contract? #rx"shape-check")
#lang racket/base
(module u racket
(define state #f)
(define (mixin cls)
(define result
(if (not state)
(class cls
(super-new)
(define/public (n x) x))
(class state (super-new))))
(set! state cls)
result)
(provide mixin))
(module t typed/racket/shallow
(require/typed (submod ".." u)
[mixin
(All (r #:row)
(-> (Class #:row-var r)
(Class #:row-var r [n (-> Integer Integer)])))])
(mixin (class object% (super-new)))
(mixin (class object%
(super-new)
(define/public (m x) x))))
(require 't)
|
446a20be9cda3fe399180b0e09322ef82af6bfe260f680630a781447c78ff077 | cojna/iota | MaxFlow.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE CPP #
# LANGUAGE LambdaCase #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
module Data.Graph.MaxFlow where
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.ST
import Data.Function
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Data.Buffer
nothingMF :: Int
nothingMF = -1
type Vertex = Int
--
|
Dinic /O(V^2E)/
> > > : set -XTypeApplications
> > > : {
maxFlow @Int 5 0 4 $ \builder - > do
addEdgeMFB builder ( 0 , 1 , 10 )
addEdgeMFB builder ( 0 , 2 , 2 )
addEdgeMFB builder ( 1 , 2 , 6 )
addEdgeMFB builder ( 1 , 3 , 6 )
addEdgeMFB builder ( 3 , 2 , 2 )
addEdgeMFB builder ( 2 , 4 , 5 )
addEdgeMFB builder ( 3 , 4 , 8)
:}
11
> > > maxFlow @Int 2 0 1 $ const ( return ( ) )
0
Dinic /O(V^2E)/
>>> :set -XTypeApplications
>>> :{
maxFlow @Int 5 0 4 $ \builder -> do
addEdgeMFB builder (0, 1, 10)
addEdgeMFB builder (0, 2, 2)
addEdgeMFB builder (1, 2, 6)
addEdgeMFB builder (1, 3, 6)
addEdgeMFB builder (3, 2, 2)
addEdgeMFB builder (2, 4, 5)
addEdgeMFB builder (3, 4, 8)
:}
11
>>> maxFlow @Int 2 0 1 $ const (return ())
0
-}
maxFlow ::
(U.Unbox cap, Num cap, Ord cap, Bounded cap) =>
-- | number of vertices
Int ->
-- | source
Vertex ->
-- | sink
Vertex ->
(forall s. MaxFlowBuilder s cap -> ST s ()) ->
cap
maxFlow numVertices src sink run = runST $ do
builder <- newMaxFlowBuilder numVertices
run builder
buildMaxFlow builder >>= runMaxFlow src sink
data MaxFlow s cap = MaxFlow
{ numVerticesMF :: !Int
, numEdgesMF :: !Int
, offsetMF :: U.Vector Int
, dstMF :: U.Vector Vertex
, residualMF :: UM.MVector s cap
, levelMF :: UM.MVector s Int
, revEdgeMF :: U.Vector Int
, iterMF :: UM.MVector s Int
, queueMF :: Queue s Vertex
}
runMaxFlow ::
(U.Unbox cap, Num cap, Ord cap, Bounded cap, PrimMonad m) =>
Vertex ->
Vertex ->
MaxFlow (PrimState m) cap ->
m cap
runMaxFlow src sink mf@MaxFlow{..} = do
flip fix 0 $ \loopBFS !flow -> do
UM.set levelMF nothingMF
clearBuffer queueMF
bfsMF src sink mf
lsink <- UM.unsafeRead levelMF sink
if lsink == nothingMF
then return flow
else do
U.unsafeCopy iterMF offsetMF
flip fix flow $ \loopDFS !f -> do
df <- dfsMF src sink maxBound mf
if df > 0
then loopDFS (f + df)
else loopBFS f
bfsMF ::
(Num cap, Ord cap, U.Unbox cap, PrimMonad m) =>
Vertex ->
Vertex ->
MaxFlow (PrimState m) cap ->
m ()
bfsMF src sink MaxFlow{..} = do
UM.unsafeWrite levelMF src 0
pushBack src queueMF
fix $ \loop -> do
popFront queueMF >>= \case
Just v -> do
lsink <- UM.unsafeRead levelMF sink
when (lsink == nothingMF) $ do
let start = U.unsafeIndex offsetMF v
end = U.unsafeIndex offsetMF (v + 1)
lv <- UM.unsafeRead levelMF v
U.forM_ (U.generate (end - start) (+ start)) $ \e -> do
let nv = U.unsafeIndex dstMF e
res <- UM.unsafeRead residualMF e
lnv <- UM.unsafeRead levelMF nv
when (res > 0 && lnv == nothingMF) $ do
UM.unsafeWrite levelMF nv (lv + 1)
pushBack nv queueMF
loop
Nothing -> return ()
# INLINE bfsMF #
dfsMF ::
(U.Unbox cap, Num cap, Ord cap, Bounded cap, PrimMonad m) =>
Vertex ->
Vertex ->
cap ->
MaxFlow (PrimState m) cap ->
m cap
dfsMF v0 sink flow0 MaxFlow{..} = dfs v0 flow0 return
where
dfs !v !flow k
| v == sink = k flow
| otherwise = fix $ \loop -> do
e <- UM.unsafeRead iterMF v
if e < U.unsafeIndex offsetMF (v + 1)
then do
UM.unsafeWrite iterMF v (e + 1)
let nv = U.unsafeIndex dstMF e
cap <- UM.unsafeRead residualMF e
lv <- UM.unsafeRead levelMF v
lnv <- UM.unsafeRead levelMF nv
if cap > 0 && lv < lnv
then do
dfs nv (min flow cap) $ \f -> do
if f > 0
then do
UM.unsafeModify residualMF (subtract f) e
UM.unsafeModify
residualMF
(+ f)
(U.unsafeIndex revEdgeMF e)
k f
else loop
else loop
else k 0
# INLINE dfsMF #
data MaxFlowBuilder s cap = MaxFlowBuilder
{ numVerticesMFB :: !Int
, inDegreeMFB :: UM.MVector s Int
| default buffer size : /1024 * 1024/
edgesMFB :: Buffer s (Vertex, Vertex, cap)
}
newMaxFlowBuilder ::
(U.Unbox cap, PrimMonad m) =>
Int ->
m (MaxFlowBuilder (PrimState m) cap)
newMaxFlowBuilder n =
MaxFlowBuilder n
<$> UM.replicate n 0
<*> newBuffer (1024 * 1024)
buildMaxFlow ::
(Num cap, U.Unbox cap, PrimMonad m) =>
MaxFlowBuilder (PrimState m) cap ->
m (MaxFlow (PrimState m) cap)
buildMaxFlow MaxFlowBuilder{..} = do
offsetMF <- U.scanl' (+) 0 <$> U.unsafeFreeze inDegreeMFB
let numVerticesMF = numVerticesMFB
let numEdgesMF = U.last offsetMF
moffset <- U.thaw offsetMF
mdstMF <- UM.replicate numEdgesMF nothingMF
mrevEdgeMF <- UM.replicate numEdgesMF nothingMF
residualMF <- UM.replicate numEdgesMF 0
edges <- unsafeFreezeBuffer edgesMFB
U.forM_ edges $ \(src, dst, cap) -> do
srcOffset <- UM.unsafeRead moffset src
dstOffset <- UM.unsafeRead moffset dst
UM.unsafeModify moffset (+ 1) src
UM.unsafeModify moffset (+ 1) dst
UM.unsafeWrite mdstMF srcOffset dst
UM.unsafeWrite mdstMF dstOffset src
UM.unsafeWrite mrevEdgeMF srcOffset dstOffset
UM.unsafeWrite mrevEdgeMF dstOffset srcOffset
UM.unsafeWrite residualMF srcOffset cap
dstMF <- U.unsafeFreeze mdstMF
levelMF <- UM.replicate numVerticesMF nothingMF
revEdgeMF <- U.unsafeFreeze mrevEdgeMF
iterMF <- UM.replicate numVerticesMF 0
U.unsafeCopy iterMF offsetMF
queueMF <- newBufferAsQueue numVerticesMF
return MaxFlow{..}
addEdgeMFB ::
(U.Unbox cap, PrimMonad m) =>
MaxFlowBuilder (PrimState m) cap ->
(Vertex, Vertex, cap) ->
m ()
addEdgeMFB MaxFlowBuilder{..} (!src, !dst, !cap) = do
UM.unsafeModify inDegreeMFB (+ 1) src
UM.unsafeModify inDegreeMFB (+ 1) dst
pushBack (src, dst, cap) edgesMFB
# INLINE addEdgeMFB #
| null | https://raw.githubusercontent.com/cojna/iota/9acaa765ad685d466d889229d97b5a1c852a00dd/src/Data/Graph/MaxFlow.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE RankNTypes #
| number of vertices
| source
| sink | # LANGUAGE CPP #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
module Data.Graph.MaxFlow where
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.ST
import Data.Function
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Data.Buffer
nothingMF :: Int
nothingMF = -1
type Vertex = Int
|
Dinic /O(V^2E)/
> > > : set -XTypeApplications
> > > : {
maxFlow @Int 5 0 4 $ \builder - > do
addEdgeMFB builder ( 0 , 1 , 10 )
addEdgeMFB builder ( 0 , 2 , 2 )
addEdgeMFB builder ( 1 , 2 , 6 )
addEdgeMFB builder ( 1 , 3 , 6 )
addEdgeMFB builder ( 3 , 2 , 2 )
addEdgeMFB builder ( 2 , 4 , 5 )
addEdgeMFB builder ( 3 , 4 , 8)
:}
11
> > > maxFlow @Int 2 0 1 $ const ( return ( ) )
0
Dinic /O(V^2E)/
>>> :set -XTypeApplications
>>> :{
maxFlow @Int 5 0 4 $ \builder -> do
addEdgeMFB builder (0, 1, 10)
addEdgeMFB builder (0, 2, 2)
addEdgeMFB builder (1, 2, 6)
addEdgeMFB builder (1, 3, 6)
addEdgeMFB builder (3, 2, 2)
addEdgeMFB builder (2, 4, 5)
addEdgeMFB builder (3, 4, 8)
:}
11
>>> maxFlow @Int 2 0 1 $ const (return ())
0
-}
maxFlow ::
(U.Unbox cap, Num cap, Ord cap, Bounded cap) =>
Int ->
Vertex ->
Vertex ->
(forall s. MaxFlowBuilder s cap -> ST s ()) ->
cap
maxFlow numVertices src sink run = runST $ do
builder <- newMaxFlowBuilder numVertices
run builder
buildMaxFlow builder >>= runMaxFlow src sink
data MaxFlow s cap = MaxFlow
{ numVerticesMF :: !Int
, numEdgesMF :: !Int
, offsetMF :: U.Vector Int
, dstMF :: U.Vector Vertex
, residualMF :: UM.MVector s cap
, levelMF :: UM.MVector s Int
, revEdgeMF :: U.Vector Int
, iterMF :: UM.MVector s Int
, queueMF :: Queue s Vertex
}
runMaxFlow ::
(U.Unbox cap, Num cap, Ord cap, Bounded cap, PrimMonad m) =>
Vertex ->
Vertex ->
MaxFlow (PrimState m) cap ->
m cap
runMaxFlow src sink mf@MaxFlow{..} = do
flip fix 0 $ \loopBFS !flow -> do
UM.set levelMF nothingMF
clearBuffer queueMF
bfsMF src sink mf
lsink <- UM.unsafeRead levelMF sink
if lsink == nothingMF
then return flow
else do
U.unsafeCopy iterMF offsetMF
flip fix flow $ \loopDFS !f -> do
df <- dfsMF src sink maxBound mf
if df > 0
then loopDFS (f + df)
else loopBFS f
bfsMF ::
(Num cap, Ord cap, U.Unbox cap, PrimMonad m) =>
Vertex ->
Vertex ->
MaxFlow (PrimState m) cap ->
m ()
bfsMF src sink MaxFlow{..} = do
UM.unsafeWrite levelMF src 0
pushBack src queueMF
fix $ \loop -> do
popFront queueMF >>= \case
Just v -> do
lsink <- UM.unsafeRead levelMF sink
when (lsink == nothingMF) $ do
let start = U.unsafeIndex offsetMF v
end = U.unsafeIndex offsetMF (v + 1)
lv <- UM.unsafeRead levelMF v
U.forM_ (U.generate (end - start) (+ start)) $ \e -> do
let nv = U.unsafeIndex dstMF e
res <- UM.unsafeRead residualMF e
lnv <- UM.unsafeRead levelMF nv
when (res > 0 && lnv == nothingMF) $ do
UM.unsafeWrite levelMF nv (lv + 1)
pushBack nv queueMF
loop
Nothing -> return ()
# INLINE bfsMF #
dfsMF ::
(U.Unbox cap, Num cap, Ord cap, Bounded cap, PrimMonad m) =>
Vertex ->
Vertex ->
cap ->
MaxFlow (PrimState m) cap ->
m cap
dfsMF v0 sink flow0 MaxFlow{..} = dfs v0 flow0 return
where
dfs !v !flow k
| v == sink = k flow
| otherwise = fix $ \loop -> do
e <- UM.unsafeRead iterMF v
if e < U.unsafeIndex offsetMF (v + 1)
then do
UM.unsafeWrite iterMF v (e + 1)
let nv = U.unsafeIndex dstMF e
cap <- UM.unsafeRead residualMF e
lv <- UM.unsafeRead levelMF v
lnv <- UM.unsafeRead levelMF nv
if cap > 0 && lv < lnv
then do
dfs nv (min flow cap) $ \f -> do
if f > 0
then do
UM.unsafeModify residualMF (subtract f) e
UM.unsafeModify
residualMF
(+ f)
(U.unsafeIndex revEdgeMF e)
k f
else loop
else loop
else k 0
# INLINE dfsMF #
data MaxFlowBuilder s cap = MaxFlowBuilder
{ numVerticesMFB :: !Int
, inDegreeMFB :: UM.MVector s Int
| default buffer size : /1024 * 1024/
edgesMFB :: Buffer s (Vertex, Vertex, cap)
}
newMaxFlowBuilder ::
(U.Unbox cap, PrimMonad m) =>
Int ->
m (MaxFlowBuilder (PrimState m) cap)
newMaxFlowBuilder n =
MaxFlowBuilder n
<$> UM.replicate n 0
<*> newBuffer (1024 * 1024)
buildMaxFlow ::
(Num cap, U.Unbox cap, PrimMonad m) =>
MaxFlowBuilder (PrimState m) cap ->
m (MaxFlow (PrimState m) cap)
buildMaxFlow MaxFlowBuilder{..} = do
offsetMF <- U.scanl' (+) 0 <$> U.unsafeFreeze inDegreeMFB
let numVerticesMF = numVerticesMFB
let numEdgesMF = U.last offsetMF
moffset <- U.thaw offsetMF
mdstMF <- UM.replicate numEdgesMF nothingMF
mrevEdgeMF <- UM.replicate numEdgesMF nothingMF
residualMF <- UM.replicate numEdgesMF 0
edges <- unsafeFreezeBuffer edgesMFB
U.forM_ edges $ \(src, dst, cap) -> do
srcOffset <- UM.unsafeRead moffset src
dstOffset <- UM.unsafeRead moffset dst
UM.unsafeModify moffset (+ 1) src
UM.unsafeModify moffset (+ 1) dst
UM.unsafeWrite mdstMF srcOffset dst
UM.unsafeWrite mdstMF dstOffset src
UM.unsafeWrite mrevEdgeMF srcOffset dstOffset
UM.unsafeWrite mrevEdgeMF dstOffset srcOffset
UM.unsafeWrite residualMF srcOffset cap
dstMF <- U.unsafeFreeze mdstMF
levelMF <- UM.replicate numVerticesMF nothingMF
revEdgeMF <- U.unsafeFreeze mrevEdgeMF
iterMF <- UM.replicate numVerticesMF 0
U.unsafeCopy iterMF offsetMF
queueMF <- newBufferAsQueue numVerticesMF
return MaxFlow{..}
addEdgeMFB ::
(U.Unbox cap, PrimMonad m) =>
MaxFlowBuilder (PrimState m) cap ->
(Vertex, Vertex, cap) ->
m ()
addEdgeMFB MaxFlowBuilder{..} (!src, !dst, !cap) = do
UM.unsafeModify inDegreeMFB (+ 1) src
UM.unsafeModify inDegreeMFB (+ 1) dst
pushBack (src, dst, cap) edgesMFB
# INLINE addEdgeMFB #
|
07d6711eab6603d0f8cfcd7cb45f2acf82e3ccc619a93029bcbd5a84e4c68d56 | input-output-hk/voting-tools | Crypto.hs | module Test.Cardano.Catalyst.Crypto
( tests
)
where
import qualified Data.Aeson as Aeson
import Hedgehog (Property, property, tripping)
import Hedgehog.Internal.Property (forAllT)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.Hedgehog (testProperty)
import qualified Cardano.Catalyst.Test.DSL.Gen as Gen
tests :: TestTree
tests = testGroup "Test.Cardano.Catalyst.Crypto"
[ testProperty "JSON roundtrip StakeVerificationKey" prop_stakeVerificationKey_json_roundtrip
]
prop_stakeVerificationKey_json_roundtrip :: Property
prop_stakeVerificationKey_json_roundtrip = property $ do
stakePub <- forAllT Gen.genStakeVerificationKey
tripping stakePub Aeson.encode Aeson.eitherDecode'
| null | https://raw.githubusercontent.com/input-output-hk/voting-tools/d14c5a456dc440b1dfe7901b6f19e53e8aadea12/test/Test/Cardano/Catalyst/Crypto.hs | haskell | module Test.Cardano.Catalyst.Crypto
( tests
)
where
import qualified Data.Aeson as Aeson
import Hedgehog (Property, property, tripping)
import Hedgehog.Internal.Property (forAllT)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.Hedgehog (testProperty)
import qualified Cardano.Catalyst.Test.DSL.Gen as Gen
tests :: TestTree
tests = testGroup "Test.Cardano.Catalyst.Crypto"
[ testProperty "JSON roundtrip StakeVerificationKey" prop_stakeVerificationKey_json_roundtrip
]
prop_stakeVerificationKey_json_roundtrip :: Property
prop_stakeVerificationKey_json_roundtrip = property $ do
stakePub <- forAllT Gen.genStakeVerificationKey
tripping stakePub Aeson.encode Aeson.eitherDecode'
| |
c5756fa166d181f4e12effd42e12f117badda895e1b0410e422504a712b2c991 | osimon8/CombinatorC | expression.ml | open Bexp
open Circuit
type var_type =
| TInt
| TCondition
| TSignal
| TCircuit
| TPattern
let string_of_type ty : string =
begin match ty with
| TInt -> "int"
| TCondition -> "condition"
| TSignal -> "signal"
| TCircuit -> "circuit"
| TPattern -> "pattern"
end
let signal_or_var bexp : bool =
begin match bexp with
| Signal _
| Var _ -> true
| _ -> false
end
let valid_condition bexp : bool =
begin match bexp with
| Gt (b1, b2)
| Gte (b1, b2)
| Lt (b1, b2)
| Lte (b1, b2)
| Eq (b1, b2)
| Neq (b1, b2) -> signal_or_var b1 &&
begin match b2 with
| Lit _ -> true
| _ -> signal_or_var b2
end
| BOOL b
| Not b -> signal_or_var b
| _ -> false
end
type compiled_circuit =
| Abstract of circuit
| Concrete of concrete_circuit
type expression =
| Call of string * delayed_expression list
| Int of int32
| Condition of bexp
| Var of string
| Signal of string
| Circuit of ctree
| Pattern of (var_type * string) list
| For of bool * string * delayed_expression * delayed_expression * bool * command list
and ctree =
| Union of ctree * ctree * loc
| Concat of ctree * ctree * loc
| Expression of delayed_expression * loc
| Compiled of compiled_circuit
| Inline of bexp * string * loc
and command =
| CircuitBind of string * bexp * delayed_expression * bool
| Assign of string * var_type * delayed_expression
| Output of delayed_expression
| OutputAt of delayed_expression * (bexp * bexp)
and delayed_expression =
| Delayed of bexp
| Immediate of expression
type block = command list
let num_outputs (block:block) : int =
let vali acc c =
begin match c with
| Output _
| OutputAt _ -> acc + 1
| _ -> acc
end
in
List.fold_left vali 0 block
let expression_of_bexp (bexp:bexp) : delayed_expression =
let lit_opt = interpret_bexp bexp in
begin match lit_opt with
| Some l -> Immediate (Int l)
| None ->
begin match bexp with
| Signal s -> Immediate (Signal s)
| _ -> if valid_condition bexp then Immediate (Condition bexp) else
Delayed bexp
end
end
let offset (origin:placement) (off:placement) : placement =
let x, y = origin in
let ox, oy = off in
(ox +. x, oy +. y)
let move_layout (l:circuit_layout) (new_p:placement) : circuit_layout =
let p, s, pl = l in
let px, py = p in
let neg_o = (Float.neg px, Float.neg py) in
let pl2 = List.map (offset (offset new_p neg_o)) pl in
new_p, s, pl2
let rec is_concrete ctree : bool =
let c loc = match loc with | Some _ -> true | None -> false in
begin match ctree with
| Union(c1, c2, loc)
| Concat(c1, c2, loc) -> c loc || is_concrete c1 || is_concrete c2
| Expression(_, loc) -> c loc
| Inline(_, _, loc) -> c loc
| Compiled c -> begin match c with
| Concrete _ -> true
| Abstract _ -> false
end
end | null | https://raw.githubusercontent.com/osimon8/CombinatorC/0bdbbc893ee458ec75eab7a48712d07a62e190aa/src/ast/expression.ml | ocaml | open Bexp
open Circuit
type var_type =
| TInt
| TCondition
| TSignal
| TCircuit
| TPattern
let string_of_type ty : string =
begin match ty with
| TInt -> "int"
| TCondition -> "condition"
| TSignal -> "signal"
| TCircuit -> "circuit"
| TPattern -> "pattern"
end
let signal_or_var bexp : bool =
begin match bexp with
| Signal _
| Var _ -> true
| _ -> false
end
let valid_condition bexp : bool =
begin match bexp with
| Gt (b1, b2)
| Gte (b1, b2)
| Lt (b1, b2)
| Lte (b1, b2)
| Eq (b1, b2)
| Neq (b1, b2) -> signal_or_var b1 &&
begin match b2 with
| Lit _ -> true
| _ -> signal_or_var b2
end
| BOOL b
| Not b -> signal_or_var b
| _ -> false
end
type compiled_circuit =
| Abstract of circuit
| Concrete of concrete_circuit
type expression =
| Call of string * delayed_expression list
| Int of int32
| Condition of bexp
| Var of string
| Signal of string
| Circuit of ctree
| Pattern of (var_type * string) list
| For of bool * string * delayed_expression * delayed_expression * bool * command list
and ctree =
| Union of ctree * ctree * loc
| Concat of ctree * ctree * loc
| Expression of delayed_expression * loc
| Compiled of compiled_circuit
| Inline of bexp * string * loc
and command =
| CircuitBind of string * bexp * delayed_expression * bool
| Assign of string * var_type * delayed_expression
| Output of delayed_expression
| OutputAt of delayed_expression * (bexp * bexp)
and delayed_expression =
| Delayed of bexp
| Immediate of expression
type block = command list
let num_outputs (block:block) : int =
let vali acc c =
begin match c with
| Output _
| OutputAt _ -> acc + 1
| _ -> acc
end
in
List.fold_left vali 0 block
let expression_of_bexp (bexp:bexp) : delayed_expression =
let lit_opt = interpret_bexp bexp in
begin match lit_opt with
| Some l -> Immediate (Int l)
| None ->
begin match bexp with
| Signal s -> Immediate (Signal s)
| _ -> if valid_condition bexp then Immediate (Condition bexp) else
Delayed bexp
end
end
let offset (origin:placement) (off:placement) : placement =
let x, y = origin in
let ox, oy = off in
(ox +. x, oy +. y)
let move_layout (l:circuit_layout) (new_p:placement) : circuit_layout =
let p, s, pl = l in
let px, py = p in
let neg_o = (Float.neg px, Float.neg py) in
let pl2 = List.map (offset (offset new_p neg_o)) pl in
new_p, s, pl2
let rec is_concrete ctree : bool =
let c loc = match loc with | Some _ -> true | None -> false in
begin match ctree with
| Union(c1, c2, loc)
| Concat(c1, c2, loc) -> c loc || is_concrete c1 || is_concrete c2
| Expression(_, loc) -> c loc
| Inline(_, _, loc) -> c loc
| Compiled c -> begin match c with
| Concrete _ -> true
| Abstract _ -> false
end
end | |
51065676ba6c5dc998ac552f096da34d2d6a65f974503be6e7998a98889a2834 | rcherrueau/APE | cond_3.rkt | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Writing Hygienic Macros in Scheme with Syntax - case
Technical Report # 356
;;
page 15
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket
(require "print-test.rkt")
;; `cond_3' recurs internally so that it always has a handle on the
;; original input expression `orig-x'.
(define-syntax (cond_3 orig-x)
(let docond ([x orig-x])
(syntax-case x (else =>)
[(_)
#'(void)]
[(_ [else e1 e2 ...])
#'(begin e1 e2 ...)]
[(_ [test => func])
#'(let ([t test]) (when t (func t)))]
[(_ [test => func] c1 c2 ...)
(with-syntax ([rest (docond #'(cond_3 c1 c2 ...))])
#'(let ([t test]) (if t (func t) rest)))]
[(_ [test])
#'(let ([t test]) (when t t))]
[(_ [test] c1 c2 ...)
(with-syntax ([rest (docond #'(cond_3 c1 c2 ...))])
#'(let ([t test]) (if t t rest)))]
[(_ [test e1 e2 ...])
#'(let ([t test]) (when t (begin e1 e2 ...)))]
[(_ [test e1 e2 ...] c1 c2 ...)
(with-syntax ([rest (docond #'(cond_3 c1 c2 ...))])
#'(if test (begin e1 e2 ...) rest))])))
(print-test (cond_3)
(cond_3
[(member 2 '(1 2 3))])
(cond_3
[(zero? -5)]
[(positive? -5)]
[(positive? 5)])
(cond_3
[else 5 6 7 8])
(cond_3
[(positive? -5) (error "doesn't get there")]
[(zero? -5) (error "doesn't get here, either")]
[(positive? 5) 'here])
(cond_3
[(member 2 '(1 2 3)) => (lambda (l) (map - l))])
(cond_3
[(member 9 '(1 2 3)) => (lambda (l) (map - l))]
[else 5]))
| null | https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/hygienic_macros/cond_3.rkt | racket |
`cond_3' recurs internally so that it always has a handle on the
original input expression `orig-x'. | Writing Hygienic Macros in Scheme with Syntax - case
Technical Report # 356
page 15
#lang racket
(require "print-test.rkt")
(define-syntax (cond_3 orig-x)
(let docond ([x orig-x])
(syntax-case x (else =>)
[(_)
#'(void)]
[(_ [else e1 e2 ...])
#'(begin e1 e2 ...)]
[(_ [test => func])
#'(let ([t test]) (when t (func t)))]
[(_ [test => func] c1 c2 ...)
(with-syntax ([rest (docond #'(cond_3 c1 c2 ...))])
#'(let ([t test]) (if t (func t) rest)))]
[(_ [test])
#'(let ([t test]) (when t t))]
[(_ [test] c1 c2 ...)
(with-syntax ([rest (docond #'(cond_3 c1 c2 ...))])
#'(let ([t test]) (if t t rest)))]
[(_ [test e1 e2 ...])
#'(let ([t test]) (when t (begin e1 e2 ...)))]
[(_ [test e1 e2 ...] c1 c2 ...)
(with-syntax ([rest (docond #'(cond_3 c1 c2 ...))])
#'(if test (begin e1 e2 ...) rest))])))
(print-test (cond_3)
(cond_3
[(member 2 '(1 2 3))])
(cond_3
[(zero? -5)]
[(positive? -5)]
[(positive? 5)])
(cond_3
[else 5 6 7 8])
(cond_3
[(positive? -5) (error "doesn't get there")]
[(zero? -5) (error "doesn't get here, either")]
[(positive? 5) 'here])
(cond_3
[(member 2 '(1 2 3)) => (lambda (l) (map - l))])
(cond_3
[(member 9 '(1 2 3)) => (lambda (l) (map - l))]
[else 5]))
|
16afefb4d8bd28b67309be3270c0e1176cbc2b3c84d63322a8b82ad23173450e | chenyukang/eopl | top.scm | (module top (lib "eopl.ss" "eopl")
;; top level module. Loads all required pieces.
;; Run the test suite with (run-all).
(require "drscheme-init.scm")
(require "data-structures.scm") ; for expval constructors
(require "lang.scm") ; for scan&parse
(require "interp.scm") ; for value-of-program
(require "tests.scm") ; for test-list
(provide run run-all)
;;;;;;;;;;;;;;;; interface to test harness ;;;;;;;;;;;;;;;;
run : String - > ExpVal
(define run
(lambda (string)
(value-of-program (scan&parse string))))
;; run-all : () -> Unspecified
;; runs all the tests in test-list, comparing the results with
;; equal-answer?
(define run-all
(lambda ()
(run-tests! run equal-answer? test-list)))
(define equal-answer?
(lambda (ans correct-ans)
(equal? ans (sloppy->expval correct-ans))))
(define sloppy->expval
(lambda (sloppy-val)
(cond
((number? sloppy-val) (num-val sloppy-val))
((boolean? sloppy-val) (bool-val sloppy-val))
(else
(eopl:error 'sloppy->expval
"Can't convert sloppy value to expval: ~s"
sloppy-val)))))
run - one : Sym - > ExpVal
( run - one sym ) runs the test whose name is sym
(define run-one
(lambda (test-name)
(let ((the-test (assoc test-name test-list)))
(cond
((assoc test-name test-list)
=> (lambda (test)
(run (cadr test))))
(else (eopl:error 'run-one "no such test: ~s" test-name))))))
;; (run-all)
)
| null | https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/base/chapter3/proc-lang/ds-rep/top.scm | scheme | top level module. Loads all required pieces.
Run the test suite with (run-all).
for expval constructors
for scan&parse
for value-of-program
for test-list
interface to test harness ;;;;;;;;;;;;;;;;
run-all : () -> Unspecified
runs all the tests in test-list, comparing the results with
equal-answer?
(run-all)
| (module top (lib "eopl.ss" "eopl")
(require "drscheme-init.scm")
(provide run run-all)
run : String - > ExpVal
(define run
(lambda (string)
(value-of-program (scan&parse string))))
(define run-all
(lambda ()
(run-tests! run equal-answer? test-list)))
(define equal-answer?
(lambda (ans correct-ans)
(equal? ans (sloppy->expval correct-ans))))
(define sloppy->expval
(lambda (sloppy-val)
(cond
((number? sloppy-val) (num-val sloppy-val))
((boolean? sloppy-val) (bool-val sloppy-val))
(else
(eopl:error 'sloppy->expval
"Can't convert sloppy value to expval: ~s"
sloppy-val)))))
run - one : Sym - > ExpVal
( run - one sym ) runs the test whose name is sym
(define run-one
(lambda (test-name)
(let ((the-test (assoc test-name test-list)))
(cond
((assoc test-name test-list)
=> (lambda (test)
(run (cadr test))))
(else (eopl:error 'run-one "no such test: ~s" test-name))))))
)
|
395746eef7be78e885dc7d2ee0bd17feb91dfb4fd151a6576703e45840c94c6e | aiya000/haskell-examples | StateT_IO.hs | import Control.Monad.State
wrapped IO { { {
ios1 :: StateT s IO Int
ios1 = StateT $ \s -> return (10, s)
runIOS1 :: IO ()
runIOS1 = do
let io = runStateT ios1 ()
io >>= print
-- }}}
-- runIO in StateT 1 {{{
ios2 :: StateT s IO String
ios2 = StateT $ \s -> do
a <- getLine
putStrLn $ "input: " ++ a
return (a, s)
runIOS2 :: IO ()
runIOS2 = do
let io = runStateT ios2 ()
io >>= \x -> putStrLn ("state: " ++ show x)
-- }}}
runIO in StateT 2 { { {
ios3 :: StateT s IO ()
ios3 = lift $ print "liftIO"
runIOS3 :: IO ()
runIOS3 = runStateT ios3 10 >>= print
-- }}}
runIO in StateT 3 { { {
ios4 :: StateT String IO ()
ios4 = do
a <- get
lift $ print a
runIOS4 :: IO ()
runIOS4 = runStateT ios4 "message" >>= print
-- }}}
main :: IO ()
main = do
runIOS1
runIOS2
runIOS3
runIOS4
| null | https://raw.githubusercontent.com/aiya000/haskell-examples/a337ba0e86be8bb1333e7eea852ba5fa1d177d8a/Control/Monad/State/StateT_IO.hs | haskell | }}}
runIO in StateT 1 {{{
}}}
}}}
}}} | import Control.Monad.State
wrapped IO { { {
ios1 :: StateT s IO Int
ios1 = StateT $ \s -> return (10, s)
runIOS1 :: IO ()
runIOS1 = do
let io = runStateT ios1 ()
io >>= print
ios2 :: StateT s IO String
ios2 = StateT $ \s -> do
a <- getLine
putStrLn $ "input: " ++ a
return (a, s)
runIOS2 :: IO ()
runIOS2 = do
let io = runStateT ios2 ()
io >>= \x -> putStrLn ("state: " ++ show x)
runIO in StateT 2 { { {
ios3 :: StateT s IO ()
ios3 = lift $ print "liftIO"
runIOS3 :: IO ()
runIOS3 = runStateT ios3 10 >>= print
runIO in StateT 3 { { {
ios4 :: StateT String IO ()
ios4 = do
a <- get
lift $ print a
runIOS4 :: IO ()
runIOS4 = runStateT ios4 "message" >>= print
main :: IO ()
main = do
runIOS1
runIOS2
runIOS3
runIOS4
|
276df1f3bbe59b16d6b93dd1e410c47c6e9da905243be1417f96b3abc0bac701 | psholtz/MIT-SICP | exercise-10.scm | ;;
Working definitions ( Data Structures )
;;
(define (make-units C L H)
(list C L H))
(define get-units-C car)
(define get-units-L cadr)
(define get-units-H caddr)
(define (make-class number units)
(list number units))
(define get-class-number car)
(define get-class-units cadr)
(define (get-class-total-units class)
(let ((units (get-class-units class)))
(+
(get-units-C units)
(get-units-L units)
(get-units-H units))))
(define (same-class? c1 c2)
(equal? (get-class-number c1) (get-class-number c2)))
;;
;; Working definitions (HOPs)
;;
(define (make-student number sched-checker)
(list number (list) sched-checker))
(define get-student-number car)
(define get-student-schedule cadr)
(define get-student-checker caddr)
(define (update-student-schedule student schedule)
(if ((get-student-checker student) schedule)
(list (get-student-number student)
schedule
(get-student-checker student))
(error "Invalid schedule!")))
;;
;; Previous solutions
;;
(define (empty-schedule) '())
(define (add-class class schedule)
(append schedule (list class)))
(define (total-scheduled-units schedule)
(define (total-scheduled-units-iter seq total)
(if (null? seq)
total
(let ((class (car seq)))
(total-scheduled-units-iter (cdr seq) (+ total (get-class-total-units class))))))
(total-scheduled-units-iter schedule 0))
(define (drop-class schedule classnum)
(let ((temp-class (make-class classnum '())))
(define (predicate class)
(not (same-class? class temp-class)))
(filter predicate schedule)))
(define (credit-limit schedule max-credits)
(define (credit-limit-iter elems)
(if (null? elems)
'()
(let ((class (car elems))
(credits (total-scheduled-units elems)))
(if (>= credits max-credits)
(credit-limit-iter (drop-class elems (get-class-number class)))
elems))))
(credit-limit-iter schedule))
(define (make-schedule-checker-1)
(lambda (schedule)
(> (length schedule) 0)))
(define (make-schedule-checker-2 max-units)
(lambda (schedule)
(<= (total-scheduled-units schedule) max-units)))
;;
;; Basic Classes
;;
(define calc1 (make-class 'CALC-101 (make-units 4 4 4)))
(define calc2 (make-class 'CALC-102 (make-units 4 4 4)))
(define algebra (make-class 'ALGB-152 (make-units 3 3 3)))
(define diff-eqs (make-class 'DIFF-201 (make-units 3 3 3)))
(define us-history (make-class 'HIST-122 (make-units 4 4 4)))
(define world-history (make-class 'HIST-324 (make-units 4 4 4)))
(define basket-weaving (make-class 'BASKETS (make-units 1 1 1)))
;;
Exercise 10
;;
;; Rewrite "credit-limit" to run in O(n) time.
;;
(define (credit-limit schedule max-credits)
;;
;; Recursive loop to walk down "schedule" in O(n) time.
;;
(define (credit-limit-iter sched working total)
;;
;; If we are the end of the list, then halt.
;;
(if (null? sched)
working
(let ((class (car sched)))
(let ((credits (get-class-total-units class)))
;;
;; If we have exceeded the maximum number of credits, then halt.
;;
(if (> (+ credits total) max-credits)
working
;;
;; Otherwise, keep recursing through the list structure.
;;
(credit-limit-iter (cdr sched) (append working (list class)) (+ credits total)))))))
;;
Invoke the method with schedule and 0 credits
;;
(credit-limit-iter schedule '() 0))
;;
;; Run some unit tests:
;;
(define s2 (empty-schedule))
(define s2 (add-class calc1 s2))
(define s2 (add-class algebra s2))
(define s2 (add-class diff-eqs s2))
(total-scheduled-units s2)
= = > 30
(credit-limit s2 11)
;; ==> ()
(credit-limit s2 12)
= = > ( ( ( 4 4 4 ) ) )
(credit-limit s2 20)
= = > ( ( ( 4 4 4 ) ) )
(credit-limit s2 21)
= = > ( ( ( 4 4 4 ) ) ( algb-152 ( 3 3 3 ) ) )
(credit-liimt s2 29)
= = > ( ( ( 4 4 4 ) ) ( algb-152 ( 3 3 3 ) ) )
(credit-limit s2 30)
= = > ( ( ( 4 4 4 ) ) ( algb-152 ( 3 3 3 ) ) ( diff-201 ( 3 3 3 ) ) ) | null | https://raw.githubusercontent.com/psholtz/MIT-SICP/01e9b722ac5008e26f386624849117ca8fa80906/Recitations-F2007/Recitation-06/mit-scheme/exercise-10.scm | scheme |
Working definitions (HOPs)
Previous solutions
Basic Classes
Rewrite "credit-limit" to run in O(n) time.
Recursive loop to walk down "schedule" in O(n) time.
If we are the end of the list, then halt.
If we have exceeded the maximum number of credits, then halt.
Otherwise, keep recursing through the list structure.
Run some unit tests:
==> () | Working definitions ( Data Structures )
(define (make-units C L H)
(list C L H))
(define get-units-C car)
(define get-units-L cadr)
(define get-units-H caddr)
(define (make-class number units)
(list number units))
(define get-class-number car)
(define get-class-units cadr)
(define (get-class-total-units class)
(let ((units (get-class-units class)))
(+
(get-units-C units)
(get-units-L units)
(get-units-H units))))
(define (same-class? c1 c2)
(equal? (get-class-number c1) (get-class-number c2)))
(define (make-student number sched-checker)
(list number (list) sched-checker))
(define get-student-number car)
(define get-student-schedule cadr)
(define get-student-checker caddr)
(define (update-student-schedule student schedule)
(if ((get-student-checker student) schedule)
(list (get-student-number student)
schedule
(get-student-checker student))
(error "Invalid schedule!")))
(define (empty-schedule) '())
(define (add-class class schedule)
(append schedule (list class)))
(define (total-scheduled-units schedule)
(define (total-scheduled-units-iter seq total)
(if (null? seq)
total
(let ((class (car seq)))
(total-scheduled-units-iter (cdr seq) (+ total (get-class-total-units class))))))
(total-scheduled-units-iter schedule 0))
(define (drop-class schedule classnum)
(let ((temp-class (make-class classnum '())))
(define (predicate class)
(not (same-class? class temp-class)))
(filter predicate schedule)))
(define (credit-limit schedule max-credits)
(define (credit-limit-iter elems)
(if (null? elems)
'()
(let ((class (car elems))
(credits (total-scheduled-units elems)))
(if (>= credits max-credits)
(credit-limit-iter (drop-class elems (get-class-number class)))
elems))))
(credit-limit-iter schedule))
(define (make-schedule-checker-1)
(lambda (schedule)
(> (length schedule) 0)))
(define (make-schedule-checker-2 max-units)
(lambda (schedule)
(<= (total-scheduled-units schedule) max-units)))
(define calc1 (make-class 'CALC-101 (make-units 4 4 4)))
(define calc2 (make-class 'CALC-102 (make-units 4 4 4)))
(define algebra (make-class 'ALGB-152 (make-units 3 3 3)))
(define diff-eqs (make-class 'DIFF-201 (make-units 3 3 3)))
(define us-history (make-class 'HIST-122 (make-units 4 4 4)))
(define world-history (make-class 'HIST-324 (make-units 4 4 4)))
(define basket-weaving (make-class 'BASKETS (make-units 1 1 1)))
Exercise 10
(define (credit-limit schedule max-credits)
(define (credit-limit-iter sched working total)
(if (null? sched)
working
(let ((class (car sched)))
(let ((credits (get-class-total-units class)))
(if (> (+ credits total) max-credits)
working
(credit-limit-iter (cdr sched) (append working (list class)) (+ credits total)))))))
Invoke the method with schedule and 0 credits
(credit-limit-iter schedule '() 0))
(define s2 (empty-schedule))
(define s2 (add-class calc1 s2))
(define s2 (add-class algebra s2))
(define s2 (add-class diff-eqs s2))
(total-scheduled-units s2)
= = > 30
(credit-limit s2 11)
(credit-limit s2 12)
= = > ( ( ( 4 4 4 ) ) )
(credit-limit s2 20)
= = > ( ( ( 4 4 4 ) ) )
(credit-limit s2 21)
= = > ( ( ( 4 4 4 ) ) ( algb-152 ( 3 3 3 ) ) )
(credit-liimt s2 29)
= = > ( ( ( 4 4 4 ) ) ( algb-152 ( 3 3 3 ) ) )
(credit-limit s2 30)
= = > ( ( ( 4 4 4 ) ) ( algb-152 ( 3 3 3 ) ) ( diff-201 ( 3 3 3 ) ) ) |
1173b1e852db8512c0c3a4c42833ea2e6dec0697ab4e578c89c3130fdc0100c3 | mirage/irmin-server | conf.ml | include Irmin.Backend.Conf
let spec = Irmin.Backend.Conf.Spec.v "irmin-client"
let uri = Irmin.Type.(map string) Uri.of_string Uri.to_string
module Key = struct
let uri =
Irmin.Backend.Conf.key ~spec "uri" uri
(Uri.of_string "tcp:9181")
let tls = Irmin.Backend.Conf.key ~spec "tls" Irmin.Type.bool false
let hostname =
Irmin.Backend.Conf.key ~spec "hostname" Irmin.Type.string "127.0.0.1"
end
let v ?(tls = false) ?hostname uri =
let default_host = Uri.host_with_default ~default:"127.0.0.1" uri in
let config =
Irmin.Backend.Conf.add (Irmin.Backend.Conf.empty spec) Key.uri uri
in
let config =
Irmin.Backend.Conf.add config Key.hostname
(Option.value ~default:default_host hostname)
in
Irmin.Backend.Conf.add config Key.tls tls
| null | https://raw.githubusercontent.com/mirage/irmin-server/ffda6269663bfe8e0dd0ce1c7053d6e57f1f2deb/src/irmin-server-internal/conf.ml | ocaml | include Irmin.Backend.Conf
let spec = Irmin.Backend.Conf.Spec.v "irmin-client"
let uri = Irmin.Type.(map string) Uri.of_string Uri.to_string
module Key = struct
let uri =
Irmin.Backend.Conf.key ~spec "uri" uri
(Uri.of_string "tcp:9181")
let tls = Irmin.Backend.Conf.key ~spec "tls" Irmin.Type.bool false
let hostname =
Irmin.Backend.Conf.key ~spec "hostname" Irmin.Type.string "127.0.0.1"
end
let v ?(tls = false) ?hostname uri =
let default_host = Uri.host_with_default ~default:"127.0.0.1" uri in
let config =
Irmin.Backend.Conf.add (Irmin.Backend.Conf.empty spec) Key.uri uri
in
let config =
Irmin.Backend.Conf.add config Key.hostname
(Option.value ~default:default_host hostname)
in
Irmin.Backend.Conf.add config Key.tls tls
| |
a16faea8f5992d24ed64095c8362142cfdb6b21f188e9766213e9613db453218 | paurkedal/batyr | config.mli | Copyright ( C ) 2022 < >
*
* 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 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 </>.
*)
type t = {
storage_uri: Uri.t;
resource: string;
port: int;
password: string;
log_level: Batyr_core.Logging.Verbosity.t;
}
val load : string -> (t, [> `Msg of string]) result Lwt.t
val verbosity : t -> Batyr_core.Logging.Verbosity.t
| null | https://raw.githubusercontent.com/paurkedal/batyr/13aa15970a60286afbd887685a816fcd5fc4976e/batyr-on-xmpp/lib/config.mli | ocaml | Copyright ( C ) 2022 < >
*
* 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 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 </>.
*)
type t = {
storage_uri: Uri.t;
resource: string;
port: int;
password: string;
log_level: Batyr_core.Logging.Verbosity.t;
}
val load : string -> (t, [> `Msg of string]) result Lwt.t
val verbosity : t -> Batyr_core.Logging.Verbosity.t
| |
31a49303a3b1baad2f80d42f12c3e9d3ba9dd5b92c6df90abb14655363c5aac5 | openbadgefactory/salava | users_test.clj | (ns salava.gallery.users-test
(:require [midje.sweet :refer :all]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]))
(def test-user 1)
(def search-data
{:name ""
:country "all"
:common_badges false})
(facts "about viewing user profiles in gallery"
(fact "user must be logged in to view profiles"
(:status (test-api-request :post "/gallery/profiles" search-data)) => 401)
(apply login! (test-user-credentials test-user))
(fact "user's name must be valid"
(:status (test-api-request :post "/gallery/profiles" (dissoc search-data :name))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :name nil))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :name (apply str (repeat 256 "a"))))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :name "Test"))) => 200)
(fact "country must be valid"
(:status (test-api-request :post "/gallery/profiles" (dissoc search-data :country))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country nil))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country ""))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country "XX"))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country "all"))) => 200
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country "FI"))) => 200)
(fact "show common badges option must be valid"
(:status (test-api-request :post "/gallery/profiles" (dissoc search-data :common_badges))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :common_badges nil))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :common_badges true))) => 200
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :common_badges false))) => 200)
(let [{:keys [status body]} (test-api-request :post "/gallery/profiles" search-data)
users (:users body)]
(fact "user can search profiles successfully"
status => 200)
(fact "there are five users with public profile"
(count users) => 3)
(fact "user's own profile is public"
(some #(= test-user (:id %)) users) => true))
(logout!)) | null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/test_old/clj/salava/gallery/users_test.clj | clojure | (ns salava.gallery.users-test
(:require [midje.sweet :refer :all]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]))
(def test-user 1)
(def search-data
{:name ""
:country "all"
:common_badges false})
(facts "about viewing user profiles in gallery"
(fact "user must be logged in to view profiles"
(:status (test-api-request :post "/gallery/profiles" search-data)) => 401)
(apply login! (test-user-credentials test-user))
(fact "user's name must be valid"
(:status (test-api-request :post "/gallery/profiles" (dissoc search-data :name))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :name nil))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :name (apply str (repeat 256 "a"))))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :name "Test"))) => 200)
(fact "country must be valid"
(:status (test-api-request :post "/gallery/profiles" (dissoc search-data :country))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country nil))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country ""))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country "XX"))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country "all"))) => 200
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :country "FI"))) => 200)
(fact "show common badges option must be valid"
(:status (test-api-request :post "/gallery/profiles" (dissoc search-data :common_badges))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :common_badges nil))) => 400
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :common_badges true))) => 200
(:status (test-api-request :post "/gallery/profiles" (assoc search-data :common_badges false))) => 200)
(let [{:keys [status body]} (test-api-request :post "/gallery/profiles" search-data)
users (:users body)]
(fact "user can search profiles successfully"
status => 200)
(fact "there are five users with public profile"
(count users) => 3)
(fact "user's own profile is public"
(some #(= test-user (:id %)) users) => true))
(logout!)) | |
a1ab266dcc4904ae675f9dc2bc32e48f4b0a4d0d175f92837fb2ec2914e27af2 | Gbury/archsat | position.ml | This file is free software , part of Archsat . See file " LICENSE " for more details .
(*
This module represents positions in
types, terms and formulas.
*)
(* Position type *)
(* ************************************************************************ *)
type t =
| Here
| Arg of int * t
(* Build positions *)
let root = Here
let arg i t =
if i >= 0 then Arg (i, t)
else invalid_arg "Position.arg"
let rec concat t t' =
match t with
| Here -> t'
| Arg(i, t'') -> Arg(i, concat t'' t')
let rec path = function
| [] -> root
| k :: r -> arg k (path r)
let follow t i = concat t (path [i])
Comparison , equality , printing .
let equal = (=)
let compare = Pervasives.compare
let rec print fmt = function
| Here -> Format.fprintf fmt "."
| Arg (i, t) -> Format.fprintf fmt "%d-%a" i print t
(* Position results. *)
(* ************************************************************************ *)
(* What might wait at the end of a path. *)
type ('a, 'b) res =
| Var
| Top of ('a, 'b) Expr.function_descr Expr.id
| Possible
| Impossible
let print_res p fmt = function
| Var -> Format.fprintf fmt "var"
| Top f -> Format.fprintf fmt "top:%a" p f
| Possible -> Format.fprintf fmt "possible"
| Impossible -> Format.fprintf fmt "impossible"
(* Positions for Proof terms *)
(* ************************************************************************ *)
module Proof = struct
let rec apply p t =
match p, t with
| Here, _ -> Some t
| Arg (0, p'), { Term.term = Term.App (t', _) }
| Arg (1, p'), { Term.term = Term.App (_, t') }
| Arg (0, p'), { Term.term = Term.Let (_, t', _) }
| Arg (1, p'), { Term.term = Term.Let (_, _, t') }
| Arg (0, p'), { Term.term = Term.Binder (_, _, t') }
-> apply p' t'
| Arg _, _ -> None
let rec substitute p ~by:u t =
match p, t with
| Here, _ -> Some u
| Arg (0, p'), { Term.term = Term.App (f, arg) } ->
CCOpt.map (fun x -> Term.app x arg) (substitute p' ~by:u f)
| Arg (1, p'), { Term.term = Term.App (f, arg) } ->
CCOpt.map (fun x -> Term.app f x) (substitute p' ~by:u arg)
| Arg (0, p'), { Term.term = Term.Let (v, e, body) } ->
CCOpt.map (fun x -> Term.letin v x body) (substitute p' ~by:u e)
| Arg (1, p'), { Term.term = Term.Let (v, e, body) } ->
CCOpt.map (fun x -> Term.letin v e x) (substitute p' ~by:u body)
| Arg (0, p'), { Term.term = Term.Binder (b, v, body) } ->
CCOpt.map (fun x -> Term.bind b v x) (substitute p' ~by:u body)
| Arg _, _ -> None
let rec find_aux cur_pos u t =
if Term.equal t u then Some (cur_pos Here)
else begin match t with
| { Term.term = Term.Type }
| { Term.term = Term.Id _ } -> None
| { Term.term = Term.App (f, arg) } ->
CCOpt.or_lazy
(find_aux (fun p -> cur_pos (Arg (0, p))) u f)
~else_:(fun () -> find_aux (fun p -> cur_pos (Arg (1, p))) u arg)
| { Term.term = Term.Let (_, e, body) } ->
CCOpt.or_lazy
(find_aux (fun p -> cur_pos (Arg (0, p))) u e)
~else_:(fun () -> find_aux (fun p -> cur_pos (Arg (1, p))) u body)
| { Term.term = Term.Binder (_, _, body) } ->
find_aux (fun p -> cur_pos (Arg (0, p))) u body
end
let find = find_aux (fun x -> x)
end
(* Positions for Types *)
(* ************************************************************************ *)
module Ty = struct
let rec apply p t = match p, t with
| Here, { Expr.ty = Expr.TyVar _ }
| Here, { Expr.ty = Expr.TyMeta _ } -> Var, Some t
| Here, { Expr.ty = Expr.TyApp (f, _) } -> Top f, Some t
| Arg _, { Expr.ty = Expr.TyVar _ }
| Arg _, { Expr.ty = Expr.TyMeta _ } -> Possible, None
| Arg (k, p'), { Expr.ty = Expr.TyApp(_, l) } ->
begin match CCList.get_at_idx k l with
| None -> Impossible, None
| Some ty -> apply p' ty
end
let rec substitute p ~by:u t =
match p, t with
| Here, _ -> Some u
| Arg (k, p'), { Expr.ty = Expr.TyApp(f, l) } ->
CCOpt.map (Expr.Ty.apply ~status:t.Expr.ty_status f) @@ CCOpt.sequence_l
(List.mapi (fun i v -> if i = k then substitute p' ~by:u v else Some v) l)
| _ -> None
let rec fold_aux f acc cur_pos t =
let acc' = f acc (cur_pos Here) t in
match t with
| { Expr.ty = Expr.TyApp (_, l) } ->
CCList.foldi (fun acc i t ->
fold_aux f acc (fun p -> cur_pos (Arg(i, p))) t) acc' l
| _ -> acc'
let fold f acc t = fold_aux f acc (fun x -> x) t
let rec find_map_aux f cur_pos t =
match f (cur_pos Here) t with
| Some res -> Some res
| None ->
begin match t with
| { Expr.ty = Expr.TyApp (_, l) } ->
CCList.find_mapi (fun i t -> find_map_aux f (fun p -> cur_pos (Arg(i, p))) t) l
| _ -> None
end
let find_map f t = find_map_aux f (fun x -> x) t
end
(* Positions for Terms *)
(* ************************************************************************ *)
module Term = struct
let rec apply p t = match p, t with
| Here, { Expr.term = Expr.Var _ }
| Here, { Expr.term = Expr.Meta _ } -> Var, Some t
| Here, { Expr.term = Expr.App (f, _, _) } -> Top f, Some t
| Arg _, { Expr.term = Expr.Var _ }
| Arg _, { Expr.term = Expr.Meta _ } -> Possible, None
| Arg (k, p'), { Expr.term = Expr.App(_, _, l) } ->
begin match CCList.get_at_idx k l with
| None -> Impossible, None
| Some term -> apply p' term
end
let rec substitute p ~by:u t =
match p, t with
| Here, _ -> Some u
| Arg (k, p'), { Expr.term = Expr.App(f, tys, l) } ->
CCOpt.map (Expr.Term.apply ~status:t.Expr.t_status f tys) @@ CCOpt.sequence_l
(List.mapi (fun i v -> if i = k then substitute p' ~by:u v else Some v) l)
| _ -> None
let rec fold_aux f acc cur_pos t =
let acc' = f acc (cur_pos Here) t in
match t with
| { Expr.term = Expr.App (_, _, l) } ->
CCList.foldi (fun acc i t ->
fold_aux f acc (fun p -> cur_pos (Arg(i, p))) t) acc' l
| _ -> acc'
let fold f acc t = fold_aux f acc (fun x -> x) t
let rec find_map_aux f cur_pos t =
match f (cur_pos Here) t with
| Some res -> Some res
| None ->
begin match t with
| { Expr.term = Expr.App (_, _, l) } ->
CCList.find_mapi (fun i t -> find_map_aux f (fun p -> cur_pos (Arg(i, p))) t) l
| _ -> None
end
let find_map f t = find_map_aux f (fun x -> x) t
end
| null | https://raw.githubusercontent.com/Gbury/archsat/322fbefa4a58023ddafb3fa1a51f8199c25cde3d/src/base/position.ml | ocaml |
This module represents positions in
types, terms and formulas.
Position type
************************************************************************
Build positions
Position results.
************************************************************************
What might wait at the end of a path.
Positions for Proof terms
************************************************************************
Positions for Types
************************************************************************
Positions for Terms
************************************************************************ | This file is free software , part of Archsat . See file " LICENSE " for more details .
type t =
| Here
| Arg of int * t
let root = Here
let arg i t =
if i >= 0 then Arg (i, t)
else invalid_arg "Position.arg"
let rec concat t t' =
match t with
| Here -> t'
| Arg(i, t'') -> Arg(i, concat t'' t')
let rec path = function
| [] -> root
| k :: r -> arg k (path r)
let follow t i = concat t (path [i])
Comparison , equality , printing .
let equal = (=)
let compare = Pervasives.compare
let rec print fmt = function
| Here -> Format.fprintf fmt "."
| Arg (i, t) -> Format.fprintf fmt "%d-%a" i print t
type ('a, 'b) res =
| Var
| Top of ('a, 'b) Expr.function_descr Expr.id
| Possible
| Impossible
let print_res p fmt = function
| Var -> Format.fprintf fmt "var"
| Top f -> Format.fprintf fmt "top:%a" p f
| Possible -> Format.fprintf fmt "possible"
| Impossible -> Format.fprintf fmt "impossible"
module Proof = struct
let rec apply p t =
match p, t with
| Here, _ -> Some t
| Arg (0, p'), { Term.term = Term.App (t', _) }
| Arg (1, p'), { Term.term = Term.App (_, t') }
| Arg (0, p'), { Term.term = Term.Let (_, t', _) }
| Arg (1, p'), { Term.term = Term.Let (_, _, t') }
| Arg (0, p'), { Term.term = Term.Binder (_, _, t') }
-> apply p' t'
| Arg _, _ -> None
let rec substitute p ~by:u t =
match p, t with
| Here, _ -> Some u
| Arg (0, p'), { Term.term = Term.App (f, arg) } ->
CCOpt.map (fun x -> Term.app x arg) (substitute p' ~by:u f)
| Arg (1, p'), { Term.term = Term.App (f, arg) } ->
CCOpt.map (fun x -> Term.app f x) (substitute p' ~by:u arg)
| Arg (0, p'), { Term.term = Term.Let (v, e, body) } ->
CCOpt.map (fun x -> Term.letin v x body) (substitute p' ~by:u e)
| Arg (1, p'), { Term.term = Term.Let (v, e, body) } ->
CCOpt.map (fun x -> Term.letin v e x) (substitute p' ~by:u body)
| Arg (0, p'), { Term.term = Term.Binder (b, v, body) } ->
CCOpt.map (fun x -> Term.bind b v x) (substitute p' ~by:u body)
| Arg _, _ -> None
let rec find_aux cur_pos u t =
if Term.equal t u then Some (cur_pos Here)
else begin match t with
| { Term.term = Term.Type }
| { Term.term = Term.Id _ } -> None
| { Term.term = Term.App (f, arg) } ->
CCOpt.or_lazy
(find_aux (fun p -> cur_pos (Arg (0, p))) u f)
~else_:(fun () -> find_aux (fun p -> cur_pos (Arg (1, p))) u arg)
| { Term.term = Term.Let (_, e, body) } ->
CCOpt.or_lazy
(find_aux (fun p -> cur_pos (Arg (0, p))) u e)
~else_:(fun () -> find_aux (fun p -> cur_pos (Arg (1, p))) u body)
| { Term.term = Term.Binder (_, _, body) } ->
find_aux (fun p -> cur_pos (Arg (0, p))) u body
end
let find = find_aux (fun x -> x)
end
module Ty = struct
let rec apply p t = match p, t with
| Here, { Expr.ty = Expr.TyVar _ }
| Here, { Expr.ty = Expr.TyMeta _ } -> Var, Some t
| Here, { Expr.ty = Expr.TyApp (f, _) } -> Top f, Some t
| Arg _, { Expr.ty = Expr.TyVar _ }
| Arg _, { Expr.ty = Expr.TyMeta _ } -> Possible, None
| Arg (k, p'), { Expr.ty = Expr.TyApp(_, l) } ->
begin match CCList.get_at_idx k l with
| None -> Impossible, None
| Some ty -> apply p' ty
end
let rec substitute p ~by:u t =
match p, t with
| Here, _ -> Some u
| Arg (k, p'), { Expr.ty = Expr.TyApp(f, l) } ->
CCOpt.map (Expr.Ty.apply ~status:t.Expr.ty_status f) @@ CCOpt.sequence_l
(List.mapi (fun i v -> if i = k then substitute p' ~by:u v else Some v) l)
| _ -> None
let rec fold_aux f acc cur_pos t =
let acc' = f acc (cur_pos Here) t in
match t with
| { Expr.ty = Expr.TyApp (_, l) } ->
CCList.foldi (fun acc i t ->
fold_aux f acc (fun p -> cur_pos (Arg(i, p))) t) acc' l
| _ -> acc'
let fold f acc t = fold_aux f acc (fun x -> x) t
let rec find_map_aux f cur_pos t =
match f (cur_pos Here) t with
| Some res -> Some res
| None ->
begin match t with
| { Expr.ty = Expr.TyApp (_, l) } ->
CCList.find_mapi (fun i t -> find_map_aux f (fun p -> cur_pos (Arg(i, p))) t) l
| _ -> None
end
let find_map f t = find_map_aux f (fun x -> x) t
end
module Term = struct
let rec apply p t = match p, t with
| Here, { Expr.term = Expr.Var _ }
| Here, { Expr.term = Expr.Meta _ } -> Var, Some t
| Here, { Expr.term = Expr.App (f, _, _) } -> Top f, Some t
| Arg _, { Expr.term = Expr.Var _ }
| Arg _, { Expr.term = Expr.Meta _ } -> Possible, None
| Arg (k, p'), { Expr.term = Expr.App(_, _, l) } ->
begin match CCList.get_at_idx k l with
| None -> Impossible, None
| Some term -> apply p' term
end
let rec substitute p ~by:u t =
match p, t with
| Here, _ -> Some u
| Arg (k, p'), { Expr.term = Expr.App(f, tys, l) } ->
CCOpt.map (Expr.Term.apply ~status:t.Expr.t_status f tys) @@ CCOpt.sequence_l
(List.mapi (fun i v -> if i = k then substitute p' ~by:u v else Some v) l)
| _ -> None
let rec fold_aux f acc cur_pos t =
let acc' = f acc (cur_pos Here) t in
match t with
| { Expr.term = Expr.App (_, _, l) } ->
CCList.foldi (fun acc i t ->
fold_aux f acc (fun p -> cur_pos (Arg(i, p))) t) acc' l
| _ -> acc'
let fold f acc t = fold_aux f acc (fun x -> x) t
let rec find_map_aux f cur_pos t =
match f (cur_pos Here) t with
| Some res -> Some res
| None ->
begin match t with
| { Expr.term = Expr.App (_, _, l) } ->
CCList.find_mapi (fun i t -> find_map_aux f (fun p -> cur_pos (Arg(i, p))) t) l
| _ -> None
end
let find_map f t = find_map_aux f (fun x -> x) t
end
|
c60e7bfb191b191659139b9802de83c3ebc147f3c6a74432f132fa1dd0ce0110 | ndmitchell/shake | Binary.hs | # LANGUAGE FlexibleInstances , ScopedTypeVariables , Rank2Types #
module General.Binary(
BinaryOp(..), binaryOpMap,
binarySplit, binarySplit2, binarySplit3, unsafeBinarySplit,
Builder(..), runBuilder, sizeBuilder,
BinaryEx(..),
Storable, putExStorable, getExStorable, putExStorableList, getExStorableList,
putExList, getExList, putExN, getExN
) where
import Development.Shake.Classes
import Control.Monad
import Data.Binary
import Data.List.Extra
import Data.Tuple.Extra
import Foreign.Storable
import Foreign.Ptr
import System.IO.Unsafe as U
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BS
import qualified Data.ByteString.Unsafe as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.UTF8 as UTF8
import Data.Semigroup
import Prelude
---------------------------------------------------------------------
-- STORE TYPE
-- | An explicit and more efficient version of Binary
data BinaryOp v = BinaryOp
{putOp :: v -> Builder
,getOp :: BS.ByteString -> v
}
binaryOpMap :: BinaryEx a => (a -> BinaryOp b) -> BinaryOp (a, b)
binaryOpMap mp = BinaryOp
{putOp = \(a, b) -> putExN (putEx a) <> putOp (mp a) b
,getOp = \bs -> let (bs1,bs2) = getExN bs; a = getEx bs1 in (a, getOp (mp a) bs2)
}
binarySplit :: forall a . Storable a => BS.ByteString -> (a, BS.ByteString)
binarySplit bs | BS.length bs < sizeOf (undefined :: a) = error "Reading from ByteString, insufficient left"
| otherwise = unsafeBinarySplit bs
binarySplit2 :: forall a b . (Storable a, Storable b) => BS.ByteString -> (a, b, BS.ByteString)
binarySplit2 bs | BS.length bs < sizeOf (undefined :: a) + sizeOf (undefined :: b) = error "Reading from ByteString, insufficient left"
| (a,bs) <- unsafeBinarySplit bs, (b,bs) <- unsafeBinarySplit bs = (a,b,bs)
binarySplit3 :: forall a b c . (Storable a, Storable b, Storable c) => BS.ByteString -> (a, b, c, BS.ByteString)
binarySplit3 bs | BS.length bs < sizeOf (undefined :: a) + sizeOf (undefined :: b) + sizeOf (undefined :: c) = error "Reading from ByteString, insufficient left"
| (a,bs) <- unsafeBinarySplit bs, (b,bs) <- unsafeBinarySplit bs, (c,bs) <- unsafeBinarySplit bs = (a,b,c,bs)
unsafeBinarySplit :: Storable a => BS.ByteString -> (a, BS.ByteString)
unsafeBinarySplit bs = (v, BS.unsafeDrop (sizeOf v) bs)
where v = unsafePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> peek (castPtr ptr)
-- forM for zipWith
for2M_ as bs f = zipWithM_ f as bs
---------------------------------------------------------------------
BINARY
-- We can't use the Data.ByteString builder as that doesn't track the size of the chunk.
data Builder = Builder {-# UNPACK #-} !Int (forall a . Ptr a -> Int -> IO ())
sizeBuilder :: Builder -> Int
sizeBuilder (Builder i _) = i
runBuilder :: Builder -> BS.ByteString
runBuilder (Builder i f) = unsafePerformIO $ BS.create i $ \ptr -> f ptr 0
instance Semigroup Builder where
(Builder x1 x2) <> (Builder y1 y2) = Builder (x1+y1) $ \p i -> do x2 p i; y2 p $ i+x1
instance Monoid Builder where
mempty = Builder 0 $ \_ _ -> pure ()
mappend = (<>)
| Methods for Binary serialisation that go directly between strict ByteString values .
When the Database is read each key / value will be loaded as a separate ByteString ,
-- and for certain types (e.g. file rules) this may remain the preferred format for storing keys.
-- Optimised for performance.
class BinaryEx a where
putEx :: a -> Builder
getEx :: BS.ByteString -> a
instance BinaryEx BS.ByteString where
putEx x = Builder n $ \ptr i -> BS.useAsCString x $ \bs -> BS.memcpy (ptr `plusPtr` i) (castPtr bs) (fromIntegral n)
where n = BS.length x
getEx = id
instance BinaryEx LBS.ByteString where
putEx x = Builder (fromIntegral $ LBS.length x) $ \ptr i -> do
let go _ [] = pure ()
go i (x:xs) = do
let n = BS.length x
BS.useAsCString x $ \bs -> BS.memcpy (ptr `plusPtr` i) (castPtr bs) (fromIntegral n)
go (i+n) xs
go i $ LBS.toChunks x
getEx = LBS.fromChunks . pure
instance BinaryEx [BS.ByteString] where
-- Format:
-- n :: Word32 - number of strings
-- ns :: [Word32]{n} - length of each string
-- contents of each string concatenated (sum ns bytes)
putEx xs = Builder (4 + (n * 4) + sum ns) $ \p i -> do
pokeByteOff p i (fromIntegral n :: Word32)
for2M_ [4+i,8+i..] ns $ \i x -> pokeByteOff p i (fromIntegral x :: Word32)
p<- pure $ p `plusPtr` (i + 4 + (n * 4))
for2M_ (scanl (+) 0 ns) xs $ \i x -> BS.useAsCStringLen x $ \(bs, n) ->
BS.memcpy (p `plusPtr` i) (castPtr bs) (fromIntegral n)
where ns = map BS.length xs
n = length ns
getEx bs = unsafePerformIO $ BS.useAsCString bs $ \p -> do
n <- fromIntegral <$> (peekByteOff p 0 :: IO Word32)
ns :: [Word32] <- forM [1..fromIntegral n] $ \i -> peekByteOff p (i * 4)
pure $ snd $ mapAccumL (\bs i -> swap $ BS.splitAt (fromIntegral i) bs) (BS.drop (4 + (n * 4)) bs) ns
instance BinaryEx () where
putEx () = mempty
getEx _ = ()
instance BinaryEx String where
putEx = putEx . UTF8.fromString
getEx = UTF8.toString
instance BinaryEx (Maybe String) where
putEx Nothing = mempty
putEx (Just xs) = putEx $ UTF8.fromString $ '\0' : xs
getEx = fmap snd . uncons . UTF8.toString
instance BinaryEx [String] where
putEx = putEx . map UTF8.fromString
getEx = map UTF8.toString . getEx
instance BinaryEx (String, [String]) where
putEx (a,bs) = putEx $ a:bs
getEx x = let a:bs = getEx x in (a,bs)
instance BinaryEx Bool where
putEx False = Builder 1 $ \ptr i -> pokeByteOff ptr i (0 :: Word8)
putEx True = mempty
getEx = BS.null
instance BinaryEx Word8 where
putEx = putExStorable
getEx = getExStorable
instance BinaryEx Word16 where
putEx = putExStorable
getEx = getExStorable
instance BinaryEx Word32 where
putEx = putExStorable
getEx = getExStorable
instance BinaryEx Int where
putEx = putExStorable
getEx = getExStorable
instance BinaryEx Float where
putEx = putExStorable
getEx = getExStorable
putExStorable :: forall a . Storable a => a -> Builder
putExStorable x = Builder (sizeOf x) $ \p i -> pokeByteOff p i x
getExStorable :: forall a . Storable a => BS.ByteString -> a
getExStorable = \bs -> unsafePerformIO $ BS.useAsCStringLen bs $ \(p, size) ->
if size /= n then error "size mismatch" else peek (castPtr p)
where n = sizeOf (undefined :: a)
putExStorableList :: forall a . Storable a => [a] -> Builder
putExStorableList xs = Builder (n * length xs) $ \ptr i ->
for2M_ [i,i+n..] xs $ \i x -> pokeByteOff ptr i x
where n = sizeOf (undefined :: a)
getExStorableList :: forall a . Storable a => BS.ByteString -> [a]
getExStorableList = \bs -> unsafePerformIO $ BS.useAsCStringLen bs $ \(p, size) ->
let (d,m) = size `divMod` n in
if m /= 0 then error "size mismatch" else forM [0..d-1] $ \i -> peekElemOff (castPtr p) i
where n = sizeOf (undefined :: a)
-- repeating:
, length of BS
-- BS
putExList :: [Builder] -> Builder
putExList xs = Builder (sum $ map (\b -> sizeBuilder b + 4) xs) $ \p i -> do
let go _ [] = pure ()
go i (Builder n b:xs) = do
pokeByteOff p i (fromIntegral n :: Word32)
b p (i+4)
go (i+4+n) xs
go i xs
getExList :: BS.ByteString -> [BS.ByteString]
getExList bs
| len == 0 = []
| len >= 4
, (n :: Word32, bs) <- unsafeBinarySplit bs
, n <- fromIntegral n
, (len - 4) >= n
= BS.unsafeTake n bs : getExList (BS.unsafeDrop n bs)
| otherwise = error "getList, corrupted binary"
where len = BS.length bs
putExN :: Builder -> Builder
putExN (Builder n old) = Builder (n+4) $ \p i -> do
pokeByteOff p i (fromIntegral n :: Word32)
old p $ i+4
getExN :: BS.ByteString -> (BS.ByteString, BS.ByteString)
getExN bs
| len >= 4
, (n :: Word32, bs) <- unsafeBinarySplit bs
, n <- fromIntegral n
, (len - 4) >= n
= (BS.unsafeTake n bs, BS.unsafeDrop n bs)
| otherwise = error "getList, corrupted binary"
where len = BS.length bs
| null | https://raw.githubusercontent.com/ndmitchell/shake/99c5a7a4dc1d5a069b13ed5c1bc8e4bc7f13f4a6/src/General/Binary.hs | haskell | -------------------------------------------------------------------
STORE TYPE
| An explicit and more efficient version of Binary
forM for zipWith
-------------------------------------------------------------------
We can't use the Data.ByteString builder as that doesn't track the size of the chunk.
# UNPACK #
and for certain types (e.g. file rules) this may remain the preferred format for storing keys.
Optimised for performance.
Format:
n :: Word32 - number of strings
ns :: [Word32]{n} - length of each string
contents of each string concatenated (sum ns bytes)
repeating:
BS | # LANGUAGE FlexibleInstances , ScopedTypeVariables , Rank2Types #
module General.Binary(
BinaryOp(..), binaryOpMap,
binarySplit, binarySplit2, binarySplit3, unsafeBinarySplit,
Builder(..), runBuilder, sizeBuilder,
BinaryEx(..),
Storable, putExStorable, getExStorable, putExStorableList, getExStorableList,
putExList, getExList, putExN, getExN
) where
import Development.Shake.Classes
import Control.Monad
import Data.Binary
import Data.List.Extra
import Data.Tuple.Extra
import Foreign.Storable
import Foreign.Ptr
import System.IO.Unsafe as U
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BS
import qualified Data.ByteString.Unsafe as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.UTF8 as UTF8
import Data.Semigroup
import Prelude
data BinaryOp v = BinaryOp
{putOp :: v -> Builder
,getOp :: BS.ByteString -> v
}
binaryOpMap :: BinaryEx a => (a -> BinaryOp b) -> BinaryOp (a, b)
binaryOpMap mp = BinaryOp
{putOp = \(a, b) -> putExN (putEx a) <> putOp (mp a) b
,getOp = \bs -> let (bs1,bs2) = getExN bs; a = getEx bs1 in (a, getOp (mp a) bs2)
}
binarySplit :: forall a . Storable a => BS.ByteString -> (a, BS.ByteString)
binarySplit bs | BS.length bs < sizeOf (undefined :: a) = error "Reading from ByteString, insufficient left"
| otherwise = unsafeBinarySplit bs
binarySplit2 :: forall a b . (Storable a, Storable b) => BS.ByteString -> (a, b, BS.ByteString)
binarySplit2 bs | BS.length bs < sizeOf (undefined :: a) + sizeOf (undefined :: b) = error "Reading from ByteString, insufficient left"
| (a,bs) <- unsafeBinarySplit bs, (b,bs) <- unsafeBinarySplit bs = (a,b,bs)
binarySplit3 :: forall a b c . (Storable a, Storable b, Storable c) => BS.ByteString -> (a, b, c, BS.ByteString)
binarySplit3 bs | BS.length bs < sizeOf (undefined :: a) + sizeOf (undefined :: b) + sizeOf (undefined :: c) = error "Reading from ByteString, insufficient left"
| (a,bs) <- unsafeBinarySplit bs, (b,bs) <- unsafeBinarySplit bs, (c,bs) <- unsafeBinarySplit bs = (a,b,c,bs)
unsafeBinarySplit :: Storable a => BS.ByteString -> (a, BS.ByteString)
unsafeBinarySplit bs = (v, BS.unsafeDrop (sizeOf v) bs)
where v = unsafePerformIO $ BS.unsafeUseAsCString bs $ \ptr -> peek (castPtr ptr)
for2M_ as bs f = zipWithM_ f as bs
BINARY
sizeBuilder :: Builder -> Int
sizeBuilder (Builder i _) = i
runBuilder :: Builder -> BS.ByteString
runBuilder (Builder i f) = unsafePerformIO $ BS.create i $ \ptr -> f ptr 0
instance Semigroup Builder where
(Builder x1 x2) <> (Builder y1 y2) = Builder (x1+y1) $ \p i -> do x2 p i; y2 p $ i+x1
instance Monoid Builder where
mempty = Builder 0 $ \_ _ -> pure ()
mappend = (<>)
| Methods for Binary serialisation that go directly between strict ByteString values .
When the Database is read each key / value will be loaded as a separate ByteString ,
class BinaryEx a where
putEx :: a -> Builder
getEx :: BS.ByteString -> a
instance BinaryEx BS.ByteString where
putEx x = Builder n $ \ptr i -> BS.useAsCString x $ \bs -> BS.memcpy (ptr `plusPtr` i) (castPtr bs) (fromIntegral n)
where n = BS.length x
getEx = id
instance BinaryEx LBS.ByteString where
putEx x = Builder (fromIntegral $ LBS.length x) $ \ptr i -> do
let go _ [] = pure ()
go i (x:xs) = do
let n = BS.length x
BS.useAsCString x $ \bs -> BS.memcpy (ptr `plusPtr` i) (castPtr bs) (fromIntegral n)
go (i+n) xs
go i $ LBS.toChunks x
getEx = LBS.fromChunks . pure
instance BinaryEx [BS.ByteString] where
putEx xs = Builder (4 + (n * 4) + sum ns) $ \p i -> do
pokeByteOff p i (fromIntegral n :: Word32)
for2M_ [4+i,8+i..] ns $ \i x -> pokeByteOff p i (fromIntegral x :: Word32)
p<- pure $ p `plusPtr` (i + 4 + (n * 4))
for2M_ (scanl (+) 0 ns) xs $ \i x -> BS.useAsCStringLen x $ \(bs, n) ->
BS.memcpy (p `plusPtr` i) (castPtr bs) (fromIntegral n)
where ns = map BS.length xs
n = length ns
getEx bs = unsafePerformIO $ BS.useAsCString bs $ \p -> do
n <- fromIntegral <$> (peekByteOff p 0 :: IO Word32)
ns :: [Word32] <- forM [1..fromIntegral n] $ \i -> peekByteOff p (i * 4)
pure $ snd $ mapAccumL (\bs i -> swap $ BS.splitAt (fromIntegral i) bs) (BS.drop (4 + (n * 4)) bs) ns
instance BinaryEx () where
putEx () = mempty
getEx _ = ()
instance BinaryEx String where
putEx = putEx . UTF8.fromString
getEx = UTF8.toString
instance BinaryEx (Maybe String) where
putEx Nothing = mempty
putEx (Just xs) = putEx $ UTF8.fromString $ '\0' : xs
getEx = fmap snd . uncons . UTF8.toString
instance BinaryEx [String] where
putEx = putEx . map UTF8.fromString
getEx = map UTF8.toString . getEx
instance BinaryEx (String, [String]) where
putEx (a,bs) = putEx $ a:bs
getEx x = let a:bs = getEx x in (a,bs)
instance BinaryEx Bool where
putEx False = Builder 1 $ \ptr i -> pokeByteOff ptr i (0 :: Word8)
putEx True = mempty
getEx = BS.null
instance BinaryEx Word8 where
putEx = putExStorable
getEx = getExStorable
instance BinaryEx Word16 where
putEx = putExStorable
getEx = getExStorable
instance BinaryEx Word32 where
putEx = putExStorable
getEx = getExStorable
instance BinaryEx Int where
putEx = putExStorable
getEx = getExStorable
instance BinaryEx Float where
putEx = putExStorable
getEx = getExStorable
putExStorable :: forall a . Storable a => a -> Builder
putExStorable x = Builder (sizeOf x) $ \p i -> pokeByteOff p i x
getExStorable :: forall a . Storable a => BS.ByteString -> a
getExStorable = \bs -> unsafePerformIO $ BS.useAsCStringLen bs $ \(p, size) ->
if size /= n then error "size mismatch" else peek (castPtr p)
where n = sizeOf (undefined :: a)
putExStorableList :: forall a . Storable a => [a] -> Builder
putExStorableList xs = Builder (n * length xs) $ \ptr i ->
for2M_ [i,i+n..] xs $ \i x -> pokeByteOff ptr i x
where n = sizeOf (undefined :: a)
getExStorableList :: forall a . Storable a => BS.ByteString -> [a]
getExStorableList = \bs -> unsafePerformIO $ BS.useAsCStringLen bs $ \(p, size) ->
let (d,m) = size `divMod` n in
if m /= 0 then error "size mismatch" else forM [0..d-1] $ \i -> peekElemOff (castPtr p) i
where n = sizeOf (undefined :: a)
, length of BS
putExList :: [Builder] -> Builder
putExList xs = Builder (sum $ map (\b -> sizeBuilder b + 4) xs) $ \p i -> do
let go _ [] = pure ()
go i (Builder n b:xs) = do
pokeByteOff p i (fromIntegral n :: Word32)
b p (i+4)
go (i+4+n) xs
go i xs
getExList :: BS.ByteString -> [BS.ByteString]
getExList bs
| len == 0 = []
| len >= 4
, (n :: Word32, bs) <- unsafeBinarySplit bs
, n <- fromIntegral n
, (len - 4) >= n
= BS.unsafeTake n bs : getExList (BS.unsafeDrop n bs)
| otherwise = error "getList, corrupted binary"
where len = BS.length bs
putExN :: Builder -> Builder
putExN (Builder n old) = Builder (n+4) $ \p i -> do
pokeByteOff p i (fromIntegral n :: Word32)
old p $ i+4
getExN :: BS.ByteString -> (BS.ByteString, BS.ByteString)
getExN bs
| len >= 4
, (n :: Word32, bs) <- unsafeBinarySplit bs
, n <- fromIntegral n
, (len - 4) >= n
= (BS.unsafeTake n bs, BS.unsafeDrop n bs)
| otherwise = error "getList, corrupted binary"
where len = BS.length bs
|
bd26d9d69c536b601e44cbb0d74167d62e679fc43a90785741d9c5178195d01d | ghcjs/jsaddle-dom | WebGPUBuffer.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.WebGPUBuffer
(getLength, getContents, WebGPUBuffer(..), gTypeWebGPUBuffer) where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/WebGPUBuffer.length Mozilla WebGPUBuffer.length documentation >
getLength :: (MonadDOM m) => WebGPUBuffer -> m Word
getLength self
= liftDOM (round <$> ((self ^. js "length") >>= valToNumber))
| < -US/docs/Web/API/WebGPUBuffer.contents Mozilla WebGPUBuffer.contents documentation >
getContents :: (MonadDOM m) => WebGPUBuffer -> m ArrayBufferView
getContents self
= liftDOM ((self ^. js "contents") >>= fromJSValUnchecked)
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/WebGPUBuffer.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.WebGPUBuffer
(getLength, getContents, WebGPUBuffer(..), gTypeWebGPUBuffer) where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/WebGPUBuffer.length Mozilla WebGPUBuffer.length documentation >
getLength :: (MonadDOM m) => WebGPUBuffer -> m Word
getLength self
= liftDOM (round <$> ((self ^. js "length") >>= valToNumber))
| < -US/docs/Web/API/WebGPUBuffer.contents Mozilla WebGPUBuffer.contents documentation >
getContents :: (MonadDOM m) => WebGPUBuffer -> m ArrayBufferView
getContents self
= liftDOM ((self ^. js "contents") >>= fromJSValUnchecked)
|
de38945ec990946e64bff3bbc79f60388978e5c142ced426a5e7b3b49da28611 | wrengr/bytestring-trie | ByteStringInternal.hs | {-# OPTIONS_GHC -Wall -fwarn-tabs #-}
----------------------------------------------------------------
-- ~ 2021.12.14
-- |
-- Module : Test.ByteStringInternal
Copyright : 2008 - -2021 wren romano
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
Testing helper functions on ' ByteString 's .
----------------------------------------------------------------
module Test.ByteStringInternal where
import Test.Utils (packC2W)
import Data.Trie.Internal.ByteString
import Data.List (unfoldr)
----------------------------------------------------------------
-- | For debugging. [] is the infinite bit, head is the little end
showBits :: (Integral a) => a -> String
showBits = unfoldr getBit
where
getBit 0 = Nothing
getBit i | odd i = Just ('I', (i-1)`div`2)
| otherwise = Just ('O', i`div`2)
TODO : make this into an HUnit test
test :: IO ()
test = do
cmp hello
cmp $ packC2W "hi"
cmp $ packC2W "heat"
cmp $ packC2W "held"
cmp $ packC2W "hell"
cmp $ packC2W "hello"
cmp $ packC2W "jello"
where
cmp y = do putStrLn . show . breakMaximalPrefix hello $ y
putStrLn . show . (\(a,b,c) -> (a,c,b)) . breakMaximalPrefix y $ hello
putStrLn "\n"
hello = packC2W "hello"
----------------------------------------------------------------
----------------------------------------------------------- fin.
| null | https://raw.githubusercontent.com/wrengr/bytestring-trie/ec2216d2f560f5e453e65d24ce9cc249fc92d3ec/dev/Test/ByteStringInternal.hs | haskell | # OPTIONS_GHC -Wall -fwarn-tabs #
--------------------------------------------------------------
~ 2021.12.14
|
Module : Test.ByteStringInternal
License : BSD-3-Clause
Maintainer :
Stability : provisional
Portability : portable
--------------------------------------------------------------
--------------------------------------------------------------
| For debugging. [] is the infinite bit, head is the little end
--------------------------------------------------------------
--------------------------------------------------------- fin. |
Copyright : 2008 - -2021 wren romano
Testing helper functions on ' ByteString 's .
module Test.ByteStringInternal where
import Test.Utils (packC2W)
import Data.Trie.Internal.ByteString
import Data.List (unfoldr)
showBits :: (Integral a) => a -> String
showBits = unfoldr getBit
where
getBit 0 = Nothing
getBit i | odd i = Just ('I', (i-1)`div`2)
| otherwise = Just ('O', i`div`2)
TODO : make this into an HUnit test
test :: IO ()
test = do
cmp hello
cmp $ packC2W "hi"
cmp $ packC2W "heat"
cmp $ packC2W "held"
cmp $ packC2W "hell"
cmp $ packC2W "hello"
cmp $ packC2W "jello"
where
cmp y = do putStrLn . show . breakMaximalPrefix hello $ y
putStrLn . show . (\(a,b,c) -> (a,c,b)) . breakMaximalPrefix y $ hello
putStrLn "\n"
hello = packC2W "hello"
|
f1a865c130a41828d3ea40d62a274e6f0939fe902a30021c7f688f21c3e35930 | gfZeng/time.clj | core.cljc | (ns time.core
(:refer-clojure :exclude [> < >= <= == set get format])
#?(:clj (:import [java.util Date TimeZone]
[java.text SimpleDateFormat]))
(:require [clojure.string :as str]
[clojure.core :as core]
#?(:cljs [goog.string :as gstr])))
#?(:cljs
(do (def Number js/Number)
(def String js/String)
(def Date js/Date)
(defrecord SimpleDateFormat [time-zone pattern ss pts regex])))
(defn str->num
[s]
(let [s (.trim s)]
(cond
(empty? s) 0
(re-find #"\.\d" s) (#?(:clj Double/parseDouble :cljs js/parseFloat) s)
:else (#?(:clj Long/parseLong :cljs js/parseInt) s))))
(defprotocol Numberable
(as-num [_]))
(extend-protocol Numberable
nil
(as-num [_] 0)
Number
(as-num [n] n)
#?(:clj String :cljs string)
(as-num [s] (str->num s)))
(defprotocol IDate
(time-zone-offset [this])
(first-day-of-week [this])
(as-date [this offset fdow]
"offset = (time-zone-offset this) & fdow = (first-day-of-week this)"))
(defprotocol IFormat
(-format [this ^Date d])
(-parse [this ^String s]))
(defn set [d field val]
(case field
:year #?(:clj (.setYear d (- val 1900))
:cljs (.setFullYear d val))
:month (.setMonth d (dec val))
:date (.setDate d val)
:day (.setDate d val)
:hour (.setHours d val)
:minute (.setMinutes d val)
:second (.setSeconds d val)
:time (.setTime d val))
d)
(defn get [d field]
(case field
:year #?(:clj (+ (.getYear d) 1900)
:cljs (.getFullYear d))
:month (inc (.getMonth d))
:date (.getDate d)
:day (.getDate d)
:hour (.getHours d)
:minute (.getMinutes d)
:second (.getSeconds d)
:time (.getTime d)))
(defn date
([] (Date.))
([d & {:keys [first-day-of-week time-zone]}]
(let [offset (if time-zone
(time-zone-offset time-zone)
(time-zone-offset d))
fdow (if first-day-of-week
({:sunday 0
:monday 1
:tuesday 2
:wednesday 3
:thursday 4
:friday 5
:saturday 6}
first-day-of-week
first-day-of-week)
(time.core/first-day-of-week d))]
(as-date d offset fdow))))
#?(:cljs (declare formatter time-zone -format-num))
#?(:clj
(do
(extend-protocol IDate
TimeZone
(time-zone-offset [this]
(.getRawOffset this)))
(defn time-zone
([] (TimeZone/getDefault))
([fmt]
(if (and (string? fmt) (str/starts-with? fmt "GMT"))
(TimeZone/getTimeZone fmt)
(doto (time-zone)
(.setRawOffset (time-zone-offset fmt))))))
(def thread-local-formatter
(memoize
(fn formatter
([pattern]
(thread-local-formatter (time-zone) pattern))
([tz pattern]
(proxy [ThreadLocal] []
(initialValue []
(doto (SimpleDateFormat. pattern)
(.setTimeZone tz))))))))
(defn formatter
([pattern] (.get (thread-local-formatter pattern)))
([tz pattern] (.get (thread-local-formatter tz pattern))))
(extend-type SimpleDateFormat
IFormat
(-format [this ^Date d]
(.format this d))
(-parse [this ^String s]
(date (.parse this s)
:time-zone (.getTimeZone this))))
)
:cljs
(do
(defn time-zone
([] (time-zone (js/Date.)))
([fmt] (let [millis (time-zone-offset fmt)]
(reify
IDate
(time-zone-offset [this] millis)
IHash
(-hash [this] millis)
IEquiv
(-equiv [this other]
(= millis (time-zone-offset other)))))))
(defn -format-num [n x]
(let [s (str x)
l (count s)]
(cond
(core/== l n) s
(core/> l n) (.substring s (- l n))
(core/< l n) (str (apply str (repeat (- n l) 0)) s))))
(defn- ->regex-digital [s]
(str \(
(if (= (first s) \')
(gstr/regExpEscape (str/replace s #"^'|'$" ""))
(apply str (repeat (count s) "\\d")))
\)))
(def formatter
(memoize
(fn formatter
([pattern]
(formatter (time-zone) pattern))
([tz pattern]
(assert (satisfies? IDate tz))
(let [pts (re-seq #"'[^']+'|y+|M+|d+|H+|m+|s+|S+" pattern)
ss (str/split pattern #"'[^']+'|y+|M+|d+|H+|m+|s+|S+")
ss (->> (repeat "")
(concat ss)
(take (count pts)))
regex (->> (map ->regex-digital pts)
(interleave ss)
(apply str)
(re-pattern))]
(map->SimpleDateFormat {:time-zone tz
:pattern pattern
:ss ss
:regex regex
:pts pts}))))))
(extend-type SimpleDateFormat
IFormat
(-format [this ^Date d]
(let [d-offset (* 60000 (.getTimezoneOffset d))
offset (time-zone-offset (:time-zone this))
d (Date. (+ (.getTime d) offset d-offset))]
(->> (map (fn [pt]
(case (first pt)
\y (-format-num (count pt) (get d :year))
\M (-format-num (count pt) (get d :month))
\d (-format-num (count pt) (get d :day))
\H (-format-num (count pt) (get d :hour))
\m (-format-num (count pt) (get d :minute))
\s (-format-num (count pt) (get d :second))
\S (-format-num (count pt) (get d :time))
\' (re-find #"[^']+" pt)
pt))
(:pts this))
(interleave (:ss this))
(apply str))))
(-parse [this ^String s]
(let [parsed (->> (re-find (:regex this) s)
(rest)
(zipmap (:pts this))
(reduce-kv (fn [m [k] v]
(if (= k \')
m
(assoc m k (js/parseInt v))))
{}))
tz (:time-zone this)
ts (-> (date)
(set :time (parsed \S 0))
(set :year (parsed \y 0))
(set :month (parsed \M 0))
(set :day (parsed \d 0))
(set :hour (parsed \H 0))
(set :minute (parsed \m 0))
(set :second (parsed \s 0))
(.getTime))
ts (+ ts
(time-zone-offset (time-zone))
(- (time-zone-offset tz)))]
(date ts :time-zone tz))))))
(extend-protocol IDate
nil
(time-zone-offset [_]
(time-zone-offset (time-zone)))
Number
(time-zone-offset [this]
(time-zone-offset (time-zone)))
(first-day-of-week [this] 0)
(as-date [this offset fdow]
#?(:clj
(proxy [Date time.core.IDate] [this]
(time_zone_offset [] offset)
(first_day_of_week [] fdow)
(as_date [offset fdow]
(as-date (.getTime this) offset fdow)))
:cljs
(specify! (js/Date. this)
IDate
(time-zone-offset [this] offset)
(first-day-of-week [this] fdow))))
Date
(time-zone-offset [this]
(* -60000 (.getTimezoneOffset this)))
(first-day-of-week [this]
0)
(as-date [this offset fdow]
(as-date (.getTime this) offset fdow))
#?(:clj String :cljs string)
(time-zone-offset [this]
(let [[op hours mins]
(rest (re-find #"(?:GMT|Z)?([-+])?(\d+)?(?::(\d+))?$" this))
op ({"+" + "-" -} op +)
millis (+ (* 3600 1000 (as-num hours))
(* 60000 (as-num mins)))]
(op millis))))
(extend-type #?(:clj String :cljs string)
IFormat
(-format [this ^Date d]
(let [^SimpleDateFormat fmt (formatter (time-zone d) this)]
(-format fmt d)))
(-parse [this ^String s]
(-parse (formatter this) s)))
(defn format [d p]
(-format p d))
(defn parse [s fmt]
(-parse fmt s))
(defn copy [x field y]
(set x field (get y field)))
(defn date-1970
([] (date-1970 (time-zone)))
([tz] (Date. (- (time-zone-offset tz)))))
(defn floor
[d period]
(if (keyword? period)
(floor d [1 period])
(let [[n period] period
begin (date-1970 d)
d-offset (* 60000 (.getTimezoneOffset d))
offset (time-zone-offset d)
d (Date. (- (.getTime d) offset d-offset))]
(if (= period :week)
(doto begin
(copy :year d)
(copy :month d)
(.setDate (- (.getDate d)
(mod (- (.getDay d)
(first-day-of-week d))
7))))
(reduce
(fn [begin field]
(if (= field period)
(reduced (set begin field (-> (get d field) (quot n) (* n))))
(copy begin field d)))
begin
[:year :month :day :hour :minute :second])))))
(defn plus [^Date d period]
(if (keyword? period)
(plus d [1 period])
(let [[n period] (if (#?(:clj identical? :cljs keyword-identical?) (second period) :week)
[(* 7 (first period)) :day]
period)]
(doto (Date. (.getTime d))
(set period (+ (get d period) n))))))
(defn floor-seq
([period] (floor-seq period (date)))
([period d]
(iterate #(plus % period) (floor d period))))
(defn now-ms []
#?(:clj (System/currentTimeMillis)
:cljs (.now js/Date)))
(defn > [d1 d2]
(core/> (.getTime d1) (.getTime d2)))
(defn < [d1 d2]
(core/< (.getTime d1) (.getTime d2)))
(defn >= [d1 d2]
(core/>= (.getTime d1) (.getTime d2)))
(defn <= [d1 d2]
(core/<= (.getTime d1) (.getTime d2)))
(defn == [d1 d2]
(core/== (.getTime d1) (.getTime d2)))
| null | https://raw.githubusercontent.com/gfZeng/time.clj/874bb2c7a1b4debc07818f4a25e241f8cfa8c5f8/src/time/core.cljc | clojure | (ns time.core
(:refer-clojure :exclude [> < >= <= == set get format])
#?(:clj (:import [java.util Date TimeZone]
[java.text SimpleDateFormat]))
(:require [clojure.string :as str]
[clojure.core :as core]
#?(:cljs [goog.string :as gstr])))
#?(:cljs
(do (def Number js/Number)
(def String js/String)
(def Date js/Date)
(defrecord SimpleDateFormat [time-zone pattern ss pts regex])))
(defn str->num
[s]
(let [s (.trim s)]
(cond
(empty? s) 0
(re-find #"\.\d" s) (#?(:clj Double/parseDouble :cljs js/parseFloat) s)
:else (#?(:clj Long/parseLong :cljs js/parseInt) s))))
(defprotocol Numberable
(as-num [_]))
(extend-protocol Numberable
nil
(as-num [_] 0)
Number
(as-num [n] n)
#?(:clj String :cljs string)
(as-num [s] (str->num s)))
(defprotocol IDate
(time-zone-offset [this])
(first-day-of-week [this])
(as-date [this offset fdow]
"offset = (time-zone-offset this) & fdow = (first-day-of-week this)"))
(defprotocol IFormat
(-format [this ^Date d])
(-parse [this ^String s]))
(defn set [d field val]
(case field
:year #?(:clj (.setYear d (- val 1900))
:cljs (.setFullYear d val))
:month (.setMonth d (dec val))
:date (.setDate d val)
:day (.setDate d val)
:hour (.setHours d val)
:minute (.setMinutes d val)
:second (.setSeconds d val)
:time (.setTime d val))
d)
(defn get [d field]
(case field
:year #?(:clj (+ (.getYear d) 1900)
:cljs (.getFullYear d))
:month (inc (.getMonth d))
:date (.getDate d)
:day (.getDate d)
:hour (.getHours d)
:minute (.getMinutes d)
:second (.getSeconds d)
:time (.getTime d)))
(defn date
([] (Date.))
([d & {:keys [first-day-of-week time-zone]}]
(let [offset (if time-zone
(time-zone-offset time-zone)
(time-zone-offset d))
fdow (if first-day-of-week
({:sunday 0
:monday 1
:tuesday 2
:wednesday 3
:thursday 4
:friday 5
:saturday 6}
first-day-of-week
first-day-of-week)
(time.core/first-day-of-week d))]
(as-date d offset fdow))))
#?(:cljs (declare formatter time-zone -format-num))
#?(:clj
(do
(extend-protocol IDate
TimeZone
(time-zone-offset [this]
(.getRawOffset this)))
(defn time-zone
([] (TimeZone/getDefault))
([fmt]
(if (and (string? fmt) (str/starts-with? fmt "GMT"))
(TimeZone/getTimeZone fmt)
(doto (time-zone)
(.setRawOffset (time-zone-offset fmt))))))
(def thread-local-formatter
(memoize
(fn formatter
([pattern]
(thread-local-formatter (time-zone) pattern))
([tz pattern]
(proxy [ThreadLocal] []
(initialValue []
(doto (SimpleDateFormat. pattern)
(.setTimeZone tz))))))))
(defn formatter
([pattern] (.get (thread-local-formatter pattern)))
([tz pattern] (.get (thread-local-formatter tz pattern))))
(extend-type SimpleDateFormat
IFormat
(-format [this ^Date d]
(.format this d))
(-parse [this ^String s]
(date (.parse this s)
:time-zone (.getTimeZone this))))
)
:cljs
(do
(defn time-zone
([] (time-zone (js/Date.)))
([fmt] (let [millis (time-zone-offset fmt)]
(reify
IDate
(time-zone-offset [this] millis)
IHash
(-hash [this] millis)
IEquiv
(-equiv [this other]
(= millis (time-zone-offset other)))))))
(defn -format-num [n x]
(let [s (str x)
l (count s)]
(cond
(core/== l n) s
(core/> l n) (.substring s (- l n))
(core/< l n) (str (apply str (repeat (- n l) 0)) s))))
(defn- ->regex-digital [s]
(str \(
(if (= (first s) \')
(gstr/regExpEscape (str/replace s #"^'|'$" ""))
(apply str (repeat (count s) "\\d")))
\)))
(def formatter
(memoize
(fn formatter
([pattern]
(formatter (time-zone) pattern))
([tz pattern]
(assert (satisfies? IDate tz))
(let [pts (re-seq #"'[^']+'|y+|M+|d+|H+|m+|s+|S+" pattern)
ss (str/split pattern #"'[^']+'|y+|M+|d+|H+|m+|s+|S+")
ss (->> (repeat "")
(concat ss)
(take (count pts)))
regex (->> (map ->regex-digital pts)
(interleave ss)
(apply str)
(re-pattern))]
(map->SimpleDateFormat {:time-zone tz
:pattern pattern
:ss ss
:regex regex
:pts pts}))))))
(extend-type SimpleDateFormat
IFormat
(-format [this ^Date d]
(let [d-offset (* 60000 (.getTimezoneOffset d))
offset (time-zone-offset (:time-zone this))
d (Date. (+ (.getTime d) offset d-offset))]
(->> (map (fn [pt]
(case (first pt)
\y (-format-num (count pt) (get d :year))
\M (-format-num (count pt) (get d :month))
\d (-format-num (count pt) (get d :day))
\H (-format-num (count pt) (get d :hour))
\m (-format-num (count pt) (get d :minute))
\s (-format-num (count pt) (get d :second))
\S (-format-num (count pt) (get d :time))
\' (re-find #"[^']+" pt)
pt))
(:pts this))
(interleave (:ss this))
(apply str))))
(-parse [this ^String s]
(let [parsed (->> (re-find (:regex this) s)
(rest)
(zipmap (:pts this))
(reduce-kv (fn [m [k] v]
(if (= k \')
m
(assoc m k (js/parseInt v))))
{}))
tz (:time-zone this)
ts (-> (date)
(set :time (parsed \S 0))
(set :year (parsed \y 0))
(set :month (parsed \M 0))
(set :day (parsed \d 0))
(set :hour (parsed \H 0))
(set :minute (parsed \m 0))
(set :second (parsed \s 0))
(.getTime))
ts (+ ts
(time-zone-offset (time-zone))
(- (time-zone-offset tz)))]
(date ts :time-zone tz))))))
(extend-protocol IDate
nil
(time-zone-offset [_]
(time-zone-offset (time-zone)))
Number
(time-zone-offset [this]
(time-zone-offset (time-zone)))
(first-day-of-week [this] 0)
(as-date [this offset fdow]
#?(:clj
(proxy [Date time.core.IDate] [this]
(time_zone_offset [] offset)
(first_day_of_week [] fdow)
(as_date [offset fdow]
(as-date (.getTime this) offset fdow)))
:cljs
(specify! (js/Date. this)
IDate
(time-zone-offset [this] offset)
(first-day-of-week [this] fdow))))
Date
(time-zone-offset [this]
(* -60000 (.getTimezoneOffset this)))
(first-day-of-week [this]
0)
(as-date [this offset fdow]
(as-date (.getTime this) offset fdow))
#?(:clj String :cljs string)
(time-zone-offset [this]
(let [[op hours mins]
(rest (re-find #"(?:GMT|Z)?([-+])?(\d+)?(?::(\d+))?$" this))
op ({"+" + "-" -} op +)
millis (+ (* 3600 1000 (as-num hours))
(* 60000 (as-num mins)))]
(op millis))))
(extend-type #?(:clj String :cljs string)
IFormat
(-format [this ^Date d]
(let [^SimpleDateFormat fmt (formatter (time-zone d) this)]
(-format fmt d)))
(-parse [this ^String s]
(-parse (formatter this) s)))
(defn format [d p]
(-format p d))
(defn parse [s fmt]
(-parse fmt s))
(defn copy [x field y]
(set x field (get y field)))
(defn date-1970
([] (date-1970 (time-zone)))
([tz] (Date. (- (time-zone-offset tz)))))
(defn floor
[d period]
(if (keyword? period)
(floor d [1 period])
(let [[n period] period
begin (date-1970 d)
d-offset (* 60000 (.getTimezoneOffset d))
offset (time-zone-offset d)
d (Date. (- (.getTime d) offset d-offset))]
(if (= period :week)
(doto begin
(copy :year d)
(copy :month d)
(.setDate (- (.getDate d)
(mod (- (.getDay d)
(first-day-of-week d))
7))))
(reduce
(fn [begin field]
(if (= field period)
(reduced (set begin field (-> (get d field) (quot n) (* n))))
(copy begin field d)))
begin
[:year :month :day :hour :minute :second])))))
(defn plus [^Date d period]
(if (keyword? period)
(plus d [1 period])
(let [[n period] (if (#?(:clj identical? :cljs keyword-identical?) (second period) :week)
[(* 7 (first period)) :day]
period)]
(doto (Date. (.getTime d))
(set period (+ (get d period) n))))))
(defn floor-seq
([period] (floor-seq period (date)))
([period d]
(iterate #(plus % period) (floor d period))))
(defn now-ms []
#?(:clj (System/currentTimeMillis)
:cljs (.now js/Date)))
(defn > [d1 d2]
(core/> (.getTime d1) (.getTime d2)))
(defn < [d1 d2]
(core/< (.getTime d1) (.getTime d2)))
(defn >= [d1 d2]
(core/>= (.getTime d1) (.getTime d2)))
(defn <= [d1 d2]
(core/<= (.getTime d1) (.getTime d2)))
(defn == [d1 d2]
(core/== (.getTime d1) (.getTime d2)))
| |
f85988a94fc9b40ebc3f7c70f8837044763078744776a7541285cfe13d33e54f | ghc/packages-dph | Unlifted.hs | # LANGUAGE TypeOperators , CPP #
-- | WARNING:
-- This is an abstract interface. All the functions will just `error` if called.
--
This module provides an API for the segmented array primitives used by DPH .
-- None of the functions here have implementations.
--
-- Client programs should use either the @dph-prim-seq@ or @dph-prim-par@
-- packages, as these provide the same API and contain real code.
--
NOTE : The API is enforced by the DPH_Header.h and DPH_Interface.h headers .
-- The dph-prim-interface, dph-prim-seq, and dph-prim-par modules all import
-- the same headers so we can be sure we're presenting the same API.
#include "DPH_Header.h"
import qualified Prelude as P
import Prelude ( Eq(..), Num(..), Bool(..), ($), (.) )
#include "DPH_Interface.h"
------------------------------------------------------------------------------
notImplemented :: P.String -> a
notImplemented fnName
= P.error $ P.unlines
[ "dph-prim-interface:Data.Array.Parallel.Unlifted." P.++ fnName
, "This module is an abstract interface and does not contain real code."
, "Use dph-prim-seq or dph-prim-par instead." ]
{-# NOINLINE notImplemented #-}
-- Types ----------------------------------------------------------------------
class Elt a
instance Elt a => Elt [a]
type Array a = [a]
-- Constructors ---------------------------------------------------------------
empty = notImplemented "empty"
(+:+) = notImplemented "(+:+)"
append_s = notImplemented "append_s"
append_vs = notImplemented "append_vs"
replicate = notImplemented "replicate"
replicate_s = notImplemented "replicate_s"
replicate_rs = notImplemented "replicate_rs"
repeat = notImplemented "repeat"
indexed = notImplemented "indexed"
indices_s = notImplemented "indices_s"
enumFromTo = notImplemented "enumFromTo"
enumFromThenTo = notImplemented "enumFromThenTo"
enumFromStepLen = notImplemented "enumFromStepLen"
enumFromStepLenEach = notImplemented "enumFromStepLenEach"
-- Conversions ----------------------------------------------------------------
nest = notImplemented "nest"
toList = notImplemented "toList"
fromList = notImplemented "fromList"
toList_s = notImplemented "toList_s"
fromList_s = notImplemented "fromList_s"
-- Projections ----------------------------------------------------------------
length = notImplemented "length"
index = notImplemented "index"
indexs = notImplemented "indexs"
indexs_avs = notImplemented "indexs_avs"
extract = notImplemented "extract"
extracts_nss = notImplemented "extract_nss"
extracts_ass = notImplemented "extract_ass"
extracts_avs = notImplemented "extract_avs"
drop = notImplemented "drop"
-- Update ---------------------------------------------------------------------
update = notImplemented "update"
-- Permutation ----------------------------------------------------------------
permute = notImplemented "permute"
bpermute = notImplemented "bpermute"
mbpermute = notImplemented "mbpermute"
bpermuteDft = notImplemented "bpermuteDft"
-- Zipping and Unzipping ------------------------------------------------------
zip = notImplemented "zip"
zip3 = notImplemented "zip3"
unzip = notImplemented "unzip"
unzip3 = notImplemented "unzip3"
fsts = notImplemented "fsts"
snds = notImplemented "snds"
-- Map and zipWith ------------------------------------------------------------
map = notImplemented "map"
zipWith = notImplemented "zipWith"
-- Scans and Folds -----------------------------------------------------------
scan = notImplemented "scan"
fold = notImplemented "fold"
fold_s = notImplemented "fold_s"
fold_ss = notImplemented "fold_ss"
fold_r = notImplemented "fold_r"
fold1 = notImplemented "fold1"
fold1_s = notImplemented "fold1_s"
fold1_ss = notImplemented "fold1_ss"
sum = notImplemented "sum"
sum_r = notImplemented "sum_r"
and = notImplemented "and"
-- Packing and Combining ------------------------------------------------------
pack = notImplemented "pack"
filter = notImplemented "filter"
combine = notImplemented "combine"
combine2 = notImplemented "combine2"
interleave = notImplemented "interleave"
-- Selectors ------------------------------------------------------------------
data Sel2
= Sel2
{ sel2_tags :: [Tag]
, sel2_indices :: [Int]
, sel2_elements0 :: Int
, sel2_elements1 :: Int }
type SelRep2 = ()
mkSel2 = notImplemented "mkSel2"
tagsSel2 = notImplemented "tagsSel2"
indicesSel2 = notImplemented "indicesSel2"
elementsSel2_0 = notImplemented "elementsSel2_0"
elementsSel2_1 = notImplemented "elementsSel2_1"
repSel2 = notImplemented "repSel2"
mkSelRep2 = notImplemented "mkSelRep2"
indicesSelRep2 = notImplemented "indicesSelRep2"
elementsSelRep2_0 = notImplemented "elementsSelRep2_0"
elementsSelRep2_1 = notImplemented "elementsSelRep2_1"
-- Segment Descriptors --------------------------------------------------------
data Segd
= Segd
{ segd_lengths :: [Int]
, segd_indices :: [Int]
, segd_elements :: Int }
mkSegd = notImplemented "mkSegd"
emptySegd = notImplemented "emptySegd"
singletonSegd = notImplemented "singletonSegd"
validSegd = notImplemented "validSegd"
lengthSegd = notImplemented "lengthSegd"
lengthsSegd = notImplemented "lengthsSegd"
indicesSegd = notImplemented "indicesSegd"
elementsSegd = notImplemented "elementsSegd"
-- Scattered Segment Descriptors ----------------------------------------------
data SSegd
= SSegd
{ ssegd_starts :: [Int]
, ssegd_sources :: [Int]
, ssegd_segd :: Segd }
mkSSegd = notImplemented "mkSSegd"
validSSegd = notImplemented "validSSegd"
emptySSegd = notImplemented "emptySSegd"
singletonSSegd = notImplemented "singletonSSegd"
promoteSegdToSSegd = notImplemented "promoteSegdToSSegd"
isContiguousSSegd = notImplemented "isContiguousSSegd"
lengthOfSSegd = notImplemented "lengthOfSSegd"
lengthsOfSSegd = notImplemented "lenghtsOfSSegd"
indicesOfSSegd = notImplemented "indicesOfSSegd"
startsOfSSegd = notImplemented "startsOfSSegd"
sourcesOfSSegd = notImplemented "sourcesOfSSegd"
getSegOfSSegd = notImplemented "getSegOfSSegd"
appendSSegd = notImplemented "appendSSegd"
-- Virtual Segment Descriptors ------------------------------------------------
data VSegd
= VSegd
{ vsegd_vsegids :: [Int]
, vsegd_ssegd :: SSegd }
mkVSegd = notImplemented "mkVSegd"
validVSegd = notImplemented "validSSegd"
emptyVSegd = notImplemented "emptyVSegd"
singletonVSegd = notImplemented "singletonVSegd"
replicatedVSegd = notImplemented "replicatedVSegd"
promoteSegdToVSegd = notImplemented "promoteSegdToVSegd"
promoteSSegdToVSegd = notImplemented "promoteSSegdToVSegd"
isContiguousVSegd = notImplemented "isContiguousVSegd"
isManifestVSegd = notImplemented "isManifestVSegd"
lengthOfVSegd = notImplemented "lengthOfVSegd"
takeVSegidsOfVSegd = notImplemented "takeVSegidsOfVSegd"
takeVSegidsRedundantOfVSegd = notImplemented "takeVSegidsRedundantOfVSegd"
takeSSegdOfVSegd = notImplemented "takeSSegdOfVSegd"
takeSSegdRedundantOfVSegd = notImplemented "takeSSegdRedundantOfVSegd"
takeLengthsOfVSegd = notImplemented "takeLengthsOfVSegd"
getSegOfVSegd = notImplemented "getSegOfVSegd"
unsafeDemoteToSSegdOfVSegd = notImplemented "unsafeDemoteToSSegdOfVSegd"
unsafeDemoteToSegdOfVSegd = notImplemented "unsafeDemoteToSegdOfVSegd"
updateVSegsOfVSegd = notImplemented "updateVSegsOfVSegd"
updateVSegsReachableOfVSegd = notImplemented "updateVSegsReachableOfVSegd"
appendVSegd = notImplemented "appendVSegd"
combine2VSegd = notImplemented "combine2VSegd"
Irregular two dimensional arrays -------------------------------------------
class Elts a
type Arrays a
= [[a]]
emptys = notImplemented "emptys"
lengths = notImplemented "lengths"
singletons = notImplemented "singletons"
unsafeIndexs = notImplemented "unsafeIndexs"
unsafeIndex2s = notImplemented "unsafeIndex2s"
appends = notImplemented "appends"
fromVectors = notImplemented "fromVectors"
toVectors = notImplemented "toVectors"
-- Random Arrays --------------------------------------------------------------
randoms n = notImplemented "randoms"
randomRs n r = notImplemented "randomRs"
-- Array IO -------------------------------------------------------------------
class Elt a => IOElt a
hPut = notImplemented "hPut"
hGet = notImplemented "hGet"
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-prim-interface/Data/Array/Parallel/Unlifted.hs | haskell | | WARNING:
This is an abstract interface. All the functions will just `error` if called.
None of the functions here have implementations.
Client programs should use either the @dph-prim-seq@ or @dph-prim-par@
packages, as these provide the same API and contain real code.
The dph-prim-interface, dph-prim-seq, and dph-prim-par modules all import
the same headers so we can be sure we're presenting the same API.
----------------------------------------------------------------------------
# NOINLINE notImplemented #
Types ----------------------------------------------------------------------
Constructors ---------------------------------------------------------------
Conversions ----------------------------------------------------------------
Projections ----------------------------------------------------------------
Update ---------------------------------------------------------------------
Permutation ----------------------------------------------------------------
Zipping and Unzipping ------------------------------------------------------
Map and zipWith ------------------------------------------------------------
Scans and Folds -----------------------------------------------------------
Packing and Combining ------------------------------------------------------
Selectors ------------------------------------------------------------------
Segment Descriptors --------------------------------------------------------
Scattered Segment Descriptors ----------------------------------------------
Virtual Segment Descriptors ------------------------------------------------
-----------------------------------------
Random Arrays --------------------------------------------------------------
Array IO ------------------------------------------------------------------- | # LANGUAGE TypeOperators , CPP #
This module provides an API for the segmented array primitives used by DPH .
NOTE : The API is enforced by the DPH_Header.h and DPH_Interface.h headers .
#include "DPH_Header.h"
import qualified Prelude as P
import Prelude ( Eq(..), Num(..), Bool(..), ($), (.) )
#include "DPH_Interface.h"
notImplemented :: P.String -> a
notImplemented fnName
= P.error $ P.unlines
[ "dph-prim-interface:Data.Array.Parallel.Unlifted." P.++ fnName
, "This module is an abstract interface and does not contain real code."
, "Use dph-prim-seq or dph-prim-par instead." ]
class Elt a
instance Elt a => Elt [a]
type Array a = [a]
empty = notImplemented "empty"
(+:+) = notImplemented "(+:+)"
append_s = notImplemented "append_s"
append_vs = notImplemented "append_vs"
replicate = notImplemented "replicate"
replicate_s = notImplemented "replicate_s"
replicate_rs = notImplemented "replicate_rs"
repeat = notImplemented "repeat"
indexed = notImplemented "indexed"
indices_s = notImplemented "indices_s"
enumFromTo = notImplemented "enumFromTo"
enumFromThenTo = notImplemented "enumFromThenTo"
enumFromStepLen = notImplemented "enumFromStepLen"
enumFromStepLenEach = notImplemented "enumFromStepLenEach"
nest = notImplemented "nest"
toList = notImplemented "toList"
fromList = notImplemented "fromList"
toList_s = notImplemented "toList_s"
fromList_s = notImplemented "fromList_s"
length = notImplemented "length"
index = notImplemented "index"
indexs = notImplemented "indexs"
indexs_avs = notImplemented "indexs_avs"
extract = notImplemented "extract"
extracts_nss = notImplemented "extract_nss"
extracts_ass = notImplemented "extract_ass"
extracts_avs = notImplemented "extract_avs"
drop = notImplemented "drop"
update = notImplemented "update"
permute = notImplemented "permute"
bpermute = notImplemented "bpermute"
mbpermute = notImplemented "mbpermute"
bpermuteDft = notImplemented "bpermuteDft"
zip = notImplemented "zip"
zip3 = notImplemented "zip3"
unzip = notImplemented "unzip"
unzip3 = notImplemented "unzip3"
fsts = notImplemented "fsts"
snds = notImplemented "snds"
map = notImplemented "map"
zipWith = notImplemented "zipWith"
scan = notImplemented "scan"
fold = notImplemented "fold"
fold_s = notImplemented "fold_s"
fold_ss = notImplemented "fold_ss"
fold_r = notImplemented "fold_r"
fold1 = notImplemented "fold1"
fold1_s = notImplemented "fold1_s"
fold1_ss = notImplemented "fold1_ss"
sum = notImplemented "sum"
sum_r = notImplemented "sum_r"
and = notImplemented "and"
pack = notImplemented "pack"
filter = notImplemented "filter"
combine = notImplemented "combine"
combine2 = notImplemented "combine2"
interleave = notImplemented "interleave"
data Sel2
= Sel2
{ sel2_tags :: [Tag]
, sel2_indices :: [Int]
, sel2_elements0 :: Int
, sel2_elements1 :: Int }
type SelRep2 = ()
mkSel2 = notImplemented "mkSel2"
tagsSel2 = notImplemented "tagsSel2"
indicesSel2 = notImplemented "indicesSel2"
elementsSel2_0 = notImplemented "elementsSel2_0"
elementsSel2_1 = notImplemented "elementsSel2_1"
repSel2 = notImplemented "repSel2"
mkSelRep2 = notImplemented "mkSelRep2"
indicesSelRep2 = notImplemented "indicesSelRep2"
elementsSelRep2_0 = notImplemented "elementsSelRep2_0"
elementsSelRep2_1 = notImplemented "elementsSelRep2_1"
data Segd
= Segd
{ segd_lengths :: [Int]
, segd_indices :: [Int]
, segd_elements :: Int }
mkSegd = notImplemented "mkSegd"
emptySegd = notImplemented "emptySegd"
singletonSegd = notImplemented "singletonSegd"
validSegd = notImplemented "validSegd"
lengthSegd = notImplemented "lengthSegd"
lengthsSegd = notImplemented "lengthsSegd"
indicesSegd = notImplemented "indicesSegd"
elementsSegd = notImplemented "elementsSegd"
data SSegd
= SSegd
{ ssegd_starts :: [Int]
, ssegd_sources :: [Int]
, ssegd_segd :: Segd }
mkSSegd = notImplemented "mkSSegd"
validSSegd = notImplemented "validSSegd"
emptySSegd = notImplemented "emptySSegd"
singletonSSegd = notImplemented "singletonSSegd"
promoteSegdToSSegd = notImplemented "promoteSegdToSSegd"
isContiguousSSegd = notImplemented "isContiguousSSegd"
lengthOfSSegd = notImplemented "lengthOfSSegd"
lengthsOfSSegd = notImplemented "lenghtsOfSSegd"
indicesOfSSegd = notImplemented "indicesOfSSegd"
startsOfSSegd = notImplemented "startsOfSSegd"
sourcesOfSSegd = notImplemented "sourcesOfSSegd"
getSegOfSSegd = notImplemented "getSegOfSSegd"
appendSSegd = notImplemented "appendSSegd"
data VSegd
= VSegd
{ vsegd_vsegids :: [Int]
, vsegd_ssegd :: SSegd }
mkVSegd = notImplemented "mkVSegd"
validVSegd = notImplemented "validSSegd"
emptyVSegd = notImplemented "emptyVSegd"
singletonVSegd = notImplemented "singletonVSegd"
replicatedVSegd = notImplemented "replicatedVSegd"
promoteSegdToVSegd = notImplemented "promoteSegdToVSegd"
promoteSSegdToVSegd = notImplemented "promoteSSegdToVSegd"
isContiguousVSegd = notImplemented "isContiguousVSegd"
isManifestVSegd = notImplemented "isManifestVSegd"
lengthOfVSegd = notImplemented "lengthOfVSegd"
takeVSegidsOfVSegd = notImplemented "takeVSegidsOfVSegd"
takeVSegidsRedundantOfVSegd = notImplemented "takeVSegidsRedundantOfVSegd"
takeSSegdOfVSegd = notImplemented "takeSSegdOfVSegd"
takeSSegdRedundantOfVSegd = notImplemented "takeSSegdRedundantOfVSegd"
takeLengthsOfVSegd = notImplemented "takeLengthsOfVSegd"
getSegOfVSegd = notImplemented "getSegOfVSegd"
unsafeDemoteToSSegdOfVSegd = notImplemented "unsafeDemoteToSSegdOfVSegd"
unsafeDemoteToSegdOfVSegd = notImplemented "unsafeDemoteToSegdOfVSegd"
updateVSegsOfVSegd = notImplemented "updateVSegsOfVSegd"
updateVSegsReachableOfVSegd = notImplemented "updateVSegsReachableOfVSegd"
appendVSegd = notImplemented "appendVSegd"
combine2VSegd = notImplemented "combine2VSegd"
class Elts a
type Arrays a
= [[a]]
emptys = notImplemented "emptys"
lengths = notImplemented "lengths"
singletons = notImplemented "singletons"
unsafeIndexs = notImplemented "unsafeIndexs"
unsafeIndex2s = notImplemented "unsafeIndex2s"
appends = notImplemented "appends"
fromVectors = notImplemented "fromVectors"
toVectors = notImplemented "toVectors"
randoms n = notImplemented "randoms"
randomRs n r = notImplemented "randomRs"
class Elt a => IOElt a
hPut = notImplemented "hPut"
hGet = notImplemented "hGet"
|
368bb51e750f4db7e02b6e527e6d1ac28b839944d807fec53d21da9f8bdbae73 | sol/logging-facade | Facade.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE ConstraintKinds #-}
-- |
-- This module is intended to be imported qualified:
--
> import qualified System . Logging . Facade as Log
module System.Logging.Facade (
-- * Producing log messages
log
, trace
, debug
, info
, warn
, error
-- * Types
, Logging
, LogLevel(..)
) where
import Prelude hiding (log, error)
import Data.CallStack
import System.Logging.Facade.Types
import System.Logging.Facade.Class
-- | Produce a log message with specified log level.
log :: (HasCallStack, Logging m) => LogLevel -> String -> m ()
log level message = consumeLogRecord (LogRecord level location message)
location :: HasCallStack => Maybe Location
location = case reverse callStack of
(_, loc) : _ -> Just $ Location (srcLocPackage loc) (srcLocModule loc) (srcLocFile loc) (srcLocStartLine loc) (srcLocStartCol loc)
_ -> Nothing
-- | Produce a log message with log level `TRACE`.
trace :: (HasCallStack, Logging m) => String -> m ()
trace = log TRACE
-- | Produce a log message with log level `DEBUG`.
debug :: (HasCallStack, Logging m) => String -> m ()
debug = log DEBUG
-- | Produce a log message with log level `INFO`.
info :: (HasCallStack, Logging m) => String -> m ()
info = log INFO
-- | Produce a log message with log level `WARN`.
warn :: (HasCallStack, Logging m) => String -> m ()
warn = log WARN
-- | Produce a log message with log level `ERROR`.
error :: (HasCallStack, Logging m) => String -> m ()
error = log ERROR
| null | https://raw.githubusercontent.com/sol/logging-facade/2ed4f0b00a3a8db11c948ff215578ba5bdbcd188/src/System/Logging/Facade.hs | haskell | # LANGUAGE ConstraintKinds #
|
This module is intended to be imported qualified:
* Producing log messages
* Types
| Produce a log message with specified log level.
| Produce a log message with log level `TRACE`.
| Produce a log message with log level `DEBUG`.
| Produce a log message with log level `INFO`.
| Produce a log message with log level `WARN`.
| Produce a log message with log level `ERROR`. | # LANGUAGE FlexibleContexts #
> import qualified System . Logging . Facade as Log
module System.Logging.Facade (
log
, trace
, debug
, info
, warn
, error
, Logging
, LogLevel(..)
) where
import Prelude hiding (log, error)
import Data.CallStack
import System.Logging.Facade.Types
import System.Logging.Facade.Class
log :: (HasCallStack, Logging m) => LogLevel -> String -> m ()
log level message = consumeLogRecord (LogRecord level location message)
location :: HasCallStack => Maybe Location
location = case reverse callStack of
(_, loc) : _ -> Just $ Location (srcLocPackage loc) (srcLocModule loc) (srcLocFile loc) (srcLocStartLine loc) (srcLocStartCol loc)
_ -> Nothing
trace :: (HasCallStack, Logging m) => String -> m ()
trace = log TRACE
debug :: (HasCallStack, Logging m) => String -> m ()
debug = log DEBUG
info :: (HasCallStack, Logging m) => String -> m ()
info = log INFO
warn :: (HasCallStack, Logging m) => String -> m ()
warn = log WARN
error :: (HasCallStack, Logging m) => String -> m ()
error = log ERROR
|
dfd569c31c93d160a2d20b991e9807a23d6148e28d9b8f1dd7a3d2d2656e64d3 | julienXX/clj-slack | core.clj | (ns clj-slack.core
(:require
[clj-http.client :as http]
[clojure.data.json :as json]
[clojure.tools.logging :as log])
(:import [java.net URLEncoder]))
(defn verify-api-url
[connection]
(assert
(and (string? (:api-url connection))
(and (not (empty? (:api-url connection)))
(not (nil? (re-find #"^https?:\/\/" (:api-url connection))))))
(str "clj-slack: API URL is not valid. :api-url has to be a valid URL ( usually), but is " (pr-str (:api-url connection)))))
(defn verify-token
[connection]
(assert
(and (string? (:token connection))
(not (empty? (:token connection))))
(str "clj-slack: Access token is not valid. :token has to be a non-empty string, but is " (pr-str (:token connection)))))
(defn verify
"Checks the connection map"
[connection]
(verify-api-url connection)
(when (not (contains? connection :skip-token-validation))
(verify-token connection))
connection)
(defn- send-request
"Sends a GET http request with formatted params.
Optional request options can be specified which will be passed to `clj-http` without any changes.
Can be useful to specify timeouts, etc."
[url params & [opts]]
(let [full-url (str url params)
response (http/get full-url opts)]
(if-let [body (:body response)]
(json/read-str body :key-fn clojure.core/keyword)
(log/error "Error from Slack API:" (:error response)))))
(defn- send-post-request
"Sends a POST http request with formatted params.
Optional request options can be specified which will be passed to `clj-http` without any changes.
Can be useful to specify timeouts, etc."
[url multiparts & [opts]]
(let [response (http/post url (merge {:multipart multiparts}
opts))]
(json/read-str (:body response) :key-fn clojure.core/keyword)))
(defn- make-query-string
"Transforms a map into url params"
[m]
(->> (for [[k v] m]
(str k "=" (URLEncoder/encode v "UTF-8")))
(interpose "&")
(apply str)))
(defn- build-params
"Builds the full URL (endpoint + params)"
([connection endpoint query-map]
(str "/" endpoint "?token=" (:token (verify connection)) "&" (make-query-string query-map))))
(defn- build-multiparts
"Builds an http-kit multiparts sequence"
[params]
(for [[k v] params]
(if (instance? java.io.File v)
{:name k :content v :filename (.getName v) :encoding "UTF-8"}
{:name k :content v :encoding "UTF-8"})))
(defn stringify-keys
"Creates a new map whose keys are all strings."
[m]
(into {} (for [[k v] m]
(if (keyword? k)
[(name k) v]
[(str k) v]))))
(defn- request-options
"Extracts request options from slack connection map.
Provides sensible defaults for timeouts."
[connection]
(let [default-options {:conn-timeout 60000
:socket-timeout 60000}]
(merge default-options
(dissoc connection :api-url :token))))
(defn slack-request
([connection endpoint]
(slack-request connection endpoint {}))
([connection endpoint query]
(let [url (-> connection verify :api-url)
params (build-params connection endpoint query)]
(send-request url params (request-options connection)))))
(defn slack-post-request
[connection endpoint post-params]
(let [api-url (-> connection verify :api-url)
url (str api-url "/" endpoint)
multiparts-params (->> (:token connection)
(hash-map :token)
(merge post-params)
stringify-keys
build-multiparts)]
(send-post-request url multiparts-params (request-options connection))))
| null | https://raw.githubusercontent.com/julienXX/clj-slack/ff5649161646f11dd8d52d1315c0e74dc723eeb7/src/clj_slack/core.clj | clojure | (ns clj-slack.core
(:require
[clj-http.client :as http]
[clojure.data.json :as json]
[clojure.tools.logging :as log])
(:import [java.net URLEncoder]))
(defn verify-api-url
[connection]
(assert
(and (string? (:api-url connection))
(and (not (empty? (:api-url connection)))
(not (nil? (re-find #"^https?:\/\/" (:api-url connection))))))
(str "clj-slack: API URL is not valid. :api-url has to be a valid URL ( usually), but is " (pr-str (:api-url connection)))))
(defn verify-token
[connection]
(assert
(and (string? (:token connection))
(not (empty? (:token connection))))
(str "clj-slack: Access token is not valid. :token has to be a non-empty string, but is " (pr-str (:token connection)))))
(defn verify
"Checks the connection map"
[connection]
(verify-api-url connection)
(when (not (contains? connection :skip-token-validation))
(verify-token connection))
connection)
(defn- send-request
"Sends a GET http request with formatted params.
Optional request options can be specified which will be passed to `clj-http` without any changes.
Can be useful to specify timeouts, etc."
[url params & [opts]]
(let [full-url (str url params)
response (http/get full-url opts)]
(if-let [body (:body response)]
(json/read-str body :key-fn clojure.core/keyword)
(log/error "Error from Slack API:" (:error response)))))
(defn- send-post-request
"Sends a POST http request with formatted params.
Optional request options can be specified which will be passed to `clj-http` without any changes.
Can be useful to specify timeouts, etc."
[url multiparts & [opts]]
(let [response (http/post url (merge {:multipart multiparts}
opts))]
(json/read-str (:body response) :key-fn clojure.core/keyword)))
(defn- make-query-string
"Transforms a map into url params"
[m]
(->> (for [[k v] m]
(str k "=" (URLEncoder/encode v "UTF-8")))
(interpose "&")
(apply str)))
(defn- build-params
"Builds the full URL (endpoint + params)"
([connection endpoint query-map]
(str "/" endpoint "?token=" (:token (verify connection)) "&" (make-query-string query-map))))
(defn- build-multiparts
"Builds an http-kit multiparts sequence"
[params]
(for [[k v] params]
(if (instance? java.io.File v)
{:name k :content v :filename (.getName v) :encoding "UTF-8"}
{:name k :content v :encoding "UTF-8"})))
(defn stringify-keys
"Creates a new map whose keys are all strings."
[m]
(into {} (for [[k v] m]
(if (keyword? k)
[(name k) v]
[(str k) v]))))
(defn- request-options
"Extracts request options from slack connection map.
Provides sensible defaults for timeouts."
[connection]
(let [default-options {:conn-timeout 60000
:socket-timeout 60000}]
(merge default-options
(dissoc connection :api-url :token))))
(defn slack-request
([connection endpoint]
(slack-request connection endpoint {}))
([connection endpoint query]
(let [url (-> connection verify :api-url)
params (build-params connection endpoint query)]
(send-request url params (request-options connection)))))
(defn slack-post-request
[connection endpoint post-params]
(let [api-url (-> connection verify :api-url)
url (str api-url "/" endpoint)
multiparts-params (->> (:token connection)
(hash-map :token)
(merge post-params)
stringify-keys
build-multiparts)]
(send-post-request url multiparts-params (request-options connection))))
| |
2a85e5d62a5923ff081ac10a25252439036c83ef183f74d5581e8c054b49d7b5 | tsloughter/kuberl | kuberl_v1beta1_cron_job_list.erl | -module(kuberl_v1beta1_cron_job_list).
-export([encode/1]).
-export_type([kuberl_v1beta1_cron_job_list/0]).
-type kuberl_v1beta1_cron_job_list() ::
#{ 'apiVersion' => binary(),
'items' := list(),
'kind' => binary(),
'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta()
}.
encode(#{ 'apiVersion' := ApiVersion,
'items' := Items,
'kind' := Kind,
'metadata' := Metadata
}) ->
#{ 'apiVersion' => ApiVersion,
'items' => Items,
'kind' => Kind,
'metadata' => Metadata
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_cron_job_list.erl | erlang | -module(kuberl_v1beta1_cron_job_list).
-export([encode/1]).
-export_type([kuberl_v1beta1_cron_job_list/0]).
-type kuberl_v1beta1_cron_job_list() ::
#{ 'apiVersion' => binary(),
'items' := list(),
'kind' => binary(),
'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta()
}.
encode(#{ 'apiVersion' := ApiVersion,
'items' := Items,
'kind' := Kind,
'metadata' := Metadata
}) ->
#{ 'apiVersion' => ApiVersion,
'items' => Items,
'kind' => Kind,
'metadata' => Metadata
}.
| |
dd8bbba1d68782c797e74e4b36412943edd40f3fa94336c8ac4142a7a5b01124 | cstar/ec2nodefinder | ec2nodefindersrv.erl | %% @hidden
%% @doc ec2-describe-instances based node discovery service.
%% @end
-module (ec2nodefindersrv).
-behaviour (gen_server).
-export ([ start_link/4, discover/0 ]).
-export ([ init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record (state, { group,
ping_timeout,
access,
secret
}).
-define(APIVERSION, "2008-12-01").
-define(ENDPOINT, "ec2.amazonaws.com").
%-=====================================================================-
%- Public -
%-=====================================================================-
start_link (Group, PingTimeout, Access, Secret)
when is_list (Group),
is_integer (PingTimeout),
is_list (Access),
is_list (Secret) ->
gen_server:start_link
({ local, ?MODULE },
?MODULE,
[ Group, PingTimeout, Access, Secret ],
[]).
discover () ->
gen_server:call (?MODULE, discover, 120000).
%-=====================================================================-
%- gen_server callbacks -
%-=====================================================================-
init ([ Group, PingTimeout, Access, Secret ]) ->
pong = net_adm:ping (node ()), % don't startup unless distributed
process_flag (trap_exit, true),
State = #state{ group = Group,
ping_timeout = PingTimeout,
access = Access,
secret = Secret },
discover (State),
{ ok, State }.
handle_call (discover, _From, State) ->
{ reply, { ok, discover (State) }, State };
handle_call (_Request, _From, State) ->
{ noreply, State }.
handle_cast (_Request, State) -> { noreply, State }.
handle_info (_Msg, State) -> { noreply, State }.
terminate (_Reason, _State) -> ok.
code_change (_OldVsn, State, _Extra) -> { ok, State }.
%-=====================================================================-
%- Private -
%-=====================================================================-
async (Fun, Timeout) ->
Me = self (),
Ref = make_ref (),
spawn (fun () ->
{ ok, _ } = timer:kill_after (Timeout),
Me ! { Ref, Fun () }
end),
Ref.
collect (Key, Timeout) ->
receive
{ Key, Status } -> Status
after Timeout ->
timeout
end.
discover (State) ->
Group = State#state.group,
Timeout = State#state.ping_timeout,
Access = State#state.access,
Secret = State#state.secret,
[ { Node, collect (Key2, Timeout) } ||
{ Node, Key2 } <-
[ { Node, start_ping (Node, Timeout) } ||
{ Host, { ok, NamesAndPorts } } <-
[ { Host, collect (Key, Timeout) } ||
{ Host, Key } <- [ { Host, start_names (Host, Timeout) }
|| Host <- awssign:describe_instances(Group, ?ENDPOINT, ?APIVERSION, Access, Secret) ] ],
{ Name, _ } <- NamesAndPorts,
Node <- [ a(Name ++ "@" ++ Host) ] ] ].
start_names (Host, Timeout) ->
async (fun () -> net_adm:names (a(Host)) end, Timeout).
start_ping (Node, Timeout) ->
async (fun () -> net_adm:ping (a(Node)) end, Timeout).
a(Name) when is_atom(Name) -> Name;
a(Name) when is_list(Name) -> list_to_atom(Name). | null | https://raw.githubusercontent.com/cstar/ec2nodefinder/42534509b88120d5581ad4a4e822bb806f3b950f/src/ec2nodefindersrv.erl | erlang | @hidden
@doc ec2-describe-instances based node discovery service.
@end
-=====================================================================-
- Public -
-=====================================================================-
-=====================================================================-
- gen_server callbacks -
-=====================================================================-
don't startup unless distributed
-=====================================================================-
- Private -
-=====================================================================- |
-module (ec2nodefindersrv).
-behaviour (gen_server).
-export ([ start_link/4, discover/0 ]).
-export ([ init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record (state, { group,
ping_timeout,
access,
secret
}).
-define(APIVERSION, "2008-12-01").
-define(ENDPOINT, "ec2.amazonaws.com").
start_link (Group, PingTimeout, Access, Secret)
when is_list (Group),
is_integer (PingTimeout),
is_list (Access),
is_list (Secret) ->
gen_server:start_link
({ local, ?MODULE },
?MODULE,
[ Group, PingTimeout, Access, Secret ],
[]).
discover () ->
gen_server:call (?MODULE, discover, 120000).
init ([ Group, PingTimeout, Access, Secret ]) ->
process_flag (trap_exit, true),
State = #state{ group = Group,
ping_timeout = PingTimeout,
access = Access,
secret = Secret },
discover (State),
{ ok, State }.
handle_call (discover, _From, State) ->
{ reply, { ok, discover (State) }, State };
handle_call (_Request, _From, State) ->
{ noreply, State }.
handle_cast (_Request, State) -> { noreply, State }.
handle_info (_Msg, State) -> { noreply, State }.
terminate (_Reason, _State) -> ok.
code_change (_OldVsn, State, _Extra) -> { ok, State }.
async (Fun, Timeout) ->
Me = self (),
Ref = make_ref (),
spawn (fun () ->
{ ok, _ } = timer:kill_after (Timeout),
Me ! { Ref, Fun () }
end),
Ref.
collect (Key, Timeout) ->
receive
{ Key, Status } -> Status
after Timeout ->
timeout
end.
discover (State) ->
Group = State#state.group,
Timeout = State#state.ping_timeout,
Access = State#state.access,
Secret = State#state.secret,
[ { Node, collect (Key2, Timeout) } ||
{ Node, Key2 } <-
[ { Node, start_ping (Node, Timeout) } ||
{ Host, { ok, NamesAndPorts } } <-
[ { Host, collect (Key, Timeout) } ||
{ Host, Key } <- [ { Host, start_names (Host, Timeout) }
|| Host <- awssign:describe_instances(Group, ?ENDPOINT, ?APIVERSION, Access, Secret) ] ],
{ Name, _ } <- NamesAndPorts,
Node <- [ a(Name ++ "@" ++ Host) ] ] ].
start_names (Host, Timeout) ->
async (fun () -> net_adm:names (a(Host)) end, Timeout).
start_ping (Node, Timeout) ->
async (fun () -> net_adm:ping (a(Node)) end, Timeout).
a(Name) when is_atom(Name) -> Name;
a(Name) when is_list(Name) -> list_to_atom(Name). |
ec6b4461088df15177dd32e84b351f6eb65add1145a9c6abb7926cde10b4af71 | ninjudd/clojure-protobuf | schema.clj | (ns flatland.protobuf.schema
(:use [flatland.useful.fn :only [fix]]
[clojure.string :only [lower-case]])
(:import (flatland.protobuf PersistentProtocolBufferMap
PersistentProtocolBufferMap$Def Extensions)
(com.google.protobuf Descriptors$Descriptor
Descriptors$FieldDescriptor
Descriptors$FieldDescriptor$Type)))
(defn extension [ext ^Descriptors$FieldDescriptor field]
(-> (.getOptions field)
(.getExtension ext)
(fix string? not-empty)))
(defn field-type [field]
(condp instance? field
Descriptors$FieldDescriptor
(if (.isRepeated ^Descriptors$FieldDescriptor field)
(condp extension field
(Extensions/counter) :counter
(Extensions/succession) :succession
(Extensions/map) :map
(Extensions/mapBy) :map-by
(Extensions/set) :set
:list)
:basic)
Descriptors$Descriptor
:struct))
(defmulti field-schema (fn [field def & _] (field-type field)))
(defn struct-schema [^Descriptors$Descriptor struct
^PersistentProtocolBufferMap$Def def
& [parents]]
(let [struct-name (.getFullName struct)]
(into {:type :struct
:name struct-name}
(when (not-any? (partial = struct-name) parents)
{:fields (into {}
(for [^Descriptors$FieldDescriptor field (.getFields struct)]
[(.intern def (.getName field))
(field-schema field def (conj parents struct-name))]))}))))
(defn basic-schema [^Descriptors$FieldDescriptor field
^PersistentProtocolBufferMap$Def def
& [parents]]
(let [java-type (keyword (lower-case (.name (.getJavaType field))))
meta-string (extension (Extensions/meta) field)]
(merge (case java-type
:message (struct-schema (.getMessageType field) def parents)
:enum {:type :enum
:values (set (map #(.clojureEnumValue def %)
(.. field getEnumType getValues)))}
{:type java-type})
(when (.hasDefaultValue field)
{:default (.getDefaultValue field)})
(when meta-string
(read-string meta-string)))))
(defn subfield [^Descriptors$FieldDescriptor field field-name]
(.findFieldByName (.getMessageType field) (name field-name)))
(defmethod field-schema :basic [field def & [parents]]
(basic-schema field def parents))
(defmethod field-schema :list [field def & [parents]]
{:type :list
:values (basic-schema field def parents)})
(defmethod field-schema :succession [field def & [parents]]
(assoc (basic-schema field def parents)
:succession true))
(defmethod field-schema :counter [field def & [parents]]
(assoc (basic-schema field def parents)
:counter true))
(defmethod field-schema :set [field def & [parents]]
{:type :set
:values (field-schema (subfield field :item) def parents)})
(defmethod field-schema :map [field def & [parents]]
{:type :map
:keys (field-schema (subfield field :key) def parents)
:values (field-schema (subfield field :val) def parents)})
(defmethod field-schema :map-by [field def & [parents]]
(let [map-by (extension (Extensions/mapBy) field)]
{:type :map
:keys (field-schema (subfield field map-by) def parents)
:values (basic-schema field def parents)}))
(defmethod field-schema :struct [field def & [parents]]
(struct-schema field def parents))
| null | https://raw.githubusercontent.com/ninjudd/clojure-protobuf/63d7192b35c3941cdaf1e13219a933b9f3286aac/src/flatland/protobuf/schema.clj | clojure | (ns flatland.protobuf.schema
(:use [flatland.useful.fn :only [fix]]
[clojure.string :only [lower-case]])
(:import (flatland.protobuf PersistentProtocolBufferMap
PersistentProtocolBufferMap$Def Extensions)
(com.google.protobuf Descriptors$Descriptor
Descriptors$FieldDescriptor
Descriptors$FieldDescriptor$Type)))
(defn extension [ext ^Descriptors$FieldDescriptor field]
(-> (.getOptions field)
(.getExtension ext)
(fix string? not-empty)))
(defn field-type [field]
(condp instance? field
Descriptors$FieldDescriptor
(if (.isRepeated ^Descriptors$FieldDescriptor field)
(condp extension field
(Extensions/counter) :counter
(Extensions/succession) :succession
(Extensions/map) :map
(Extensions/mapBy) :map-by
(Extensions/set) :set
:list)
:basic)
Descriptors$Descriptor
:struct))
(defmulti field-schema (fn [field def & _] (field-type field)))
(defn struct-schema [^Descriptors$Descriptor struct
^PersistentProtocolBufferMap$Def def
& [parents]]
(let [struct-name (.getFullName struct)]
(into {:type :struct
:name struct-name}
(when (not-any? (partial = struct-name) parents)
{:fields (into {}
(for [^Descriptors$FieldDescriptor field (.getFields struct)]
[(.intern def (.getName field))
(field-schema field def (conj parents struct-name))]))}))))
(defn basic-schema [^Descriptors$FieldDescriptor field
^PersistentProtocolBufferMap$Def def
& [parents]]
(let [java-type (keyword (lower-case (.name (.getJavaType field))))
meta-string (extension (Extensions/meta) field)]
(merge (case java-type
:message (struct-schema (.getMessageType field) def parents)
:enum {:type :enum
:values (set (map #(.clojureEnumValue def %)
(.. field getEnumType getValues)))}
{:type java-type})
(when (.hasDefaultValue field)
{:default (.getDefaultValue field)})
(when meta-string
(read-string meta-string)))))
(defn subfield [^Descriptors$FieldDescriptor field field-name]
(.findFieldByName (.getMessageType field) (name field-name)))
(defmethod field-schema :basic [field def & [parents]]
(basic-schema field def parents))
(defmethod field-schema :list [field def & [parents]]
{:type :list
:values (basic-schema field def parents)})
(defmethod field-schema :succession [field def & [parents]]
(assoc (basic-schema field def parents)
:succession true))
(defmethod field-schema :counter [field def & [parents]]
(assoc (basic-schema field def parents)
:counter true))
(defmethod field-schema :set [field def & [parents]]
{:type :set
:values (field-schema (subfield field :item) def parents)})
(defmethod field-schema :map [field def & [parents]]
{:type :map
:keys (field-schema (subfield field :key) def parents)
:values (field-schema (subfield field :val) def parents)})
(defmethod field-schema :map-by [field def & [parents]]
(let [map-by (extension (Extensions/mapBy) field)]
{:type :map
:keys (field-schema (subfield field map-by) def parents)
:values (basic-schema field def parents)}))
(defmethod field-schema :struct [field def & [parents]]
(struct-schema field def parents))
| |
65fd7f12de3c0bac1499d370c90836104908d08789eb8868cdb41290c2beac15 | albertoruiz/easyVision | mineig.hs | {-# LANGUAGE RecordWildCards, TemplateHaskell #-}
import Vision.GUI
import Image.Processing
autoParam "DemoParam" ""
[ ("sigma","Float",realParam 3 0.1 10)
]
data Experiment = Experiment
{ σ :: Float
, orig :: Image RGB
, mono :: Image Float
, smooth :: Image Float
, grads :: Grads
, e1 :: Image Float
, e2 :: Image Float
, d :: Image Float
}
work DemoParam{..} x = Experiment {..}
where
σ = sigma
orig = rgb x
mono = grayf x
(smooth, grads) = scalingGrad sigma (mono, gradients mono)
(e1,e2,d) = eigs grads
sqr32f x = x |*| x
eigs Grads{..} = (l1,l2,t)
where
d = sqrt32f (sqr32f (gxx |-| gyy) |+| sqr32f (2 .* gxy))
s = gxx |+| gyy
l1 = s |+| d
l2 = s |-| d
t = abs32f ( gxx |-| gyy )
t = d
t = abs32f ( gxx |-| gyy ) |-| d
--t = l1 |-| l2
main = run $ withParam work
-- >>> observe "source" mono
>>> sMonitor "features" shfeat
-- >>> sMonitor "grayscale" sh
scalingGrad σ (x,g) = (s x, r)
where
s = gaussS σ
dx = σ .* s (gx g)
dy = σ .* s (gy g)
r = Grads { gx = dx
, gy = dy
, gm = sqrt32f $ dx |*| dx |+| dy |*| dy
, gxx = σ^2 .* s (gxx g)
, gyy = σ^2 .* s (gyy g)
, gxy = σ^2 .* s (gxy g)
}
shfeat _roi Experiment{..} =
[ Draw $ smooth
, Draw $ 1/2 .* gm grads
, Draw $ tosig $ 1/7 .* e1
, Draw $ tosig $ 1/7 .* e2
, Draw $ tosig $ 1/49 .* (e1 |*| e2)
, Draw $ tosig $ gx (grads)
, Draw $ tosig $ (1/5) .* (gxx grads)
, Draw $ 1/20 .* (abs32f e1 |+| abs32f e2)
, Draw $ tosig $ 1/10 .* (gxx grads |+| gyy grads)
, Draw $ tosig $ 1/20 .* (abs32f e1 |-| abs32f e2)
, Draw $ 1/10 .* d
, Draw $ 1/10 .* ( d |-| abs32f (gxx grads |+| gyy grads))
, Draw $ tosig $ 1/10 .* hessian grads
]
where
tosig = scale32f8u (-2) 2
sh _roi Experiment{..} =
[ Draw ((-10) .* hessian grads)
, Draw ((-10/4) .* (e1 |*| e2))
, Draw $ scale32f8u (-1) 1 (hessian grads)
, Draw smooth, Draw (gm grads)
, Draw e1
, Draw (e2)
, Draw ((-1) .* e1)
, Draw ((-1) .* e2)
, Draw $ scale32f8u (-1) 1 e1
, Draw $ scale32f8u (-1) 1 e2
, Draw $ (1/3) .* d
, Draw $ scale32f8u (-1) 1 d
, Draw $ d .>. 0
]
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/examples/mineig.hs | haskell | # LANGUAGE RecordWildCards, TemplateHaskell #
t = l1 |-| l2
>>> observe "source" mono
>>> sMonitor "grayscale" sh |
import Vision.GUI
import Image.Processing
autoParam "DemoParam" ""
[ ("sigma","Float",realParam 3 0.1 10)
]
data Experiment = Experiment
{ σ :: Float
, orig :: Image RGB
, mono :: Image Float
, smooth :: Image Float
, grads :: Grads
, e1 :: Image Float
, e2 :: Image Float
, d :: Image Float
}
work DemoParam{..} x = Experiment {..}
where
σ = sigma
orig = rgb x
mono = grayf x
(smooth, grads) = scalingGrad sigma (mono, gradients mono)
(e1,e2,d) = eigs grads
sqr32f x = x |*| x
eigs Grads{..} = (l1,l2,t)
where
d = sqrt32f (sqr32f (gxx |-| gyy) |+| sqr32f (2 .* gxy))
s = gxx |+| gyy
l1 = s |+| d
l2 = s |-| d
t = abs32f ( gxx |-| gyy )
t = d
t = abs32f ( gxx |-| gyy ) |-| d
main = run $ withParam work
>>> sMonitor "features" shfeat
scalingGrad σ (x,g) = (s x, r)
where
s = gaussS σ
dx = σ .* s (gx g)
dy = σ .* s (gy g)
r = Grads { gx = dx
, gy = dy
, gm = sqrt32f $ dx |*| dx |+| dy |*| dy
, gxx = σ^2 .* s (gxx g)
, gyy = σ^2 .* s (gyy g)
, gxy = σ^2 .* s (gxy g)
}
shfeat _roi Experiment{..} =
[ Draw $ smooth
, Draw $ 1/2 .* gm grads
, Draw $ tosig $ 1/7 .* e1
, Draw $ tosig $ 1/7 .* e2
, Draw $ tosig $ 1/49 .* (e1 |*| e2)
, Draw $ tosig $ gx (grads)
, Draw $ tosig $ (1/5) .* (gxx grads)
, Draw $ 1/20 .* (abs32f e1 |+| abs32f e2)
, Draw $ tosig $ 1/10 .* (gxx grads |+| gyy grads)
, Draw $ tosig $ 1/20 .* (abs32f e1 |-| abs32f e2)
, Draw $ 1/10 .* d
, Draw $ 1/10 .* ( d |-| abs32f (gxx grads |+| gyy grads))
, Draw $ tosig $ 1/10 .* hessian grads
]
where
tosig = scale32f8u (-2) 2
sh _roi Experiment{..} =
[ Draw ((-10) .* hessian grads)
, Draw ((-10/4) .* (e1 |*| e2))
, Draw $ scale32f8u (-1) 1 (hessian grads)
, Draw smooth, Draw (gm grads)
, Draw e1
, Draw (e2)
, Draw ((-1) .* e1)
, Draw ((-1) .* e2)
, Draw $ scale32f8u (-1) 1 e1
, Draw $ scale32f8u (-1) 1 e2
, Draw $ (1/3) .* d
, Draw $ scale32f8u (-1) 1 d
, Draw $ d .>. 0
]
|
065ba59b280d8e13f20f60ac8ee05e437df4c601a754db529c28901c246e2751 | alphagov/govuk-guix | cuirass-specifications.scm | (define-module (gds build-jobs govuk cuirass-specifications)
#:export (govuk-packages))
(define govuk-packages
`((#:name . "govuk-packages")
(#:url . "govuk-guix")
(#:load-path . ".")
(#:file . "gds/build-jobs/cuirass-entry-point.scm")
(#:proc . govuk-packages-jobs)
(#:arguments . ())
(#:branch . "master")
(#:no-compile? . 1)))
(list govuk-packages)
| null | https://raw.githubusercontent.com/alphagov/govuk-guix/dea8c26d2ae882d0278be5c745e23abb25d4a4e2/gds/build-jobs/govuk/cuirass-specifications.scm | scheme | (define-module (gds build-jobs govuk cuirass-specifications)
#:export (govuk-packages))
(define govuk-packages
`((#:name . "govuk-packages")
(#:url . "govuk-guix")
(#:load-path . ".")
(#:file . "gds/build-jobs/cuirass-entry-point.scm")
(#:proc . govuk-packages-jobs)
(#:arguments . ())
(#:branch . "master")
(#:no-compile? . 1)))
(list govuk-packages)
| |
24a9bf0152c1f1393513a8e822f923a049cb6d12e35550ac5014d1f3c454457d | rescript-lang/syntax | obj.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Operations on internal representations of values.
Not for the casual user.
*)
type t
external repr : 'a -> t = "%identity"
external obj : t -> 'a = "%identity"
external magic : 'a -> 'b = "%identity"
val [@inline always] is_block : t -> bool
external is_int : t -> bool = "%obj_is_int"
external tag : t -> int = "caml_obj_tag"
external size : t -> int = "%obj_size"
external reachable_words : t -> int = "caml_obj_reachable_words"
*
Computes the total size ( in words , including the headers ) of all
heap blocks accessible from the argument . Statically
allocated blocks are excluded .
@Since 4.04
Computes the total size (in words, including the headers) of all
heap blocks accessible from the argument. Statically
allocated blocks are excluded.
@Since 4.04
*)
external field : t -> int -> t = "%obj_field"
* When using flambda :
[ set_field ] MUST NOT be called on immutable blocks . ( Blocks allocated
in C stubs , or with [ new_block ] below , are always considered mutable . )
The same goes for [ set_double_field ] and [ set_tag ] . However , for
[ set_tag ] , in the case of immutable blocks where the middle - end optimizers
never see code that discriminates on their tag ( for example records ) , the
operation should be safe . Such uses are nonetheless discouraged .
For experts only :
[ set_field ] et al can be made safe by first wrapping the block in
{ ! Sys.opaque_identity } , so any information about its contents will not
be propagated .
[set_field] MUST NOT be called on immutable blocks. (Blocks allocated
in C stubs, or with [new_block] below, are always considered mutable.)
The same goes for [set_double_field] and [set_tag]. However, for
[set_tag], in the case of immutable blocks where the middle-end optimizers
never see code that discriminates on their tag (for example records), the
operation should be safe. Such uses are nonetheless discouraged.
For experts only:
[set_field] et al can be made safe by first wrapping the block in
{!Sys.opaque_identity}, so any information about its contents will not
be propagated.
*)
external set_field : t -> int -> t -> unit = "%obj_set_field"
external set_tag : t -> int -> unit = "caml_obj_set_tag"
@since 3.11.2
val [@inline always] set_double_field : t -> int -> float -> unit
@since 3.11.2
external new_block : int -> int -> t = "caml_obj_block"
external dup : t -> t = "caml_obj_dup"
external truncate : t -> int -> unit = "caml_obj_truncate"
external add_offset : t -> Int32.t -> t = "caml_obj_add_offset"
@since 3.12.0
val first_non_constant_constructor_tag : int
val last_non_constant_constructor_tag : int
val lazy_tag : int
val closure_tag : int
val object_tag : int
val infix_tag : int
val forward_tag : int
val no_scan_tag : int
val abstract_tag : int
val string_tag : int (* both [string] and [bytes] *)
val double_tag : int
val double_array_tag : int
val custom_tag : int
val final_tag : int
[@@ocaml.deprecated "Replaced by custom_tag."]
val int_tag : int
val out_of_heap_tag : int
should never happen @since 3.11.0
val extension_constructor : 'a -> extension_constructor
val [@inline always] extension_name : extension_constructor -> string
val [@inline always] extension_id : extension_constructor -> int
* The following two functions are deprecated . Use module { ! Marshal }
instead .
instead. *)
val marshal : t -> bytes
[@@ocaml.deprecated "Use Marshal.to_bytes instead."]
val unmarshal : bytes -> int -> t * int
[@@ocaml.deprecated "Use Marshal.from_bytes and Marshal.total_size instead."]
module Ephemeron: sig
* Ephemeron with arbitrary arity and untyped
type obj_t = t
(** alias for {!Obj.t} *)
type t
* an ephemeron cf { ! Ephemeron }
val create: int -> t
* [ create n ] returns an ephemeron with [ n ] keys .
All the keys and the data are initially empty
All the keys and the data are initially empty *)
val length: t -> int
(** return the number of keys *)
val get_key: t -> int -> obj_t option
* Same as { ! Ephemeron . }
val get_key_copy: t -> int -> obj_t option
* Same as { ! Ephemeron . K1.get_key_copy }
val set_key: t -> int -> obj_t -> unit
* Same as { ! Ephemeron . K1.set_key }
val unset_key: t -> int -> unit
* Same as { ! Ephemeron . K1.unset_key }
val check_key: t -> int -> bool
* Same as { ! Ephemeron . }
val blit_key : t -> int -> t -> int -> int -> unit
* Same as { ! Ephemeron . }
val get_data: t -> obj_t option
* Same as { ! Ephemeron . K1.get_data }
val get_data_copy: t -> obj_t option
* Same as { ! Ephemeron . K1.get_data_copy }
val set_data: t -> obj_t -> unit
* Same as { ! Ephemeron . }
val unset_data: t -> unit
* Same as { ! Ephemeron . K1.unset_data }
val check_data: t -> bool
* Same as { ! Ephemeron . K1.check_data }
val blit_data : t -> t -> unit
* Same as { ! Ephemeron . K1.blit_data }
end
| null | https://raw.githubusercontent.com/rescript-lang/syntax/891fe05b88be2aa4443a951a0d16088b69b2e279/compiler-libs-406/obj.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Operations on internal representations of values.
Not for the casual user.
both [string] and [bytes]
* alias for {!Obj.t}
* return the number of keys | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
type t
external repr : 'a -> t = "%identity"
external obj : t -> 'a = "%identity"
external magic : 'a -> 'b = "%identity"
val [@inline always] is_block : t -> bool
external is_int : t -> bool = "%obj_is_int"
external tag : t -> int = "caml_obj_tag"
external size : t -> int = "%obj_size"
external reachable_words : t -> int = "caml_obj_reachable_words"
*
Computes the total size ( in words , including the headers ) of all
heap blocks accessible from the argument . Statically
allocated blocks are excluded .
@Since 4.04
Computes the total size (in words, including the headers) of all
heap blocks accessible from the argument. Statically
allocated blocks are excluded.
@Since 4.04
*)
external field : t -> int -> t = "%obj_field"
* When using flambda :
[ set_field ] MUST NOT be called on immutable blocks . ( Blocks allocated
in C stubs , or with [ new_block ] below , are always considered mutable . )
The same goes for [ set_double_field ] and [ set_tag ] . However , for
[ set_tag ] , in the case of immutable blocks where the middle - end optimizers
never see code that discriminates on their tag ( for example records ) , the
operation should be safe . Such uses are nonetheless discouraged .
For experts only :
[ set_field ] et al can be made safe by first wrapping the block in
{ ! Sys.opaque_identity } , so any information about its contents will not
be propagated .
[set_field] MUST NOT be called on immutable blocks. (Blocks allocated
in C stubs, or with [new_block] below, are always considered mutable.)
The same goes for [set_double_field] and [set_tag]. However, for
[set_tag], in the case of immutable blocks where the middle-end optimizers
never see code that discriminates on their tag (for example records), the
operation should be safe. Such uses are nonetheless discouraged.
For experts only:
[set_field] et al can be made safe by first wrapping the block in
{!Sys.opaque_identity}, so any information about its contents will not
be propagated.
*)
external set_field : t -> int -> t -> unit = "%obj_set_field"
external set_tag : t -> int -> unit = "caml_obj_set_tag"
@since 3.11.2
val [@inline always] set_double_field : t -> int -> float -> unit
@since 3.11.2
external new_block : int -> int -> t = "caml_obj_block"
external dup : t -> t = "caml_obj_dup"
external truncate : t -> int -> unit = "caml_obj_truncate"
external add_offset : t -> Int32.t -> t = "caml_obj_add_offset"
@since 3.12.0
val first_non_constant_constructor_tag : int
val last_non_constant_constructor_tag : int
val lazy_tag : int
val closure_tag : int
val object_tag : int
val infix_tag : int
val forward_tag : int
val no_scan_tag : int
val abstract_tag : int
val double_tag : int
val double_array_tag : int
val custom_tag : int
val final_tag : int
[@@ocaml.deprecated "Replaced by custom_tag."]
val int_tag : int
val out_of_heap_tag : int
should never happen @since 3.11.0
val extension_constructor : 'a -> extension_constructor
val [@inline always] extension_name : extension_constructor -> string
val [@inline always] extension_id : extension_constructor -> int
* The following two functions are deprecated . Use module { ! Marshal }
instead .
instead. *)
val marshal : t -> bytes
[@@ocaml.deprecated "Use Marshal.to_bytes instead."]
val unmarshal : bytes -> int -> t * int
[@@ocaml.deprecated "Use Marshal.from_bytes and Marshal.total_size instead."]
module Ephemeron: sig
* Ephemeron with arbitrary arity and untyped
type obj_t = t
type t
* an ephemeron cf { ! Ephemeron }
val create: int -> t
* [ create n ] returns an ephemeron with [ n ] keys .
All the keys and the data are initially empty
All the keys and the data are initially empty *)
val length: t -> int
val get_key: t -> int -> obj_t option
* Same as { ! Ephemeron . }
val get_key_copy: t -> int -> obj_t option
* Same as { ! Ephemeron . K1.get_key_copy }
val set_key: t -> int -> obj_t -> unit
* Same as { ! Ephemeron . K1.set_key }
val unset_key: t -> int -> unit
* Same as { ! Ephemeron . K1.unset_key }
val check_key: t -> int -> bool
* Same as { ! Ephemeron . }
val blit_key : t -> int -> t -> int -> int -> unit
* Same as { ! Ephemeron . }
val get_data: t -> obj_t option
* Same as { ! Ephemeron . K1.get_data }
val get_data_copy: t -> obj_t option
* Same as { ! Ephemeron . K1.get_data_copy }
val set_data: t -> obj_t -> unit
* Same as { ! Ephemeron . }
val unset_data: t -> unit
* Same as { ! Ephemeron . K1.unset_data }
val check_data: t -> bool
* Same as { ! Ephemeron . K1.check_data }
val blit_data : t -> t -> unit
* Same as { ! Ephemeron . K1.blit_data }
end
|
3b7970b2ec06ca721e9cc65e84ff7aa4cadfce2839b4b6e52ef0ffea0e774f9d | rowangithub/DOrder | 416_repeat.ml | (*
USED: PLDI2011 as repeat
*)
let succ x = x + 1
let rec repeat (f:int->int) n s =
if n = 0 then
s
else
f (repeat f (n-1) s)
let main n = assert (repeat succ n 0 = n)
| null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/mochi2/benchs/416_repeat.ml | ocaml |
USED: PLDI2011 as repeat
|
let succ x = x + 1
let rec repeat (f:int->int) n s =
if n = 0 then
s
else
f (repeat f (n-1) s)
let main n = assert (repeat succ n 0 = n)
|
c9cc8c064e4e55367c7b01104c5df67f9c12aed893a75a5b98b21a56d96c7f42 | Decentralized-Pictures/T4L3NT | client_proto_contracts.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
open Protocol
open Alpha_context
module ContractEntity = struct
include Contract (* t, Compare, encoding *)
let of_source s =
Contract.of_b58check s |> Environment.wrap_tzresult
|> record_trace_eval (fun () -> error_of_fmt "bad contract notation")
|> Lwt.return
let to_source s = return (Contract.to_b58check s)
let name = "contract"
end
module RawContractAlias = Client_aliases.Alias (ContractEntity)
module ContractAlias = struct
let find cctxt s =
RawContractAlias.find_opt cctxt s >>=? function
| Some v -> return (s, v)
| None -> (
Client_keys.Public_key_hash.find_opt cctxt s >>=? function
| Some v -> return (s, Contract.implicit_contract v)
| None -> failwith "no contract or key named %s" s)
let find_key cctxt name =
Client_keys.Public_key_hash.find cctxt name >>=? fun v ->
return (name, Contract.implicit_contract v)
let rev_find cctxt c =
match Contract.is_implicit c with
| Some hash -> (
Client_keys.Public_key_hash.rev_find cctxt hash >>=? function
| Some name -> return_some ("key:" ^ name)
| None -> return_none)
| None -> RawContractAlias.rev_find cctxt c
let get_contract cctxt s =
match String.split ~limit:1 ':' s with
| ["key"; key] -> find_key cctxt key
| _ -> find cctxt s
let autocomplete cctxt =
Client_keys.Public_key_hash.autocomplete cctxt >>=? fun keys ->
RawContractAlias.autocomplete cctxt >>=? fun contracts ->
return (List.map (( ^ ) "key:") keys @ contracts)
let alias_param ?(name = "name") ?(desc = "existing contract alias") next =
let desc =
desc ^ "\n"
^ "Can be a contract alias or a key alias (autodetected in order).\n\
Use 'key:name' to force the later."
in
Clic.(
param
~name
~desc
(parameter ~autocomplete (fun cctxt p -> get_contract cctxt p))
next)
let find_destination cctxt s =
match String.split ~limit:1 ':' s with
| ["alias"; alias] -> find cctxt alias
| ["key"; text] ->
Client_keys.Public_key_hash.find cctxt text >>=? fun v ->
return (s, Contract.implicit_contract v)
| _ -> (
find cctxt s >>= function
| Ok v -> return v
| Error k_errs -> (
ContractEntity.of_source s >>= function
| Ok v -> return (s, v)
| Error c_errs -> Lwt.return_error (k_errs @ c_errs)))
let destination_parameter () =
Clic.parameter
~autocomplete:(fun cctxt ->
autocomplete cctxt >>=? fun list1 ->
Client_keys.Public_key_hash.autocomplete cctxt >>=? fun list2 ->
return (list1 @ list2))
find_destination
let destination_param ?(name = "dst") ?(desc = "destination contract") next =
let desc =
String.concat
"\n"
[
desc;
"Can be an alias, a key, or a literal (autodetected in order).\n\
Use 'text:literal', 'alias:name', 'key:name' to force.";
]
in
Clic.param ~name ~desc (destination_parameter ()) next
let destination_arg ?(name = "dst") ?(doc = "destination contract") () =
let doc =
String.concat
"\n"
[
doc;
"Can be an alias, a key, or a literal (autodetected in order).\n\
Use 'text:literal', 'alias:name', 'key:name' to force.";
]
in
Clic.arg ~long:name ~doc ~placeholder:name (destination_parameter ())
let name cctxt contract =
rev_find cctxt contract >>=? function
| None -> return (Contract.to_b58check contract)
| Some name -> return name
end
let list_contracts cctxt =
RawContractAlias.load cctxt >>=? fun raw_contracts ->
List.map_s (fun (n, v) -> Lwt.return ("", n, v)) raw_contracts
>>= fun contracts ->
Client_keys.Public_key_hash.load cctxt >>=? fun keys ->
(* List accounts (implicit contracts of identities) *)
List.map_es
(fun (n, v) ->
RawContractAlias.mem cctxt n >>=? fun mem ->
let p = if mem then "key:" else "" in
let v' = Contract.implicit_contract v in
return (p, n, v'))
keys
>>=? fun accounts -> return (contracts @ accounts)
let get_delegate cctxt ~chain ~block source =
Alpha_services.Contract.delegate_opt cctxt (chain, block) source
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_alpha/lib_client/client_proto_contracts.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
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.
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
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
t, Compare, encoding
List accounts (implicit contracts of identities) | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Protocol
open Alpha_context
module ContractEntity = struct
let of_source s =
Contract.of_b58check s |> Environment.wrap_tzresult
|> record_trace_eval (fun () -> error_of_fmt "bad contract notation")
|> Lwt.return
let to_source s = return (Contract.to_b58check s)
let name = "contract"
end
module RawContractAlias = Client_aliases.Alias (ContractEntity)
module ContractAlias = struct
let find cctxt s =
RawContractAlias.find_opt cctxt s >>=? function
| Some v -> return (s, v)
| None -> (
Client_keys.Public_key_hash.find_opt cctxt s >>=? function
| Some v -> return (s, Contract.implicit_contract v)
| None -> failwith "no contract or key named %s" s)
let find_key cctxt name =
Client_keys.Public_key_hash.find cctxt name >>=? fun v ->
return (name, Contract.implicit_contract v)
let rev_find cctxt c =
match Contract.is_implicit c with
| Some hash -> (
Client_keys.Public_key_hash.rev_find cctxt hash >>=? function
| Some name -> return_some ("key:" ^ name)
| None -> return_none)
| None -> RawContractAlias.rev_find cctxt c
let get_contract cctxt s =
match String.split ~limit:1 ':' s with
| ["key"; key] -> find_key cctxt key
| _ -> find cctxt s
let autocomplete cctxt =
Client_keys.Public_key_hash.autocomplete cctxt >>=? fun keys ->
RawContractAlias.autocomplete cctxt >>=? fun contracts ->
return (List.map (( ^ ) "key:") keys @ contracts)
let alias_param ?(name = "name") ?(desc = "existing contract alias") next =
let desc =
desc ^ "\n"
^ "Can be a contract alias or a key alias (autodetected in order).\n\
Use 'key:name' to force the later."
in
Clic.(
param
~name
~desc
(parameter ~autocomplete (fun cctxt p -> get_contract cctxt p))
next)
let find_destination cctxt s =
match String.split ~limit:1 ':' s with
| ["alias"; alias] -> find cctxt alias
| ["key"; text] ->
Client_keys.Public_key_hash.find cctxt text >>=? fun v ->
return (s, Contract.implicit_contract v)
| _ -> (
find cctxt s >>= function
| Ok v -> return v
| Error k_errs -> (
ContractEntity.of_source s >>= function
| Ok v -> return (s, v)
| Error c_errs -> Lwt.return_error (k_errs @ c_errs)))
let destination_parameter () =
Clic.parameter
~autocomplete:(fun cctxt ->
autocomplete cctxt >>=? fun list1 ->
Client_keys.Public_key_hash.autocomplete cctxt >>=? fun list2 ->
return (list1 @ list2))
find_destination
let destination_param ?(name = "dst") ?(desc = "destination contract") next =
let desc =
String.concat
"\n"
[
desc;
"Can be an alias, a key, or a literal (autodetected in order).\n\
Use 'text:literal', 'alias:name', 'key:name' to force.";
]
in
Clic.param ~name ~desc (destination_parameter ()) next
let destination_arg ?(name = "dst") ?(doc = "destination contract") () =
let doc =
String.concat
"\n"
[
doc;
"Can be an alias, a key, or a literal (autodetected in order).\n\
Use 'text:literal', 'alias:name', 'key:name' to force.";
]
in
Clic.arg ~long:name ~doc ~placeholder:name (destination_parameter ())
let name cctxt contract =
rev_find cctxt contract >>=? function
| None -> return (Contract.to_b58check contract)
| Some name -> return name
end
let list_contracts cctxt =
RawContractAlias.load cctxt >>=? fun raw_contracts ->
List.map_s (fun (n, v) -> Lwt.return ("", n, v)) raw_contracts
>>= fun contracts ->
Client_keys.Public_key_hash.load cctxt >>=? fun keys ->
List.map_es
(fun (n, v) ->
RawContractAlias.mem cctxt n >>=? fun mem ->
let p = if mem then "key:" else "" in
let v' = Contract.implicit_contract v in
return (p, n, v'))
keys
>>=? fun accounts -> return (contracts @ accounts)
let get_delegate cctxt ~chain ~block source =
Alpha_services.Contract.delegate_opt cctxt (chain, block) source
|
bb1585ae94a00c664b83dd25f51d2df9aca180505318bbd67a4cb55d23dbe254 | projectcs13/sensor-cloud | plus_srv.erl | %%%-------------------------------------------------------------------
File : plus_srv.erl
@author
2012 Google
%%% @doc Example code on interacting with the discovery API
%%%
%%% @end
%%%
@since 2012 - 11 - 05
%%%-------------------------------------------------------------------
-module(plus_srv).
-author('Ian Barber').
-behaviour(gen_server).
%% API
-export([start_link/4,list_apis/0,set_api/1,call_method/3,
list_methods/0,list_scopes/1,gen_token_url/1,exchange_token/2,get_url/1]).
%% gen_server callbacks
-export([init/1, handle_call/3,handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {methods, baseurl, discovery, apikey, authtoken, oauth2state, clientid, clientsecret, redirecturl}).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
( ) - > { ok , Pid } | ignore | { error , Error }
%% @doc Starts the server
%% @end
%%--------------------------------------------------------------------
start_link(APIKey, ClientID, ClientSecret, RedirectURL) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [APIKey, ClientID, ClientSecret, RedirectURL], []).
%%--------------------------------------------------------------------
calL_method ( ) - > { ok , Results } | { error , Error }
%% @doc Call a method and retrieve the resulting JSON document
%% @end
%%--------------------------------------------------------------------
call_method(Service, Parameters, Body)->
gen_server:call(?MODULE,{call_method,Service,Parameters, Body}).
%%--------------------------------------------------------------------
list_apis ( ) - > { ok , Methods } | { error , Error }
%% @doc Returns a list of discoverable APIs
%% @end
%%--------------------------------------------------------------------
list_apis()->
gen_server:call(?MODULE,{list_apis}).
%%--------------------------------------------------------------------
( ) - > { k | { error , Error }
%% @doc Set the server to operate against a specific API
%% @end
%%--------------------------------------------------------------------
set_api(ApiRestUrl)->
gen_server:call(?MODULE,{set_api, ApiRestUrl}).
%%--------------------------------------------------------------------
( ) - > { ok , Methods } | { error , Error }
%% @doc Returns a list of methods strings and aritys
%% @end
%%--------------------------------------------------------------------
list_methods()->
gen_server:call(?MODULE,{list_methods}).
%%--------------------------------------------------------------------
list_scopes ( ) - > { ok , } | { error , Error }
%% @doc Returns a list of methods scopes. If empty, does not require auth
%% @end
%%--------------------------------------------------------------------
list_scopes(Method)->
gen_server:call(?MODULE,{list_scopes,Method}).
%%--------------------------------------------------------------------
%% @spec gen_token_url() -> {ok,Url} | {error,Error}
%% @doc Returns a URL to pass to the user to authenticate the app
%% @end
%%--------------------------------------------------------------------
gen_token_url(Scopes)->
gen_server:call(?MODULE,{gen_token_url,Scopes}).
%%--------------------------------------------------------------------
( ) - > ok | { error , Error }
%% @doc Returns a URL to pass to the user to authenticate the app
%% @end
%%--------------------------------------------------------------------
exchange_token(Code, State)->
gen_server:call(?MODULE,{exchange_token,Code,State}).
%%====================================================================
%% gen_server callbacks
%%====================================================================
init([APIKey, ClientID, ClientSecret, RedirectURL]) ->
inets:start(),
ssl:start(),
{ok, #state{apikey=APIKey, clientid=ClientID, clientsecret=ClientSecret, redirecturl=RedirectURL,
methods=[], baseurl=[], discovery=[], authtoken=[]}}.
%% Directory calls
handle_call({list_apis}, _From, State) ->
[Apis, Discovery] = get_api_list(State#state.discovery),
{reply, Apis, State#state{discovery=Discovery}};
handle_call({set_api, ApiRestUrl}, _From, State) ->
[Methods, BaseURL] = get_api_methods(ApiRestUrl),
{reply, ok, State#state{methods=Methods,baseurl=BaseURL}};
%% OAuth Calls
handle_call({gen_token_url, Scopes}, _From, State) ->
[URL, OAuth2State] = get_authurl(Scopes, State),
{reply, URL, State#state{oauth2state=OAuth2State}};
handle_call({exchange_token, Code, _}, _From, State) ->
handle_call({exchange_token , Code , OAuth2State } , _ From , State ) when OAuth2State = = State#state.oauth2state - >
{ok, Token} = get_authtoken(Code, State),
{reply, Token, State#state{authtoken=Token}};
handle_call({exchange_token, _, _}, _From, State) ->
{reply, {error, "Invalid State"}, State};
%% Method calls
%% Error case for following calls - requires API to be set.
handle_call(_, _From, State) when length(State#state.methods)==0 ->
{reply, {error, "No API Set"}, State};
handle_call({list_methods}, _From, State) ->
{reply, get_method_names(State#state.methods), State};
handle_call({list_scopes, Method}, _From, State) ->
{reply, get_method_scopes(Method, State#state.methods), State};
handle_call({call_method, Service, Parameters, Body}, _From, State) ->
Reply = call_method(Service, Parameters, Body, State#state.methods, State),
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%====================================================================
%% helper functions
%%====================================================================
get_url(Request) ->
case Request of
{ok, {{_Version, 200, _ReasonPhrase}, _Headers, Body}}->
{struct, Json} = mochijson2:decode(Body),
{ok, Json};
{ok, {{_Version, Code, _ReasonPhrase}, _Headers, _Body}}->
{error,Code};
{error,Error}->
{error,Error}
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% List APIs %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
get_api_list([]) ->
case get_url(httpc:request(get,{"",[]},[],[])) of
{error, Error} -> {stop, Error};
{ok, Json} ->
get_api_list(Json)
end;
get_api_list(Discovery) ->
Apis = proplists:get_value(<<"items">>, Discovery),
[get_apis(Apis), Discovery].
get_api_methods(ApiRestUrl) ->
case get_url(httpc:request(get,{ApiRestUrl,[]},[],[])) of
{error, Error} -> {stop, Error};
{ok, Json} ->
Methods = get_resources(Json),
BaseURL = binary_to_list(proplists:get_value(<<"baseUrl">>, Json)),
[Methods, BaseURL]
end.
get_apis([]) ->
[];
get_apis([H|T]) ->
{struct, API} = H,
[{binary_to_list(proplists:get_value(<<"name">>, API)),
binary_to_list(proplists:get_value(<<"discoveryRestUrl">>, API))}|get_apis(T)].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Call Methods %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
call_method(Service, Parameters, Body, [[Service, Method]|_], State) ->
If we have an APIKey and do n't need OAuth , include that
BaseString = get_base_params(State#state.apikey, State#state.authtoken),
Headers = get_headers(State),
%% URL encode args,and paste on to end of string
QS = lists:foldl(fun({Q,V}, QS) -> QS ++ "&" ++ Q ++ "=" ++ V end,
BaseString, Parameters),
%% Join method path on to uri
Path = get_path(binary_to_list(proplists:get_value(<<"path">>, Method)), Parameters),
Url = State#state.baseurl ++ Path ++ "?" ++ QS,
%% erlang:display(Headers), %%% DEBUG %%%
erlang : ) , % % % DEBUG % % %
Switch on method
[HttpMethod, Request] = case proplists:get_value(<<"httpMethod">>, Method) of
<<"GET">> -> [get, {Url, Headers}];
<<"POST">> -> [post, {Url, Headers, "application/json", Body}]
end,
%% Retrieve response
[ HttpMethod , Request ] ;
get_url(httpc:request(HttpMethod, Request, [], []));
call_method(Service, Parameters, Body, [_|Methods], State) ->
call_method(Service, Parameters, Body, Methods, State).
get_headers(#state{authtoken=Token}) when 0 == length(Token) ->
[];
get_headers(#state{authtoken=Token}) ->
TODO : We should check the expiry of our authtoken !
Auth = binary_to_list(proplists:get_value(<<"access_token">>, Token)),
[{"Authorization", "Bearer " ++ Auth}].
get_base_params(APIKey, []) when APIKey /= [] ->
"key=" ++ APIKey;
get_base_params(_, _) ->
"".
get_path(Path, []) ->
Path;
get_path(Path, [{Key, Value}|Parameters]) ->
get_path(re:replace(Path, "{" ++ Key ++ "}", Value, [global, {return, list}]), Parameters).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Retrieve Methods & Resources % %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
get_method_scopes(Service, [[Service, Method]|_]) ->
case proplists:get_value(<<"scopes">>, Method) of
undefined -> [];
Scopes -> Scopes
end;
get_method_scopes(Service, [_|Methods]) ->
get_method_scopes(Service, Methods).
get_method_names([[Method,_]|[]]) ->
[Method];
get_method_names([[Method, _]|Methods]) ->
[Method | get_method_names(Methods)].
get_resources(_, []) ->
[];
get_resources(Json, [ResourceName|Resources]) ->
{struct, Resource} = proplists:get_value(ResourceName, Json),
lists:append(get_resources(Resource), get_resources(Json, Resources)).
get_resources(Json) ->
%% If methods array defined, pull out list
case proplists:get_value(<<"methods">>, Json) of
{struct, Methods} ->
get_methods(Methods, proplists:get_keys(Methods));
undefined ->
%% If resource array defined, pull out and iterate over children
{struct, ResourceTypes} = proplists:get_value(<<"resources">>, Json),
get_resources(ResourceTypes, proplists:get_keys(ResourceTypes))
end.
get_methods(_, []) ->
[];
get_methods(Json, [MethodName|Methods]) ->
{struct, Method} = proplists:get_value(MethodName, Json),
[[binary_to_list(proplists:get_value(<<"id">>, Method)), Method] | get_methods(Json, Methods)].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
OAuth % %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
get_authurl(Scopes, #state{clientid = ClientID, redirecturl = RedirectURL}) ->
OAuth2State = base64:encode_to_string(crypto:rand_bytes(12)),
["?" ++
"client_id=" ++ ClientID ++
"&response_type=code" ++
"&access_type=offline" ++
% "&approval_prompt=force" ++
"&redirect_uri=" ++ edoc_lib:escape_uri(RedirectURL) ++
"&scope=" ++ edoc_lib:escape_uri(Scopes) ++
"&state=" ++ edoc_lib:escape_uri(OAuth2State), OAuth2State].
get_authtoken(Code, #state{clientid = ClientID, clientsecret=ClientSecret, redirecturl = RedirectURL}) ->
%% We check the OAuth2 state variable in the handler for security
URL = "",
Data = "code=" ++ edoc_lib:escape_uri(Code) ++
"&client_id=" ++ edoc_lib:escape_uri(ClientID) ++
"&client_secret=" ++ edoc_lib:escape_uri(ClientSecret) ++
"&redirect_uri=" ++ edoc_lib:escape_uri(RedirectURL) ++
"&grant_type=authorization_code",
get_url(httpc:request(post, {URL, [], "application/x-www-form-urlencoded", Data}, [], [])).
| null | https://raw.githubusercontent.com/projectcs13/sensor-cloud/0302bd74b2e62fddbd832fb4c7a27b9c62852b90/src/plus_srv.erl | erlang | -------------------------------------------------------------------
@doc Example code on interacting with the discovery API
@end
-------------------------------------------------------------------
API
gen_server callbacks
====================================================================
API
====================================================================
--------------------------------------------------------------------
@doc Starts the server
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Call a method and retrieve the resulting JSON document
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Returns a list of discoverable APIs
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Set the server to operate against a specific API
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Returns a list of methods strings and aritys
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Returns a list of methods scopes. If empty, does not require auth
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec gen_token_url() -> {ok,Url} | {error,Error}
@doc Returns a URL to pass to the user to authenticate the app
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Returns a URL to pass to the user to authenticate the app
@end
--------------------------------------------------------------------
====================================================================
gen_server callbacks
====================================================================
Directory calls
OAuth Calls
Method calls
Error case for following calls - requires API to be set.
====================================================================
helper functions
====================================================================
List APIs %%
Call Methods %%
URL encode args,and paste on to end of string
Join method path on to uri
erlang:display(Headers), %%% DEBUG %%%
% % DEBUG % % %
Retrieve response
%
If methods array defined, pull out list
If resource array defined, pull out and iterate over children
%
"&approval_prompt=force" ++
We check the OAuth2 state variable in the handler for security | File : plus_srv.erl
@author
2012 Google
@since 2012 - 11 - 05
-module(plus_srv).
-author('Ian Barber').
-behaviour(gen_server).
-export([start_link/4,list_apis/0,set_api/1,call_method/3,
list_methods/0,list_scopes/1,gen_token_url/1,exchange_token/2,get_url/1]).
-export([init/1, handle_call/3,handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {methods, baseurl, discovery, apikey, authtoken, oauth2state, clientid, clientsecret, redirecturl}).
( ) - > { ok , Pid } | ignore | { error , Error }
start_link(APIKey, ClientID, ClientSecret, RedirectURL) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [APIKey, ClientID, ClientSecret, RedirectURL], []).
calL_method ( ) - > { ok , Results } | { error , Error }
call_method(Service, Parameters, Body)->
gen_server:call(?MODULE,{call_method,Service,Parameters, Body}).
list_apis ( ) - > { ok , Methods } | { error , Error }
list_apis()->
gen_server:call(?MODULE,{list_apis}).
( ) - > { k | { error , Error }
set_api(ApiRestUrl)->
gen_server:call(?MODULE,{set_api, ApiRestUrl}).
( ) - > { ok , Methods } | { error , Error }
list_methods()->
gen_server:call(?MODULE,{list_methods}).
list_scopes ( ) - > { ok , } | { error , Error }
list_scopes(Method)->
gen_server:call(?MODULE,{list_scopes,Method}).
gen_token_url(Scopes)->
gen_server:call(?MODULE,{gen_token_url,Scopes}).
( ) - > ok | { error , Error }
exchange_token(Code, State)->
gen_server:call(?MODULE,{exchange_token,Code,State}).
init([APIKey, ClientID, ClientSecret, RedirectURL]) ->
inets:start(),
ssl:start(),
{ok, #state{apikey=APIKey, clientid=ClientID, clientsecret=ClientSecret, redirecturl=RedirectURL,
methods=[], baseurl=[], discovery=[], authtoken=[]}}.
handle_call({list_apis}, _From, State) ->
[Apis, Discovery] = get_api_list(State#state.discovery),
{reply, Apis, State#state{discovery=Discovery}};
handle_call({set_api, ApiRestUrl}, _From, State) ->
[Methods, BaseURL] = get_api_methods(ApiRestUrl),
{reply, ok, State#state{methods=Methods,baseurl=BaseURL}};
handle_call({gen_token_url, Scopes}, _From, State) ->
[URL, OAuth2State] = get_authurl(Scopes, State),
{reply, URL, State#state{oauth2state=OAuth2State}};
handle_call({exchange_token, Code, _}, _From, State) ->
handle_call({exchange_token , Code , OAuth2State } , _ From , State ) when OAuth2State = = State#state.oauth2state - >
{ok, Token} = get_authtoken(Code, State),
{reply, Token, State#state{authtoken=Token}};
handle_call({exchange_token, _, _}, _From, State) ->
{reply, {error, "Invalid State"}, State};
handle_call(_, _From, State) when length(State#state.methods)==0 ->
{reply, {error, "No API Set"}, State};
handle_call({list_methods}, _From, State) ->
{reply, get_method_names(State#state.methods), State};
handle_call({list_scopes, Method}, _From, State) ->
{reply, get_method_scopes(Method, State#state.methods), State};
handle_call({call_method, Service, Parameters, Body}, _From, State) ->
Reply = call_method(Service, Parameters, Body, State#state.methods, State),
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
get_url(Request) ->
case Request of
{ok, {{_Version, 200, _ReasonPhrase}, _Headers, Body}}->
{struct, Json} = mochijson2:decode(Body),
{ok, Json};
{ok, {{_Version, Code, _ReasonPhrase}, _Headers, _Body}}->
{error,Code};
{error,Error}->
{error,Error}
end.
get_api_list([]) ->
case get_url(httpc:request(get,{"",[]},[],[])) of
{error, Error} -> {stop, Error};
{ok, Json} ->
get_api_list(Json)
end;
get_api_list(Discovery) ->
Apis = proplists:get_value(<<"items">>, Discovery),
[get_apis(Apis), Discovery].
get_api_methods(ApiRestUrl) ->
case get_url(httpc:request(get,{ApiRestUrl,[]},[],[])) of
{error, Error} -> {stop, Error};
{ok, Json} ->
Methods = get_resources(Json),
BaseURL = binary_to_list(proplists:get_value(<<"baseUrl">>, Json)),
[Methods, BaseURL]
end.
get_apis([]) ->
[];
get_apis([H|T]) ->
{struct, API} = H,
[{binary_to_list(proplists:get_value(<<"name">>, API)),
binary_to_list(proplists:get_value(<<"discoveryRestUrl">>, API))}|get_apis(T)].
call_method(Service, Parameters, Body, [[Service, Method]|_], State) ->
If we have an APIKey and do n't need OAuth , include that
BaseString = get_base_params(State#state.apikey, State#state.authtoken),
Headers = get_headers(State),
QS = lists:foldl(fun({Q,V}, QS) -> QS ++ "&" ++ Q ++ "=" ++ V end,
BaseString, Parameters),
Path = get_path(binary_to_list(proplists:get_value(<<"path">>, Method)), Parameters),
Url = State#state.baseurl ++ Path ++ "?" ++ QS,
Switch on method
[HttpMethod, Request] = case proplists:get_value(<<"httpMethod">>, Method) of
<<"GET">> -> [get, {Url, Headers}];
<<"POST">> -> [post, {Url, Headers, "application/json", Body}]
end,
[ HttpMethod , Request ] ;
get_url(httpc:request(HttpMethod, Request, [], []));
call_method(Service, Parameters, Body, [_|Methods], State) ->
call_method(Service, Parameters, Body, Methods, State).
get_headers(#state{authtoken=Token}) when 0 == length(Token) ->
[];
get_headers(#state{authtoken=Token}) ->
TODO : We should check the expiry of our authtoken !
Auth = binary_to_list(proplists:get_value(<<"access_token">>, Token)),
[{"Authorization", "Bearer " ++ Auth}].
get_base_params(APIKey, []) when APIKey /= [] ->
"key=" ++ APIKey;
get_base_params(_, _) ->
"".
get_path(Path, []) ->
Path;
get_path(Path, [{Key, Value}|Parameters]) ->
get_path(re:replace(Path, "{" ++ Key ++ "}", Value, [global, {return, list}]), Parameters).
get_method_scopes(Service, [[Service, Method]|_]) ->
case proplists:get_value(<<"scopes">>, Method) of
undefined -> [];
Scopes -> Scopes
end;
get_method_scopes(Service, [_|Methods]) ->
get_method_scopes(Service, Methods).
get_method_names([[Method,_]|[]]) ->
[Method];
get_method_names([[Method, _]|Methods]) ->
[Method | get_method_names(Methods)].
get_resources(_, []) ->
[];
get_resources(Json, [ResourceName|Resources]) ->
{struct, Resource} = proplists:get_value(ResourceName, Json),
lists:append(get_resources(Resource), get_resources(Json, Resources)).
get_resources(Json) ->
case proplists:get_value(<<"methods">>, Json) of
{struct, Methods} ->
get_methods(Methods, proplists:get_keys(Methods));
undefined ->
{struct, ResourceTypes} = proplists:get_value(<<"resources">>, Json),
get_resources(ResourceTypes, proplists:get_keys(ResourceTypes))
end.
get_methods(_, []) ->
[];
get_methods(Json, [MethodName|Methods]) ->
{struct, Method} = proplists:get_value(MethodName, Json),
[[binary_to_list(proplists:get_value(<<"id">>, Method)), Method] | get_methods(Json, Methods)].
get_authurl(Scopes, #state{clientid = ClientID, redirecturl = RedirectURL}) ->
OAuth2State = base64:encode_to_string(crypto:rand_bytes(12)),
["?" ++
"client_id=" ++ ClientID ++
"&response_type=code" ++
"&access_type=offline" ++
"&redirect_uri=" ++ edoc_lib:escape_uri(RedirectURL) ++
"&scope=" ++ edoc_lib:escape_uri(Scopes) ++
"&state=" ++ edoc_lib:escape_uri(OAuth2State), OAuth2State].
get_authtoken(Code, #state{clientid = ClientID, clientsecret=ClientSecret, redirecturl = RedirectURL}) ->
URL = "",
Data = "code=" ++ edoc_lib:escape_uri(Code) ++
"&client_id=" ++ edoc_lib:escape_uri(ClientID) ++
"&client_secret=" ++ edoc_lib:escape_uri(ClientSecret) ++
"&redirect_uri=" ++ edoc_lib:escape_uri(RedirectURL) ++
"&grant_type=authorization_code",
get_url(httpc:request(post, {URL, [], "application/x-www-form-urlencoded", Data}, [], [])).
|
4d69cac077bf58d89071fdb494f0b20a274f19e90be1231a8ddaf4ac101153d4 | ghcjs/ghcjs-dom | IDBIndex.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
module GHCJS.DOM.JSFFI.Generated.IDBIndex
(js_openCursorRange, openCursorRange, openCursorRange_,
js_openCursor, openCursor, openCursor_, js_openKeyCursorRange,
openKeyCursorRange, openKeyCursorRange_, js_openKeyCursor,
openKeyCursor, openKeyCursor_, js_getRange, getRange, getRange_,
js_get, get, get_, js_getKeyRange, getKeyRange, getKeyRange_,
js_getKey, getKey, getKey_, js_getAllRange, getAllRange,
getAllRange_, js_getAll, getAll, getAll_, js_getAllKeysRange,
getAllKeysRange, getAllKeysRange_, js_getAllKeys, getAllKeys,
getAllKeys_, js_countRange, countRange, countRange_, js_count,
count, count_, js_setName, setName, js_getName, getName,
js_getObjectStore, getObjectStore, js_getKeyPath, getKeyPath,
getKeyPathUnsafe, getKeyPathUnchecked, js_getMultiEntry,
getMultiEntry, js_getUnique, getUnique, IDBIndex(..),
gTypeIDBIndex)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript safe "$1[\"openCursor\"]($2, $3)"
js_openCursorRange ::
IDBIndex ->
Optional IDBKeyRange ->
Optional IDBCursorDirection -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.openCursor Mozilla IDBIndex.openCursor documentation >
openCursorRange ::
(MonadIO m) =>
IDBIndex ->
Maybe IDBKeyRange -> Maybe IDBCursorDirection -> m IDBRequest
openCursorRange self range direction
= liftIO
(js_openCursorRange self (maybeToOptional range)
(maybeToOptional direction))
| < -US/docs/Web/API/IDBIndex.openCursor Mozilla IDBIndex.openCursor documentation >
openCursorRange_ ::
(MonadIO m) =>
IDBIndex -> Maybe IDBKeyRange -> Maybe IDBCursorDirection -> m ()
openCursorRange_ self range direction
= liftIO
(void
(js_openCursorRange self (maybeToOptional range)
(maybeToOptional direction)))
foreign import javascript safe "$1[\"openCursor\"]($2, $3)"
js_openCursor ::
IDBIndex -> JSVal -> Optional IDBCursorDirection -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.openCursor Mozilla IDBIndex.openCursor documentation >
openCursor ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe IDBCursorDirection -> m IDBRequest
openCursor self key direction
= liftIO
(toJSVal key >>= \ key' -> js_openCursor self key'
(maybeToOptional direction))
| < -US/docs/Web/API/IDBIndex.openCursor Mozilla IDBIndex.openCursor documentation >
openCursor_ ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe IDBCursorDirection -> m ()
openCursor_ self key direction
= liftIO
(void
(toJSVal key >>= \ key' -> js_openCursor self key'
(maybeToOptional direction)))
foreign import javascript safe "$1[\"openKeyCursor\"]($2, $3)"
js_openKeyCursorRange ::
IDBIndex ->
Optional IDBKeyRange ->
Optional IDBCursorDirection -> IO IDBRequest
-- | <-US/docs/Web/API/IDBIndex.openKeyCursor Mozilla IDBIndex.openKeyCursor documentation>
openKeyCursorRange ::
(MonadIO m) =>
IDBIndex ->
Maybe IDBKeyRange -> Maybe IDBCursorDirection -> m IDBRequest
openKeyCursorRange self range direction
= liftIO
(js_openKeyCursorRange self (maybeToOptional range)
(maybeToOptional direction))
-- | <-US/docs/Web/API/IDBIndex.openKeyCursor Mozilla IDBIndex.openKeyCursor documentation>
openKeyCursorRange_ ::
(MonadIO m) =>
IDBIndex -> Maybe IDBKeyRange -> Maybe IDBCursorDirection -> m ()
openKeyCursorRange_ self range direction
= liftIO
(void
(js_openKeyCursorRange self (maybeToOptional range)
(maybeToOptional direction)))
foreign import javascript safe "$1[\"openKeyCursor\"]($2, $3)"
js_openKeyCursor ::
IDBIndex -> JSVal -> Optional IDBCursorDirection -> IO IDBRequest
-- | <-US/docs/Web/API/IDBIndex.openKeyCursor Mozilla IDBIndex.openKeyCursor documentation>
openKeyCursor ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe IDBCursorDirection -> m IDBRequest
openKeyCursor self key direction
= liftIO
(toJSVal key >>= \ key' -> js_openKeyCursor self key'
(maybeToOptional direction))
-- | <-US/docs/Web/API/IDBIndex.openKeyCursor Mozilla IDBIndex.openKeyCursor documentation>
openKeyCursor_ ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe IDBCursorDirection -> m ()
openKeyCursor_ self key direction
= liftIO
(void
(toJSVal key >>= \ key' -> js_openKeyCursor self key'
(maybeToOptional direction)))
foreign import javascript safe "$1[\"get\"]($2)" js_getRange ::
IDBIndex -> Optional IDBKeyRange -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.get Mozilla IDBIndex.get documentation >
getRange ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m IDBRequest
getRange self key = liftIO (js_getRange self (maybeToOptional key))
| < -US/docs/Web/API/IDBIndex.get Mozilla IDBIndex.get documentation >
getRange_ :: (MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m ()
getRange_ self key
= liftIO (void (js_getRange self (maybeToOptional key)))
foreign import javascript safe "$1[\"get\"]($2)" js_get ::
IDBIndex -> JSVal -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.get Mozilla IDBIndex.get documentation >
get :: (MonadIO m, ToJSVal key) => IDBIndex -> key -> m IDBRequest
get self key = liftIO (toJSVal key >>= \ key' -> js_get self key')
| < -US/docs/Web/API/IDBIndex.get Mozilla IDBIndex.get documentation >
get_ :: (MonadIO m, ToJSVal key) => IDBIndex -> key -> m ()
get_ self key
= liftIO (void (toJSVal key >>= \ key' -> js_get self key'))
foreign import javascript safe "$1[\"getKey\"]($2)" js_getKeyRange
:: IDBIndex -> Optional IDBKeyRange -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getKey Mozilla IDBIndex.getKey documentation >
getKeyRange ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m IDBRequest
getKeyRange self key
= liftIO (js_getKeyRange self (maybeToOptional key))
| < -US/docs/Web/API/IDBIndex.getKey Mozilla IDBIndex.getKey documentation >
getKeyRange_ ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m ()
getKeyRange_ self key
= liftIO (void (js_getKeyRange self (maybeToOptional key)))
foreign import javascript safe "$1[\"getKey\"]($2)" js_getKey ::
IDBIndex -> JSVal -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getKey Mozilla IDBIndex.getKey documentation >
getKey ::
(MonadIO m, ToJSVal key) => IDBIndex -> key -> m IDBRequest
getKey self key
= liftIO (toJSVal key >>= \ key' -> js_getKey self key')
| < -US/docs/Web/API/IDBIndex.getKey Mozilla IDBIndex.getKey documentation >
getKey_ :: (MonadIO m, ToJSVal key) => IDBIndex -> key -> m ()
getKey_ self key
= liftIO (void (toJSVal key >>= \ key' -> js_getKey self key'))
foreign import javascript safe "$1[\"getAll\"]($2, $3)"
js_getAllRange ::
IDBIndex -> Optional IDBKeyRange -> Optional Word -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getAll Mozilla IDBIndex.getAll documentation >
getAllRange ::
(MonadIO m) =>
IDBIndex -> Maybe IDBKeyRange -> Maybe Word -> m IDBRequest
getAllRange self range count
= liftIO
(js_getAllRange self (maybeToOptional range)
(maybeToOptional count))
| < -US/docs/Web/API/IDBIndex.getAll Mozilla IDBIndex.getAll documentation >
getAllRange_ ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> Maybe Word -> m ()
getAllRange_ self range count
= liftIO
(void
(js_getAllRange self (maybeToOptional range)
(maybeToOptional count)))
foreign import javascript safe "$1[\"getAll\"]($2, $3)" js_getAll
:: IDBIndex -> JSVal -> Optional Word -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getAll Mozilla IDBIndex.getAll documentation >
getAll ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe Word -> m IDBRequest
getAll self key count
= liftIO
(toJSVal key >>= \ key' -> js_getAll self key'
(maybeToOptional count))
| < -US/docs/Web/API/IDBIndex.getAll Mozilla IDBIndex.getAll documentation >
getAll_ ::
(MonadIO m, ToJSVal key) => IDBIndex -> key -> Maybe Word -> m ()
getAll_ self key count
= liftIO
(void
(toJSVal key >>= \ key' -> js_getAll self key'
(maybeToOptional count)))
foreign import javascript safe "$1[\"getAllKeys\"]($2, $3)"
js_getAllKeysRange ::
IDBIndex -> Optional IDBKeyRange -> Optional Word -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getAllKeys Mozilla IDBIndex.getAllKeys documentation >
getAllKeysRange ::
(MonadIO m) =>
IDBIndex -> Maybe IDBKeyRange -> Maybe Word -> m IDBRequest
getAllKeysRange self range count
= liftIO
(js_getAllKeysRange self (maybeToOptional range)
(maybeToOptional count))
| < -US/docs/Web/API/IDBIndex.getAllKeys Mozilla IDBIndex.getAllKeys documentation >
getAllKeysRange_ ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> Maybe Word -> m ()
getAllKeysRange_ self range count
= liftIO
(void
(js_getAllKeysRange self (maybeToOptional range)
(maybeToOptional count)))
foreign import javascript safe "$1[\"getAllKeys\"]($2, $3)"
js_getAllKeys ::
IDBIndex -> JSVal -> Optional Word -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getAllKeys Mozilla IDBIndex.getAllKeys documentation >
getAllKeys ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe Word -> m IDBRequest
getAllKeys self key count
= liftIO
(toJSVal key >>= \ key' -> js_getAllKeys self key'
(maybeToOptional count))
| < -US/docs/Web/API/IDBIndex.getAllKeys Mozilla IDBIndex.getAllKeys documentation >
getAllKeys_ ::
(MonadIO m, ToJSVal key) => IDBIndex -> key -> Maybe Word -> m ()
getAllKeys_ self key count
= liftIO
(void
(toJSVal key >>= \ key' -> js_getAllKeys self key'
(maybeToOptional count)))
foreign import javascript safe "$1[\"count\"]($2)" js_countRange ::
IDBIndex -> Optional IDBKeyRange -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.count Mozilla IDBIndex.count documentation >
countRange ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m IDBRequest
countRange self range
= liftIO (js_countRange self (maybeToOptional range))
| < -US/docs/Web/API/IDBIndex.count Mozilla IDBIndex.count documentation >
countRange_ :: (MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m ()
countRange_ self range
= liftIO (void (js_countRange self (maybeToOptional range)))
foreign import javascript safe "$1[\"count\"]($2)" js_count ::
IDBIndex -> JSVal -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.count Mozilla IDBIndex.count documentation >
count ::
(MonadIO m, ToJSVal key) => IDBIndex -> key -> m IDBRequest
count self key
= liftIO (toJSVal key >>= \ key' -> js_count self key')
| < -US/docs/Web/API/IDBIndex.count Mozilla IDBIndex.count documentation >
count_ :: (MonadIO m, ToJSVal key) => IDBIndex -> key -> m ()
count_ self key
= liftIO (void (toJSVal key >>= \ key' -> js_count self key'))
foreign import javascript safe "$1[\"name\"] = $2;" js_setName ::
IDBIndex -> JSString -> IO ()
| < -US/docs/Web/API/IDBIndex.name Mozilla IDBIndex.name documentation >
setName :: (MonadIO m, ToJSString val) => IDBIndex -> val -> m ()
setName self val = liftIO (js_setName self (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
IDBIndex -> IO JSString
| < -US/docs/Web/API/IDBIndex.name Mozilla IDBIndex.name documentation >
getName :: (MonadIO m, FromJSString result) => IDBIndex -> m result
getName self = liftIO (fromJSString <$> (js_getName self))
foreign import javascript unsafe "$1[\"objectStore\"]"
js_getObjectStore :: IDBIndex -> IO IDBObjectStore
| < -US/docs/Web/API/IDBIndex.objectStore Mozilla IDBIndex.objectStore documentation >
getObjectStore :: (MonadIO m) => IDBIndex -> m IDBObjectStore
getObjectStore self = liftIO (js_getObjectStore self)
foreign import javascript unsafe "$1[\"keyPath\"]" js_getKeyPath ::
IDBIndex -> IO (Nullable IDBKeyPath)
-- | <-US/docs/Web/API/IDBIndex.keyPath Mozilla IDBIndex.keyPath documentation>
getKeyPath :: (MonadIO m) => IDBIndex -> m (Maybe IDBKeyPath)
getKeyPath self = liftIO (nullableToMaybe <$> (js_getKeyPath self))
-- | <-US/docs/Web/API/IDBIndex.keyPath Mozilla IDBIndex.keyPath documentation>
getKeyPathUnsafe ::
(MonadIO m, HasCallStack) => IDBIndex -> m IDBKeyPath
getKeyPathUnsafe self
= liftIO
((nullableToMaybe <$> (js_getKeyPath self)) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <-US/docs/Web/API/IDBIndex.keyPath Mozilla IDBIndex.keyPath documentation>
getKeyPathUnchecked :: (MonadIO m) => IDBIndex -> m IDBKeyPath
getKeyPathUnchecked self
= liftIO (fromJust . nullableToMaybe <$> (js_getKeyPath self))
foreign import javascript unsafe "($1[\"multiEntry\"] ? 1 : 0)"
js_getMultiEntry :: IDBIndex -> IO Bool
| < -US/docs/Web/API/IDBIndex.multiEntry Mozilla IDBIndex.multiEntry documentation >
getMultiEntry :: (MonadIO m) => IDBIndex -> m Bool
getMultiEntry self = liftIO (js_getMultiEntry self)
foreign import javascript unsafe "($1[\"unique\"] ? 1 : 0)"
js_getUnique :: IDBIndex -> IO Bool
-- | <-US/docs/Web/API/IDBIndex.unique Mozilla IDBIndex.unique documentation>
getUnique :: (MonadIO m) => IDBIndex -> m Bool
getUnique self = liftIO (js_getUnique self) | null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/IDBIndex.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/IDBIndex.openKeyCursor Mozilla IDBIndex.openKeyCursor documentation>
| <-US/docs/Web/API/IDBIndex.openKeyCursor Mozilla IDBIndex.openKeyCursor documentation>
| <-US/docs/Web/API/IDBIndex.openKeyCursor Mozilla IDBIndex.openKeyCursor documentation>
| <-US/docs/Web/API/IDBIndex.openKeyCursor Mozilla IDBIndex.openKeyCursor documentation>
| <-US/docs/Web/API/IDBIndex.keyPath Mozilla IDBIndex.keyPath documentation>
| <-US/docs/Web/API/IDBIndex.keyPath Mozilla IDBIndex.keyPath documentation>
| <-US/docs/Web/API/IDBIndex.keyPath Mozilla IDBIndex.keyPath documentation>
| <-US/docs/Web/API/IDBIndex.unique Mozilla IDBIndex.unique documentation> | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.Generated.IDBIndex
(js_openCursorRange, openCursorRange, openCursorRange_,
js_openCursor, openCursor, openCursor_, js_openKeyCursorRange,
openKeyCursorRange, openKeyCursorRange_, js_openKeyCursor,
openKeyCursor, openKeyCursor_, js_getRange, getRange, getRange_,
js_get, get, get_, js_getKeyRange, getKeyRange, getKeyRange_,
js_getKey, getKey, getKey_, js_getAllRange, getAllRange,
getAllRange_, js_getAll, getAll, getAll_, js_getAllKeysRange,
getAllKeysRange, getAllKeysRange_, js_getAllKeys, getAllKeys,
getAllKeys_, js_countRange, countRange, countRange_, js_count,
count, count_, js_setName, setName, js_getName, getName,
js_getObjectStore, getObjectStore, js_getKeyPath, getKeyPath,
getKeyPathUnsafe, getKeyPathUnchecked, js_getMultiEntry,
getMultiEntry, js_getUnique, getUnique, IDBIndex(..),
gTypeIDBIndex)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript safe "$1[\"openCursor\"]($2, $3)"
js_openCursorRange ::
IDBIndex ->
Optional IDBKeyRange ->
Optional IDBCursorDirection -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.openCursor Mozilla IDBIndex.openCursor documentation >
openCursorRange ::
(MonadIO m) =>
IDBIndex ->
Maybe IDBKeyRange -> Maybe IDBCursorDirection -> m IDBRequest
openCursorRange self range direction
= liftIO
(js_openCursorRange self (maybeToOptional range)
(maybeToOptional direction))
| < -US/docs/Web/API/IDBIndex.openCursor Mozilla IDBIndex.openCursor documentation >
openCursorRange_ ::
(MonadIO m) =>
IDBIndex -> Maybe IDBKeyRange -> Maybe IDBCursorDirection -> m ()
openCursorRange_ self range direction
= liftIO
(void
(js_openCursorRange self (maybeToOptional range)
(maybeToOptional direction)))
foreign import javascript safe "$1[\"openCursor\"]($2, $3)"
js_openCursor ::
IDBIndex -> JSVal -> Optional IDBCursorDirection -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.openCursor Mozilla IDBIndex.openCursor documentation >
openCursor ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe IDBCursorDirection -> m IDBRequest
openCursor self key direction
= liftIO
(toJSVal key >>= \ key' -> js_openCursor self key'
(maybeToOptional direction))
| < -US/docs/Web/API/IDBIndex.openCursor Mozilla IDBIndex.openCursor documentation >
openCursor_ ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe IDBCursorDirection -> m ()
openCursor_ self key direction
= liftIO
(void
(toJSVal key >>= \ key' -> js_openCursor self key'
(maybeToOptional direction)))
foreign import javascript safe "$1[\"openKeyCursor\"]($2, $3)"
js_openKeyCursorRange ::
IDBIndex ->
Optional IDBKeyRange ->
Optional IDBCursorDirection -> IO IDBRequest
openKeyCursorRange ::
(MonadIO m) =>
IDBIndex ->
Maybe IDBKeyRange -> Maybe IDBCursorDirection -> m IDBRequest
openKeyCursorRange self range direction
= liftIO
(js_openKeyCursorRange self (maybeToOptional range)
(maybeToOptional direction))
openKeyCursorRange_ ::
(MonadIO m) =>
IDBIndex -> Maybe IDBKeyRange -> Maybe IDBCursorDirection -> m ()
openKeyCursorRange_ self range direction
= liftIO
(void
(js_openKeyCursorRange self (maybeToOptional range)
(maybeToOptional direction)))
foreign import javascript safe "$1[\"openKeyCursor\"]($2, $3)"
js_openKeyCursor ::
IDBIndex -> JSVal -> Optional IDBCursorDirection -> IO IDBRequest
openKeyCursor ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe IDBCursorDirection -> m IDBRequest
openKeyCursor self key direction
= liftIO
(toJSVal key >>= \ key' -> js_openKeyCursor self key'
(maybeToOptional direction))
openKeyCursor_ ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe IDBCursorDirection -> m ()
openKeyCursor_ self key direction
= liftIO
(void
(toJSVal key >>= \ key' -> js_openKeyCursor self key'
(maybeToOptional direction)))
foreign import javascript safe "$1[\"get\"]($2)" js_getRange ::
IDBIndex -> Optional IDBKeyRange -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.get Mozilla IDBIndex.get documentation >
getRange ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m IDBRequest
getRange self key = liftIO (js_getRange self (maybeToOptional key))
| < -US/docs/Web/API/IDBIndex.get Mozilla IDBIndex.get documentation >
getRange_ :: (MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m ()
getRange_ self key
= liftIO (void (js_getRange self (maybeToOptional key)))
foreign import javascript safe "$1[\"get\"]($2)" js_get ::
IDBIndex -> JSVal -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.get Mozilla IDBIndex.get documentation >
get :: (MonadIO m, ToJSVal key) => IDBIndex -> key -> m IDBRequest
get self key = liftIO (toJSVal key >>= \ key' -> js_get self key')
| < -US/docs/Web/API/IDBIndex.get Mozilla IDBIndex.get documentation >
get_ :: (MonadIO m, ToJSVal key) => IDBIndex -> key -> m ()
get_ self key
= liftIO (void (toJSVal key >>= \ key' -> js_get self key'))
foreign import javascript safe "$1[\"getKey\"]($2)" js_getKeyRange
:: IDBIndex -> Optional IDBKeyRange -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getKey Mozilla IDBIndex.getKey documentation >
getKeyRange ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m IDBRequest
getKeyRange self key
= liftIO (js_getKeyRange self (maybeToOptional key))
| < -US/docs/Web/API/IDBIndex.getKey Mozilla IDBIndex.getKey documentation >
getKeyRange_ ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m ()
getKeyRange_ self key
= liftIO (void (js_getKeyRange self (maybeToOptional key)))
foreign import javascript safe "$1[\"getKey\"]($2)" js_getKey ::
IDBIndex -> JSVal -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getKey Mozilla IDBIndex.getKey documentation >
getKey ::
(MonadIO m, ToJSVal key) => IDBIndex -> key -> m IDBRequest
getKey self key
= liftIO (toJSVal key >>= \ key' -> js_getKey self key')
| < -US/docs/Web/API/IDBIndex.getKey Mozilla IDBIndex.getKey documentation >
getKey_ :: (MonadIO m, ToJSVal key) => IDBIndex -> key -> m ()
getKey_ self key
= liftIO (void (toJSVal key >>= \ key' -> js_getKey self key'))
foreign import javascript safe "$1[\"getAll\"]($2, $3)"
js_getAllRange ::
IDBIndex -> Optional IDBKeyRange -> Optional Word -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getAll Mozilla IDBIndex.getAll documentation >
getAllRange ::
(MonadIO m) =>
IDBIndex -> Maybe IDBKeyRange -> Maybe Word -> m IDBRequest
getAllRange self range count
= liftIO
(js_getAllRange self (maybeToOptional range)
(maybeToOptional count))
| < -US/docs/Web/API/IDBIndex.getAll Mozilla IDBIndex.getAll documentation >
getAllRange_ ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> Maybe Word -> m ()
getAllRange_ self range count
= liftIO
(void
(js_getAllRange self (maybeToOptional range)
(maybeToOptional count)))
foreign import javascript safe "$1[\"getAll\"]($2, $3)" js_getAll
:: IDBIndex -> JSVal -> Optional Word -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getAll Mozilla IDBIndex.getAll documentation >
getAll ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe Word -> m IDBRequest
getAll self key count
= liftIO
(toJSVal key >>= \ key' -> js_getAll self key'
(maybeToOptional count))
| < -US/docs/Web/API/IDBIndex.getAll Mozilla IDBIndex.getAll documentation >
getAll_ ::
(MonadIO m, ToJSVal key) => IDBIndex -> key -> Maybe Word -> m ()
getAll_ self key count
= liftIO
(void
(toJSVal key >>= \ key' -> js_getAll self key'
(maybeToOptional count)))
foreign import javascript safe "$1[\"getAllKeys\"]($2, $3)"
js_getAllKeysRange ::
IDBIndex -> Optional IDBKeyRange -> Optional Word -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getAllKeys Mozilla IDBIndex.getAllKeys documentation >
getAllKeysRange ::
(MonadIO m) =>
IDBIndex -> Maybe IDBKeyRange -> Maybe Word -> m IDBRequest
getAllKeysRange self range count
= liftIO
(js_getAllKeysRange self (maybeToOptional range)
(maybeToOptional count))
| < -US/docs/Web/API/IDBIndex.getAllKeys Mozilla IDBIndex.getAllKeys documentation >
getAllKeysRange_ ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> Maybe Word -> m ()
getAllKeysRange_ self range count
= liftIO
(void
(js_getAllKeysRange self (maybeToOptional range)
(maybeToOptional count)))
foreign import javascript safe "$1[\"getAllKeys\"]($2, $3)"
js_getAllKeys ::
IDBIndex -> JSVal -> Optional Word -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.getAllKeys Mozilla IDBIndex.getAllKeys documentation >
getAllKeys ::
(MonadIO m, ToJSVal key) =>
IDBIndex -> key -> Maybe Word -> m IDBRequest
getAllKeys self key count
= liftIO
(toJSVal key >>= \ key' -> js_getAllKeys self key'
(maybeToOptional count))
| < -US/docs/Web/API/IDBIndex.getAllKeys Mozilla IDBIndex.getAllKeys documentation >
getAllKeys_ ::
(MonadIO m, ToJSVal key) => IDBIndex -> key -> Maybe Word -> m ()
getAllKeys_ self key count
= liftIO
(void
(toJSVal key >>= \ key' -> js_getAllKeys self key'
(maybeToOptional count)))
foreign import javascript safe "$1[\"count\"]($2)" js_countRange ::
IDBIndex -> Optional IDBKeyRange -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.count Mozilla IDBIndex.count documentation >
countRange ::
(MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m IDBRequest
countRange self range
= liftIO (js_countRange self (maybeToOptional range))
| < -US/docs/Web/API/IDBIndex.count Mozilla IDBIndex.count documentation >
countRange_ :: (MonadIO m) => IDBIndex -> Maybe IDBKeyRange -> m ()
countRange_ self range
= liftIO (void (js_countRange self (maybeToOptional range)))
foreign import javascript safe "$1[\"count\"]($2)" js_count ::
IDBIndex -> JSVal -> IO IDBRequest
| < -US/docs/Web/API/IDBIndex.count Mozilla IDBIndex.count documentation >
count ::
(MonadIO m, ToJSVal key) => IDBIndex -> key -> m IDBRequest
count self key
= liftIO (toJSVal key >>= \ key' -> js_count self key')
| < -US/docs/Web/API/IDBIndex.count Mozilla IDBIndex.count documentation >
count_ :: (MonadIO m, ToJSVal key) => IDBIndex -> key -> m ()
count_ self key
= liftIO (void (toJSVal key >>= \ key' -> js_count self key'))
foreign import javascript safe "$1[\"name\"] = $2;" js_setName ::
IDBIndex -> JSString -> IO ()
| < -US/docs/Web/API/IDBIndex.name Mozilla IDBIndex.name documentation >
setName :: (MonadIO m, ToJSString val) => IDBIndex -> val -> m ()
setName self val = liftIO (js_setName self (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
IDBIndex -> IO JSString
| < -US/docs/Web/API/IDBIndex.name Mozilla IDBIndex.name documentation >
getName :: (MonadIO m, FromJSString result) => IDBIndex -> m result
getName self = liftIO (fromJSString <$> (js_getName self))
foreign import javascript unsafe "$1[\"objectStore\"]"
js_getObjectStore :: IDBIndex -> IO IDBObjectStore
| < -US/docs/Web/API/IDBIndex.objectStore Mozilla IDBIndex.objectStore documentation >
getObjectStore :: (MonadIO m) => IDBIndex -> m IDBObjectStore
getObjectStore self = liftIO (js_getObjectStore self)
foreign import javascript unsafe "$1[\"keyPath\"]" js_getKeyPath ::
IDBIndex -> IO (Nullable IDBKeyPath)
getKeyPath :: (MonadIO m) => IDBIndex -> m (Maybe IDBKeyPath)
getKeyPath self = liftIO (nullableToMaybe <$> (js_getKeyPath self))
getKeyPathUnsafe ::
(MonadIO m, HasCallStack) => IDBIndex -> m IDBKeyPath
getKeyPathUnsafe self
= liftIO
((nullableToMaybe <$> (js_getKeyPath self)) >>=
maybe (Prelude.error "Nothing to return") return)
getKeyPathUnchecked :: (MonadIO m) => IDBIndex -> m IDBKeyPath
getKeyPathUnchecked self
= liftIO (fromJust . nullableToMaybe <$> (js_getKeyPath self))
foreign import javascript unsafe "($1[\"multiEntry\"] ? 1 : 0)"
js_getMultiEntry :: IDBIndex -> IO Bool
| < -US/docs/Web/API/IDBIndex.multiEntry Mozilla IDBIndex.multiEntry documentation >
getMultiEntry :: (MonadIO m) => IDBIndex -> m Bool
getMultiEntry self = liftIO (js_getMultiEntry self)
foreign import javascript unsafe "($1[\"unique\"] ? 1 : 0)"
js_getUnique :: IDBIndex -> IO Bool
getUnique :: (MonadIO m) => IDBIndex -> m Bool
getUnique self = liftIO (js_getUnique self) |
6338b125c335b6d6867121904035fd3e813157b6032e7c0844c9982340af1305 | tarides/dune-release | github_v4_api.mli | open Bos_setup
val with_auth : token:string -> Curl.t -> Curl.t
module Pull_request : sig
module Request : sig
val node_id : user:string -> repo:string -> id:int -> Curl.t
val ready_for_review : node_id:string -> Curl.t
end
module Response : sig
val node_id : Yojson.Basic.t -> (string, R.msg) result
val url : Yojson.Basic.t -> (string, R.msg) result
end
end
| null | https://raw.githubusercontent.com/tarides/dune-release/6bfed0f299b82c0931c78d4e216fd0efedff0673/lib/github_v4_api.mli | ocaml | open Bos_setup
val with_auth : token:string -> Curl.t -> Curl.t
module Pull_request : sig
module Request : sig
val node_id : user:string -> repo:string -> id:int -> Curl.t
val ready_for_review : node_id:string -> Curl.t
end
module Response : sig
val node_id : Yojson.Basic.t -> (string, R.msg) result
val url : Yojson.Basic.t -> (string, R.msg) result
end
end
| |
94f43dbf6f462687c217f4adbbc85dee91219458755e05cef95c76bc8f7cb80a | hugoduncan/makejack | fs.clj | (ns hooks.fs
(:require
[clj-kondo.hooks-api :as api]))
(defn with-binding
"A form that has a first vector argument and a body.
The first element of the vector is considered a binding. Other
elements are evaluated."
[{:keys [node]}]
(let [[_ binding-vec & body] (:children node)
[binding & others] (:children binding-vec)
new-node (api/list-node
(list*
(api/token-node 'let)
(api/vector-node
(reduce
into
[binding (api/token-node 'nil)]
(mapv
#(vector (api/token-node '_) %)
others)))
body))]
un - comment below to debug changes
#_(prn :with-binding (api/sexpr new-node))
{:node (with-meta new-node (meta node))}))
| null | https://raw.githubusercontent.com/hugoduncan/makejack/9676516be89b36295477bb59e26e09b8c9916597/components/filesystem/resources/clj-kondo.exports/org.hugoduncan/makejack-filesystem/hooks/fs.clj | clojure | (ns hooks.fs
(:require
[clj-kondo.hooks-api :as api]))
(defn with-binding
"A form that has a first vector argument and a body.
The first element of the vector is considered a binding. Other
elements are evaluated."
[{:keys [node]}]
(let [[_ binding-vec & body] (:children node)
[binding & others] (:children binding-vec)
new-node (api/list-node
(list*
(api/token-node 'let)
(api/vector-node
(reduce
into
[binding (api/token-node 'nil)]
(mapv
#(vector (api/token-node '_) %)
others)))
body))]
un - comment below to debug changes
#_(prn :with-binding (api/sexpr new-node))
{:node (with-meta new-node (meta node))}))
| |
3a07bef508ab220a3a473f8f3b52d4c5d2960a74bee1038c670969d0c9022f9b | Wizek/hs-di | NotSoEasyToTestCode.hs | # language NoMonomorphismRestriction #
# language TemplateHaskell #
module NotSoEasyToTestCode where
import DI
import System.IO
import Data.IORef
import Control.Monad
import Data.Time
injLeaf "putStrLn"
injLeaf "getCurrentTime"
inj
makeTimer putStrLn getCurrentTime = liftIO $ do
prevTime <- newIORef Nothing
return $ liftIO $ do
pTime <- readIORef prevTime
time <- getCurrentTime
writeIORef prevTime $ Just time
case pTime of
Nothing -> putStrLn $ show time
Just a -> putStrLn $ show time ++ ", diff: " ++ (show $ diffUTCTime time a)
Consider importing to make this even more realistic
liftIO = id
-- Dep "makeTimer" [Dep "putStrLn" [], Dep "getCurrentTime" []]
a = ( makeTimer , putStrLn , getCurrentTime )
-- makeTimer' = let (f, a, b) = a in f a b
-- Dep "makeTimer" [Dep "putStrLn" [], Dep "getCurrentTime" [], Dep "foo" [Dep "bar" []]]
a = ( makeTimer , putStrLn , getCurrentTime , ( foo , bar ) )
-- makeTimer' = let (f, a, b, (g, d)) = a in f a b (g d)
| null | https://raw.githubusercontent.com/Wizek/hs-di/4e7d11f4341a155667cb856b6f231d7b6af2c935/test/NotSoEasyToTestCode.hs | haskell | Dep "makeTimer" [Dep "putStrLn" [], Dep "getCurrentTime" []]
makeTimer' = let (f, a, b) = a in f a b
Dep "makeTimer" [Dep "putStrLn" [], Dep "getCurrentTime" [], Dep "foo" [Dep "bar" []]]
makeTimer' = let (f, a, b, (g, d)) = a in f a b (g d) | # language NoMonomorphismRestriction #
# language TemplateHaskell #
module NotSoEasyToTestCode where
import DI
import System.IO
import Data.IORef
import Control.Monad
import Data.Time
injLeaf "putStrLn"
injLeaf "getCurrentTime"
inj
makeTimer putStrLn getCurrentTime = liftIO $ do
prevTime <- newIORef Nothing
return $ liftIO $ do
pTime <- readIORef prevTime
time <- getCurrentTime
writeIORef prevTime $ Just time
case pTime of
Nothing -> putStrLn $ show time
Just a -> putStrLn $ show time ++ ", diff: " ++ (show $ diffUTCTime time a)
Consider importing to make this even more realistic
liftIO = id
a = ( makeTimer , putStrLn , getCurrentTime )
a = ( makeTimer , putStrLn , getCurrentTime , ( foo , bar ) )
|
d07fd020c6551cf7a0328750e6f6b01a57e46fc85fbc97ef9cbab9237911f701 | infinisil/nixbot | NixEval.hs | {-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module NixEval ( nixInstantiate
, NixOptions(..)
, unsetNixOptions
, EvalMode(..)
, NixEvalOptions(..)
, defNixEvalOptions
, outputTransform
) where
import Data.ByteString.Lazy (ByteString)
import Data.Char
import Data.Function (on)
import Data.List
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe
import System.Exit
import qualified System.Process.Typed as TP
data NixOptions = NixOptions
{ cores :: Maybe Int
, fsyncMetadata :: Maybe Bool
, restrictEval :: Maybe Bool
, sandbox :: Maybe Bool
, timeout :: Maybe Int
, maxJobs :: Maybe Int
, allowImportFromDerivation :: Maybe Bool
, allowedUris :: Maybe [String]
, showTrace :: Maybe Bool
}
deriving (Show)
unsetNixOptions :: NixOptions
unsetNixOptions = NixOptions
{ cores = Nothing
, fsyncMetadata = Nothing
, restrictEval = Nothing
, sandbox = Nothing
, timeout = Nothing
, maxJobs = Nothing
, allowImportFromDerivation = Nothing
, allowedUris = Nothing
, showTrace = Nothing
}
publicOptions : :
publicOptions = def
{ cores = 0
, fsyncMetadata = False
, restrictEval = True
, sandbox = True
, timeout = 3
, maxJobs = 0
, allowImportFromDerivation = False
}
publicOptions :: NixOptions
publicOptions = def
{ cores = 0
, fsyncMetadata = False
, restrictEval = True
, sandbox = True
, timeout = 3
, maxJobs = 0
, allowImportFromDerivation = False
}
-}
optionsToArgs :: NixOptions -> [String]
optionsToArgs opts = concat
[ opt "cores" cores show
, opt "fsync-metadata" fsyncMetadata bool
, opt "restrict-eval" restrictEval bool
, opt "sandbox" sandbox bool
, opt "timeout" timeout show
, opt "max-jobs" maxJobs show
, opt "allow-import-from-derivation" allowImportFromDerivation bool
, opt "allowed-uris" allowedUris unwords
, opt "show-trace" showTrace bool
] where
opt :: String -> (NixOptions -> Maybe a) -> (a -> String) -> [String]
opt name get toStr = case get opts of
Nothing -> []
Just value -> [ "--option", name, toStr value ]
bool True = "true"
bool False = "false"
data EvalMode = Parse | Lazy | Strict | Json
modeToArgs :: EvalMode -> [String]
modeToArgs Parse = ["--parse"]
modeToArgs Lazy = ["--eval"]
modeToArgs Strict = ["--eval", "--strict"]
modeToArgs Json = ["--eval", "--strict", "--json"]
data NixEvalOptions = NixEvalOptions
{ contents :: Either ByteString FilePath
, attributes :: [String]
, arguments :: Map String String
, nixPath :: [String]
, mode :: EvalMode
, options :: NixOptions
}
defNixEvalOptions :: Either ByteString FilePath -> NixEvalOptions
defNixEvalOptions file = NixEvalOptions
{ contents = file
, attributes = []
, arguments = M.empty
, nixPath = []
, mode = Lazy
, options = unsetNixOptions
}
toProc :: FilePath -> NixEvalOptions -> TP.ProcessConfig () () ()
toProc nixInstantiatePath NixEvalOptions { contents, attributes, arguments, nixPath, mode, options } = let
opts = modeToArgs mode
++ [case contents of
Left _ -> "-"
Right path -> path
]
++ concatMap (\a -> [ "-A", a ]) attributes
++ concatMap (\(var, val) -> [ "--arg", var, val ]) (M.assocs arguments)
++ concatMap (\p -> [ "-I", p ]) nixPath
++ optionsToArgs options
process = TP.proc nixInstantiatePath opts
in case contents of
Left bytes -> TP.setStdin (TP.byteStringInput bytes) process
Right _ -> process
nixInstantiate :: FilePath -> NixEvalOptions -> IO (Either ByteString ByteString)
nixInstantiate nixInstPath opts = toEither <$> TP.readProcess (toProc nixInstPath opts)
where toEither (ExitSuccess, stdout, _) = Right stdout
toEither (ExitFailure _, _, stderr) = Left stderr
data Command = Command [Int] Char deriving Show
trans :: String -> [Either Command Char]
trans ('\ESC':'[':rest) = case right of
(c:r) -> Left (Command (getNumbers codes) c) : trans r
[] -> []
where
(codes, right) = flip break rest $
\s -> not (s == ';' || generalCategory s == DecimalNumber)
getNumbers = getNum . groups
groups = groupBy ((&&) `on` isNumber)
getNum [] = []
getNum [num] = [read num]
getNum (num:_:restnum) = read num : getNum restnum
trans (c:rest) = Right c : trans rest
trans [] = []
From :
toIRCCodes :: Map Int String
toIRCCodes = M.fromList
[ (0, "\SI")
, (37, "\ETX00")
, (30, "\ETX01")
, (34, "\ETX02")
, (32, "\ETX03")
, (31, "\ETX04")
, (33, "\ETX05")
, (35, "\ETX06")
, (33, "\ETX07")
, (33, "\ETX08")
, (32, "\ETX09")
, (36, "\ETX10")
, (36, "\ETX11")
, (34, "\ETX12")
, (31, "\ETX13")
, (30, "\ETX14")
, (37, "\ETX15")
, (1, "\STX")
, (22, "\STX")
]
toIRC :: Command -> String
toIRC (Command [] 'm') = ""
toIRC (Command ints 'm') = concatMap (\i -> M.findWithDefault "" i toIRCCodes) ints
toIRC _ = ""
translateCodes :: Either Command Char -> String
translateCodes (Left cmd) = toIRC cmd
translateCodes (Right char) = [char]
limit :: Int -> [Either Command Char] -> [Either Command Char]
limit 0 [] = []
limit 0 _ = fmap Right "..."
limit _ [] = []
limit n (Left cmd:rest) = Left cmd : limit n rest
limit n (Right char:rest) = Right char : limit (n-1) rest
outputTransform :: String -> String
outputTransform = concatMap translateCodes . limit 200 . trans . fromMaybe "(no output)" . listToMaybe . take 1 . reverse . lines
| null | https://raw.githubusercontent.com/infinisil/nixbot/e8695fd73c07bc115ee0dd3e7c121cd985c04c06/src/NixEval.hs | haskell | # LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedStrings # | module NixEval ( nixInstantiate
, NixOptions(..)
, unsetNixOptions
, EvalMode(..)
, NixEvalOptions(..)
, defNixEvalOptions
, outputTransform
) where
import Data.ByteString.Lazy (ByteString)
import Data.Char
import Data.Function (on)
import Data.List
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe
import System.Exit
import qualified System.Process.Typed as TP
data NixOptions = NixOptions
{ cores :: Maybe Int
, fsyncMetadata :: Maybe Bool
, restrictEval :: Maybe Bool
, sandbox :: Maybe Bool
, timeout :: Maybe Int
, maxJobs :: Maybe Int
, allowImportFromDerivation :: Maybe Bool
, allowedUris :: Maybe [String]
, showTrace :: Maybe Bool
}
deriving (Show)
unsetNixOptions :: NixOptions
unsetNixOptions = NixOptions
{ cores = Nothing
, fsyncMetadata = Nothing
, restrictEval = Nothing
, sandbox = Nothing
, timeout = Nothing
, maxJobs = Nothing
, allowImportFromDerivation = Nothing
, allowedUris = Nothing
, showTrace = Nothing
}
publicOptions : :
publicOptions = def
{ cores = 0
, fsyncMetadata = False
, restrictEval = True
, sandbox = True
, timeout = 3
, maxJobs = 0
, allowImportFromDerivation = False
}
publicOptions :: NixOptions
publicOptions = def
{ cores = 0
, fsyncMetadata = False
, restrictEval = True
, sandbox = True
, timeout = 3
, maxJobs = 0
, allowImportFromDerivation = False
}
-}
optionsToArgs :: NixOptions -> [String]
optionsToArgs opts = concat
[ opt "cores" cores show
, opt "fsync-metadata" fsyncMetadata bool
, opt "restrict-eval" restrictEval bool
, opt "sandbox" sandbox bool
, opt "timeout" timeout show
, opt "max-jobs" maxJobs show
, opt "allow-import-from-derivation" allowImportFromDerivation bool
, opt "allowed-uris" allowedUris unwords
, opt "show-trace" showTrace bool
] where
opt :: String -> (NixOptions -> Maybe a) -> (a -> String) -> [String]
opt name get toStr = case get opts of
Nothing -> []
Just value -> [ "--option", name, toStr value ]
bool True = "true"
bool False = "false"
data EvalMode = Parse | Lazy | Strict | Json
modeToArgs :: EvalMode -> [String]
modeToArgs Parse = ["--parse"]
modeToArgs Lazy = ["--eval"]
modeToArgs Strict = ["--eval", "--strict"]
modeToArgs Json = ["--eval", "--strict", "--json"]
data NixEvalOptions = NixEvalOptions
{ contents :: Either ByteString FilePath
, attributes :: [String]
, arguments :: Map String String
, nixPath :: [String]
, mode :: EvalMode
, options :: NixOptions
}
defNixEvalOptions :: Either ByteString FilePath -> NixEvalOptions
defNixEvalOptions file = NixEvalOptions
{ contents = file
, attributes = []
, arguments = M.empty
, nixPath = []
, mode = Lazy
, options = unsetNixOptions
}
toProc :: FilePath -> NixEvalOptions -> TP.ProcessConfig () () ()
toProc nixInstantiatePath NixEvalOptions { contents, attributes, arguments, nixPath, mode, options } = let
opts = modeToArgs mode
++ [case contents of
Left _ -> "-"
Right path -> path
]
++ concatMap (\a -> [ "-A", a ]) attributes
++ concatMap (\(var, val) -> [ "--arg", var, val ]) (M.assocs arguments)
++ concatMap (\p -> [ "-I", p ]) nixPath
++ optionsToArgs options
process = TP.proc nixInstantiatePath opts
in case contents of
Left bytes -> TP.setStdin (TP.byteStringInput bytes) process
Right _ -> process
nixInstantiate :: FilePath -> NixEvalOptions -> IO (Either ByteString ByteString)
nixInstantiate nixInstPath opts = toEither <$> TP.readProcess (toProc nixInstPath opts)
where toEither (ExitSuccess, stdout, _) = Right stdout
toEither (ExitFailure _, _, stderr) = Left stderr
data Command = Command [Int] Char deriving Show
trans :: String -> [Either Command Char]
trans ('\ESC':'[':rest) = case right of
(c:r) -> Left (Command (getNumbers codes) c) : trans r
[] -> []
where
(codes, right) = flip break rest $
\s -> not (s == ';' || generalCategory s == DecimalNumber)
getNumbers = getNum . groups
groups = groupBy ((&&) `on` isNumber)
getNum [] = []
getNum [num] = [read num]
getNum (num:_:restnum) = read num : getNum restnum
trans (c:rest) = Right c : trans rest
trans [] = []
From :
toIRCCodes :: Map Int String
toIRCCodes = M.fromList
[ (0, "\SI")
, (37, "\ETX00")
, (30, "\ETX01")
, (34, "\ETX02")
, (32, "\ETX03")
, (31, "\ETX04")
, (33, "\ETX05")
, (35, "\ETX06")
, (33, "\ETX07")
, (33, "\ETX08")
, (32, "\ETX09")
, (36, "\ETX10")
, (36, "\ETX11")
, (34, "\ETX12")
, (31, "\ETX13")
, (30, "\ETX14")
, (37, "\ETX15")
, (1, "\STX")
, (22, "\STX")
]
toIRC :: Command -> String
toIRC (Command [] 'm') = ""
toIRC (Command ints 'm') = concatMap (\i -> M.findWithDefault "" i toIRCCodes) ints
toIRC _ = ""
translateCodes :: Either Command Char -> String
translateCodes (Left cmd) = toIRC cmd
translateCodes (Right char) = [char]
limit :: Int -> [Either Command Char] -> [Either Command Char]
limit 0 [] = []
limit 0 _ = fmap Right "..."
limit _ [] = []
limit n (Left cmd:rest) = Left cmd : limit n rest
limit n (Right char:rest) = Right char : limit (n-1) rest
outputTransform :: String -> String
outputTransform = concatMap translateCodes . limit 200 . trans . fromMaybe "(no output)" . listToMaybe . take 1 . reverse . lines
|
72b2f03242f124bb1c33d6beedaa132fdbe5fd452ac6e6ad1f4889bcbf0609e9 | TrustInSoft/tis-interpreter | eval_exprs.mli | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open Cil_types
open Locations
(* Evaluation of expressions and l-values. *)
val eval_expr :
with_alarms:CilE.warn_mode -> Cvalue.Model.t -> exp -> Cvalue.V.t
val eval_expr_with_deps_state :
with_alarms:CilE.warn_mode ->
Zone.t option ->
Cvalue.Model.t ->
exp ->
Cvalue.Model.t * Zone.t option * Location_Bytes.t
val eval_lval_one_loc : with_alarms:CilE.warn_mode ->
Locations.Zone.t option ->
Cvalue.Model.t ->
Cil_types.lval ->
Cil_types.typ ->
Locations.location -> Cvalue.Model.t * Locations.Zone.t option * Cvalue.V.t
val eval_lval :
with_alarms:CilE.warn_mode ->
Zone.t option ->
Cvalue.Model.t ->
lval -> Cvalue.Model.t * Zone.t option * Cvalue.V.t * typ
(* -------------------------------------------------------------------------- *)
(* --- Evaluation to locations --- *)
(* -------------------------------------------------------------------------- *)
val lval_to_loc :
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval -> location
val lval_to_precise_loc :
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval -> Precise_locs.precise_location
val lval_to_loc_state :
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval -> Cvalue.Model.t * location * typ
val lval_to_precise_loc_state :
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval -> Cvalue.Model.t * Precise_locs.precise_location * typ
val lval_to_loc_deps_state :
with_alarms:CilE.warn_mode ->
deps:Zone.t option ->
Cvalue.Model.t ->
reduce_valid_index:Kernel.SafeArrays.t ->
lval ->
Cvalue.Model.t * Zone.t option * location * typ
val lval_to_precise_loc_deps_state :
with_alarms:CilE.warn_mode ->
deps:Zone.t option ->
Cvalue.Model.t ->
reduce_valid_index:Kernel.SafeArrays.t ->
lval ->
Cvalue.Model.t * Zone.t option * Precise_locs.precise_location * typ
(* -------------------------------------------------------------------------- *)
(* --- Reduction --- *)
(* -------------------------------------------------------------------------- *)
(** Reduction by operators condition *)
type cond = { exp : exp; positive : bool; }
exception Reduce_to_bottom
val reduce_by_cond : Cvalue.Model.t -> cond -> Cvalue.Model.t
* Never returns [ Model.bottom ] . Instead , raises [ Reduce_to_bottom ]
(** Reduction by accesses *)
val reduce_by_accessed_loc :
for_writing:bool ->
Cvalue.Model.t -> Cil_types.lval -> Locations.location ->
Cvalue.Model.t * Locations.location
(** Misc functions related to reduction *)
exception Cannot_find_lv
val find_lv : Cvalue.Model.t -> exp -> lval
val get_influential_vars :
Cvalue.Model.t -> exp -> location list
(* -------------------------------------------------------------------------- *)
(* --- Alarms and imprecision --- *)
(* -------------------------------------------------------------------------- *)
(* -------------------------------------------------------------------------- *)
(* --- Alarms and reduction --- *)
(* -------------------------------------------------------------------------- *)
val warn_reduce_by_accessed_loc:
with_alarms:CilE.warn_mode ->
for_writing:bool ->
Cvalue.Model.t -> Locations.location -> Cil_types.lval ->
Cvalue.Model.t * Locations.location
(* -------------------------------------------------------------------------- *)
(* --- Misc --- *)
(* -------------------------------------------------------------------------- *)
val resolv_func_vinfo :
with_alarms:CilE.warn_mode ->
Zone.t option ->
Cvalue.Model.t ->
exp -> Kernel_function.Hptset.t * Zone.t option
val offsetmap_of_lv:
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval ->
Precise_locs.precise_location * Cvalue.Model.t * Cvalue.V_Offsetmap.t_top_bottom
* May raise [ Int_Base . Error_Top ]
(*
Local Variables:
compile-command: "make -C ../../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/value/legacy/eval_exprs.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
Evaluation of expressions and l-values.
--------------------------------------------------------------------------
--- Evaluation to locations ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Reduction ---
--------------------------------------------------------------------------
* Reduction by operators condition
* Reduction by accesses
* Misc functions related to reduction
--------------------------------------------------------------------------
--- Alarms and imprecision ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Alarms and reduction ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Misc ---
--------------------------------------------------------------------------
Local Variables:
compile-command: "make -C ../../../.."
End:
| Modified by TrustInSoft
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Cil_types
open Locations
val eval_expr :
with_alarms:CilE.warn_mode -> Cvalue.Model.t -> exp -> Cvalue.V.t
val eval_expr_with_deps_state :
with_alarms:CilE.warn_mode ->
Zone.t option ->
Cvalue.Model.t ->
exp ->
Cvalue.Model.t * Zone.t option * Location_Bytes.t
val eval_lval_one_loc : with_alarms:CilE.warn_mode ->
Locations.Zone.t option ->
Cvalue.Model.t ->
Cil_types.lval ->
Cil_types.typ ->
Locations.location -> Cvalue.Model.t * Locations.Zone.t option * Cvalue.V.t
val eval_lval :
with_alarms:CilE.warn_mode ->
Zone.t option ->
Cvalue.Model.t ->
lval -> Cvalue.Model.t * Zone.t option * Cvalue.V.t * typ
val lval_to_loc :
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval -> location
val lval_to_precise_loc :
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval -> Precise_locs.precise_location
val lval_to_loc_state :
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval -> Cvalue.Model.t * location * typ
val lval_to_precise_loc_state :
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval -> Cvalue.Model.t * Precise_locs.precise_location * typ
val lval_to_loc_deps_state :
with_alarms:CilE.warn_mode ->
deps:Zone.t option ->
Cvalue.Model.t ->
reduce_valid_index:Kernel.SafeArrays.t ->
lval ->
Cvalue.Model.t * Zone.t option * location * typ
val lval_to_precise_loc_deps_state :
with_alarms:CilE.warn_mode ->
deps:Zone.t option ->
Cvalue.Model.t ->
reduce_valid_index:Kernel.SafeArrays.t ->
lval ->
Cvalue.Model.t * Zone.t option * Precise_locs.precise_location * typ
type cond = { exp : exp; positive : bool; }
exception Reduce_to_bottom
val reduce_by_cond : Cvalue.Model.t -> cond -> Cvalue.Model.t
* Never returns [ Model.bottom ] . Instead , raises [ Reduce_to_bottom ]
val reduce_by_accessed_loc :
for_writing:bool ->
Cvalue.Model.t -> Cil_types.lval -> Locations.location ->
Cvalue.Model.t * Locations.location
exception Cannot_find_lv
val find_lv : Cvalue.Model.t -> exp -> lval
val get_influential_vars :
Cvalue.Model.t -> exp -> location list
val warn_reduce_by_accessed_loc:
with_alarms:CilE.warn_mode ->
for_writing:bool ->
Cvalue.Model.t -> Locations.location -> Cil_types.lval ->
Cvalue.Model.t * Locations.location
val resolv_func_vinfo :
with_alarms:CilE.warn_mode ->
Zone.t option ->
Cvalue.Model.t ->
exp -> Kernel_function.Hptset.t * Zone.t option
val offsetmap_of_lv:
with_alarms:CilE.warn_mode ->
Cvalue.Model.t -> lval ->
Precise_locs.precise_location * Cvalue.Model.t * Cvalue.V_Offsetmap.t_top_bottom
* May raise [ Int_Base . Error_Top ]
|
fa91f908f52cec1c436a3ba3eb8f807697df1617742c111a2f59ca5c71917769 | dgtized/shimmers | brush_sweep.cljs | (ns shimmers.sketches.brush-sweep
(:require
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[shimmers.common.framerate :as framerate]
[shimmers.common.quil :as cq]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.core :as g]
[thi.ng.geom.line :as gl]
[thi.ng.geom.triangle :as gt]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
(defn setup []
(q/color-mode :hsl 1.0)
{:t 0})
(defn update-state [state]
(update state :t (fn [t] (mod (+ t (tm/random 0.05)) 100.0))))
(defn hairs [line]
(let [hair (-> (gt/triangle2 [0 0] [3 7] [7 5])
g/center
(g/scale-size 5))]
(->> (if true
(g/sample-uniform line 20 true)
(repeatedly 64 #(g/random-point line)))
(map (fn [p] (-> hair
(g/rotate (* tm/TWO_PI (tm/random)))
(g/translate p)))))))
(defn draw [{:keys [t]}]
(q/stroke-weight 0.5)
(q/stroke 0 0.01)
(let [t' (/ t 100)]
(q/fill (tm/mix* 0.5 0.9 (+ t' (tm/random -0.05 0.05)))
(tm/mix-circular 0.5 0.8 t')
(tm/random 0.5 0.7)
0.02)
(let [pos (cq/rel-vec (+ -0.1
(/ (tm/smoothstep* 0.3 0.4 t') 30)
(/ (- (tm/step* 0.6 t')) 30))
(* 0.01 t))
slope (* (q/random 0.1) t')
line (gl/line2 pos
(gv/vec2 (q/width) (+ (* slope (q/width)) (:y pos))))]
(doseq [hair (shuffle (hairs line))]
(cq/draw-polygon hair)))))
(sketch/defquil brush-sweep
:created-at "2021-04-12"
:size [1200 900]
:setup setup
:update update-state
:draw draw
:middleware [m/fun-mode framerate/mode])
| null | https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/sketches/brush_sweep.cljs | clojure | (ns shimmers.sketches.brush-sweep
(:require
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[shimmers.common.framerate :as framerate]
[shimmers.common.quil :as cq]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.core :as g]
[thi.ng.geom.line :as gl]
[thi.ng.geom.triangle :as gt]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
(defn setup []
(q/color-mode :hsl 1.0)
{:t 0})
(defn update-state [state]
(update state :t (fn [t] (mod (+ t (tm/random 0.05)) 100.0))))
(defn hairs [line]
(let [hair (-> (gt/triangle2 [0 0] [3 7] [7 5])
g/center
(g/scale-size 5))]
(->> (if true
(g/sample-uniform line 20 true)
(repeatedly 64 #(g/random-point line)))
(map (fn [p] (-> hair
(g/rotate (* tm/TWO_PI (tm/random)))
(g/translate p)))))))
(defn draw [{:keys [t]}]
(q/stroke-weight 0.5)
(q/stroke 0 0.01)
(let [t' (/ t 100)]
(q/fill (tm/mix* 0.5 0.9 (+ t' (tm/random -0.05 0.05)))
(tm/mix-circular 0.5 0.8 t')
(tm/random 0.5 0.7)
0.02)
(let [pos (cq/rel-vec (+ -0.1
(/ (tm/smoothstep* 0.3 0.4 t') 30)
(/ (- (tm/step* 0.6 t')) 30))
(* 0.01 t))
slope (* (q/random 0.1) t')
line (gl/line2 pos
(gv/vec2 (q/width) (+ (* slope (q/width)) (:y pos))))]
(doseq [hair (shuffle (hairs line))]
(cq/draw-polygon hair)))))
(sketch/defquil brush-sweep
:created-at "2021-04-12"
:size [1200 900]
:setup setup
:update update-state
:draw draw
:middleware [m/fun-mode framerate/mode])
| |
d2cb3ac1621671da55790810f2dd0ae6f2cf853291deca77392a92bc3c0cf112 | rm-hull/project-euler | euler003.clj | EULER # 003
;; ==========
;; Find the largest prime factor of a composite number.
;;
The prime factors of 13195 are 5 , 7 , 13 and 29 .
;;
What is the largest prime factor of the number 600,851,475,143 ?
;;
(ns euler003
(:use [util.primes]))
(prime-factors-of 13195)
(time (sort (prime-factors-of 600851475143)))
| null | https://raw.githubusercontent.com/rm-hull/project-euler/04e689e87a1844cfd83229bb4628051e3ac6a325/src/euler003.clj | clojure | ==========
Find the largest prime factor of a composite number.
| EULER # 003
The prime factors of 13195 are 5 , 7 , 13 and 29 .
What is the largest prime factor of the number 600,851,475,143 ?
(ns euler003
(:use [util.primes]))
(prime-factors-of 13195)
(time (sort (prime-factors-of 600851475143)))
|
ec00590070e103a67decea81d28736569210a364d6bbd9c8aefbc8f2856cf59f | eval/deps-try | sexp_test.clj | (ns rebel-readline.clojure.sexp-test
(:require
[rebel-readline.clojure.tokenizer :as tokenize]
[rebel-readline.clojure.sexp :refer :all]
[clojure.test :refer [deftest is are testing]]))
(defn find-open [sexp pos]
(find-open-sexp-start (tokenize/tag-sexp-traversal sexp) pos))
(def find-open-pos (comp second find-open))
(deftest find-open-sexp-start-test
(is (= 4 (find-open-pos "0123(5" 20)))
(is (= 4 (find-open-pos "0123(5" 6)))
(is (= 4 (find-open-pos "0123(5" 5)))
;; position is a cursor position
(is (nil? (find-open-pos "0123(5" 4)))
(is (= 4 (find-open-pos "0123(5)" 6)))
(is (nil? (find-open-pos "0123(5)" 7)))
(is (= 4 (find-open-pos "0123[5" 20)))
(is (= 4 (find-open-pos "0123{5" 20)))
;; more complex example
(is (= 6 (find-open-pos "0123(5[7{9}" 20)))
(is (= 6 (find-open-pos "0123(5[7{9}" 11)))
(is (= 8 (find-open-pos "0123(5[7{9}" 10)))
(is (= 8 (find-open-pos "0123(5[7{9}" 9)))
(is (= 6 (find-open-pos "0123(5[7{9}" 8)))
(is (= 6 (find-open-pos "0123(5[7{9}" 7)))
(is (= 4 (find-open-pos "0123(5[7{9}" 6)))
(is (= 4 (find-open-pos "0123(5[7{9}" 5)))
(is (nil? (find-open-pos "0123(5[7{9}" 4)))
(is (nil? (find-open-pos "0123(5[7{9}" 3)))
(is (nil? (find-open-pos "0123(5[7{9}" 1)))
(is (nil? (find-open-pos "0123(5[7{9}" 0)))
(is (nil? (find-open-pos "0123(5[7{9}" -1)))
(testing "strings"
(is (not (find-open-pos "0123\"56\"8\"ab" 4)))
(is (= 4 (find-open-pos "0123\"56\"8\"ab" 5)))
(is (= 4 (find-open-pos "0123\"56\"8\"ab" 6)))
(is (= 4 (find-open-pos "0123\"56\"8\"ab" 7)))
(is (not (find-open-pos "0123\"56\"8\"ab" 8)))
(is (not (find-open-pos "0123\"56\"8\"ab" 9)))
(is (= 9 (find-open-pos "0123\"56\"8\"ab" 10)))
(is (= 9 (find-open-pos "0123\"56\"8\"ab" 11)))
(is (= 9 (find-open-pos "0123\"56\"8\"ab" 20)))
(is (= 9 (find-open-pos "0123\"56\"8\"ab" 20))))
)
(defn find-end [sexp pos]
(find-open-sexp-end (tokenize/tag-sexp-traversal sexp) pos))
(def find-end-pos (comp second find-end))
(deftest find-open-sexp-end-test
(is (= 4 (find-end-pos "0123)5" 0)))
(is (= 4 (find-end-pos "0123)5" 2)))
(is (= 4 (find-end-pos "0123)5" 3)))
(is (= 4 (find-end-pos "0123)5" 4)))
;; position is a cursor position
(is (nil? (find-end-pos "0123)5" 5)))
(is (nil? (find-end-pos "0123(5)" 3)))
(is (nil? (find-end-pos "0123(5)" 4)))
(is (= 6 (find-end-pos "0123(5)" 5)))
(is (= 6 (find-end-pos "0123(5)" 6)))
(is (nil? (find-end-pos "0123(5)" 7)))
(is (= 5 (find-end-pos "01234]6" 0)))
(is (= 5 (find-end-pos "01234}6" 4)))
;; more complex example
(is (= 7 (find-end-pos "012{4}6]8)a" -1)))
(is (= 7 (find-end-pos "012{4}6]8)a" 0)))
(is (= 7 (find-end-pos "012{4}6]8)a" 1)))
(is (= 7 (find-end-pos "012{4}6]8)a" 2)))
(is (= 7 (find-end-pos "012{4}6]8)a" 3)))
(is (= 5 (find-end-pos "012{4}6]8)a" 4)))
(is (= 5 (find-end-pos "012{4}6]8)a" 5)))
(is (= 7 (find-end-pos "012{4}6]8)a" 6)))
(is (= 7 (find-end-pos "012{4}6]8)a" 7)))
(is (= 9 (find-end-pos "012{4}6]8)a" 8)))
(is (= 9 (find-end-pos "012{4}6]8)a" 9)))
(is (nil? (find-end-pos "012{4}6]8)a" 10)))
(is (not (find-end-pos "012\"45\"78" 3)))
(is (= 6 (find-end-pos "012\"45\"78" 4)))
(is (= 6 (find-end-pos "012\"45\"78" 5)))
(is (= 6 (find-end-pos "012\"45\"78" 6)))
(is (not (find-end-pos "012\"45\"78" 7)))
)
(defn in-quote* [sexp pos]
(in-quote? (tokenize/tag-sexp-traversal sexp) pos))
(deftest in-quote-test
(is (not (in-quote* "0123\"56\"8\"ab" 3)))
(is (not (in-quote* "0123\"56\"8\"ab" 4)))
(is (in-quote* "0123\"56\"8\"ab" 5))
(is (in-quote* "0123\"56\"8\"ab" 6))
(is (in-quote* "0123\"56\"8\"ab" 7))
(is (not (in-quote* "0123\"56\"8\"ab" 8)))
(is (not (in-quote* "0123\"56\"8\"ab" 9)))
(is (in-quote* "0123\"56\"8\"ab" 10))
(is (in-quote* "0123\"56\"8\"ab" 11))
(is (in-quote* "0123\"56\"8\"ab" 12))
(is (not (in-quote* "0123\"56\"8\"ab" 13)))
(is (not (in-quote* "012 \\a" 3)))
(is (not (in-quote* "012 \\a" 4)))
(is (in-quote* "012 \\a" 5))
(is (in-quote* "012 \\a" 6))
(is (not (in-quote* "012 \\a " 7)))
)
(defn in-line-comment* [sexp pos]
(in-line-comment? (tokenize/tag-sexp-traversal sexp) pos))
(deftest in-line-comment-test
(is (in-line-comment* "012;456" 4))
(is (in-line-comment* "012;456" 5))
(is (in-line-comment* "012;456" 6))
(is (in-line-comment* "012;456" 7))
(is (not (in-line-comment* "012;456" 8)))
(is (in-line-comment* "012;456\n" 7))
(is (not (in-line-comment* "012;456\n" 8)))
)
(deftest valid-sexp-from-point-test
(is (= "(do (let [x y] (.asdf sdfsd)))"
(valid-sexp-from-point " (do (let [x y] (.asdf sdfsd) " 22)))
(is (= "(do (let [x y]))"
(valid-sexp-from-point " (do (let [x y] (.asdf sdfsd) " 20)))
(is (= "(do (let [x y] ))"
(valid-sexp-from-point " (do (let [x y] " 22)))
(is (= "([{(\"hello\")}])"
(valid-sexp-from-point " ([{(\"hello\" " 10)))
(is (= "{(\"hello\")}"
(valid-sexp-from-point " ([{(\"hello\")}) " 10)))
)
(deftest word-at-position-test
(is (not (word-at-position " 1234 " 0)))
(is (= ["1234" 1 5 :word]
(word-at-position " 1234 " 1)))
(is (= ["1234" 1 5 :word]
(word-at-position " 1234 " 4)))
(is (= ["1234" 1 5 :word]
(word-at-position " 1234 " 5)))
(is (not (word-at-position " 1234 " 6)))
)
(deftest sexp-ending-at-position-test
(is (= ["(34)" 2 6 :sexp]
(sexp-ending-at-position "01(34)" 5)))
(is (= ["\"34\"" 2 6 :sexp]
(sexp-ending-at-position "01\"34\"" 5)))
(is (not (sexp-ending-at-position "01(34)" 4)))
(is (not (sexp-ending-at-position "01\"34\"" 4)))
(is (not (sexp-ending-at-position "01(34)" 1)))
(is (not (sexp-ending-at-position "01\"34\"" 1)))
(is (not (sexp-ending-at-position "01(34)" 6)))
(is (not (sexp-ending-at-position "01\"34\"" 6)))
)
| null | https://raw.githubusercontent.com/eval/deps-try/da691c68b527ad5f9e770dbad82cce6cbbe16fb4/vendor/rebel-readline/rebel-readline/test/rebel_readline/clojure/sexp_test.clj | clojure | position is a cursor position
more complex example
position is a cursor position
more complex example | (ns rebel-readline.clojure.sexp-test
(:require
[rebel-readline.clojure.tokenizer :as tokenize]
[rebel-readline.clojure.sexp :refer :all]
[clojure.test :refer [deftest is are testing]]))
(defn find-open [sexp pos]
(find-open-sexp-start (tokenize/tag-sexp-traversal sexp) pos))
(def find-open-pos (comp second find-open))
(deftest find-open-sexp-start-test
(is (= 4 (find-open-pos "0123(5" 20)))
(is (= 4 (find-open-pos "0123(5" 6)))
(is (= 4 (find-open-pos "0123(5" 5)))
(is (nil? (find-open-pos "0123(5" 4)))
(is (= 4 (find-open-pos "0123(5)" 6)))
(is (nil? (find-open-pos "0123(5)" 7)))
(is (= 4 (find-open-pos "0123[5" 20)))
(is (= 4 (find-open-pos "0123{5" 20)))
(is (= 6 (find-open-pos "0123(5[7{9}" 20)))
(is (= 6 (find-open-pos "0123(5[7{9}" 11)))
(is (= 8 (find-open-pos "0123(5[7{9}" 10)))
(is (= 8 (find-open-pos "0123(5[7{9}" 9)))
(is (= 6 (find-open-pos "0123(5[7{9}" 8)))
(is (= 6 (find-open-pos "0123(5[7{9}" 7)))
(is (= 4 (find-open-pos "0123(5[7{9}" 6)))
(is (= 4 (find-open-pos "0123(5[7{9}" 5)))
(is (nil? (find-open-pos "0123(5[7{9}" 4)))
(is (nil? (find-open-pos "0123(5[7{9}" 3)))
(is (nil? (find-open-pos "0123(5[7{9}" 1)))
(is (nil? (find-open-pos "0123(5[7{9}" 0)))
(is (nil? (find-open-pos "0123(5[7{9}" -1)))
(testing "strings"
(is (not (find-open-pos "0123\"56\"8\"ab" 4)))
(is (= 4 (find-open-pos "0123\"56\"8\"ab" 5)))
(is (= 4 (find-open-pos "0123\"56\"8\"ab" 6)))
(is (= 4 (find-open-pos "0123\"56\"8\"ab" 7)))
(is (not (find-open-pos "0123\"56\"8\"ab" 8)))
(is (not (find-open-pos "0123\"56\"8\"ab" 9)))
(is (= 9 (find-open-pos "0123\"56\"8\"ab" 10)))
(is (= 9 (find-open-pos "0123\"56\"8\"ab" 11)))
(is (= 9 (find-open-pos "0123\"56\"8\"ab" 20)))
(is (= 9 (find-open-pos "0123\"56\"8\"ab" 20))))
)
(defn find-end [sexp pos]
(find-open-sexp-end (tokenize/tag-sexp-traversal sexp) pos))
(def find-end-pos (comp second find-end))
(deftest find-open-sexp-end-test
(is (= 4 (find-end-pos "0123)5" 0)))
(is (= 4 (find-end-pos "0123)5" 2)))
(is (= 4 (find-end-pos "0123)5" 3)))
(is (= 4 (find-end-pos "0123)5" 4)))
(is (nil? (find-end-pos "0123)5" 5)))
(is (nil? (find-end-pos "0123(5)" 3)))
(is (nil? (find-end-pos "0123(5)" 4)))
(is (= 6 (find-end-pos "0123(5)" 5)))
(is (= 6 (find-end-pos "0123(5)" 6)))
(is (nil? (find-end-pos "0123(5)" 7)))
(is (= 5 (find-end-pos "01234]6" 0)))
(is (= 5 (find-end-pos "01234}6" 4)))
(is (= 7 (find-end-pos "012{4}6]8)a" -1)))
(is (= 7 (find-end-pos "012{4}6]8)a" 0)))
(is (= 7 (find-end-pos "012{4}6]8)a" 1)))
(is (= 7 (find-end-pos "012{4}6]8)a" 2)))
(is (= 7 (find-end-pos "012{4}6]8)a" 3)))
(is (= 5 (find-end-pos "012{4}6]8)a" 4)))
(is (= 5 (find-end-pos "012{4}6]8)a" 5)))
(is (= 7 (find-end-pos "012{4}6]8)a" 6)))
(is (= 7 (find-end-pos "012{4}6]8)a" 7)))
(is (= 9 (find-end-pos "012{4}6]8)a" 8)))
(is (= 9 (find-end-pos "012{4}6]8)a" 9)))
(is (nil? (find-end-pos "012{4}6]8)a" 10)))
(is (not (find-end-pos "012\"45\"78" 3)))
(is (= 6 (find-end-pos "012\"45\"78" 4)))
(is (= 6 (find-end-pos "012\"45\"78" 5)))
(is (= 6 (find-end-pos "012\"45\"78" 6)))
(is (not (find-end-pos "012\"45\"78" 7)))
)
(defn in-quote* [sexp pos]
(in-quote? (tokenize/tag-sexp-traversal sexp) pos))
(deftest in-quote-test
(is (not (in-quote* "0123\"56\"8\"ab" 3)))
(is (not (in-quote* "0123\"56\"8\"ab" 4)))
(is (in-quote* "0123\"56\"8\"ab" 5))
(is (in-quote* "0123\"56\"8\"ab" 6))
(is (in-quote* "0123\"56\"8\"ab" 7))
(is (not (in-quote* "0123\"56\"8\"ab" 8)))
(is (not (in-quote* "0123\"56\"8\"ab" 9)))
(is (in-quote* "0123\"56\"8\"ab" 10))
(is (in-quote* "0123\"56\"8\"ab" 11))
(is (in-quote* "0123\"56\"8\"ab" 12))
(is (not (in-quote* "0123\"56\"8\"ab" 13)))
(is (not (in-quote* "012 \\a" 3)))
(is (not (in-quote* "012 \\a" 4)))
(is (in-quote* "012 \\a" 5))
(is (in-quote* "012 \\a" 6))
(is (not (in-quote* "012 \\a " 7)))
)
(defn in-line-comment* [sexp pos]
(in-line-comment? (tokenize/tag-sexp-traversal sexp) pos))
(deftest in-line-comment-test
(is (in-line-comment* "012;456" 4))
(is (in-line-comment* "012;456" 5))
(is (in-line-comment* "012;456" 6))
(is (in-line-comment* "012;456" 7))
(is (not (in-line-comment* "012;456" 8)))
(is (in-line-comment* "012;456\n" 7))
(is (not (in-line-comment* "012;456\n" 8)))
)
(deftest valid-sexp-from-point-test
(is (= "(do (let [x y] (.asdf sdfsd)))"
(valid-sexp-from-point " (do (let [x y] (.asdf sdfsd) " 22)))
(is (= "(do (let [x y]))"
(valid-sexp-from-point " (do (let [x y] (.asdf sdfsd) " 20)))
(is (= "(do (let [x y] ))"
(valid-sexp-from-point " (do (let [x y] " 22)))
(is (= "([{(\"hello\")}])"
(valid-sexp-from-point " ([{(\"hello\" " 10)))
(is (= "{(\"hello\")}"
(valid-sexp-from-point " ([{(\"hello\")}) " 10)))
)
(deftest word-at-position-test
(is (not (word-at-position " 1234 " 0)))
(is (= ["1234" 1 5 :word]
(word-at-position " 1234 " 1)))
(is (= ["1234" 1 5 :word]
(word-at-position " 1234 " 4)))
(is (= ["1234" 1 5 :word]
(word-at-position " 1234 " 5)))
(is (not (word-at-position " 1234 " 6)))
)
(deftest sexp-ending-at-position-test
(is (= ["(34)" 2 6 :sexp]
(sexp-ending-at-position "01(34)" 5)))
(is (= ["\"34\"" 2 6 :sexp]
(sexp-ending-at-position "01\"34\"" 5)))
(is (not (sexp-ending-at-position "01(34)" 4)))
(is (not (sexp-ending-at-position "01\"34\"" 4)))
(is (not (sexp-ending-at-position "01(34)" 1)))
(is (not (sexp-ending-at-position "01\"34\"" 1)))
(is (not (sexp-ending-at-position "01(34)" 6)))
(is (not (sexp-ending-at-position "01\"34\"" 6)))
)
|
f5db59c27c3b958d72c36e84135261f0cca44c947c743d4108854aa95565211f | fetburner/Coq2SML | gmap.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Maps using the generic comparison function of ocaml . Code borrowed from
the ocaml standard library ( Copyright 1996 , INRIA ) .
the ocaml standard library (Copyright 1996, INRIA). *)
type ('a,'b) t =
Empty
| Node of ('a,'b) t * 'a * 'b * ('a,'b) t * int
let empty = Empty
let is_empty = function Empty -> true | _ -> false
let height = function
Empty -> 0
| Node(_,_,_,_,h) -> h
let create l x d r =
let hl = height l and hr = height r in
Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
let bal l x d r =
let hl = match l with Empty -> 0 | Node(_,_,_,_,h) -> h in
let hr = match r with Empty -> 0 | Node(_,_,_,_,h) -> h in
if hl > hr + 2 then begin
match l with
Empty -> invalid_arg "Map.bal"
| Node(ll, lv, ld, lr, _) ->
if height ll >= height lr then
create ll lv ld (create lr x d r)
else begin
match lr with
Empty -> invalid_arg "Map.bal"
| Node(lrl, lrv, lrd, lrr, _)->
create (create ll lv ld lrl) lrv lrd (create lrr x d r)
end
end else if hr > hl + 2 then begin
match r with
Empty -> invalid_arg "Map.bal"
| Node(rl, rv, rd, rr, _) ->
if height rr >= height rl then
create (create l x d rl) rv rd rr
else begin
match rl with
Empty -> invalid_arg "Map.bal"
| Node(rll, rlv, rld, rlr, _) ->
create (create l x d rll) rlv rld (create rlr rv rd rr)
end
end else
Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
let rec add x data = function
Empty ->
Node(Empty, x, data, Empty, 1)
| Node(l, v, d, r, h) ->
let c = Pervasives.compare x v in
if c = 0 then
Node(l, x, data, r, h)
else if c < 0 then
bal (add x data l) v d r
else
bal l v d (add x data r)
let rec find x = function
Empty ->
raise Not_found
| Node(l, v, d, r, _) ->
let c = Pervasives.compare x v in
if c = 0 then d
else find x (if c < 0 then l else r)
let rec mem x = function
Empty ->
false
| Node(l, v, d, r, _) ->
let c = Pervasives.compare x v in
c = 0 || mem x (if c < 0 then l else r)
let rec min_binding = function
Empty -> raise Not_found
| Node(Empty, x, d, r, _) -> (x, d)
| Node(l, x, d, r, _) -> min_binding l
let rec remove_min_binding = function
Empty -> invalid_arg "Map.remove_min_elt"
| Node(Empty, x, d, r, _) -> r
| Node(l, x, d, r, _) -> bal (remove_min_binding l) x d r
let merge t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let (x, d) = min_binding t2 in
bal t1 x d (remove_min_binding t2)
let rec remove x = function
Empty ->
Empty
| Node(l, v, d, r, h) ->
let c = Pervasives.compare x v in
if c = 0 then
merge l r
else if c < 0 then
bal (remove x l) v d r
else
bal l v d (remove x r)
let rec iter f = function
Empty -> ()
| Node(l, v, d, r, _) ->
iter f l; f v d; iter f r
let rec map f = function
Empty -> Empty
| Node(l, v, d, r, h) -> Node(map f l, v, f d, map f r, h)
(* Maintien de fold_right par compatibilité (changé en fold_left dans
ocaml-3.09.0) *)
let rec fold f m accu =
match m with
Empty -> accu
| Node(l, v, d, r, _) ->
fold f l (f v d (fold f r accu))
(* Added with respect to ocaml standard library. *)
let dom m = fold (fun x _ acc -> x::acc) m []
let rng m = fold (fun _ y acc -> y::acc) m []
let to_list m = fold (fun x y acc -> (x,y)::acc) m []
| null | https://raw.githubusercontent.com/fetburner/Coq2SML/322d613619edbb62edafa999bff24b1993f37612/coq-8.4pl4/lib/gmap.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Maintien de fold_right par compatibilité (changé en fold_left dans
ocaml-3.09.0)
Added with respect to ocaml standard library. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Maps using the generic comparison function of ocaml . Code borrowed from
the ocaml standard library ( Copyright 1996 , INRIA ) .
the ocaml standard library (Copyright 1996, INRIA). *)
type ('a,'b) t =
Empty
| Node of ('a,'b) t * 'a * 'b * ('a,'b) t * int
let empty = Empty
let is_empty = function Empty -> true | _ -> false
let height = function
Empty -> 0
| Node(_,_,_,_,h) -> h
let create l x d r =
let hl = height l and hr = height r in
Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
let bal l x d r =
let hl = match l with Empty -> 0 | Node(_,_,_,_,h) -> h in
let hr = match r with Empty -> 0 | Node(_,_,_,_,h) -> h in
if hl > hr + 2 then begin
match l with
Empty -> invalid_arg "Map.bal"
| Node(ll, lv, ld, lr, _) ->
if height ll >= height lr then
create ll lv ld (create lr x d r)
else begin
match lr with
Empty -> invalid_arg "Map.bal"
| Node(lrl, lrv, lrd, lrr, _)->
create (create ll lv ld lrl) lrv lrd (create lrr x d r)
end
end else if hr > hl + 2 then begin
match r with
Empty -> invalid_arg "Map.bal"
| Node(rl, rv, rd, rr, _) ->
if height rr >= height rl then
create (create l x d rl) rv rd rr
else begin
match rl with
Empty -> invalid_arg "Map.bal"
| Node(rll, rlv, rld, rlr, _) ->
create (create l x d rll) rlv rld (create rlr rv rd rr)
end
end else
Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
let rec add x data = function
Empty ->
Node(Empty, x, data, Empty, 1)
| Node(l, v, d, r, h) ->
let c = Pervasives.compare x v in
if c = 0 then
Node(l, x, data, r, h)
else if c < 0 then
bal (add x data l) v d r
else
bal l v d (add x data r)
let rec find x = function
Empty ->
raise Not_found
| Node(l, v, d, r, _) ->
let c = Pervasives.compare x v in
if c = 0 then d
else find x (if c < 0 then l else r)
let rec mem x = function
Empty ->
false
| Node(l, v, d, r, _) ->
let c = Pervasives.compare x v in
c = 0 || mem x (if c < 0 then l else r)
let rec min_binding = function
Empty -> raise Not_found
| Node(Empty, x, d, r, _) -> (x, d)
| Node(l, x, d, r, _) -> min_binding l
let rec remove_min_binding = function
Empty -> invalid_arg "Map.remove_min_elt"
| Node(Empty, x, d, r, _) -> r
| Node(l, x, d, r, _) -> bal (remove_min_binding l) x d r
let merge t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let (x, d) = min_binding t2 in
bal t1 x d (remove_min_binding t2)
let rec remove x = function
Empty ->
Empty
| Node(l, v, d, r, h) ->
let c = Pervasives.compare x v in
if c = 0 then
merge l r
else if c < 0 then
bal (remove x l) v d r
else
bal l v d (remove x r)
let rec iter f = function
Empty -> ()
| Node(l, v, d, r, _) ->
iter f l; f v d; iter f r
let rec map f = function
Empty -> Empty
| Node(l, v, d, r, h) -> Node(map f l, v, f d, map f r, h)
let rec fold f m accu =
match m with
Empty -> accu
| Node(l, v, d, r, _) ->
fold f l (f v d (fold f r accu))
let dom m = fold (fun x _ acc -> x::acc) m []
let rng m = fold (fun _ y acc -> y::acc) m []
let to_list m = fold (fun x y acc -> (x,y)::acc) m []
|
e7e41c6de50f3f7953000d359bedac448e91baf57aeeccfbe2aac2455210764a | Rotaerk/vulkanTest | DescriptorSetLayout.hs | module Graphics.VulkanAux.DescriptorSetLayout where
import Data.Reflection
import Graphics.Vulkan.Core_1_0
import Graphics.Vulkan.Marshal.Create
import Graphics.VulkanAux.Resource
vkaDescriptorSetLayoutResource :: Given VkDevice => VkaResource VkDescriptorSetLayoutCreateInfo VkDescriptorSetLayout
vkaDescriptorSetLayoutResource = vkaSimpleParamResource_ vkCreateDescriptorSetLayout vkDestroyDescriptorSetLayout "vkCreateDescriptorSetLayout" given
initStandardDescriptorSetLayoutCreateInfo :: CreateVkStruct VkDescriptorSetLayoutCreateInfo '["sType", "pNext"] ()
initStandardDescriptorSetLayoutCreateInfo =
set @"sType" VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO &*
set @"pNext" VK_NULL
| null | https://raw.githubusercontent.com/Rotaerk/vulkanTest/beafd3cc27ba60561b9e76cd0058e30949a5affb/sandbox/sandbox/src/Graphics/VulkanAux/DescriptorSetLayout.hs | haskell | module Graphics.VulkanAux.DescriptorSetLayout where
import Data.Reflection
import Graphics.Vulkan.Core_1_0
import Graphics.Vulkan.Marshal.Create
import Graphics.VulkanAux.Resource
vkaDescriptorSetLayoutResource :: Given VkDevice => VkaResource VkDescriptorSetLayoutCreateInfo VkDescriptorSetLayout
vkaDescriptorSetLayoutResource = vkaSimpleParamResource_ vkCreateDescriptorSetLayout vkDestroyDescriptorSetLayout "vkCreateDescriptorSetLayout" given
initStandardDescriptorSetLayoutCreateInfo :: CreateVkStruct VkDescriptorSetLayoutCreateInfo '["sType", "pNext"] ()
initStandardDescriptorSetLayoutCreateInfo =
set @"sType" VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO &*
set @"pNext" VK_NULL
| |
1728a702af90f0aa77e16d822d859a3850def025520f6846f0e63cc3aa5acfcf | brendanhay/amazonka | ListContents.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
Module : Amazonka . Wisdom . ListContents
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Lists the content.
--
-- This operation returns paginated results.
module Amazonka.Wisdom.ListContents
( -- * Creating a Request
ListContents (..),
newListContents,
-- * Request Lenses
listContents_maxResults,
listContents_nextToken,
listContents_knowledgeBaseId,
-- * Destructuring the Response
ListContentsResponse (..),
newListContentsResponse,
-- * Response Lenses
listContentsResponse_nextToken,
listContentsResponse_httpStatus,
listContentsResponse_contentSummaries,
)
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 qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.Wisdom.Types
-- | /See:/ 'newListContents' smart constructor.
data ListContents = ListContents'
{ -- | The maximum number of results to return per page.
maxResults :: Prelude.Maybe Prelude.Natural,
-- | The token for the next set of results. Use the value returned in the
-- previous response in the next request to retrieve the next set of
-- results.
nextToken :: Prelude.Maybe Prelude.Text,
| The identifier of the knowledge base . Can be either the ID or the ARN .
URLs can not contain the ARN .
knowledgeBaseId :: Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
Create a value of ' ListContents ' 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:
--
-- 'maxResults', 'listContents_maxResults' - The maximum number of results to return per page.
--
' ' , ' listContents_nextToken ' - The token for the next set of results . Use the value returned in the
-- previous response in the next request to retrieve the next set of
-- results.
--
' knowledgeBaseId ' , ' listContents_knowledgeBaseId ' - The identifier of the knowledge base . Can be either the ID or the ARN .
URLs can not contain the ARN .
newListContents ::
-- | 'knowledgeBaseId'
Prelude.Text ->
ListContents
newListContents pKnowledgeBaseId_ =
ListContents'
{ maxResults = Prelude.Nothing,
nextToken = Prelude.Nothing,
knowledgeBaseId = pKnowledgeBaseId_
}
-- | The maximum number of results to return per page.
listContents_maxResults :: Lens.Lens' ListContents (Prelude.Maybe Prelude.Natural)
listContents_maxResults = Lens.lens (\ListContents' {maxResults} -> maxResults) (\s@ListContents' {} a -> s {maxResults = a} :: ListContents)
-- | The token for the next set of results. Use the value returned in the
-- previous response in the next request to retrieve the next set of
-- results.
listContents_nextToken :: Lens.Lens' ListContents (Prelude.Maybe Prelude.Text)
listContents_nextToken = Lens.lens (\ListContents' {nextToken} -> nextToken) (\s@ListContents' {} a -> s {nextToken = a} :: ListContents)
| The identifier of the knowledge base . Can be either the ID or the ARN .
URLs can not contain the ARN .
listContents_knowledgeBaseId :: Lens.Lens' ListContents Prelude.Text
listContents_knowledgeBaseId = Lens.lens (\ListContents' {knowledgeBaseId} -> knowledgeBaseId) (\s@ListContents' {} a -> s {knowledgeBaseId = a} :: ListContents)
instance Core.AWSPager ListContents where
page rq rs
| Core.stop
( rs
Lens.^? listContentsResponse_nextToken Prelude.. Lens._Just
) =
Prelude.Nothing
| Core.stop
(rs Lens.^. listContentsResponse_contentSummaries) =
Prelude.Nothing
| Prelude.otherwise =
Prelude.Just Prelude.$
rq
Prelude.& listContents_nextToken
Lens..~ rs
Lens.^? listContentsResponse_nextToken Prelude.. Lens._Just
instance Core.AWSRequest ListContents where
type AWSResponse ListContents = ListContentsResponse
request overrides =
Request.get (overrides defaultService)
response =
Response.receiveJSON
( \s h x ->
ListContentsResponse'
Prelude.<$> (x Data..?> "nextToken")
Prelude.<*> (Prelude.pure (Prelude.fromEnum s))
Prelude.<*> ( x Data..?> "contentSummaries"
Core..!@ Prelude.mempty
)
)
instance Prelude.Hashable ListContents where
hashWithSalt _salt ListContents' {..} =
_salt `Prelude.hashWithSalt` maxResults
`Prelude.hashWithSalt` nextToken
`Prelude.hashWithSalt` knowledgeBaseId
instance Prelude.NFData ListContents where
rnf ListContents' {..} =
Prelude.rnf maxResults
`Prelude.seq` Prelude.rnf nextToken
`Prelude.seq` Prelude.rnf knowledgeBaseId
instance Data.ToHeaders ListContents where
toHeaders =
Prelude.const
( Prelude.mconcat
[ "Content-Type"
Data.=# ( "application/x-amz-json-1.1" ::
Prelude.ByteString
)
]
)
instance Data.ToPath ListContents where
toPath ListContents' {..} =
Prelude.mconcat
[ "/knowledgeBases/",
Data.toBS knowledgeBaseId,
"/contents"
]
instance Data.ToQuery ListContents where
toQuery ListContents' {..} =
Prelude.mconcat
[ "maxResults" Data.=: maxResults,
"nextToken" Data.=: nextToken
]
-- | /See:/ 'newListContentsResponse' smart constructor.
data ListContentsResponse = ListContentsResponse'
{ -- | If there are additional results, this is the token for the next set of
-- results.
nextToken :: Prelude.Maybe Prelude.Text,
-- | The response's http status code.
httpStatus :: Prelude.Int,
-- | Information about the content.
contentSummaries :: [ContentSummary]
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'ListContentsResponse' 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:
--
' ' , ' listContentsResponse_nextToken ' - If there are additional results , this is the token for the next set of
-- results.
--
-- 'httpStatus', 'listContentsResponse_httpStatus' - The response's http status code.
--
-- 'contentSummaries', 'listContentsResponse_contentSummaries' - Information about the content.
newListContentsResponse ::
-- | 'httpStatus'
Prelude.Int ->
ListContentsResponse
newListContentsResponse pHttpStatus_ =
ListContentsResponse'
{ nextToken = Prelude.Nothing,
httpStatus = pHttpStatus_,
contentSummaries = Prelude.mempty
}
-- | If there are additional results, this is the token for the next set of
-- results.
listContentsResponse_nextToken :: Lens.Lens' ListContentsResponse (Prelude.Maybe Prelude.Text)
listContentsResponse_nextToken = Lens.lens (\ListContentsResponse' {nextToken} -> nextToken) (\s@ListContentsResponse' {} a -> s {nextToken = a} :: ListContentsResponse)
-- | The response's http status code.
listContentsResponse_httpStatus :: Lens.Lens' ListContentsResponse Prelude.Int
listContentsResponse_httpStatus = Lens.lens (\ListContentsResponse' {httpStatus} -> httpStatus) (\s@ListContentsResponse' {} a -> s {httpStatus = a} :: ListContentsResponse)
-- | Information about the content.
listContentsResponse_contentSummaries :: Lens.Lens' ListContentsResponse [ContentSummary]
listContentsResponse_contentSummaries = Lens.lens (\ListContentsResponse' {contentSummaries} -> contentSummaries) (\s@ListContentsResponse' {} a -> s {contentSummaries = a} :: ListContentsResponse) Prelude.. Lens.coerced
instance Prelude.NFData ListContentsResponse where
rnf ListContentsResponse' {..} =
Prelude.rnf nextToken
`Prelude.seq` Prelude.rnf httpStatus
`Prelude.seq` Prelude.rnf contentSummaries
| null | https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-wisdom/gen/Amazonka/Wisdom/ListContents.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Lists the content.
This operation returns paginated results.
* Creating a Request
* Request Lenses
* Destructuring the Response
* Response Lenses
| /See:/ 'newListContents' smart constructor.
| The maximum number of results to return per page.
| The token for the next set of results. Use the value returned in the
previous response in the next request to retrieve the next set of
results.
|
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'maxResults', 'listContents_maxResults' - The maximum number of results to return per page.
previous response in the next request to retrieve the next set of
results.
| 'knowledgeBaseId'
| The maximum number of results to return per page.
| The token for the next set of results. Use the value returned in the
previous response in the next request to retrieve the next set of
results.
| /See:/ 'newListContentsResponse' smart constructor.
| If there are additional results, this is the token for the next set of
results.
| The response's http status code.
| Information about the content.
|
Create a value of 'ListContentsResponse' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
results.
'httpStatus', 'listContentsResponse_httpStatus' - The response's http status code.
'contentSummaries', 'listContentsResponse_contentSummaries' - Information about the content.
| 'httpStatus'
| If there are additional results, this is the token for the next set of
results.
| The response's http status code.
| Information about the content. | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Module : Amazonka . Wisdom . ListContents
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Amazonka.Wisdom.ListContents
ListContents (..),
newListContents,
listContents_maxResults,
listContents_nextToken,
listContents_knowledgeBaseId,
ListContentsResponse (..),
newListContentsResponse,
listContentsResponse_nextToken,
listContentsResponse_httpStatus,
listContentsResponse_contentSummaries,
)
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 qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.Wisdom.Types
data ListContents = ListContents'
maxResults :: Prelude.Maybe Prelude.Natural,
nextToken :: Prelude.Maybe Prelude.Text,
| The identifier of the knowledge base . Can be either the ID or the ARN .
URLs can not contain the ARN .
knowledgeBaseId :: Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Create a value of ' ListContents ' with all optional fields omitted .
Use < -lens generic - lens > or < optics > to modify other optional fields .
' ' , ' listContents_nextToken ' - The token for the next set of results . Use the value returned in the
' knowledgeBaseId ' , ' listContents_knowledgeBaseId ' - The identifier of the knowledge base . Can be either the ID or the ARN .
URLs can not contain the ARN .
newListContents ::
Prelude.Text ->
ListContents
newListContents pKnowledgeBaseId_ =
ListContents'
{ maxResults = Prelude.Nothing,
nextToken = Prelude.Nothing,
knowledgeBaseId = pKnowledgeBaseId_
}
listContents_maxResults :: Lens.Lens' ListContents (Prelude.Maybe Prelude.Natural)
listContents_maxResults = Lens.lens (\ListContents' {maxResults} -> maxResults) (\s@ListContents' {} a -> s {maxResults = a} :: ListContents)
listContents_nextToken :: Lens.Lens' ListContents (Prelude.Maybe Prelude.Text)
listContents_nextToken = Lens.lens (\ListContents' {nextToken} -> nextToken) (\s@ListContents' {} a -> s {nextToken = a} :: ListContents)
| The identifier of the knowledge base . Can be either the ID or the ARN .
URLs can not contain the ARN .
listContents_knowledgeBaseId :: Lens.Lens' ListContents Prelude.Text
listContents_knowledgeBaseId = Lens.lens (\ListContents' {knowledgeBaseId} -> knowledgeBaseId) (\s@ListContents' {} a -> s {knowledgeBaseId = a} :: ListContents)
instance Core.AWSPager ListContents where
page rq rs
| Core.stop
( rs
Lens.^? listContentsResponse_nextToken Prelude.. Lens._Just
) =
Prelude.Nothing
| Core.stop
(rs Lens.^. listContentsResponse_contentSummaries) =
Prelude.Nothing
| Prelude.otherwise =
Prelude.Just Prelude.$
rq
Prelude.& listContents_nextToken
Lens..~ rs
Lens.^? listContentsResponse_nextToken Prelude.. Lens._Just
instance Core.AWSRequest ListContents where
type AWSResponse ListContents = ListContentsResponse
request overrides =
Request.get (overrides defaultService)
response =
Response.receiveJSON
( \s h x ->
ListContentsResponse'
Prelude.<$> (x Data..?> "nextToken")
Prelude.<*> (Prelude.pure (Prelude.fromEnum s))
Prelude.<*> ( x Data..?> "contentSummaries"
Core..!@ Prelude.mempty
)
)
instance Prelude.Hashable ListContents where
hashWithSalt _salt ListContents' {..} =
_salt `Prelude.hashWithSalt` maxResults
`Prelude.hashWithSalt` nextToken
`Prelude.hashWithSalt` knowledgeBaseId
instance Prelude.NFData ListContents where
rnf ListContents' {..} =
Prelude.rnf maxResults
`Prelude.seq` Prelude.rnf nextToken
`Prelude.seq` Prelude.rnf knowledgeBaseId
instance Data.ToHeaders ListContents where
toHeaders =
Prelude.const
( Prelude.mconcat
[ "Content-Type"
Data.=# ( "application/x-amz-json-1.1" ::
Prelude.ByteString
)
]
)
instance Data.ToPath ListContents where
toPath ListContents' {..} =
Prelude.mconcat
[ "/knowledgeBases/",
Data.toBS knowledgeBaseId,
"/contents"
]
instance Data.ToQuery ListContents where
toQuery ListContents' {..} =
Prelude.mconcat
[ "maxResults" Data.=: maxResults,
"nextToken" Data.=: nextToken
]
data ListContentsResponse = ListContentsResponse'
nextToken :: Prelude.Maybe Prelude.Text,
httpStatus :: Prelude.Int,
contentSummaries :: [ContentSummary]
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
' ' , ' listContentsResponse_nextToken ' - If there are additional results , this is the token for the next set of
newListContentsResponse ::
Prelude.Int ->
ListContentsResponse
newListContentsResponse pHttpStatus_ =
ListContentsResponse'
{ nextToken = Prelude.Nothing,
httpStatus = pHttpStatus_,
contentSummaries = Prelude.mempty
}
listContentsResponse_nextToken :: Lens.Lens' ListContentsResponse (Prelude.Maybe Prelude.Text)
listContentsResponse_nextToken = Lens.lens (\ListContentsResponse' {nextToken} -> nextToken) (\s@ListContentsResponse' {} a -> s {nextToken = a} :: ListContentsResponse)
listContentsResponse_httpStatus :: Lens.Lens' ListContentsResponse Prelude.Int
listContentsResponse_httpStatus = Lens.lens (\ListContentsResponse' {httpStatus} -> httpStatus) (\s@ListContentsResponse' {} a -> s {httpStatus = a} :: ListContentsResponse)
listContentsResponse_contentSummaries :: Lens.Lens' ListContentsResponse [ContentSummary]
listContentsResponse_contentSummaries = Lens.lens (\ListContentsResponse' {contentSummaries} -> contentSummaries) (\s@ListContentsResponse' {} a -> s {contentSummaries = a} :: ListContentsResponse) Prelude.. Lens.coerced
instance Prelude.NFData ListContentsResponse where
rnf ListContentsResponse' {..} =
Prelude.rnf nextToken
`Prelude.seq` Prelude.rnf httpStatus
`Prelude.seq` Prelude.rnf contentSummaries
|
206fd81bc31d195ae36484210e6e290b2870cf39828d491211aab781604c50e6 | cyverse-archive/DiscoveryEnvironmentBackend | app_metadata.clj | (ns metadactyl.persistence.app-metadata
"Persistence layer for app metadata."
(:use [kameleon.entities]
[kameleon.uuids :only [uuidify]]
[korma.core :exclude [update]]
[korma.db :only [transaction]]
[metadactyl.user :only [current-user]]
[metadactyl.util.assertions]
[metadactyl.util.conversions :only [remove-nil-vals]])
(:require [clojure.set :as set]
[kameleon.app-listing :as app-listing]
[korma.core :as sql]
[metadactyl.persistence.app-metadata.delete :as delete]
[metadactyl.persistence.app-metadata.relabel :as relabel]))
(def param-multi-input-type "MultiFileSelector")
(def param-flex-input-type "FileFolderInput")
(def param-input-reference-types #{"ReferenceAnnotation" "ReferenceGenome" "ReferenceSequence"})
(def param-ds-input-types #{"FileInput" "FolderInput" param-multi-input-type param-flex-input-type})
(def param-input-types (set/union param-ds-input-types param-input-reference-types))
(def param-output-types #{"FileOutput" "FolderOutput" "MultiFileOutput"})
(def param-file-types (set/union param-input-types param-output-types))
(def param-selection-types #{"TextSelection" "DoubleSelection" "IntegerSelection"})
(def param-tree-type "TreeSelection")
(def param-list-types (conj param-selection-types param-tree-type))
(def param-reference-genome-types #{"ReferenceGenome" "ReferenceSequence" "ReferenceAnnotation"})
(defn- filter-valid-app-values
"Filters valid keys from the given App for inserting or updating in the database, setting the
current date as the edited date."
[app]
(-> app
(select-keys [:name :description])
(assoc :edited_date (sqlfn now))))
(defn- filter-valid-tool-values
"Filters valid keys from the given Tool for inserting or updating in the database."
[tool]
(select-keys tool [:id
:container_images_id
:name
:description
:attribution
:location
:version
:integration_data_id
:tool_type_id]))
(defn- filter-valid-task-values
"Filters valid keys from the given Task for inserting or updating in the database."
[task]
(select-keys task [:name :description :label :tool_id :external_app_id]))
(defn- filter-valid-app-group-values
"Filters and renames valid keys from the given App group for inserting or updating in the database."
[group]
(-> group
(set/rename-keys {:isVisible :is_visible})
(select-keys [:id :task_id :name :description :label :display_order :is_visible])))
(defn- filter-valid-app-parameter-values
"Filters and renames valid keys from the given App parameter for inserting or updating in the
database."
[parameter]
(-> parameter
(set/rename-keys {:isVisible :is_visible
:order :ordering})
(select-keys [:id
:parameter_group_id
:name
:description
:label
:is_visible
:ordering
:display_order
:parameter_type
:required
:omit_if_blank])))
(defn- filter-valid-file-parameter-values
"Filters valid keys from the given file-parameter for inserting or updating in the database."
[file-parameter]
(select-keys file-parameter [:parameter_id
:retain
:is_implicit
:info_type
:data_format
:data_source_id
:repeat_option_flag]))
(defn- filter-valid-parameter-value-values
"Filters and renames valid keys from the given parameter-value for inserting or updating in the
database."
[parameter-value]
(-> parameter-value
(set/rename-keys {:display :label
:isDefault :is_default})
(select-keys [:id
:parameter_id
:parent_id
:is_default
:display_order
:name
:value
:description
:label])))
(defn get-app
"Retrieves all app listing fields from the database."
[app-id]
(assert-not-nil [:app-id app-id] (app-listing/get-app-listing (uuidify app-id))))
(defn get-integration-data
"Retrieves integrator info from the database, adding it first if not already there."
([{:keys [email first-name last-name]}]
(get-integration-data email (str first-name " " last-name)))
([integrator-email integrator-name]
(if-let [integration-data (first (select integration_data
(where {:integrator_email integrator-email})))]
integration-data
(insert integration_data (values {:integrator_email integrator-email
:integrator_name integrator-name})))))
(defn get-tool-listing-base-query
"Common select query for tool listings."
[]
(-> (select* tool_listing)
(fields [:tool_id :id]
:name
:description
:location
:type
:version
:attribution)))
(defn get-app-tools
"Loads information about the tools associated with an app."
[app-id]
(select (get-tool-listing-base-query) (where {:app_id app-id})))
(defn get-tools-by-image-id
"Loads information about the tools associated with a Docker image."
[image-id]
(select (get-tool-listing-base-query)
(modifier "DISTINCT")
(where {:container_images_id image-id})))
(defn get-public-tools-by-image-id
"Loads information about public tools associated with a Docker image."
[img-id]
(select (get-tool-listing-base-query)
(modifier "DISTINCT")
(where {:container_images_id img-id
:is_public true})))
(defn get-tool-type-id
"Gets the ID of the given tool type name."
[tool-type]
(:id (first (select tool_types (fields :id) (where {:name tool-type})))))
(defn add-tool-data-file
"Adds a tool's test data files to the database"
[tool-id input-file filename]
(insert tool_test_data_files (values {:tool_id tool-id
:input_file input-file
:filename filename})))
(defn add-tool
"Adds a new tool and its test data files to the database"
[{type :type {:keys [implementor_email implementor test]} :implementation :as tool}]
(transaction
(let [integration-data-id (:id (get-integration-data implementor_email implementor))
tool (-> tool
(assoc :integration_data_id integration-data-id
:tool_type_id (get-tool-type-id type))
(filter-valid-tool-values))
tool-id (:id (insert tools (values tool)))]
(dorun (map (partial add-tool-data-file tool-id true) (:input_files test)))
(dorun (map (partial add-tool-data-file tool-id false) (:output_files test)))
tool-id)))
(defn update-tool
"Updates a tool and its test data files in the database"
[{tool-id :id
type :type
{:keys [implementor_email implementor test] :as implementation} :implementation
:as tool}]
(transaction
(let [integration-data-id (when implementation
(:id (get-integration-data implementor_email implementor)))
type-id (when type (get-tool-type-id type))
tool (-> tool
(assoc :integration_data_id integration-data-id
:tool_type_id type-id)
(dissoc :id)
filter-valid-tool-values
remove-nil-vals)]
(when-not (empty? tool)
(sql/update tools (set-fields tool) (where {:id tool-id})))
(when-not (empty? test)
(delete tool_test_data_files (where {:tool_id tool-id}))
(dorun (map (partial add-tool-data-file tool-id true) (:input_files test)))
(dorun (map (partial add-tool-data-file tool-id false) (:output_files test)))))))
(defn- prep-app
"Prepares an app for insertion into the database."
[app integration-data-id]
(-> (select-keys app [:id :name :description])
(assoc :integration_data_id integration-data-id
:edited_date (sqlfn now))))
(defn add-app
"Adds top-level app info to the database and returns the new app info, including its new ID."
([app]
(add-app app current-user))
([app user]
(insert apps (values (prep-app app (:id (get-integration-data user)))))))
(defn add-step
"Adds an app step to the database for the given app ID."
[app-id step-number step]
(let [step (-> step
(select-keys [:task_id])
(update-in [:task_id] uuidify)
(assoc :app_id app-id
:step step-number))]
(insert app_steps (values step))))
(defn- add-workflow-io-map
[mapping]
(insert :workflow_io_maps
(values {:app_id (:app_id mapping)
:source_step (get-in mapping [:source_step :id])
:target_step (get-in mapping [:target_step :id])})))
(defn- build-io-key
[step de-app-key external-app-key value]
(let [stringify #(if (keyword? %) (name %) %)]
(if (= (:app_type step) "External")
[external-app-key (stringify value)]
[de-app-key (uuidify value)])))
(defn- io-mapping-builder
[mapping-id mapping]
(fn [[input output]]
(into {} [(vector :mapping_id mapping-id)
(build-io-key (:target_step mapping) :input :external_input input)
(build-io-key (:source_step mapping) :output :external_output output)])))
(defn add-mapping
"Adds an input/output workflow mapping to the database for the given app source->target mapping."
[mapping]
(let [mapping-id (:id (add-workflow-io-map mapping))]
(->> (:map mapping)
(map (io-mapping-builder mapping-id mapping))
(map #(insert :input_output_mapping (values %)))
(dorun))))
(defn update-app
"Updates top-level app info in the database."
([app]
(update-app app false))
([app publish?]
(let [app-id (:id app)
app (-> app
(select-keys [:name :description :wiki_url :deleted :disabled])
(assoc :edited_date (sqlfn now)
:integration_date (when publish? (sqlfn now)))
(remove-nil-vals))]
(sql/update apps (set-fields app) (where {:id app-id})))))
(defn add-app-reference
"Adds an App's reference to the database."
[app-id reference]
(insert app_references (values {:app_id app-id, :reference_text reference})))
(defn set-app-references
"Resets the given App's references with the given list."
[app-id references]
(transaction
(delete app_references (where {:app_id app-id}))
(dorun (map (partial add-app-reference app-id) references))))
(defn add-app-suggested-category
"Adds an App's suggested category to the database."
[app-id category-id]
(insert :suggested_groups (values {:app_id app-id, :app_category_id category-id})))
(defn set-app-suggested-categories
"Resets the given App's suggested categories with the given category ID list."
[app-id category-ids]
(transaction
(delete :suggested_groups (where {:app_id app-id}))
(dorun (map (partial add-app-suggested-category app-id) category-ids))))
(defn add-task
"Adds a task to the database."
[task]
(insert tasks (values (filter-valid-task-values task))))
(defn update-task
"Updates a task in the database."
[{task-id :id :as task}]
(sql/update tasks (set-fields (filter-valid-task-values task)) (where {:id task-id})))
(defn remove-app-steps
"Removes all steps from an App. This delete will cascade to workflow_io_maps and
input_output_mapping entries."
[app-id]
(delete app_steps (where {:app_id app-id})))
(defn remove-workflow-map-orphans
"Removes any orphaned workflow_io_maps table entries."
[]
(delete :workflow_io_maps
(where (not (exists (subselect [:input_output_mapping :iom]
(where {:iom.mapping_id :workflow_io_maps.id})))))))
(defn remove-parameter-mappings
"Removes all input-output mappings associated with the given parameter ID, then removes any
orphaned workflow_io_maps table entries."
[parameter-id]
(transaction
(delete :input_output_mapping (where (or {:input parameter-id}
{:output parameter-id})))
(remove-workflow-map-orphans)))
(defn update-app-labels
"Updates the labels in an app."
[req]
(relabel/update-app-labels req))
(defn get-app-group
"Fetches an App group."
([group-id]
(first (select parameter_groups (where {:id group-id}))))
([group-id task-id]
(first (select parameter_groups (where {:id group-id, :task_id task-id})))))
(defn add-app-group
"Adds an App group to the database."
[group]
(insert parameter_groups (values (filter-valid-app-group-values group))))
(defn update-app-group
"Updates an App group in the database."
[{group-id :id :as group}]
(sql/update parameter_groups
(set-fields (filter-valid-app-group-values group))
(where {:id group-id})))
(defn remove-app-group-orphans
"Removes groups associated with the given task ID, but not in the given group-ids list."
[task-id group-ids]
(delete parameter_groups (where {:task_id task-id
:id [not-in group-ids]})))
(defn get-parameter-type-id
"Gets the ID of the given parameter type name."
[parameter-type]
(:id (first
(select parameter_types
(fields :id)
(where {:name parameter-type :deprecated false})))))
(defn get-info-type-id
"Gets the ID of the given info type name."
[info-type]
(:id (first
(select info_type
(fields :id)
(where {:name info-type :deprecated false})))))
(defn get-data-format-id
"Gets the ID of the data format with the given name."
[data-format]
(:id (first
(select data_formats
(fields :id)
(where {:name data-format})))))
(defn get-data-source-id
"Gets the ID of the data source with the given name."
[data-source]
(:id (first
(select data_source
(fields :id)
(where {:name data-source})))))
(defn get-app-parameter
"Fetches an App parameter."
([parameter-id]
(first (select parameters (where {:id parameter-id}))))
([parameter-id task-id]
(first (select :task_param_listing (where {:id parameter-id, :task_id task-id})))))
(defn add-app-parameter
"Adds an App parameter to the parameters table."
[{param-type :type :as parameter}]
(insert parameters
(values (filter-valid-app-parameter-values
(assoc parameter :parameter_type (get-parameter-type-id param-type))))))
(defn update-app-parameter
"Updates a parameter in the parameters table."
[{parameter-id :id param-type :type :as parameter}]
(sql/update parameters
(set-fields (filter-valid-app-parameter-values
(assoc parameter
:parameter_type (get-parameter-type-id param-type))))
(where {:id parameter-id})))
(defn remove-parameter-orphans
"Removes parameters associated with the given group ID, but not in the given parameter-ids list."
[group-id parameter-ids]
(delete parameters (where {:parameter_group_id group-id
:id [not-in parameter-ids]})))
(defn clear-group-parameters
"Removes parameters associated with the given group ID."
[group-id]
(delete parameters (where {:parameter_group_id group-id})))
(defn add-file-parameter
"Adds file parameter fields to the database."
[{info-type :file_info_type data-format :format data-source :data_source :as file-parameter}]
(insert file_parameters
(values (filter-valid-file-parameter-values
(assoc file-parameter
:info_type (get-info-type-id info-type)
:data_format (get-data-format-id data-format)
:data_source_id (get-data-source-id data-source))))))
(defn remove-file-parameter
"Removes all file parameters associated with the given parameter ID."
[parameter-id]
(delete file_parameters (where {:parameter_id parameter-id})))
(defn add-validation-rule
"Adds a validation rule to the database."
[parameter-id rule-type]
(insert validation_rules
(values {:parameter_id parameter-id
:rule_type (subselect rule_type
(fields :id)
(where {:name rule-type
:deprecated false}))})))
(defn remove-parameter-validation-rules
"Removes all validation rules and rule arguments associated with the given parameter ID."
[parameter-id]
(delete validation_rules (where {:parameter_id parameter-id})))
(defn add-validation-rule-argument
"Adds a validation rule argument to the database."
[validation-rule-id ordering argument-value]
(insert validation_rule_arguments (values {:rule_id validation-rule-id
:ordering ordering
:argument_value argument-value})))
(defn add-parameter-default-value
"Adds a parameter's default value to the database."
[parameter-id default-value]
(insert parameter_values (values {:parameter_id parameter-id
:value default-value
:is_default true})))
(defn add-app-parameter-value
"Adds a parameter value to the database."
[parameter-value]
(insert parameter_values (values (filter-valid-parameter-value-values parameter-value))))
(defn remove-parameter-values
"Removes all parameter values associated with the given parameter IDs."
[parameter-ids]
(delete parameter_values (where {:parameter_id [in parameter-ids]})))
(defn app-accessible-by
"Obtains the list of users who can access an app."
[app-id]
(map :username
(select [:apps :a]
(join [:app_category_app :aca]
{:a.id :aca.app_id})
(join [:app_categories :g]
{:aca.app_category_id :g.id})
(join [:workspace :w]
{:g.workspace_id :w.id})
(join [:users :u]
{:w.user_id :u.id})
(fields :u.username)
(where {:a.id app-id}))))
(defn count-external-steps
"Counts how many steps have an external ID in the given app."
[app-id]
((comp :count first)
(select [:app_steps :s]
(aggregate (count :external_app_id) :count)
(join [:tasks :t] {:s.task_id :t.id})
(where {:s.app_id (uuidify app-id)})
(where (raw "t.external_app_id IS NOT NULL")))))
(defn permanently-delete-app
"Permanently removes an app from the metadata database."
[app-id]
(delete/permanently-delete-app ((comp :id get-app) app-id)))
(defn delete-app
"Marks or unmarks an app as deleted in the metadata database."
([app-id]
(delete-app true app-id))
([deleted? app-id]
(sql/update :apps (set-fields {:deleted deleted?}) (where {:id app-id}))))
(defn disable-app
"Marks or unmarks an app as disabled in the metadata database."
([app-id]
(disable-app true app-id))
([disabled? app-id]
(sql/update :apps (set-fields {:disabled disabled?}) (where {:id app-id}))))
(defn rate-app
"Adds or updates a user's rating and comment ID for the given app."
[app-id user-id request]
(let [rating (first (select ratings (where {:app_id app-id, :user_id user-id})))]
(if rating
(sql/update ratings
(set-fields (remove-nil-vals request))
(where {:app_id app-id
:user_id user-id}))
(insert ratings
(values (assoc (remove-nil-vals request) :app_id app-id, :user_id user-id))))))
(defn delete-app-rating
"Removes a user's rating and comment ID for the given app."
[app-id user-id]
(delete ratings
(where {:app_id app-id
:user_id user-id})))
(defn get-app-avg-rating
"Gets the average and total number of user ratings for the given app ID."
[app-id]
(first
(select ratings
(fields (raw "CAST(COALESCE(AVG(rating), 0.0) AS DOUBLE PRECISION) AS average"))
(aggregate (count :rating) :total)
(where {:app_id app-id}))))
(defn load-app-info
[app-id]
(first
(select [:apps :a] (where {:id (uuidify app-id)}))))
(defn load-app-steps
[app-id]
(select [:apps :a]
(join [:app_steps :s] {:a.id :s.app_id})
(join [:tasks :t] {:s.task_id :t.id})
(fields [:s.id :step_id]
[:t.id :task_id]
[:t.tool_id :tool_id]
[:t.external_app_id :external_app_id])
(where {:a.id (uuidify app-id)})))
(defn- mapping-base-query
[]
(-> (select* [:workflow_io_maps :wim])
(join [:input_output_mapping :iom] {:wim.id :iom.mapping_id})
(fields [:wim.source_step :source_id]
[:wim.target_step :target_id]
[:iom.input :input_id]
[:iom.external_input :external_input_id]
[:iom.output :output_id]
[:iom.external_output :external_output_id])))
(defn load-target-step-mappings
[step-id]
(select (mapping-base-query)
(where {:wim.target_step step-id})))
(defn load-app-mappings
[app-id]
(select (mapping-base-query)
(where {:wim.app_id (uuidify app-id)})))
(defn load-app-details
[app-ids]
(select app_listing
(where {:id [in (map uuidify app-ids)]})))
(defn get-default-output-name
[task-id parameter-id]
(some->> (-> (select* [:tasks :t])
(join [:parameter_groups :pg] {:t.id :pg.task_id})
(join [:parameters :p] {:pg.id :p.parameter_group_id})
(join [:parameter_values :pv] {:p.id :pv.parameter_id})
(fields [:pv.value :default_value])
(where {:pv.is_default true
:t.id task-id
:p.id parameter-id})
(select))
(first)
(:default_value)))
(defn- default-value-subselect
[]
(subselect [:parameter_values :pv]
(fields [:pv.value :default_value])
(where {:pv.parameter_id :p.id
:pv.is_default true})))
(defn get-app-parameters
[app-id]
(select [:task_param_listing :p]
(fields :p.id
:p.name
:p.description
:p.label
[(default-value-subselect) :default_value]
:p.is_visible
:p.ordering
:p.omit_if_blank
[:p.parameter_type :type]
:p.value_type
:p.is_implicit
:p.info_type
:p.data_format
[:s.id :step_id]
[:t.external_app_id :external_app_id])
(join [:app_steps :s]
{:s.task_id :p.task_id})
(join [:tasks :t]
{:p.task_id :t.id})
(join [:apps :app]
{:app.id :s.app_id})
(where {:app.id (uuidify app-id)})))
| null | https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/metadactyl-clj/src/metadactyl/persistence/app_metadata.clj | clojure | (ns metadactyl.persistence.app-metadata
"Persistence layer for app metadata."
(:use [kameleon.entities]
[kameleon.uuids :only [uuidify]]
[korma.core :exclude [update]]
[korma.db :only [transaction]]
[metadactyl.user :only [current-user]]
[metadactyl.util.assertions]
[metadactyl.util.conversions :only [remove-nil-vals]])
(:require [clojure.set :as set]
[kameleon.app-listing :as app-listing]
[korma.core :as sql]
[metadactyl.persistence.app-metadata.delete :as delete]
[metadactyl.persistence.app-metadata.relabel :as relabel]))
(def param-multi-input-type "MultiFileSelector")
(def param-flex-input-type "FileFolderInput")
(def param-input-reference-types #{"ReferenceAnnotation" "ReferenceGenome" "ReferenceSequence"})
(def param-ds-input-types #{"FileInput" "FolderInput" param-multi-input-type param-flex-input-type})
(def param-input-types (set/union param-ds-input-types param-input-reference-types))
(def param-output-types #{"FileOutput" "FolderOutput" "MultiFileOutput"})
(def param-file-types (set/union param-input-types param-output-types))
(def param-selection-types #{"TextSelection" "DoubleSelection" "IntegerSelection"})
(def param-tree-type "TreeSelection")
(def param-list-types (conj param-selection-types param-tree-type))
(def param-reference-genome-types #{"ReferenceGenome" "ReferenceSequence" "ReferenceAnnotation"})
(defn- filter-valid-app-values
"Filters valid keys from the given App for inserting or updating in the database, setting the
current date as the edited date."
[app]
(-> app
(select-keys [:name :description])
(assoc :edited_date (sqlfn now))))
(defn- filter-valid-tool-values
"Filters valid keys from the given Tool for inserting or updating in the database."
[tool]
(select-keys tool [:id
:container_images_id
:name
:description
:attribution
:location
:version
:integration_data_id
:tool_type_id]))
(defn- filter-valid-task-values
"Filters valid keys from the given Task for inserting or updating in the database."
[task]
(select-keys task [:name :description :label :tool_id :external_app_id]))
(defn- filter-valid-app-group-values
"Filters and renames valid keys from the given App group for inserting or updating in the database."
[group]
(-> group
(set/rename-keys {:isVisible :is_visible})
(select-keys [:id :task_id :name :description :label :display_order :is_visible])))
(defn- filter-valid-app-parameter-values
"Filters and renames valid keys from the given App parameter for inserting or updating in the
database."
[parameter]
(-> parameter
(set/rename-keys {:isVisible :is_visible
:order :ordering})
(select-keys [:id
:parameter_group_id
:name
:description
:label
:is_visible
:ordering
:display_order
:parameter_type
:required
:omit_if_blank])))
(defn- filter-valid-file-parameter-values
"Filters valid keys from the given file-parameter for inserting or updating in the database."
[file-parameter]
(select-keys file-parameter [:parameter_id
:retain
:is_implicit
:info_type
:data_format
:data_source_id
:repeat_option_flag]))
(defn- filter-valid-parameter-value-values
"Filters and renames valid keys from the given parameter-value for inserting or updating in the
database."
[parameter-value]
(-> parameter-value
(set/rename-keys {:display :label
:isDefault :is_default})
(select-keys [:id
:parameter_id
:parent_id
:is_default
:display_order
:name
:value
:description
:label])))
(defn get-app
"Retrieves all app listing fields from the database."
[app-id]
(assert-not-nil [:app-id app-id] (app-listing/get-app-listing (uuidify app-id))))
(defn get-integration-data
"Retrieves integrator info from the database, adding it first if not already there."
([{:keys [email first-name last-name]}]
(get-integration-data email (str first-name " " last-name)))
([integrator-email integrator-name]
(if-let [integration-data (first (select integration_data
(where {:integrator_email integrator-email})))]
integration-data
(insert integration_data (values {:integrator_email integrator-email
:integrator_name integrator-name})))))
(defn get-tool-listing-base-query
"Common select query for tool listings."
[]
(-> (select* tool_listing)
(fields [:tool_id :id]
:name
:description
:location
:type
:version
:attribution)))
(defn get-app-tools
"Loads information about the tools associated with an app."
[app-id]
(select (get-tool-listing-base-query) (where {:app_id app-id})))
(defn get-tools-by-image-id
"Loads information about the tools associated with a Docker image."
[image-id]
(select (get-tool-listing-base-query)
(modifier "DISTINCT")
(where {:container_images_id image-id})))
(defn get-public-tools-by-image-id
"Loads information about public tools associated with a Docker image."
[img-id]
(select (get-tool-listing-base-query)
(modifier "DISTINCT")
(where {:container_images_id img-id
:is_public true})))
(defn get-tool-type-id
"Gets the ID of the given tool type name."
[tool-type]
(:id (first (select tool_types (fields :id) (where {:name tool-type})))))
(defn add-tool-data-file
"Adds a tool's test data files to the database"
[tool-id input-file filename]
(insert tool_test_data_files (values {:tool_id tool-id
:input_file input-file
:filename filename})))
(defn add-tool
"Adds a new tool and its test data files to the database"
[{type :type {:keys [implementor_email implementor test]} :implementation :as tool}]
(transaction
(let [integration-data-id (:id (get-integration-data implementor_email implementor))
tool (-> tool
(assoc :integration_data_id integration-data-id
:tool_type_id (get-tool-type-id type))
(filter-valid-tool-values))
tool-id (:id (insert tools (values tool)))]
(dorun (map (partial add-tool-data-file tool-id true) (:input_files test)))
(dorun (map (partial add-tool-data-file tool-id false) (:output_files test)))
tool-id)))
(defn update-tool
"Updates a tool and its test data files in the database"
[{tool-id :id
type :type
{:keys [implementor_email implementor test] :as implementation} :implementation
:as tool}]
(transaction
(let [integration-data-id (when implementation
(:id (get-integration-data implementor_email implementor)))
type-id (when type (get-tool-type-id type))
tool (-> tool
(assoc :integration_data_id integration-data-id
:tool_type_id type-id)
(dissoc :id)
filter-valid-tool-values
remove-nil-vals)]
(when-not (empty? tool)
(sql/update tools (set-fields tool) (where {:id tool-id})))
(when-not (empty? test)
(delete tool_test_data_files (where {:tool_id tool-id}))
(dorun (map (partial add-tool-data-file tool-id true) (:input_files test)))
(dorun (map (partial add-tool-data-file tool-id false) (:output_files test)))))))
(defn- prep-app
"Prepares an app for insertion into the database."
[app integration-data-id]
(-> (select-keys app [:id :name :description])
(assoc :integration_data_id integration-data-id
:edited_date (sqlfn now))))
(defn add-app
"Adds top-level app info to the database and returns the new app info, including its new ID."
([app]
(add-app app current-user))
([app user]
(insert apps (values (prep-app app (:id (get-integration-data user)))))))
(defn add-step
"Adds an app step to the database for the given app ID."
[app-id step-number step]
(let [step (-> step
(select-keys [:task_id])
(update-in [:task_id] uuidify)
(assoc :app_id app-id
:step step-number))]
(insert app_steps (values step))))
(defn- add-workflow-io-map
[mapping]
(insert :workflow_io_maps
(values {:app_id (:app_id mapping)
:source_step (get-in mapping [:source_step :id])
:target_step (get-in mapping [:target_step :id])})))
(defn- build-io-key
[step de-app-key external-app-key value]
(let [stringify #(if (keyword? %) (name %) %)]
(if (= (:app_type step) "External")
[external-app-key (stringify value)]
[de-app-key (uuidify value)])))
(defn- io-mapping-builder
[mapping-id mapping]
(fn [[input output]]
(into {} [(vector :mapping_id mapping-id)
(build-io-key (:target_step mapping) :input :external_input input)
(build-io-key (:source_step mapping) :output :external_output output)])))
(defn add-mapping
"Adds an input/output workflow mapping to the database for the given app source->target mapping."
[mapping]
(let [mapping-id (:id (add-workflow-io-map mapping))]
(->> (:map mapping)
(map (io-mapping-builder mapping-id mapping))
(map #(insert :input_output_mapping (values %)))
(dorun))))
(defn update-app
"Updates top-level app info in the database."
([app]
(update-app app false))
([app publish?]
(let [app-id (:id app)
app (-> app
(select-keys [:name :description :wiki_url :deleted :disabled])
(assoc :edited_date (sqlfn now)
:integration_date (when publish? (sqlfn now)))
(remove-nil-vals))]
(sql/update apps (set-fields app) (where {:id app-id})))))
(defn add-app-reference
"Adds an App's reference to the database."
[app-id reference]
(insert app_references (values {:app_id app-id, :reference_text reference})))
(defn set-app-references
"Resets the given App's references with the given list."
[app-id references]
(transaction
(delete app_references (where {:app_id app-id}))
(dorun (map (partial add-app-reference app-id) references))))
(defn add-app-suggested-category
"Adds an App's suggested category to the database."
[app-id category-id]
(insert :suggested_groups (values {:app_id app-id, :app_category_id category-id})))
(defn set-app-suggested-categories
"Resets the given App's suggested categories with the given category ID list."
[app-id category-ids]
(transaction
(delete :suggested_groups (where {:app_id app-id}))
(dorun (map (partial add-app-suggested-category app-id) category-ids))))
(defn add-task
"Adds a task to the database."
[task]
(insert tasks (values (filter-valid-task-values task))))
(defn update-task
"Updates a task in the database."
[{task-id :id :as task}]
(sql/update tasks (set-fields (filter-valid-task-values task)) (where {:id task-id})))
(defn remove-app-steps
"Removes all steps from an App. This delete will cascade to workflow_io_maps and
input_output_mapping entries."
[app-id]
(delete app_steps (where {:app_id app-id})))
(defn remove-workflow-map-orphans
"Removes any orphaned workflow_io_maps table entries."
[]
(delete :workflow_io_maps
(where (not (exists (subselect [:input_output_mapping :iom]
(where {:iom.mapping_id :workflow_io_maps.id})))))))
(defn remove-parameter-mappings
"Removes all input-output mappings associated with the given parameter ID, then removes any
orphaned workflow_io_maps table entries."
[parameter-id]
(transaction
(delete :input_output_mapping (where (or {:input parameter-id}
{:output parameter-id})))
(remove-workflow-map-orphans)))
(defn update-app-labels
"Updates the labels in an app."
[req]
(relabel/update-app-labels req))
(defn get-app-group
"Fetches an App group."
([group-id]
(first (select parameter_groups (where {:id group-id}))))
([group-id task-id]
(first (select parameter_groups (where {:id group-id, :task_id task-id})))))
(defn add-app-group
"Adds an App group to the database."
[group]
(insert parameter_groups (values (filter-valid-app-group-values group))))
(defn update-app-group
"Updates an App group in the database."
[{group-id :id :as group}]
(sql/update parameter_groups
(set-fields (filter-valid-app-group-values group))
(where {:id group-id})))
(defn remove-app-group-orphans
"Removes groups associated with the given task ID, but not in the given group-ids list."
[task-id group-ids]
(delete parameter_groups (where {:task_id task-id
:id [not-in group-ids]})))
(defn get-parameter-type-id
"Gets the ID of the given parameter type name."
[parameter-type]
(:id (first
(select parameter_types
(fields :id)
(where {:name parameter-type :deprecated false})))))
(defn get-info-type-id
"Gets the ID of the given info type name."
[info-type]
(:id (first
(select info_type
(fields :id)
(where {:name info-type :deprecated false})))))
(defn get-data-format-id
"Gets the ID of the data format with the given name."
[data-format]
(:id (first
(select data_formats
(fields :id)
(where {:name data-format})))))
(defn get-data-source-id
"Gets the ID of the data source with the given name."
[data-source]
(:id (first
(select data_source
(fields :id)
(where {:name data-source})))))
(defn get-app-parameter
"Fetches an App parameter."
([parameter-id]
(first (select parameters (where {:id parameter-id}))))
([parameter-id task-id]
(first (select :task_param_listing (where {:id parameter-id, :task_id task-id})))))
(defn add-app-parameter
"Adds an App parameter to the parameters table."
[{param-type :type :as parameter}]
(insert parameters
(values (filter-valid-app-parameter-values
(assoc parameter :parameter_type (get-parameter-type-id param-type))))))
(defn update-app-parameter
"Updates a parameter in the parameters table."
[{parameter-id :id param-type :type :as parameter}]
(sql/update parameters
(set-fields (filter-valid-app-parameter-values
(assoc parameter
:parameter_type (get-parameter-type-id param-type))))
(where {:id parameter-id})))
(defn remove-parameter-orphans
"Removes parameters associated with the given group ID, but not in the given parameter-ids list."
[group-id parameter-ids]
(delete parameters (where {:parameter_group_id group-id
:id [not-in parameter-ids]})))
(defn clear-group-parameters
"Removes parameters associated with the given group ID."
[group-id]
(delete parameters (where {:parameter_group_id group-id})))
(defn add-file-parameter
"Adds file parameter fields to the database."
[{info-type :file_info_type data-format :format data-source :data_source :as file-parameter}]
(insert file_parameters
(values (filter-valid-file-parameter-values
(assoc file-parameter
:info_type (get-info-type-id info-type)
:data_format (get-data-format-id data-format)
:data_source_id (get-data-source-id data-source))))))
(defn remove-file-parameter
"Removes all file parameters associated with the given parameter ID."
[parameter-id]
(delete file_parameters (where {:parameter_id parameter-id})))
(defn add-validation-rule
"Adds a validation rule to the database."
[parameter-id rule-type]
(insert validation_rules
(values {:parameter_id parameter-id
:rule_type (subselect rule_type
(fields :id)
(where {:name rule-type
:deprecated false}))})))
(defn remove-parameter-validation-rules
"Removes all validation rules and rule arguments associated with the given parameter ID."
[parameter-id]
(delete validation_rules (where {:parameter_id parameter-id})))
(defn add-validation-rule-argument
"Adds a validation rule argument to the database."
[validation-rule-id ordering argument-value]
(insert validation_rule_arguments (values {:rule_id validation-rule-id
:ordering ordering
:argument_value argument-value})))
(defn add-parameter-default-value
"Adds a parameter's default value to the database."
[parameter-id default-value]
(insert parameter_values (values {:parameter_id parameter-id
:value default-value
:is_default true})))
(defn add-app-parameter-value
"Adds a parameter value to the database."
[parameter-value]
(insert parameter_values (values (filter-valid-parameter-value-values parameter-value))))
(defn remove-parameter-values
"Removes all parameter values associated with the given parameter IDs."
[parameter-ids]
(delete parameter_values (where {:parameter_id [in parameter-ids]})))
(defn app-accessible-by
"Obtains the list of users who can access an app."
[app-id]
(map :username
(select [:apps :a]
(join [:app_category_app :aca]
{:a.id :aca.app_id})
(join [:app_categories :g]
{:aca.app_category_id :g.id})
(join [:workspace :w]
{:g.workspace_id :w.id})
(join [:users :u]
{:w.user_id :u.id})
(fields :u.username)
(where {:a.id app-id}))))
(defn count-external-steps
"Counts how many steps have an external ID in the given app."
[app-id]
((comp :count first)
(select [:app_steps :s]
(aggregate (count :external_app_id) :count)
(join [:tasks :t] {:s.task_id :t.id})
(where {:s.app_id (uuidify app-id)})
(where (raw "t.external_app_id IS NOT NULL")))))
(defn permanently-delete-app
"Permanently removes an app from the metadata database."
[app-id]
(delete/permanently-delete-app ((comp :id get-app) app-id)))
(defn delete-app
"Marks or unmarks an app as deleted in the metadata database."
([app-id]
(delete-app true app-id))
([deleted? app-id]
(sql/update :apps (set-fields {:deleted deleted?}) (where {:id app-id}))))
(defn disable-app
"Marks or unmarks an app as disabled in the metadata database."
([app-id]
(disable-app true app-id))
([disabled? app-id]
(sql/update :apps (set-fields {:disabled disabled?}) (where {:id app-id}))))
(defn rate-app
"Adds or updates a user's rating and comment ID for the given app."
[app-id user-id request]
(let [rating (first (select ratings (where {:app_id app-id, :user_id user-id})))]
(if rating
(sql/update ratings
(set-fields (remove-nil-vals request))
(where {:app_id app-id
:user_id user-id}))
(insert ratings
(values (assoc (remove-nil-vals request) :app_id app-id, :user_id user-id))))))
(defn delete-app-rating
"Removes a user's rating and comment ID for the given app."
[app-id user-id]
(delete ratings
(where {:app_id app-id
:user_id user-id})))
(defn get-app-avg-rating
"Gets the average and total number of user ratings for the given app ID."
[app-id]
(first
(select ratings
(fields (raw "CAST(COALESCE(AVG(rating), 0.0) AS DOUBLE PRECISION) AS average"))
(aggregate (count :rating) :total)
(where {:app_id app-id}))))
(defn load-app-info
[app-id]
(first
(select [:apps :a] (where {:id (uuidify app-id)}))))
(defn load-app-steps
[app-id]
(select [:apps :a]
(join [:app_steps :s] {:a.id :s.app_id})
(join [:tasks :t] {:s.task_id :t.id})
(fields [:s.id :step_id]
[:t.id :task_id]
[:t.tool_id :tool_id]
[:t.external_app_id :external_app_id])
(where {:a.id (uuidify app-id)})))
(defn- mapping-base-query
[]
(-> (select* [:workflow_io_maps :wim])
(join [:input_output_mapping :iom] {:wim.id :iom.mapping_id})
(fields [:wim.source_step :source_id]
[:wim.target_step :target_id]
[:iom.input :input_id]
[:iom.external_input :external_input_id]
[:iom.output :output_id]
[:iom.external_output :external_output_id])))
(defn load-target-step-mappings
[step-id]
(select (mapping-base-query)
(where {:wim.target_step step-id})))
(defn load-app-mappings
[app-id]
(select (mapping-base-query)
(where {:wim.app_id (uuidify app-id)})))
(defn load-app-details
[app-ids]
(select app_listing
(where {:id [in (map uuidify app-ids)]})))
(defn get-default-output-name
[task-id parameter-id]
(some->> (-> (select* [:tasks :t])
(join [:parameter_groups :pg] {:t.id :pg.task_id})
(join [:parameters :p] {:pg.id :p.parameter_group_id})
(join [:parameter_values :pv] {:p.id :pv.parameter_id})
(fields [:pv.value :default_value])
(where {:pv.is_default true
:t.id task-id
:p.id parameter-id})
(select))
(first)
(:default_value)))
(defn- default-value-subselect
[]
(subselect [:parameter_values :pv]
(fields [:pv.value :default_value])
(where {:pv.parameter_id :p.id
:pv.is_default true})))
(defn get-app-parameters
[app-id]
(select [:task_param_listing :p]
(fields :p.id
:p.name
:p.description
:p.label
[(default-value-subselect) :default_value]
:p.is_visible
:p.ordering
:p.omit_if_blank
[:p.parameter_type :type]
:p.value_type
:p.is_implicit
:p.info_type
:p.data_format
[:s.id :step_id]
[:t.external_app_id :external_app_id])
(join [:app_steps :s]
{:s.task_id :p.task_id})
(join [:tasks :t]
{:p.task_id :t.id})
(join [:apps :app]
{:app.id :s.app_id})
(where {:app.id (uuidify app-id)})))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.